feat(purchase): 생산소모품 구매 관리 시스템 구현
tkuser: 업체(공급업체) CRUD + 소모품 마스터 CRUD (사진 업로드 포함) tkfb: 구매신청 → 구매 처리 → 월간 분석/정산 전체 워크플로 설비(equipment) 분류 구매 시 자동 등록 + 실패 시 admin 알림 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -52,6 +52,9 @@ function setupRoutes(app) {
|
||||
const patrolRoutes = require('../routes/patrolRoutes');
|
||||
const notificationRoutes = require('../routes/notificationRoutes');
|
||||
const pushSubscriptionRoutes = require('../routes/pushSubscriptionRoutes');
|
||||
const purchaseRequestRoutes = require('../routes/purchaseRequestRoutes');
|
||||
const purchaseRoutes = require('../routes/purchaseRoutes');
|
||||
const settlementRoutes = require('../routes/settlementRoutes');
|
||||
|
||||
// Rate Limiters 설정
|
||||
const rateLimit = require('express-rate-limit');
|
||||
@@ -161,6 +164,9 @@ function setupRoutes(app) {
|
||||
app.use('/api/patrol', patrolRoutes); // 일일순회점검 시스템
|
||||
app.use('/api/notifications', notificationRoutes); // 알림 시스템
|
||||
app.use('/api/push', pushSubscriptionRoutes); // Push 구독
|
||||
app.use('/api/purchase-requests', purchaseRequestRoutes); // 구매신청
|
||||
app.use('/api/purchases', purchaseRoutes); // 구매 내역
|
||||
app.use('/api/settlements', settlementRoutes); // 월간 정산
|
||||
app.use('/api', uploadBgRoutes);
|
||||
|
||||
// Swagger API 문서
|
||||
|
||||
104
system1-factory/api/controllers/purchaseController.js
Normal file
104
system1-factory/api/controllers/purchaseController.js
Normal file
@@ -0,0 +1,104 @@
|
||||
const PurchaseModel = require('../models/purchaseModel');
|
||||
const PurchaseRequestModel = require('../models/purchaseRequestModel');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
const PurchaseController = {
|
||||
// 구매 처리 (신청 → 구매)
|
||||
create: async (req, res) => {
|
||||
try {
|
||||
const { request_id, item_id, vendor_id, quantity, unit_price, purchase_date, update_base_price, notes } = req.body;
|
||||
|
||||
if (!item_id) return res.status(400).json({ success: false, message: '소모품을 선택해주세요.' });
|
||||
if (!unit_price) return res.status(400).json({ success: false, message: '구매 단가를 입력해주세요.' });
|
||||
if (!purchase_date) return res.status(400).json({ success: false, message: '구매일을 입력해주세요.' });
|
||||
|
||||
// 구매 내역 생성
|
||||
const purchaseId = await PurchaseModel.createFromRequest({
|
||||
request_id: request_id || null,
|
||||
item_id,
|
||||
vendor_id: vendor_id || null,
|
||||
quantity: quantity || 1,
|
||||
unit_price,
|
||||
purchase_date,
|
||||
purchaser_id: req.user.id,
|
||||
notes
|
||||
});
|
||||
|
||||
// 기준가 업데이트 요청 시
|
||||
if (update_base_price) {
|
||||
const items = await PurchaseModel.getConsumableItems(false);
|
||||
const item = items.find(i => i.item_id === parseInt(item_id));
|
||||
if (item) {
|
||||
await PurchaseModel.updateBasePrice(item_id, unit_price, item.base_price, req.user.id);
|
||||
}
|
||||
}
|
||||
|
||||
// 설비 자동 등록 (category='equipment')
|
||||
let equipmentResult = null;
|
||||
if (request_id) {
|
||||
const requestData = await PurchaseRequestModel.getById(request_id);
|
||||
if (requestData && requestData.category === 'equipment') {
|
||||
equipmentResult = await PurchaseModel.tryAutoRegisterEquipment({
|
||||
item_name: requestData.item_name,
|
||||
maker: requestData.maker,
|
||||
vendor_name: null,
|
||||
unit_price,
|
||||
purchase_date,
|
||||
purchase_id: purchaseId,
|
||||
purchaser_id: req.user.id
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// 직접 구매 시에도 category 확인
|
||||
const items = await PurchaseModel.getConsumableItems(false);
|
||||
const item = items.find(i => i.item_id === parseInt(item_id));
|
||||
if (item && item.category === 'equipment') {
|
||||
const vendors = await PurchaseModel.getVendors();
|
||||
const vendor = vendors.find(v => v.vendor_id === parseInt(vendor_id));
|
||||
equipmentResult = await PurchaseModel.tryAutoRegisterEquipment({
|
||||
item_name: item.item_name,
|
||||
maker: item.maker,
|
||||
vendor_name: vendor ? vendor.vendor_name : null,
|
||||
unit_price,
|
||||
purchase_date,
|
||||
purchase_id: purchaseId,
|
||||
purchaser_id: req.user.id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const result = { purchase_id: purchaseId };
|
||||
if (equipmentResult) result.equipment = equipmentResult;
|
||||
|
||||
res.status(201).json({ success: true, data: result, message: '구매 처리가 완료되었습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('Purchase create error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 구매 내역 목록
|
||||
getAll: async (req, res) => {
|
||||
try {
|
||||
const { vendor_id, category, from_date, to_date, year_month } = req.query;
|
||||
const rows = await PurchaseModel.getAll({ vendor_id, category, from_date, to_date, year_month });
|
||||
res.json({ success: true, data: rows });
|
||||
} catch (err) {
|
||||
logger.error('Purchase getAll error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 가격 변동 이력
|
||||
getPriceHistory: async (req, res) => {
|
||||
try {
|
||||
const rows = await PurchaseModel.getPriceHistory(req.params.itemId);
|
||||
res.json({ success: true, data: rows });
|
||||
} catch (err) {
|
||||
logger.error('PriceHistory get error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = PurchaseController;
|
||||
120
system1-factory/api/controllers/purchaseRequestController.js
Normal file
120
system1-factory/api/controllers/purchaseRequestController.js
Normal file
@@ -0,0 +1,120 @@
|
||||
const PurchaseRequestModel = require('../models/purchaseRequestModel');
|
||||
const PurchaseModel = require('../models/purchaseModel');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
const PurchaseRequestController = {
|
||||
// 구매신청 목록
|
||||
getAll: async (req, res) => {
|
||||
try {
|
||||
const { status, category, from_date, to_date } = req.query;
|
||||
const isAdmin = req.user && ['admin', 'system'].includes(req.user.access_level);
|
||||
const filters = { status, category, from_date, to_date };
|
||||
if (!isAdmin) filters.requester_id = req.user.id;
|
||||
const rows = await PurchaseRequestModel.getAll(filters);
|
||||
res.json({ success: true, data: rows });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseRequest getAll error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 구매신청 상세
|
||||
getById: async (req, res) => {
|
||||
try {
|
||||
const row = await PurchaseRequestModel.getById(req.params.id);
|
||||
if (!row) return res.status(404).json({ success: false, message: '신청 건을 찾을 수 없습니다.' });
|
||||
res.json({ success: true, data: row });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseRequest getById error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 구매신청 생성
|
||||
create: async (req, res) => {
|
||||
try {
|
||||
const { item_id, quantity, notes } = req.body;
|
||||
if (!item_id) return res.status(400).json({ success: false, message: '소모품을 선택해주세요.' });
|
||||
if (!quantity || quantity < 1) return res.status(400).json({ success: false, message: '수량은 1 이상이어야 합니다.' });
|
||||
|
||||
const request = await PurchaseRequestModel.create({
|
||||
item_id,
|
||||
quantity,
|
||||
requester_id: req.user.id,
|
||||
request_date: new Date().toISOString().substring(0, 10),
|
||||
notes
|
||||
});
|
||||
res.status(201).json({ success: true, data: request, message: '구매신청이 등록되었습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseRequest create error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 보류 처리 (admin)
|
||||
hold: async (req, res) => {
|
||||
try {
|
||||
const { hold_reason } = req.body;
|
||||
const request = await PurchaseRequestModel.hold(req.params.id, hold_reason);
|
||||
if (!request) return res.status(404).json({ success: false, message: '신청 건을 찾을 수 없습니다.' });
|
||||
res.json({ success: true, data: request, message: '보류 처리되었습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseRequest hold error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// pending으로 되돌리기 (admin)
|
||||
revert: async (req, res) => {
|
||||
try {
|
||||
const request = await PurchaseRequestModel.revertToPending(req.params.id);
|
||||
if (!request) return res.status(404).json({ success: false, message: '신청 건을 찾을 수 없습니다.' });
|
||||
res.json({ success: true, data: request, message: '대기 상태로 되돌렸습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseRequest revert error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 삭제 (본인 + pending만)
|
||||
delete: async (req, res) => {
|
||||
try {
|
||||
const existing = await PurchaseRequestModel.getById(req.params.id);
|
||||
if (!existing) return res.status(404).json({ success: false, message: '신청 건을 찾을 수 없습니다.' });
|
||||
const isAdmin = req.user && ['admin', 'system'].includes(req.user.access_level);
|
||||
if (!isAdmin && existing.requester_id !== req.user.id) {
|
||||
return res.status(403).json({ success: false, message: '본인의 신청만 삭제할 수 있습니다.' });
|
||||
}
|
||||
const deleted = await PurchaseRequestModel.delete(req.params.id);
|
||||
if (!deleted) return res.status(400).json({ success: false, message: '대기 상태의 신청만 삭제할 수 있습니다.' });
|
||||
res.json({ success: true, message: '삭제되었습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseRequest delete error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 소모품 목록 (select용)
|
||||
getConsumableItems: async (req, res) => {
|
||||
try {
|
||||
const items = await PurchaseModel.getConsumableItems();
|
||||
res.json({ success: true, data: items });
|
||||
} catch (err) {
|
||||
logger.error('ConsumableItems get error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 업체 목록 (select용)
|
||||
getVendors: async (req, res) => {
|
||||
try {
|
||||
const vendors = await PurchaseModel.getVendors();
|
||||
res.json({ success: true, data: vendors });
|
||||
} catch (err) {
|
||||
logger.error('Vendors get error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = PurchaseRequestController;
|
||||
76
system1-factory/api/controllers/settlementController.js
Normal file
76
system1-factory/api/controllers/settlementController.js
Normal file
@@ -0,0 +1,76 @@
|
||||
const SettlementModel = require('../models/settlementModel');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
const SettlementController = {
|
||||
// 월간 요약 (분류별 + 업체별)
|
||||
getMonthlySummary: async (req, res) => {
|
||||
try {
|
||||
const { year_month } = req.query;
|
||||
if (!year_month) return res.status(400).json({ success: false, message: '년월을 선택해주세요.' });
|
||||
|
||||
const [categorySummary, vendorSummary] = await Promise.all([
|
||||
SettlementModel.getCategorySummary(year_month),
|
||||
SettlementModel.getVendorSummary(year_month)
|
||||
]);
|
||||
|
||||
res.json({ success: true, data: { categorySummary, vendorSummary } });
|
||||
} catch (err) {
|
||||
logger.error('Settlement summary error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 월간 상세 구매 목록
|
||||
getMonthlyPurchases: async (req, res) => {
|
||||
try {
|
||||
const { year_month } = req.query;
|
||||
if (!year_month) return res.status(400).json({ success: false, message: '년월을 선택해주세요.' });
|
||||
const rows = await SettlementModel.getMonthlyPurchases(year_month);
|
||||
res.json({ success: true, data: rows });
|
||||
} catch (err) {
|
||||
logger.error('Settlement purchases error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 가격 변동 목록
|
||||
getPriceChanges: async (req, res) => {
|
||||
try {
|
||||
const { year_month } = req.query;
|
||||
if (!year_month) return res.status(400).json({ success: false, message: '년월을 선택해주세요.' });
|
||||
const rows = await SettlementModel.getPriceChanges(year_month);
|
||||
res.json({ success: true, data: rows });
|
||||
} catch (err) {
|
||||
logger.error('Settlement priceChanges error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 정산 완료
|
||||
complete: async (req, res) => {
|
||||
try {
|
||||
const { year_month, vendor_id, notes } = req.body;
|
||||
if (!year_month || !vendor_id) return res.status(400).json({ success: false, message: '년월과 업체를 선택해주세요.' });
|
||||
const result = await SettlementModel.completeSettlement(year_month, vendor_id, req.user.id, notes);
|
||||
res.json({ success: true, data: result, message: '정산 완료 처리되었습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('Settlement complete error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 정산 취소
|
||||
cancel: async (req, res) => {
|
||||
try {
|
||||
const { year_month, vendor_id } = req.body;
|
||||
if (!year_month || !vendor_id) return res.status(400).json({ success: false, message: '년월과 업체를 선택해주세요.' });
|
||||
const result = await SettlementModel.cancelSettlement(year_month, vendor_id);
|
||||
res.json({ success: true, data: result, message: '정산이 취소되었습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('Settlement cancel error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = SettlementController;
|
||||
@@ -0,0 +1,102 @@
|
||||
-- 생산소모품 구매 관리 시스템 테이블
|
||||
|
||||
-- 업체 (tkuser에서 CRUD)
|
||||
CREATE TABLE IF NOT EXISTS vendors (
|
||||
vendor_id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
vendor_name VARCHAR(100) NOT NULL,
|
||||
business_number VARCHAR(20),
|
||||
representative VARCHAR(50),
|
||||
contact_name VARCHAR(50),
|
||||
contact_phone VARCHAR(20),
|
||||
address VARCHAR(200),
|
||||
bank_name VARCHAR(50),
|
||||
bank_account VARCHAR(50),
|
||||
notes TEXT,
|
||||
is_active TINYINT(1) DEFAULT 1,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- 소모품 마스터 (tkuser에서 CRUD)
|
||||
CREATE TABLE IF NOT EXISTS consumable_items (
|
||||
item_id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
item_name VARCHAR(100) NOT NULL,
|
||||
maker VARCHAR(100),
|
||||
category ENUM('consumable','safety','repair','equipment') NOT NULL
|
||||
COMMENT '소모품, 안전용품, 수선비, 설비',
|
||||
base_price DECIMAL(12,0) DEFAULT 0,
|
||||
unit VARCHAR(20) DEFAULT 'EA',
|
||||
photo_path VARCHAR(255),
|
||||
is_active TINYINT(1) DEFAULT 1,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY uq_name_maker (item_name, maker)
|
||||
);
|
||||
|
||||
-- 구매신청 (tkfb에서 CRUD)
|
||||
CREATE TABLE IF NOT EXISTS purchase_requests (
|
||||
request_id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
item_id INT NOT NULL,
|
||||
quantity INT NOT NULL DEFAULT 1,
|
||||
requester_id INT NOT NULL COMMENT 'FK → sso_users.user_id',
|
||||
request_date DATE NOT NULL,
|
||||
status ENUM('pending','purchased','hold') DEFAULT 'pending'
|
||||
COMMENT '대기, 구매완료, 보류',
|
||||
hold_reason TEXT,
|
||||
notes TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (item_id) REFERENCES consumable_items(item_id),
|
||||
FOREIGN KEY (requester_id) REFERENCES sso_users(user_id)
|
||||
);
|
||||
|
||||
-- 구매 내역 (tkfb에서 CRUD)
|
||||
CREATE TABLE IF NOT EXISTS purchases (
|
||||
purchase_id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
request_id INT,
|
||||
item_id INT NOT NULL,
|
||||
vendor_id INT,
|
||||
quantity INT NOT NULL DEFAULT 1,
|
||||
unit_price DECIMAL(12,0) NOT NULL,
|
||||
purchase_date DATE NOT NULL,
|
||||
purchaser_id INT NOT NULL COMMENT 'FK → sso_users.user_id',
|
||||
notes TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (item_id) REFERENCES consumable_items(item_id),
|
||||
FOREIGN KEY (request_id) REFERENCES purchase_requests(request_id),
|
||||
FOREIGN KEY (vendor_id) REFERENCES vendors(vendor_id),
|
||||
FOREIGN KEY (purchaser_id) REFERENCES sso_users(user_id)
|
||||
);
|
||||
|
||||
-- 가격 변동 이력
|
||||
CREATE TABLE IF NOT EXISTS consumable_price_history (
|
||||
history_id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
item_id INT NOT NULL,
|
||||
old_price DECIMAL(12,0),
|
||||
new_price DECIMAL(12,0) NOT NULL,
|
||||
changed_by INT COMMENT 'FK → sso_users.user_id',
|
||||
changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (item_id) REFERENCES consumable_items(item_id)
|
||||
);
|
||||
|
||||
-- 월간 정산
|
||||
CREATE TABLE IF NOT EXISTS monthly_settlements (
|
||||
settlement_id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
year_month VARCHAR(7) NOT NULL COMMENT 'YYYY-MM',
|
||||
vendor_id INT NOT NULL,
|
||||
total_amount DECIMAL(12,0) DEFAULT 0,
|
||||
status ENUM('pending','completed') DEFAULT 'pending',
|
||||
completed_at TIMESTAMP NULL,
|
||||
completed_by INT COMMENT 'FK → sso_users.user_id',
|
||||
notes TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (vendor_id) REFERENCES vendors(vendor_id),
|
||||
UNIQUE KEY uq_ym_vendor (year_month, vendor_id)
|
||||
);
|
||||
|
||||
-- 페이지 키 등록
|
||||
INSERT IGNORE INTO pages (page_key, page_name, page_path, category, is_admin_only, display_order) VALUES
|
||||
('purchase.request', '구매신청', '/pages/purchase/request.html', 'purchase', 0, 40),
|
||||
('purchase.analysis', '구매 분석', '/pages/admin/purchase-analysis.html', 'purchase', 1, 41);
|
||||
147
system1-factory/api/models/purchaseModel.js
Normal file
147
system1-factory/api/models/purchaseModel.js
Normal file
@@ -0,0 +1,147 @@
|
||||
// models/purchaseModel.js
|
||||
const { getDb } = require('../dbPool');
|
||||
|
||||
const PurchaseModel = {
|
||||
// 구매 내역 목록
|
||||
async getAll(filters = {}) {
|
||||
const db = await getDb();
|
||||
let sql = `
|
||||
SELECT p.*, ci.item_name, ci.maker, ci.category, ci.unit, ci.photo_path,
|
||||
v.vendor_name, su.name AS purchaser_name
|
||||
FROM purchases p
|
||||
JOIN consumable_items ci ON p.item_id = ci.item_id
|
||||
LEFT JOIN vendors v ON p.vendor_id = v.vendor_id
|
||||
LEFT JOIN sso_users su ON p.purchaser_id = su.user_id
|
||||
WHERE 1=1
|
||||
`;
|
||||
const params = [];
|
||||
|
||||
if (filters.vendor_id) { sql += ' AND p.vendor_id = ?'; params.push(filters.vendor_id); }
|
||||
if (filters.category) { sql += ' AND ci.category = ?'; params.push(filters.category); }
|
||||
if (filters.from_date) { sql += ' AND p.purchase_date >= ?'; params.push(filters.from_date); }
|
||||
if (filters.to_date) { sql += ' AND p.purchase_date <= ?'; params.push(filters.to_date); }
|
||||
if (filters.year_month) {
|
||||
sql += ' AND DATE_FORMAT(p.purchase_date, "%Y-%m") = ?';
|
||||
params.push(filters.year_month);
|
||||
}
|
||||
|
||||
sql += ' ORDER BY p.purchase_date DESC, p.created_at DESC';
|
||||
const [rows] = await db.query(sql, params);
|
||||
return rows;
|
||||
},
|
||||
|
||||
// 구매 처리 (구매신청 → 구매 내역 생성 + 상태 변경)
|
||||
async createFromRequest(data) {
|
||||
const db = await getDb();
|
||||
|
||||
// 구매 내역 INSERT
|
||||
const [result] = await db.query(
|
||||
`INSERT INTO purchases (request_id, item_id, vendor_id, quantity, unit_price, purchase_date, purchaser_id, notes)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[data.request_id || null, data.item_id, data.vendor_id || null,
|
||||
data.quantity, data.unit_price, data.purchase_date, data.purchaser_id, data.notes || null]
|
||||
);
|
||||
|
||||
// 구매신청 상태 → purchased
|
||||
if (data.request_id) {
|
||||
await db.query(
|
||||
`UPDATE purchase_requests SET status = 'purchased' WHERE request_id = ?`,
|
||||
[data.request_id]
|
||||
);
|
||||
}
|
||||
|
||||
return result.insertId;
|
||||
},
|
||||
|
||||
// 기준가 업데이트 + 이력 기록
|
||||
async updateBasePrice(itemId, newPrice, oldPrice, changedBy) {
|
||||
const db = await getDb();
|
||||
|
||||
// 이력 기록
|
||||
await db.query(
|
||||
`INSERT INTO consumable_price_history (item_id, old_price, new_price, changed_by)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
[itemId, oldPrice, newPrice, changedBy]
|
||||
);
|
||||
|
||||
// base_price 갱신
|
||||
await db.query(
|
||||
`UPDATE consumable_items SET base_price = ? WHERE item_id = ?`,
|
||||
[newPrice, itemId]
|
||||
);
|
||||
},
|
||||
|
||||
// 설비 자동 등록 시도 (category='equipment')
|
||||
async tryAutoRegisterEquipment(purchaseData) {
|
||||
try {
|
||||
const EquipmentModel = require('./equipmentModel');
|
||||
const equipmentCode = await EquipmentModel.getNextEquipmentCode('TKP');
|
||||
|
||||
await EquipmentModel.create({
|
||||
equipment_code: equipmentCode,
|
||||
equipment_name: purchaseData.item_name,
|
||||
manufacturer: purchaseData.maker || null,
|
||||
supplier: purchaseData.vendor_name || null,
|
||||
purchase_price: purchaseData.unit_price,
|
||||
installation_date: purchaseData.purchase_date,
|
||||
status: 'active',
|
||||
notes: `구매 자동 등록 (purchase_id: ${purchaseData.purchase_id})`
|
||||
});
|
||||
|
||||
return { success: true, equipment_code: equipmentCode };
|
||||
} catch (err) {
|
||||
console.error('[purchase] 설비 자동 등록 실패:', err.message);
|
||||
|
||||
// admin 알림 전송
|
||||
try {
|
||||
const notificationModel = require('./notificationModel');
|
||||
await notificationModel.createTypedNotification({
|
||||
type: 'equipment',
|
||||
title: `설비 자동 등록 실패: ${purchaseData.item_name}`,
|
||||
message: `구매 완료 후 설비 자동 등록에 실패했습니다. 수동으로 등록해주세요. 오류: ${err.message}`,
|
||||
link_url: '/pages/admin/equipments.html',
|
||||
created_by: purchaseData.purchaser_id
|
||||
});
|
||||
} catch (notifErr) {
|
||||
console.error('[purchase] 설비 등록 실패 알림 전송 오류:', notifErr.message);
|
||||
}
|
||||
|
||||
return { success: false, error: err.message };
|
||||
}
|
||||
},
|
||||
|
||||
// 업체 목록 (vendors 테이블 직접 조회)
|
||||
async getVendors() {
|
||||
const db = await getDb();
|
||||
const [rows] = await db.query(
|
||||
'SELECT vendor_id, vendor_name FROM vendors WHERE is_active = 1 ORDER BY vendor_name'
|
||||
);
|
||||
return rows;
|
||||
},
|
||||
|
||||
// 소모품 목록 (구매신청용)
|
||||
async getConsumableItems(activeOnly = true) {
|
||||
const db = await getDb();
|
||||
let sql = 'SELECT item_id, item_name, maker, category, base_price, unit, photo_path FROM consumable_items';
|
||||
if (activeOnly) sql += ' WHERE is_active = 1';
|
||||
sql += ' ORDER BY category, item_name';
|
||||
const [rows] = await db.query(sql);
|
||||
return rows;
|
||||
},
|
||||
|
||||
// 가격 변동 이력
|
||||
async getPriceHistory(itemId) {
|
||||
const db = await getDb();
|
||||
const [rows] = await db.query(
|
||||
`SELECT cph.*, su.name AS changed_by_name
|
||||
FROM consumable_price_history cph
|
||||
LEFT JOIN sso_users su ON cph.changed_by = su.user_id
|
||||
WHERE cph.item_id = ?
|
||||
ORDER BY cph.changed_at DESC`,
|
||||
[itemId]
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = PurchaseModel;
|
||||
94
system1-factory/api/models/purchaseRequestModel.js
Normal file
94
system1-factory/api/models/purchaseRequestModel.js
Normal file
@@ -0,0 +1,94 @@
|
||||
// models/purchaseRequestModel.js
|
||||
const { getDb } = require('../dbPool');
|
||||
|
||||
const PurchaseRequestModel = {
|
||||
// 구매신청 목록 (소모품 정보 JOIN)
|
||||
async getAll(filters = {}) {
|
||||
const db = await getDb();
|
||||
let sql = `
|
||||
SELECT pr.*, ci.item_name, ci.maker, ci.category, ci.base_price, ci.unit, ci.photo_path,
|
||||
su.name AS requester_name
|
||||
FROM purchase_requests pr
|
||||
JOIN consumable_items ci ON pr.item_id = ci.item_id
|
||||
LEFT JOIN sso_users su ON pr.requester_id = su.user_id
|
||||
WHERE 1=1
|
||||
`;
|
||||
const params = [];
|
||||
|
||||
if (filters.status) { sql += ' AND pr.status = ?'; params.push(filters.status); }
|
||||
if (filters.requester_id) { sql += ' AND pr.requester_id = ?'; params.push(filters.requester_id); }
|
||||
if (filters.category) { sql += ' AND ci.category = ?'; params.push(filters.category); }
|
||||
if (filters.from_date) { sql += ' AND pr.request_date >= ?'; params.push(filters.from_date); }
|
||||
if (filters.to_date) { sql += ' AND pr.request_date <= ?'; params.push(filters.to_date); }
|
||||
|
||||
sql += ' ORDER BY pr.created_at DESC';
|
||||
const [rows] = await db.query(sql, params);
|
||||
return rows;
|
||||
},
|
||||
|
||||
// 단건 조회
|
||||
async getById(requestId) {
|
||||
const db = await getDb();
|
||||
const [rows] = await db.query(`
|
||||
SELECT pr.*, ci.item_name, ci.maker, ci.category, ci.base_price, ci.unit, ci.photo_path,
|
||||
su.name AS requester_name
|
||||
FROM purchase_requests pr
|
||||
JOIN consumable_items ci ON pr.item_id = ci.item_id
|
||||
LEFT JOIN sso_users su ON pr.requester_id = su.user_id
|
||||
WHERE pr.request_id = ?
|
||||
`, [requestId]);
|
||||
return rows[0] || null;
|
||||
},
|
||||
|
||||
// 구매신청 생성
|
||||
async create(data) {
|
||||
const db = await getDb();
|
||||
const [result] = await db.query(
|
||||
`INSERT INTO purchase_requests (item_id, quantity, requester_id, request_date, notes)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
[data.item_id, data.quantity || 1, data.requester_id, data.request_date, data.notes || null]
|
||||
);
|
||||
return this.getById(result.insertId);
|
||||
},
|
||||
|
||||
// 상태 변경 (보류)
|
||||
async hold(requestId, holdReason) {
|
||||
const db = await getDb();
|
||||
await db.query(
|
||||
`UPDATE purchase_requests SET status = 'hold', hold_reason = ? WHERE request_id = ?`,
|
||||
[holdReason || null, requestId]
|
||||
);
|
||||
return this.getById(requestId);
|
||||
},
|
||||
|
||||
// 상태 → purchased
|
||||
async markPurchased(requestId) {
|
||||
const db = await getDb();
|
||||
await db.query(
|
||||
`UPDATE purchase_requests SET status = 'purchased' WHERE request_id = ?`,
|
||||
[requestId]
|
||||
);
|
||||
},
|
||||
|
||||
// pending으로 되돌리기
|
||||
async revertToPending(requestId) {
|
||||
const db = await getDb();
|
||||
await db.query(
|
||||
`UPDATE purchase_requests SET status = 'pending', hold_reason = NULL WHERE request_id = ?`,
|
||||
[requestId]
|
||||
);
|
||||
return this.getById(requestId);
|
||||
},
|
||||
|
||||
// 삭제 (admin only, pending 상태만)
|
||||
async delete(requestId) {
|
||||
const db = await getDb();
|
||||
const [result] = await db.query(
|
||||
`DELETE FROM purchase_requests WHERE request_id = ? AND status = 'pending'`,
|
||||
[requestId]
|
||||
);
|
||||
return result.affectedRows > 0;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = PurchaseRequestModel;
|
||||
104
system1-factory/api/models/settlementModel.js
Normal file
104
system1-factory/api/models/settlementModel.js
Normal file
@@ -0,0 +1,104 @@
|
||||
// models/settlementModel.js
|
||||
const { getDb } = require('../dbPool');
|
||||
|
||||
const SettlementModel = {
|
||||
// 월간 분류별 요약
|
||||
async getCategorySummary(yearMonth) {
|
||||
const db = await getDb();
|
||||
const [rows] = await db.query(`
|
||||
SELECT ci.category,
|
||||
COUNT(*) AS count,
|
||||
SUM(p.quantity * p.unit_price) AS total_amount
|
||||
FROM purchases p
|
||||
JOIN consumable_items ci ON p.item_id = ci.item_id
|
||||
WHERE DATE_FORMAT(p.purchase_date, '%Y-%m') = ?
|
||||
GROUP BY ci.category
|
||||
`, [yearMonth]);
|
||||
return rows;
|
||||
},
|
||||
|
||||
// 월간 업체별 요약
|
||||
async getVendorSummary(yearMonth) {
|
||||
const db = await getDb();
|
||||
const [rows] = await db.query(`
|
||||
SELECT v.vendor_id, v.vendor_name,
|
||||
COUNT(*) AS count,
|
||||
SUM(p.quantity * p.unit_price) AS total_amount,
|
||||
ms.settlement_id, ms.status AS settlement_status,
|
||||
ms.completed_at, ms.notes AS settlement_notes
|
||||
FROM purchases p
|
||||
LEFT JOIN vendors v ON p.vendor_id = v.vendor_id
|
||||
LEFT JOIN monthly_settlements ms ON ms.vendor_id = p.vendor_id AND ms.year_month = ?
|
||||
WHERE DATE_FORMAT(p.purchase_date, '%Y-%m') = ?
|
||||
GROUP BY COALESCE(v.vendor_id, 0), v.vendor_name, ms.settlement_id, ms.status, ms.completed_at, ms.notes
|
||||
ORDER BY total_amount DESC
|
||||
`, [yearMonth, yearMonth]);
|
||||
return rows;
|
||||
},
|
||||
|
||||
// 월간 상세 구매 목록
|
||||
async getMonthlyPurchases(yearMonth) {
|
||||
const db = await getDb();
|
||||
const [rows] = await db.query(`
|
||||
SELECT p.*, ci.item_name, ci.maker, ci.category, ci.unit, ci.base_price, ci.photo_path,
|
||||
v.vendor_name, su.name AS purchaser_name
|
||||
FROM purchases p
|
||||
JOIN consumable_items ci ON p.item_id = ci.item_id
|
||||
LEFT JOIN vendors v ON p.vendor_id = v.vendor_id
|
||||
LEFT JOIN sso_users su ON p.purchaser_id = su.user_id
|
||||
WHERE DATE_FORMAT(p.purchase_date, '%Y-%m') = ?
|
||||
ORDER BY p.purchase_date DESC
|
||||
`, [yearMonth]);
|
||||
return rows;
|
||||
},
|
||||
|
||||
// 정산 완료 처리
|
||||
async completeSettlement(yearMonth, vendorId, completedBy, notes) {
|
||||
const db = await getDb();
|
||||
|
||||
// 총액 계산
|
||||
const [[{ total }]] = await db.query(`
|
||||
SELECT COALESCE(SUM(p.quantity * p.unit_price), 0) AS total
|
||||
FROM purchases p
|
||||
WHERE p.vendor_id = ? AND DATE_FORMAT(p.purchase_date, '%Y-%m') = ?
|
||||
`, [vendorId, yearMonth]);
|
||||
|
||||
// UPSERT
|
||||
await db.query(`
|
||||
INSERT INTO monthly_settlements (year_month, vendor_id, total_amount, status, completed_at, completed_by, notes)
|
||||
VALUES (?, ?, ?, 'completed', NOW(), ?, ?)
|
||||
ON DUPLICATE KEY UPDATE status = 'completed', total_amount = ?, completed_at = NOW(), completed_by = ?, notes = ?
|
||||
`, [yearMonth, vendorId, total, completedBy, notes || null, total, completedBy, notes || null]);
|
||||
|
||||
return { year_month: yearMonth, vendor_id: vendorId, total_amount: total, status: 'completed' };
|
||||
},
|
||||
|
||||
// 정산 취소
|
||||
async cancelSettlement(yearMonth, vendorId) {
|
||||
const db = await getDb();
|
||||
await db.query(`
|
||||
UPDATE monthly_settlements SET status = 'pending', completed_at = NULL, completed_by = NULL
|
||||
WHERE year_month = ? AND vendor_id = ?
|
||||
`, [yearMonth, vendorId]);
|
||||
return { year_month: yearMonth, vendor_id: vendorId, status: 'pending' };
|
||||
},
|
||||
|
||||
// 가격 변동 목록 (월간)
|
||||
async getPriceChanges(yearMonth) {
|
||||
const db = await getDb();
|
||||
const [rows] = await db.query(`
|
||||
SELECT p.purchase_id, p.purchase_date, p.unit_price, p.quantity,
|
||||
ci.item_id, ci.item_name, ci.maker, ci.category, ci.base_price,
|
||||
v.vendor_name
|
||||
FROM purchases p
|
||||
JOIN consumable_items ci ON p.item_id = ci.item_id
|
||||
LEFT JOIN vendors v ON p.vendor_id = v.vendor_id
|
||||
WHERE DATE_FORMAT(p.purchase_date, '%Y-%m') = ?
|
||||
AND p.unit_price != ci.base_price
|
||||
ORDER BY ABS(p.unit_price - ci.base_price) DESC
|
||||
`, [yearMonth]);
|
||||
return rows;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = SettlementModel;
|
||||
18
system1-factory/api/routes/purchaseRequestRoutes.js
Normal file
18
system1-factory/api/routes/purchaseRequestRoutes.js
Normal file
@@ -0,0 +1,18 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const ctrl = require('../controllers/purchaseRequestController');
|
||||
const { requireMinLevel } = require('../middlewares/auth');
|
||||
|
||||
// 보조 데이터
|
||||
router.get('/consumable-items', ctrl.getConsumableItems);
|
||||
router.get('/vendors', ctrl.getVendors);
|
||||
|
||||
// 구매신청 CRUD
|
||||
router.get('/', ctrl.getAll);
|
||||
router.get('/:id', ctrl.getById);
|
||||
router.post('/', ctrl.create);
|
||||
router.put('/:id/hold', requireMinLevel('admin'), ctrl.hold);
|
||||
router.put('/:id/revert', requireMinLevel('admin'), ctrl.revert);
|
||||
router.delete('/:id', ctrl.delete);
|
||||
|
||||
module.exports = router;
|
||||
10
system1-factory/api/routes/purchaseRoutes.js
Normal file
10
system1-factory/api/routes/purchaseRoutes.js
Normal file
@@ -0,0 +1,10 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const ctrl = require('../controllers/purchaseController');
|
||||
const { requireMinLevel } = require('../middlewares/auth');
|
||||
|
||||
router.get('/', ctrl.getAll);
|
||||
router.post('/', requireMinLevel('admin'), ctrl.create);
|
||||
router.get('/price-history/:itemId', ctrl.getPriceHistory);
|
||||
|
||||
module.exports = router;
|
||||
12
system1-factory/api/routes/settlementRoutes.js
Normal file
12
system1-factory/api/routes/settlementRoutes.js
Normal file
@@ -0,0 +1,12 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const ctrl = require('../controllers/settlementController');
|
||||
const { requireMinLevel } = require('../middlewares/auth');
|
||||
|
||||
router.get('/summary', ctrl.getMonthlySummary);
|
||||
router.get('/purchases', ctrl.getMonthlyPurchases);
|
||||
router.get('/price-changes', ctrl.getPriceChanges);
|
||||
router.post('/complete', requireMinLevel('admin'), ctrl.complete);
|
||||
router.post('/cancel', requireMinLevel('admin'), ctrl.cancel);
|
||||
|
||||
module.exports = router;
|
||||
113
system1-factory/web/pages/admin/purchase-analysis.html
Normal file
113
system1-factory/web/pages/admin/purchase-analysis.html
Normal file
@@ -0,0 +1,113 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>구매 분석 - TK 공장관리</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<link rel="stylesheet" href="/static/css/tkfb.css">
|
||||
</head>
|
||||
<body class="bg-gray-50">
|
||||
<header class="bg-orange-700 text-white sticky top-0 z-50">
|
||||
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
<div class="flex justify-between items-center h-14">
|
||||
<div class="flex items-center gap-3">
|
||||
<button id="mobileMenuBtn" class="lg:hidden text-orange-200 hover:text-white"><i class="fas fa-bars text-xl"></i></button>
|
||||
<i class="fas fa-industry text-xl text-orange-200"></i>
|
||||
<h1 class="text-lg font-semibold">TK 공장관리</h1>
|
||||
</div>
|
||||
<div class="flex items-center gap-4">
|
||||
<span id="headerUserName" class="text-sm hidden sm:block">-</span>
|
||||
<div id="headerUserAvatar" class="w-8 h-8 bg-orange-600 rounded-full flex items-center justify-center text-sm font-bold">-</div>
|
||||
<button onclick="doLogout()" class="text-orange-200 hover:text-white" title="로그아웃"><i class="fas fa-sign-out-alt"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div id="mobileOverlay" class="hidden fixed inset-0 bg-black/50 z-30 lg:hidden"></div>
|
||||
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 fade-in">
|
||||
<div class="flex gap-6">
|
||||
<nav id="sideNav" class="hidden lg:flex flex-col gap-1 w-52 flex-shrink-0 pt-2 fixed lg:static z-40 bg-white lg:bg-transparent p-4 lg:p-0 rounded-lg lg:rounded-none shadow-lg lg:shadow-none top-14 left-0 bottom-0 overflow-y-auto"></nav>
|
||||
<div class="flex-1 min-w-0">
|
||||
|
||||
<div class="page-header">
|
||||
<div class="page-title-section">
|
||||
<h1 class="page-title">구매 분석</h1>
|
||||
<p class="page-description">월간 구매 현황 분석 및 업체별 정산 관리</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 월 선택 -->
|
||||
<div class="flex items-center gap-3 mb-6">
|
||||
<input type="month" id="paMonth" class="px-3 py-2 border rounded-lg text-sm">
|
||||
<button onclick="loadAnalysis()" class="px-4 py-2 bg-orange-600 text-white rounded-lg text-sm hover:bg-orange-700">
|
||||
<i class="fas fa-search mr-1"></i>조회
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 분류별 요약 카드 -->
|
||||
<div id="paCategorySummary" class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
|
||||
<div class="bg-white rounded-xl shadow-sm p-4 text-center text-gray-400 col-span-4">월을 선택하고 조회해주세요</div>
|
||||
</div>
|
||||
|
||||
<!-- 업체별 요약 -->
|
||||
<div class="bg-white rounded-xl shadow-sm p-5 mb-6">
|
||||
<h2 class="text-base font-semibold text-gray-800 mb-4"><i class="fas fa-building text-orange-500 mr-2"></i>업체별 요약</h2>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead class="bg-gray-50 text-gray-600 text-xs uppercase">
|
||||
<tr>
|
||||
<th class="px-4 py-3 text-left">업체</th>
|
||||
<th class="px-4 py-3 text-right">건수</th>
|
||||
<th class="px-4 py-3 text-right">총액</th>
|
||||
<th class="px-4 py-3 text-center">정산</th>
|
||||
<th class="px-4 py-3 text-center">액션</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="paVendorSummary" class="divide-y">
|
||||
<tr><td colspan="5" class="px-4 py-8 text-center text-gray-400">-</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 상세 구매 목록 -->
|
||||
<div class="bg-white rounded-xl shadow-sm p-5 mb-6">
|
||||
<h2 class="text-base font-semibold text-gray-800 mb-4"><i class="fas fa-list text-orange-500 mr-2"></i>상세 구매 목록</h2>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead class="bg-gray-50 text-gray-600 text-xs uppercase">
|
||||
<tr>
|
||||
<th class="px-4 py-3 text-left">품목</th>
|
||||
<th class="px-4 py-3 text-left">분류</th>
|
||||
<th class="px-4 py-3 text-right">수량</th>
|
||||
<th class="px-4 py-3 text-right">단가</th>
|
||||
<th class="px-4 py-3 text-right">소계</th>
|
||||
<th class="px-4 py-3 text-left">업체</th>
|
||||
<th class="px-4 py-3 text-left">구매일</th>
|
||||
<th class="px-4 py-3 text-left">비고</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="paPurchaseList" class="divide-y">
|
||||
<tr><td colspan="8" class="px-4 py-8 text-center text-gray-400">-</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 가격 변동 -->
|
||||
<div class="bg-white rounded-xl shadow-sm p-5">
|
||||
<h2 class="text-base font-semibold text-gray-800 mb-4"><i class="fas fa-exchange-alt text-orange-500 mr-2"></i>가격 변동 항목</h2>
|
||||
<div id="paPriceChanges" class="overflow-x-auto">
|
||||
<p class="text-gray-400 text-center py-4 text-sm">-</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/static/js/tkfb-core.js?v=20260313"></script>
|
||||
<script src="/static/js/purchase-analysis.js?v=20260313"></script>
|
||||
</body>
|
||||
</html>
|
||||
181
system1-factory/web/pages/purchase/request.html
Normal file
181
system1-factory/web/pages/purchase/request.html
Normal file
@@ -0,0 +1,181 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>구매신청 - TK 공장관리</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<link rel="stylesheet" href="/static/css/tkfb.css">
|
||||
</head>
|
||||
<body class="bg-gray-50">
|
||||
<header class="bg-orange-700 text-white sticky top-0 z-50">
|
||||
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
<div class="flex justify-between items-center h-14">
|
||||
<div class="flex items-center gap-3">
|
||||
<button id="mobileMenuBtn" class="lg:hidden text-orange-200 hover:text-white"><i class="fas fa-bars text-xl"></i></button>
|
||||
<i class="fas fa-industry text-xl text-orange-200"></i>
|
||||
<h1 class="text-lg font-semibold">TK 공장관리</h1>
|
||||
</div>
|
||||
<div class="flex items-center gap-4">
|
||||
<span id="headerUserName" class="text-sm hidden sm:block">-</span>
|
||||
<div id="headerUserAvatar" class="w-8 h-8 bg-orange-600 rounded-full flex items-center justify-center text-sm font-bold">-</div>
|
||||
<button onclick="doLogout()" class="text-orange-200 hover:text-white" title="로그아웃"><i class="fas fa-sign-out-alt"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div id="mobileOverlay" class="hidden fixed inset-0 bg-black/50 z-30 lg:hidden"></div>
|
||||
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 fade-in">
|
||||
<div class="flex gap-6">
|
||||
<nav id="sideNav" class="hidden lg:flex flex-col gap-1 w-52 flex-shrink-0 pt-2 fixed lg:static z-40 bg-white lg:bg-transparent p-4 lg:p-0 rounded-lg lg:rounded-none shadow-lg lg:shadow-none top-14 left-0 bottom-0 overflow-y-auto"></nav>
|
||||
<div class="flex-1 min-w-0">
|
||||
|
||||
<div class="page-header">
|
||||
<div class="page-title-section">
|
||||
<h1 class="page-title">구매신청</h1>
|
||||
<p class="page-description">생산소모품 구매를 신청하고 처리 현황을 확인합니다</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 구매신청 폼 -->
|
||||
<div class="bg-white rounded-xl shadow-sm p-5 mb-6">
|
||||
<h2 class="text-base font-semibold text-gray-800 mb-4"><i class="fas fa-plus-circle text-orange-500 mr-2"></i>신규 구매신청</h2>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-4 gap-4 items-end">
|
||||
<div class="sm:col-span-2">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">소모품 <span class="text-red-400">*</span></label>
|
||||
<select id="prItemSelect" class="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-orange-300" onchange="onItemSelect()">
|
||||
<option value="">소모품 선택</option>
|
||||
</select>
|
||||
<div id="prItemPreview" class="mt-2 hidden flex items-center gap-3 p-2 bg-gray-50 rounded-lg">
|
||||
<img id="prItemPhoto" class="w-12 h-12 rounded object-cover hidden">
|
||||
<div>
|
||||
<div id="prItemInfo" class="text-sm text-gray-700"></div>
|
||||
<div id="prItemPrice" class="text-xs text-gray-500"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">수량 <span class="text-red-400">*</span></label>
|
||||
<input type="number" id="prQuantity" class="w-full px-3 py-2 border rounded-lg text-sm" min="1" value="1">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">메모</label>
|
||||
<input type="text" id="prNotes" class="w-full px-3 py-2 border rounded-lg text-sm" placeholder="선택 사항">
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-4 flex justify-end">
|
||||
<button onclick="submitPurchaseRequest()" class="px-5 py-2 bg-orange-600 text-white rounded-lg text-sm hover:bg-orange-700">
|
||||
<i class="fas fa-paper-plane mr-1"></i>구매신청
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 필터 -->
|
||||
<div class="flex gap-3 mb-4 flex-wrap items-center">
|
||||
<select id="prFilterStatus" class="px-3 py-2 border rounded-lg text-sm" onchange="loadRequests()">
|
||||
<option value="">전체 상태</option>
|
||||
<option value="pending">대기</option>
|
||||
<option value="purchased">구매완료</option>
|
||||
<option value="hold">보류</option>
|
||||
</select>
|
||||
<select id="prFilterCategory" class="px-3 py-2 border rounded-lg text-sm" onchange="loadRequests()">
|
||||
<option value="">전체 분류</option>
|
||||
<option value="consumable">소모품</option>
|
||||
<option value="safety">안전용품</option>
|
||||
<option value="repair">수선비</option>
|
||||
<option value="equipment">설비</option>
|
||||
</select>
|
||||
<button onclick="loadRequests()" class="px-3 py-2 border rounded-lg text-sm text-gray-600 hover:bg-gray-100">
|
||||
<i class="fas fa-sync-alt"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 신청 목록 -->
|
||||
<div class="bg-white rounded-xl shadow-sm overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead class="bg-gray-50 text-gray-600 text-xs uppercase">
|
||||
<tr>
|
||||
<th class="px-4 py-3 text-left">품목</th>
|
||||
<th class="px-4 py-3 text-left">분류</th>
|
||||
<th class="px-4 py-3 text-right">수량</th>
|
||||
<th class="px-4 py-3 text-left">신청자</th>
|
||||
<th class="px-4 py-3 text-left">신청일</th>
|
||||
<th class="px-4 py-3 text-center">상태</th>
|
||||
<th class="px-4 py-3 text-center">액션</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="prRequestList" class="divide-y">
|
||||
<tr><td colspan="7" class="px-4 py-8 text-center text-gray-400">데이터를 불러오는 중...</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 구매 처리 모달 -->
|
||||
<div id="purchaseModal" class="hidden fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closePurchaseModal()">
|
||||
<div class="bg-white rounded-xl shadow-xl max-w-lg w-full p-6">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h3 class="text-lg font-semibold">구매 처리</h3>
|
||||
<button onclick="closePurchaseModal()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
|
||||
</div>
|
||||
<div id="purchaseModalInfo" class="bg-gray-50 rounded-lg p-3 mb-4 text-sm"></div>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">업체</label>
|
||||
<select id="pmVendor" class="w-full px-3 py-2 border rounded-lg text-sm">
|
||||
<option value="">업체 선택</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">구매일 <span class="text-red-400">*</span></label>
|
||||
<input type="date" id="pmDate" class="w-full px-3 py-2 border rounded-lg text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">실구매 단가 <span class="text-red-400">*</span></label>
|
||||
<input type="number" id="pmUnitPrice" class="w-full px-3 py-2 border rounded-lg text-sm" min="0" oninput="showPriceDiff()">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">수량</label>
|
||||
<input type="number" id="pmQuantity" class="w-full px-3 py-2 border rounded-lg text-sm" min="1" value="1">
|
||||
</div>
|
||||
<div class="col-span-2" id="pmPriceDiffArea" class="hidden">
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">메모</label>
|
||||
<input type="text" id="pmNotes" class="w-full px-3 py-2 border rounded-lg text-sm">
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end mt-4 gap-2">
|
||||
<button type="button" onclick="closePurchaseModal()" class="px-4 py-2 border rounded-lg text-sm hover:bg-gray-50">취소</button>
|
||||
<button type="button" onclick="submitPurchase()" class="px-4 py-2 bg-orange-600 text-white rounded-lg text-sm hover:bg-orange-700">구매 완료</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 보류 모달 -->
|
||||
<div id="holdModal" class="hidden fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeHoldModal()">
|
||||
<div class="bg-white rounded-xl shadow-xl max-w-md w-full p-6">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h3 class="text-lg font-semibold">보류 처리</h3>
|
||||
<button onclick="closeHoldModal()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">보류 사유</label>
|
||||
<textarea id="holdReason" rows="3" class="w-full px-3 py-2 border rounded-lg text-sm" placeholder="보류 사유를 입력하세요"></textarea>
|
||||
</div>
|
||||
<div class="flex justify-end mt-4 gap-2">
|
||||
<button type="button" onclick="closeHoldModal()" class="px-4 py-2 border rounded-lg text-sm hover:bg-gray-50">취소</button>
|
||||
<button type="button" onclick="submitHold()" class="px-4 py-2 bg-gray-600 text-white rounded-lg text-sm hover:bg-gray-700">보류</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/static/js/tkfb-core.js?v=20260313"></script>
|
||||
<script src="/static/js/purchase-request.js?v=20260313"></script>
|
||||
</body>
|
||||
</html>
|
||||
183
system1-factory/web/static/js/purchase-analysis.js
Normal file
183
system1-factory/web/static/js/purchase-analysis.js
Normal file
@@ -0,0 +1,183 @@
|
||||
/* ===== 구매 분석 페이지 ===== */
|
||||
const CAT_LABELS = { consumable: '소모품', safety: '안전용품', repair: '수선비', equipment: '설비' };
|
||||
const CAT_ICONS = { consumable: 'fa-box', safety: 'fa-hard-hat', repair: 'fa-wrench', equipment: 'fa-cogs' };
|
||||
const CAT_BG = { consumable: 'bg-blue-50 text-blue-700', safety: 'bg-green-50 text-green-700', repair: 'bg-amber-50 text-amber-700', equipment: 'bg-purple-50 text-purple-700' };
|
||||
|
||||
let currentYearMonth = '';
|
||||
|
||||
async function loadAnalysis() {
|
||||
currentYearMonth = document.getElementById('paMonth').value;
|
||||
if (!currentYearMonth) { showToast('월을 선택해주세요.', 'error'); return; }
|
||||
|
||||
try {
|
||||
const [summaryRes, purchasesRes, priceChangesRes] = await Promise.all([
|
||||
api(`/settlements/summary?year_month=${currentYearMonth}`),
|
||||
api(`/settlements/purchases?year_month=${currentYearMonth}`),
|
||||
api(`/settlements/price-changes?year_month=${currentYearMonth}`)
|
||||
]);
|
||||
|
||||
renderCategorySummary(summaryRes.data?.categorySummary || []);
|
||||
renderVendorSummary(summaryRes.data?.vendorSummary || []);
|
||||
renderPurchaseList(purchasesRes.data || []);
|
||||
renderPriceChanges(priceChangesRes.data || []);
|
||||
} catch (e) {
|
||||
showToast('데이터 로드 실패: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function renderCategorySummary(data) {
|
||||
const el = document.getElementById('paCategorySummary');
|
||||
const allCategories = ['consumable', 'safety', 'repair', 'equipment'];
|
||||
const dataMap = {};
|
||||
data.forEach(d => { dataMap[d.category] = d; });
|
||||
|
||||
const totalAmount = data.reduce((sum, d) => sum + Number(d.total_amount || 0), 0);
|
||||
|
||||
el.innerHTML = allCategories.map(cat => {
|
||||
const d = dataMap[cat] || { count: 0, total_amount: 0 };
|
||||
const label = CAT_LABELS[cat];
|
||||
const icon = CAT_ICONS[cat];
|
||||
const bg = CAT_BG[cat];
|
||||
return `<div class="bg-white rounded-xl shadow-sm p-4">
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<div class="w-8 h-8 rounded-lg ${bg} flex items-center justify-center"><i class="fas ${icon} text-sm"></i></div>
|
||||
<span class="text-sm font-medium text-gray-700">${label}</span>
|
||||
</div>
|
||||
<div class="text-xl font-bold text-gray-800">${Number(d.total_amount || 0).toLocaleString()}<span class="text-xs font-normal text-gray-400 ml-1">원</span></div>
|
||||
<div class="text-xs text-gray-500 mt-1">${d.count || 0}건</div>
|
||||
</div>`;
|
||||
}).join('') + `
|
||||
<div class="col-span-2 lg:col-span-4 bg-orange-50 rounded-xl p-3 text-center">
|
||||
<span class="text-sm text-orange-700 font-semibold">월 합계: ${totalAmount.toLocaleString()}원</span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function renderVendorSummary(data) {
|
||||
const tbody = document.getElementById('paVendorSummary');
|
||||
if (!data.length) {
|
||||
tbody.innerHTML = '<tr><td colspan="5" class="px-4 py-8 text-center text-gray-400">해당 월 구매 내역이 없습니다.</td></tr>';
|
||||
return;
|
||||
}
|
||||
tbody.innerHTML = data.map(v => {
|
||||
const isCompleted = v.settlement_status === 'completed';
|
||||
const statusBadge = isCompleted
|
||||
? '<span class="badge badge-green">정산완료</span>'
|
||||
: '<span class="badge badge-gray">미정산</span>';
|
||||
const vendorName = v.vendor_name || '(업체 미지정)';
|
||||
const vendorId = v.vendor_id || 0;
|
||||
|
||||
let actionBtn = '';
|
||||
if (vendorId > 0) {
|
||||
if (isCompleted) {
|
||||
actionBtn = `<button onclick="cancelSettlement(${vendorId})" class="px-3 py-1 border border-gray-300 rounded text-xs text-gray-600 hover:bg-gray-50">정산 취소</button>`;
|
||||
} else {
|
||||
actionBtn = `<button onclick="completeSettlement(${vendorId})" class="px-3 py-1 bg-green-500 text-white rounded text-xs hover:bg-green-600">정산완료</button>`;
|
||||
}
|
||||
}
|
||||
|
||||
return `<tr class="hover:bg-gray-50">
|
||||
<td class="px-4 py-3 font-medium text-gray-800">${escapeHtml(vendorName)}</td>
|
||||
<td class="px-4 py-3 text-right">${v.count}건</td>
|
||||
<td class="px-4 py-3 text-right font-medium">${Number(v.total_amount || 0).toLocaleString()}원</td>
|
||||
<td class="px-4 py-3 text-center">${statusBadge}</td>
|
||||
<td class="px-4 py-3 text-center">${actionBtn}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderPurchaseList(data) {
|
||||
const tbody = document.getElementById('paPurchaseList');
|
||||
if (!data.length) {
|
||||
tbody.innerHTML = '<tr><td colspan="8" class="px-4 py-8 text-center text-gray-400">해당 월 구매 내역이 없습니다.</td></tr>';
|
||||
return;
|
||||
}
|
||||
tbody.innerHTML = data.map(p => {
|
||||
const catLabel = CAT_LABELS[p.category] || p.category;
|
||||
const catColor = CAT_BG[p.category] || '';
|
||||
const subtotal = (p.quantity || 0) * (p.unit_price || 0);
|
||||
const basePrice = Number(p.base_price || 0);
|
||||
const unitPrice = Number(p.unit_price || 0);
|
||||
const hasPriceDiff = basePrice > 0 && unitPrice > 0 && basePrice !== unitPrice;
|
||||
const priceDiffClass = hasPriceDiff ? (unitPrice > basePrice ? 'text-red-600 font-semibold' : 'text-blue-600 font-semibold') : '';
|
||||
|
||||
return `<tr class="hover:bg-gray-50 ${hasPriceDiff ? 'bg-yellow-50' : ''}">
|
||||
<td class="px-4 py-3">
|
||||
<div class="font-medium text-gray-800">${escapeHtml(p.item_name)}</div>
|
||||
<div class="text-xs text-gray-500">${escapeHtml(p.maker || '')}</div>
|
||||
</td>
|
||||
<td class="px-4 py-3"><span class="px-1.5 py-0.5 rounded text-xs ${catColor}">${catLabel}</span></td>
|
||||
<td class="px-4 py-3 text-right">${p.quantity}</td>
|
||||
<td class="px-4 py-3 text-right ${priceDiffClass}">${unitPrice.toLocaleString()}원${hasPriceDiff ? `<div class="text-xs text-gray-400">(기준: ${basePrice.toLocaleString()})</div>` : ''}</td>
|
||||
<td class="px-4 py-3 text-right font-medium">${subtotal.toLocaleString()}원</td>
|
||||
<td class="px-4 py-3 text-gray-600">${escapeHtml(p.vendor_name || '-')}</td>
|
||||
<td class="px-4 py-3 text-gray-600">${formatDate(p.purchase_date)}</td>
|
||||
<td class="px-4 py-3 text-gray-500 text-xs">${escapeHtml(p.notes || '')}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderPriceChanges(data) {
|
||||
const el = document.getElementById('paPriceChanges');
|
||||
if (!data.length) {
|
||||
el.innerHTML = '<p class="text-gray-400 text-center py-4 text-sm">가격 변동 항목이 없습니다.</p>';
|
||||
return;
|
||||
}
|
||||
el.innerHTML = `<table class="w-full text-sm">
|
||||
<thead class="bg-gray-50 text-gray-600 text-xs uppercase">
|
||||
<tr>
|
||||
<th class="px-4 py-3 text-left">품목</th>
|
||||
<th class="px-4 py-3 text-right">기준가</th>
|
||||
<th class="px-4 py-3 text-right">실구매가</th>
|
||||
<th class="px-4 py-3 text-right">차이</th>
|
||||
<th class="px-4 py-3 text-left">업체</th>
|
||||
<th class="px-4 py-3 text-left">구매일</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y">${data.map(p => {
|
||||
const diff = Number(p.unit_price) - Number(p.base_price);
|
||||
const arrow = diff > 0 ? '▲' : '▼';
|
||||
const color = diff > 0 ? 'text-red-600' : 'text-blue-600';
|
||||
return `<tr class="hover:bg-gray-50">
|
||||
<td class="px-4 py-3">${escapeHtml(p.item_name)} ${p.maker ? '(' + escapeHtml(p.maker) + ')' : ''}</td>
|
||||
<td class="px-4 py-3 text-right">${Number(p.base_price).toLocaleString()}원</td>
|
||||
<td class="px-4 py-3 text-right font-medium ${color}">${Number(p.unit_price).toLocaleString()}원</td>
|
||||
<td class="px-4 py-3 text-right ${color}">${arrow} ${Math.abs(diff).toLocaleString()}원</td>
|
||||
<td class="px-4 py-3 text-gray-600">${escapeHtml(p.vendor_name || '-')}</td>
|
||||
<td class="px-4 py-3 text-gray-600">${formatDate(p.purchase_date)}</td>
|
||||
</tr>`;
|
||||
}).join('')}</tbody>
|
||||
</table>`;
|
||||
}
|
||||
|
||||
/* ===== 정산 처리 ===== */
|
||||
async function completeSettlement(vendorId) {
|
||||
if (!confirm('이 업체의 정산을 완료 처리하시겠습니까?')) return;
|
||||
try {
|
||||
await api('/settlements/complete', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ year_month: currentYearMonth, vendor_id: vendorId })
|
||||
});
|
||||
showToast('정산 완료 처리되었습니다.');
|
||||
await loadAnalysis();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
async function cancelSettlement(vendorId) {
|
||||
if (!confirm('정산 완료를 취소하시겠습니까?')) return;
|
||||
try {
|
||||
await api('/settlements/cancel', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ year_month: currentYearMonth, vendor_id: vendorId })
|
||||
});
|
||||
showToast('정산이 취소되었습니다.');
|
||||
await loadAnalysis();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
/* ===== Init ===== */
|
||||
(async function() {
|
||||
if (!await initAuth()) return;
|
||||
// 기본값: 현재 월
|
||||
const now = new Date();
|
||||
document.getElementById('paMonth').value = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
|
||||
})();
|
||||
294
system1-factory/web/static/js/purchase-request.js
Normal file
294
system1-factory/web/static/js/purchase-request.js
Normal file
@@ -0,0 +1,294 @@
|
||||
/* ===== 구매신청 페이지 ===== */
|
||||
const TKUSER_BASE_URL = location.hostname.includes('technicalkorea.net')
|
||||
? 'https://tkuser.technicalkorea.net'
|
||||
: location.protocol + '//' + location.hostname + ':30180';
|
||||
|
||||
const CAT_LABELS = { consumable: '소모품', safety: '안전용품', repair: '수선비', equipment: '설비' };
|
||||
const CAT_COLORS = { consumable: 'badge-blue', safety: 'badge-green', repair: 'badge-amber', equipment: 'badge-purple' };
|
||||
const STATUS_LABELS = { pending: '대기', purchased: '구매완료', hold: '보류' };
|
||||
const STATUS_COLORS = { pending: 'badge-amber', purchased: 'badge-green', hold: 'badge-gray' };
|
||||
|
||||
let consumableItems = [];
|
||||
let vendorsList = [];
|
||||
let requestsList = [];
|
||||
let currentRequestForPurchase = null;
|
||||
let currentRequestForHold = null;
|
||||
let isAdmin = false;
|
||||
|
||||
async function loadInitialData() {
|
||||
try {
|
||||
const [itemsRes, vendorsRes] = await Promise.all([
|
||||
api('/purchase-requests/consumable-items'),
|
||||
api('/purchase-requests/vendors')
|
||||
]);
|
||||
consumableItems = itemsRes.data || [];
|
||||
vendorsList = vendorsRes.data || [];
|
||||
populateItemSelect();
|
||||
populateVendorSelect();
|
||||
} catch (e) {
|
||||
console.error('초기 데이터 로드 실패:', e);
|
||||
}
|
||||
}
|
||||
|
||||
function populateItemSelect() {
|
||||
const sel = document.getElementById('prItemSelect');
|
||||
const groups = {};
|
||||
consumableItems.forEach(item => {
|
||||
const cat = CAT_LABELS[item.category] || item.category;
|
||||
if (!groups[cat]) groups[cat] = [];
|
||||
groups[cat].push(item);
|
||||
});
|
||||
let html = '<option value="">소모품 선택</option>';
|
||||
for (const [cat, items] of Object.entries(groups)) {
|
||||
html += `<optgroup label="${cat}">`;
|
||||
items.forEach(item => {
|
||||
const maker = item.maker ? ` (${escapeHtml(item.maker)})` : '';
|
||||
html += `<option value="${item.item_id}">${escapeHtml(item.item_name)}${maker}</option>`;
|
||||
});
|
||||
html += '</optgroup>';
|
||||
}
|
||||
sel.innerHTML = html;
|
||||
}
|
||||
|
||||
function populateVendorSelect() {
|
||||
const sel = document.getElementById('pmVendor');
|
||||
sel.innerHTML = '<option value="">업체 선택 (선택사항)</option>' +
|
||||
vendorsList.map(v => `<option value="${v.vendor_id}">${escapeHtml(v.vendor_name)}</option>`).join('');
|
||||
}
|
||||
|
||||
function onItemSelect() {
|
||||
const itemId = parseInt(document.getElementById('prItemSelect').value);
|
||||
const preview = document.getElementById('prItemPreview');
|
||||
const item = consumableItems.find(i => i.item_id === itemId);
|
||||
if (!item) { preview.classList.add('hidden'); return; }
|
||||
|
||||
preview.classList.remove('hidden');
|
||||
const photoEl = document.getElementById('prItemPhoto');
|
||||
if (item.photo_path) {
|
||||
photoEl.src = TKUSER_BASE_URL + item.photo_path;
|
||||
photoEl.classList.remove('hidden');
|
||||
photoEl.onerror = () => photoEl.classList.add('hidden');
|
||||
} else {
|
||||
photoEl.classList.add('hidden');
|
||||
}
|
||||
document.getElementById('prItemInfo').textContent = `${item.item_name} ${item.maker ? '(' + item.maker + ')' : ''}`;
|
||||
const price = item.base_price ? Number(item.base_price).toLocaleString() + '원/' + (item.unit || 'EA') : '기준가 미설정';
|
||||
document.getElementById('prItemPrice').textContent = price;
|
||||
}
|
||||
|
||||
/* ===== 구매신청 제출 ===== */
|
||||
async function submitPurchaseRequest() {
|
||||
const item_id = document.getElementById('prItemSelect').value;
|
||||
const quantity = parseInt(document.getElementById('prQuantity').value) || 0;
|
||||
const notes = document.getElementById('prNotes').value.trim();
|
||||
|
||||
if (!item_id) { showToast('소모품을 선택해주세요.', 'error'); return; }
|
||||
if (quantity < 1) { showToast('수량은 1 이상이어야 합니다.', 'error'); return; }
|
||||
|
||||
try {
|
||||
await api('/purchase-requests', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ item_id: parseInt(item_id), quantity, notes })
|
||||
});
|
||||
showToast('구매신청이 등록되었습니다.');
|
||||
document.getElementById('prItemSelect').value = '';
|
||||
document.getElementById('prQuantity').value = '1';
|
||||
document.getElementById('prNotes').value = '';
|
||||
document.getElementById('prItemPreview').classList.add('hidden');
|
||||
await loadRequests();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
/* ===== 신청 목록 ===== */
|
||||
async function loadRequests() {
|
||||
try {
|
||||
const status = document.getElementById('prFilterStatus').value;
|
||||
const category = document.getElementById('prFilterCategory').value;
|
||||
const params = new URLSearchParams();
|
||||
if (status) params.set('status', status);
|
||||
if (category) params.set('category', category);
|
||||
const res = await api('/purchase-requests?' + params.toString());
|
||||
requestsList = res.data || [];
|
||||
renderRequests();
|
||||
} catch (e) {
|
||||
document.getElementById('prRequestList').innerHTML = `<tr><td colspan="7" class="px-4 py-8 text-center text-red-500">${escapeHtml(e.message)}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderRequests() {
|
||||
const tbody = document.getElementById('prRequestList');
|
||||
if (!requestsList.length) {
|
||||
tbody.innerHTML = '<tr><td colspan="7" class="px-4 py-8 text-center text-gray-400">구매신청 내역이 없습니다.</td></tr>';
|
||||
return;
|
||||
}
|
||||
tbody.innerHTML = requestsList.map(r => {
|
||||
const catLabel = CAT_LABELS[r.category] || r.category;
|
||||
const catColor = CAT_COLORS[r.category] || 'badge-gray';
|
||||
const statusLabel = STATUS_LABELS[r.status] || r.status;
|
||||
const statusColor = STATUS_COLORS[r.status] || 'badge-gray';
|
||||
const photoSrc = r.photo_path ? TKUSER_BASE_URL + r.photo_path : '';
|
||||
|
||||
let actions = '';
|
||||
if (isAdmin && r.status === 'pending') {
|
||||
actions = `<button onclick="openPurchaseModal(${r.request_id})" class="px-2 py-1 bg-orange-500 text-white rounded text-xs hover:bg-orange-600 mr-1" title="구매 처리"><i class="fas fa-shopping-cart"></i></button>
|
||||
<button onclick="openHoldModal(${r.request_id})" class="px-2 py-1 bg-gray-400 text-white rounded text-xs hover:bg-gray-500" title="보류"><i class="fas fa-pause"></i></button>`;
|
||||
} else if (isAdmin && r.status === 'hold') {
|
||||
actions = `<button onclick="revertRequest(${r.request_id})" class="px-2 py-1 bg-blue-500 text-white rounded text-xs hover:bg-blue-600" title="대기로 되돌리기"><i class="fas fa-undo"></i></button>`;
|
||||
}
|
||||
if (r.status === 'pending' && (isAdmin || r.requester_id === currentUser.id)) {
|
||||
actions += ` <button onclick="deleteRequest(${r.request_id})" class="px-2 py-1 bg-red-400 text-white rounded text-xs hover:bg-red-500" title="삭제"><i class="fas fa-trash"></i></button>`;
|
||||
}
|
||||
|
||||
return `<tr class="hover:bg-gray-50">
|
||||
<td class="px-4 py-3">
|
||||
<div class="flex items-center gap-2">
|
||||
${photoSrc ? `<img src="${photoSrc}" class="w-8 h-8 rounded object-cover" onerror="this.style.display='none'">` : ''}
|
||||
<div>
|
||||
<div class="font-medium text-gray-800">${escapeHtml(r.item_name)}</div>
|
||||
<div class="text-xs text-gray-500">${escapeHtml(r.maker || '')}</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-4 py-3"><span class="badge ${catColor}">${catLabel}</span></td>
|
||||
<td class="px-4 py-3 text-right font-medium">${r.quantity}</td>
|
||||
<td class="px-4 py-3 text-gray-600">${escapeHtml(r.requester_name || '')}</td>
|
||||
<td class="px-4 py-3 text-gray-600">${formatDate(r.request_date)}</td>
|
||||
<td class="px-4 py-3 text-center">
|
||||
<span class="badge ${statusColor}">${statusLabel}</span>
|
||||
${r.status === 'hold' && r.hold_reason ? `<div class="text-xs text-gray-400 mt-1">${escapeHtml(r.hold_reason)}</div>` : ''}
|
||||
</td>
|
||||
<td class="px-4 py-3 text-center">${actions}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
/* ===== 구매 처리 모달 ===== */
|
||||
function openPurchaseModal(requestId) {
|
||||
const r = requestsList.find(x => x.request_id === requestId);
|
||||
if (!r) return;
|
||||
currentRequestForPurchase = r;
|
||||
|
||||
const basePrice = r.base_price ? Number(r.base_price).toLocaleString() + '원' : '-';
|
||||
document.getElementById('purchaseModalInfo').innerHTML = `
|
||||
<div class="font-medium">${escapeHtml(r.item_name)} ${r.maker ? '(' + escapeHtml(r.maker) + ')' : ''}</div>
|
||||
<div class="text-xs text-gray-500 mt-1">분류: ${CAT_LABELS[r.category] || r.category} | 기준가: ${basePrice} | 신청수량: ${r.quantity}</div>
|
||||
`;
|
||||
document.getElementById('pmUnitPrice').value = r.base_price || '';
|
||||
document.getElementById('pmQuantity').value = r.quantity;
|
||||
document.getElementById('pmDate').value = new Date().toISOString().substring(0, 10);
|
||||
document.getElementById('pmNotes').value = '';
|
||||
document.getElementById('pmPriceDiffArea').innerHTML = '';
|
||||
document.getElementById('purchaseModal').classList.remove('hidden');
|
||||
showPriceDiff();
|
||||
}
|
||||
|
||||
function closePurchaseModal() {
|
||||
document.getElementById('purchaseModal').classList.add('hidden');
|
||||
currentRequestForPurchase = null;
|
||||
}
|
||||
|
||||
function showPriceDiff() {
|
||||
if (!currentRequestForPurchase) return;
|
||||
const basePrice = Number(currentRequestForPurchase.base_price) || 0;
|
||||
const unitPrice = Number(document.getElementById('pmUnitPrice').value) || 0;
|
||||
const area = document.getElementById('pmPriceDiffArea');
|
||||
|
||||
if (basePrice > 0 && unitPrice > 0 && basePrice !== unitPrice) {
|
||||
const diff = unitPrice - basePrice;
|
||||
const arrow = diff > 0 ? '▲' : '▼';
|
||||
const color = diff > 0 ? 'text-red-600' : 'text-blue-600';
|
||||
area.innerHTML = `
|
||||
<div class="flex items-center gap-2 text-sm ${color}">
|
||||
<span>기준가 ${basePrice.toLocaleString()}원 → 실구매가 ${unitPrice.toLocaleString()}원 ${arrow}${Math.abs(diff).toLocaleString()}</span>
|
||||
</div>
|
||||
<label class="flex items-center gap-2 mt-1 cursor-pointer">
|
||||
<input type="checkbox" id="pmUpdateBasePrice" class="h-4 w-4 rounded">
|
||||
<span class="text-xs text-gray-600">기준가를 ${unitPrice.toLocaleString()}원으로 업데이트</span>
|
||||
</label>`;
|
||||
} else {
|
||||
area.innerHTML = '';
|
||||
}
|
||||
}
|
||||
|
||||
async function submitPurchase() {
|
||||
if (!currentRequestForPurchase) return;
|
||||
const unit_price = Number(document.getElementById('pmUnitPrice').value);
|
||||
const purchase_date = document.getElementById('pmDate').value;
|
||||
if (!unit_price) { showToast('구매 단가를 입력해주세요.', 'error'); return; }
|
||||
if (!purchase_date) { showToast('구매일을 입력해주세요.', 'error'); return; }
|
||||
|
||||
const updateCheckbox = document.getElementById('pmUpdateBasePrice');
|
||||
const body = {
|
||||
request_id: currentRequestForPurchase.request_id,
|
||||
item_id: currentRequestForPurchase.item_id,
|
||||
vendor_id: parseInt(document.getElementById('pmVendor').value) || null,
|
||||
quantity: parseInt(document.getElementById('pmQuantity').value) || currentRequestForPurchase.quantity,
|
||||
unit_price,
|
||||
purchase_date,
|
||||
update_base_price: updateCheckbox ? updateCheckbox.checked : false,
|
||||
notes: document.getElementById('pmNotes').value.trim()
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await api('/purchases', { method: 'POST', body: JSON.stringify(body) });
|
||||
let msg = '구매 처리가 완료되었습니다.';
|
||||
if (res.data?.equipment?.success) msg += ` 설비 ${res.data.equipment.equipment_code} 자동 등록됨.`;
|
||||
else if (res.data?.equipment && !res.data.equipment.success) msg += ' (설비 자동 등록 실패 - 수동 등록 필요)';
|
||||
showToast(msg);
|
||||
closePurchaseModal();
|
||||
await loadRequests();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
/* ===== 보류 모달 ===== */
|
||||
function openHoldModal(requestId) {
|
||||
currentRequestForHold = requestId;
|
||||
document.getElementById('holdReason').value = '';
|
||||
document.getElementById('holdModal').classList.remove('hidden');
|
||||
}
|
||||
|
||||
function closeHoldModal() {
|
||||
document.getElementById('holdModal').classList.add('hidden');
|
||||
currentRequestForHold = null;
|
||||
}
|
||||
|
||||
async function submitHold() {
|
||||
if (!currentRequestForHold) return;
|
||||
const hold_reason = document.getElementById('holdReason').value.trim();
|
||||
try {
|
||||
await api(`/purchase-requests/${currentRequestForHold}/hold`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ hold_reason })
|
||||
});
|
||||
showToast('보류 처리되었습니다.');
|
||||
closeHoldModal();
|
||||
await loadRequests();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
/* ===== 기타 액션 ===== */
|
||||
async function revertRequest(requestId) {
|
||||
if (!confirm('이 신청을 대기 상태로 되돌리시겠습니까?')) return;
|
||||
try {
|
||||
await api(`/purchase-requests/${requestId}/revert`, { method: 'PUT' });
|
||||
showToast('대기 상태로 되돌렸습니다.');
|
||||
await loadRequests();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
async function deleteRequest(requestId) {
|
||||
if (!confirm('이 구매신청을 삭제하시겠습니까?')) return;
|
||||
try {
|
||||
await api(`/purchase-requests/${requestId}`, { method: 'DELETE' });
|
||||
showToast('삭제되었습니다.');
|
||||
await loadRequests();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
/* ===== Init ===== */
|
||||
(async function() {
|
||||
if (!await initAuth()) return;
|
||||
isAdmin = currentUser && ['admin', 'system', 'system admin'].includes(currentUser.role);
|
||||
await loadInitialData();
|
||||
await loadRequests();
|
||||
})();
|
||||
@@ -119,6 +119,10 @@ const NAV_MENU = [
|
||||
{ href: '/pages/attendance/checkin.html', icon: 'fa-user-check', label: '출근 체크', key: 'inspection.checkin' },
|
||||
{ href: '/pages/attendance/work-status.html', icon: 'fa-briefcase', label: '근무 현황', key: 'inspection.work_status' },
|
||||
]},
|
||||
{ cat: '구매 관리', items: [
|
||||
{ href: '/pages/purchase/request.html', icon: 'fa-shopping-cart', label: '구매신청', key: 'purchase.request' },
|
||||
{ href: '/pages/admin/purchase-analysis.html', icon: 'fa-chart-line', label: '구매 분석', key: 'purchase.analysis', admin: true },
|
||||
]},
|
||||
{ cat: '근태 관리', items: [
|
||||
{ href: '/pages/attendance/my-vacation-info.html', icon: 'fa-info-circle', label: '내 연차 정보', key: 'attendance.my_vacation_info' },
|
||||
{ href: '/pages/attendance/monthly.html', icon: 'fa-calendar', label: '월간 근태', key: 'attendance.monthly' },
|
||||
|
||||
90
user-management/api/controllers/consumableItemController.js
Normal file
90
user-management/api/controllers/consumableItemController.js
Normal file
@@ -0,0 +1,90 @@
|
||||
const consumableItemModel = require('../models/consumableItemModel');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
async function list(req, res) {
|
||||
try {
|
||||
const { category, search, is_active } = req.query;
|
||||
const rows = await consumableItemModel.findAll({
|
||||
category,
|
||||
search,
|
||||
is_active: is_active !== undefined ? is_active === 'true' || is_active === '1' : undefined
|
||||
});
|
||||
res.json({ success: true, data: rows });
|
||||
} catch (err) {
|
||||
console.error('ConsumableItem list error:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
async function getById(req, res) {
|
||||
try {
|
||||
const item = await consumableItemModel.findById(req.params.id);
|
||||
if (!item) return res.status(404).json({ success: false, error: '소모품을 찾을 수 없습니다' });
|
||||
res.json({ success: true, data: item });
|
||||
} catch (err) {
|
||||
console.error('ConsumableItem get error:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
async function create(req, res) {
|
||||
try {
|
||||
const { item_name, category } = req.body;
|
||||
if (!item_name || !item_name.trim()) {
|
||||
return res.status(400).json({ success: false, error: '품명은 필수입니다' });
|
||||
}
|
||||
if (!category) {
|
||||
return res.status(400).json({ success: false, error: '분류는 필수입니다' });
|
||||
}
|
||||
const data = { ...req.body };
|
||||
if (req.file) {
|
||||
data.photo_path = '/uploads/consumables/' + req.file.filename;
|
||||
}
|
||||
const item = await consumableItemModel.create(data);
|
||||
res.status(201).json({ success: true, data: item });
|
||||
} catch (err) {
|
||||
if (err.code === 'ER_DUP_ENTRY') {
|
||||
return res.status(400).json({ success: false, error: '동일한 품명+메이커 조합이 이미 존재합니다' });
|
||||
}
|
||||
console.error('ConsumableItem create error:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
async function update(req, res) {
|
||||
try {
|
||||
const existing = await consumableItemModel.findById(req.params.id);
|
||||
if (!existing) return res.status(404).json({ success: false, error: '소모품을 찾을 수 없습니다' });
|
||||
|
||||
const data = { ...req.body };
|
||||
if (req.file) {
|
||||
data.photo_path = '/uploads/consumables/' + req.file.filename;
|
||||
// 기존 사진 삭제
|
||||
if (existing.photo_path) {
|
||||
const oldPath = path.join(__dirname, '..', existing.photo_path);
|
||||
fs.unlink(oldPath, () => {});
|
||||
}
|
||||
}
|
||||
const item = await consumableItemModel.update(req.params.id, data);
|
||||
res.json({ success: true, data: item });
|
||||
} catch (err) {
|
||||
if (err.code === 'ER_DUP_ENTRY') {
|
||||
return res.status(400).json({ success: false, error: '동일한 품명+메이커 조합이 이미 존재합니다' });
|
||||
}
|
||||
console.error('ConsumableItem update error:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
async function deactivate(req, res) {
|
||||
try {
|
||||
await consumableItemModel.deactivate(req.params.id);
|
||||
res.json({ success: true, message: '비활성화 완료' });
|
||||
} catch (err) {
|
||||
console.error('ConsumableItem deactivate error:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { list, getById, create, update, deactivate };
|
||||
66
user-management/api/controllers/vendorController.js
Normal file
66
user-management/api/controllers/vendorController.js
Normal file
@@ -0,0 +1,66 @@
|
||||
const vendorModel = require('../models/vendorModel');
|
||||
|
||||
async function list(req, res) {
|
||||
try {
|
||||
const { search, is_active } = req.query;
|
||||
const rows = await vendorModel.findAll({
|
||||
search,
|
||||
is_active: is_active !== undefined ? is_active === 'true' || is_active === '1' : undefined
|
||||
});
|
||||
res.json({ success: true, data: rows });
|
||||
} catch (err) {
|
||||
console.error('Vendor list error:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
async function getById(req, res) {
|
||||
try {
|
||||
const vendor = await vendorModel.findById(req.params.id);
|
||||
if (!vendor) return res.status(404).json({ success: false, error: '업체를 찾을 수 없습니다' });
|
||||
res.json({ success: true, data: vendor });
|
||||
} catch (err) {
|
||||
console.error('Vendor get error:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
async function create(req, res) {
|
||||
try {
|
||||
const { vendor_name } = req.body;
|
||||
if (!vendor_name || !vendor_name.trim()) {
|
||||
return res.status(400).json({ success: false, error: '업체명은 필수입니다' });
|
||||
}
|
||||
const vendor = await vendorModel.create(req.body);
|
||||
res.status(201).json({ success: true, data: vendor });
|
||||
} catch (err) {
|
||||
if (err.code === 'ER_DUP_ENTRY') {
|
||||
return res.status(400).json({ success: false, error: '이미 등록된 업체입니다' });
|
||||
}
|
||||
console.error('Vendor create error:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
async function update(req, res) {
|
||||
try {
|
||||
const vendor = await vendorModel.update(req.params.id, req.body);
|
||||
if (!vendor) return res.status(404).json({ success: false, error: '업체를 찾을 수 없습니다' });
|
||||
res.json({ success: true, data: vendor });
|
||||
} catch (err) {
|
||||
console.error('Vendor update error:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
async function deactivate(req, res) {
|
||||
try {
|
||||
await vendorModel.deactivate(req.params.id);
|
||||
res.json({ success: true, message: '비활성화 완료' });
|
||||
} catch (err) {
|
||||
console.error('Vendor deactivate error:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { list, getById, create, update, deactivate };
|
||||
@@ -18,6 +18,8 @@ const equipmentRoutes = require('./routes/equipmentRoutes');
|
||||
const taskRoutes = require('./routes/taskRoutes');
|
||||
const vacationRoutes = require('./routes/vacationRoutes');
|
||||
const partnerRoutes = require('./routes/partnerRoutes');
|
||||
const vendorRoutes = require('./routes/vendorRoutes');
|
||||
const consumableItemRoutes = require('./routes/consumableItemRoutes');
|
||||
const notificationRecipientRoutes = require('./routes/notificationRecipientRoutes');
|
||||
|
||||
const app = express();
|
||||
@@ -59,6 +61,8 @@ app.use('/api/equipments', equipmentRoutes);
|
||||
app.use('/api/tasks', taskRoutes);
|
||||
app.use('/api/vacations', vacationRoutes);
|
||||
app.use('/api/partners', partnerRoutes);
|
||||
app.use('/api/vendors', vendorRoutes);
|
||||
app.use('/api/consumable-items', consumableItemRoutes);
|
||||
app.use('/api/notification-recipients', notificationRecipientRoutes);
|
||||
|
||||
// 404
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
const multer = require('multer');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (req, file, cb) => {
|
||||
@@ -32,4 +33,26 @@ const upload = multer({
|
||||
limits: { fileSize: 5 * 1024 * 1024 }
|
||||
});
|
||||
|
||||
// 소모품 사진 업로드
|
||||
const consumablesDir = path.join(__dirname, '..', 'uploads', 'consumables');
|
||||
if (!fs.existsSync(consumablesDir)) { fs.mkdirSync(consumablesDir, { recursive: true }); }
|
||||
|
||||
const consumableStorage = multer.diskStorage({
|
||||
destination: (req, file, cb) => {
|
||||
cb(null, consumablesDir);
|
||||
},
|
||||
filename: (req, file, cb) => {
|
||||
const ext = path.extname(file.originalname).toLowerCase();
|
||||
const uniqueName = `consumable-${Date.now()}-${crypto.randomInt(100000000, 999999999)}${ext}`;
|
||||
cb(null, uniqueName);
|
||||
}
|
||||
});
|
||||
|
||||
const consumableUpload = multer({
|
||||
storage: consumableStorage,
|
||||
fileFilter,
|
||||
limits: { fileSize: 5 * 1024 * 1024 }
|
||||
});
|
||||
|
||||
module.exports = upload;
|
||||
module.exports.consumableUpload = consumableUpload;
|
||||
|
||||
56
user-management/api/models/consumableItemModel.js
Normal file
56
user-management/api/models/consumableItemModel.js
Normal file
@@ -0,0 +1,56 @@
|
||||
const { getPool } = require('./userModel');
|
||||
|
||||
// ===== 소모품 마스터 =====
|
||||
|
||||
async function findAll({ category, search, is_active } = {}) {
|
||||
const db = getPool();
|
||||
let sql = 'SELECT * FROM consumable_items WHERE 1=1';
|
||||
const params = [];
|
||||
if (is_active !== undefined) { sql += ' AND is_active = ?'; params.push(is_active); }
|
||||
if (category) { sql += ' AND category = ?'; params.push(category); }
|
||||
if (search) { sql += ' AND (item_name LIKE ? OR maker LIKE ?)'; params.push(`%${search}%`, `%${search}%`); }
|
||||
sql += ' ORDER BY category, item_name';
|
||||
const [rows] = await db.query(sql, params);
|
||||
return rows;
|
||||
}
|
||||
|
||||
async function findById(id) {
|
||||
const db = getPool();
|
||||
const [rows] = await db.query('SELECT * FROM consumable_items WHERE item_id = ?', [id]);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
async function create(data) {
|
||||
const db = getPool();
|
||||
const [result] = await db.query(
|
||||
`INSERT INTO consumable_items (item_name, maker, category, base_price, unit, photo_path)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
[data.item_name, data.maker || null, data.category,
|
||||
data.base_price || 0, data.unit || 'EA', data.photo_path || null]
|
||||
);
|
||||
return findById(result.insertId);
|
||||
}
|
||||
|
||||
async function update(id, data) {
|
||||
const db = getPool();
|
||||
const fields = [];
|
||||
const values = [];
|
||||
if (data.item_name !== undefined) { fields.push('item_name = ?'); values.push(data.item_name); }
|
||||
if (data.maker !== undefined) { fields.push('maker = ?'); values.push(data.maker || null); }
|
||||
if (data.category !== undefined) { fields.push('category = ?'); values.push(data.category); }
|
||||
if (data.base_price !== undefined) { fields.push('base_price = ?'); values.push(data.base_price); }
|
||||
if (data.unit !== undefined) { fields.push('unit = ?'); values.push(data.unit || 'EA'); }
|
||||
if (data.photo_path !== undefined) { fields.push('photo_path = ?'); values.push(data.photo_path || null); }
|
||||
if (data.is_active !== undefined) { fields.push('is_active = ?'); values.push(data.is_active); }
|
||||
if (fields.length === 0) return findById(id);
|
||||
values.push(id);
|
||||
await db.query(`UPDATE consumable_items SET ${fields.join(', ')} WHERE item_id = ?`, values);
|
||||
return findById(id);
|
||||
}
|
||||
|
||||
async function deactivate(id) {
|
||||
const db = getPool();
|
||||
await db.query('UPDATE consumable_items SET is_active = FALSE WHERE item_id = ?', [id]);
|
||||
}
|
||||
|
||||
module.exports = { findAll, findById, create, update, deactivate };
|
||||
59
user-management/api/models/vendorModel.js
Normal file
59
user-management/api/models/vendorModel.js
Normal file
@@ -0,0 +1,59 @@
|
||||
const { getPool } = require('./userModel');
|
||||
|
||||
// ===== 업체(공급업체) =====
|
||||
|
||||
async function findAll({ search, is_active } = {}) {
|
||||
const db = getPool();
|
||||
let sql = 'SELECT * FROM vendors WHERE 1=1';
|
||||
const params = [];
|
||||
if (is_active !== undefined) { sql += ' AND is_active = ?'; params.push(is_active); }
|
||||
if (search) { sql += ' AND (vendor_name LIKE ? OR business_number LIKE ? OR contact_name LIKE ?)'; params.push(`%${search}%`, `%${search}%`, `%${search}%`); }
|
||||
sql += ' ORDER BY vendor_name';
|
||||
const [rows] = await db.query(sql, params);
|
||||
return rows;
|
||||
}
|
||||
|
||||
async function findById(id) {
|
||||
const db = getPool();
|
||||
const [rows] = await db.query('SELECT * FROM vendors WHERE vendor_id = ?', [id]);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
async function create(data) {
|
||||
const db = getPool();
|
||||
const [result] = await db.query(
|
||||
`INSERT INTO vendors (vendor_name, business_number, representative, contact_name, contact_phone, address, bank_name, bank_account, notes)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[data.vendor_name, data.business_number || null, data.representative || null,
|
||||
data.contact_name || null, data.contact_phone || null, data.address || null,
|
||||
data.bank_name || null, data.bank_account || null, data.notes || null]
|
||||
);
|
||||
return findById(result.insertId);
|
||||
}
|
||||
|
||||
async function update(id, data) {
|
||||
const db = getPool();
|
||||
const fields = [];
|
||||
const values = [];
|
||||
if (data.vendor_name !== undefined) { fields.push('vendor_name = ?'); values.push(data.vendor_name); }
|
||||
if (data.business_number !== undefined) { fields.push('business_number = ?'); values.push(data.business_number || null); }
|
||||
if (data.representative !== undefined) { fields.push('representative = ?'); values.push(data.representative || null); }
|
||||
if (data.contact_name !== undefined) { fields.push('contact_name = ?'); values.push(data.contact_name || null); }
|
||||
if (data.contact_phone !== undefined) { fields.push('contact_phone = ?'); values.push(data.contact_phone || null); }
|
||||
if (data.address !== undefined) { fields.push('address = ?'); values.push(data.address || null); }
|
||||
if (data.bank_name !== undefined) { fields.push('bank_name = ?'); values.push(data.bank_name || null); }
|
||||
if (data.bank_account !== undefined) { fields.push('bank_account = ?'); values.push(data.bank_account || null); }
|
||||
if (data.notes !== undefined) { fields.push('notes = ?'); values.push(data.notes || null); }
|
||||
if (data.is_active !== undefined) { fields.push('is_active = ?'); values.push(data.is_active); }
|
||||
if (fields.length === 0) return findById(id);
|
||||
values.push(id);
|
||||
await db.query(`UPDATE vendors SET ${fields.join(', ')} WHERE vendor_id = ?`, values);
|
||||
return findById(id);
|
||||
}
|
||||
|
||||
async function deactivate(id) {
|
||||
const db = getPool();
|
||||
await db.query('UPDATE vendors SET is_active = FALSE WHERE vendor_id = ?', [id]);
|
||||
}
|
||||
|
||||
module.exports = { findAll, findById, create, update, deactivate };
|
||||
15
user-management/api/routes/consumableItemRoutes.js
Normal file
15
user-management/api/routes/consumableItemRoutes.js
Normal file
@@ -0,0 +1,15 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { requireAuth, requireAdmin } = require('../middleware/auth');
|
||||
const ctrl = require('../controllers/consumableItemController');
|
||||
const { consumableUpload } = require('../middleware/upload');
|
||||
|
||||
router.use(requireAuth);
|
||||
|
||||
router.get('/', ctrl.list);
|
||||
router.get('/:id', ctrl.getById);
|
||||
router.post('/', requireAdmin, consumableUpload.single('photo'), ctrl.create);
|
||||
router.put('/:id', requireAdmin, consumableUpload.single('photo'), ctrl.update);
|
||||
router.delete('/:id', requireAdmin, ctrl.deactivate);
|
||||
|
||||
module.exports = router;
|
||||
14
user-management/api/routes/vendorRoutes.js
Normal file
14
user-management/api/routes/vendorRoutes.js
Normal file
@@ -0,0 +1,14 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { requireAuth, requireAdmin } = require('../middleware/auth');
|
||||
const ctrl = require('../controllers/vendorController');
|
||||
|
||||
router.use(requireAuth);
|
||||
|
||||
router.get('/', ctrl.list);
|
||||
router.get('/:id', ctrl.getById);
|
||||
router.post('/', requireAdmin, ctrl.create);
|
||||
router.put('/:id', requireAdmin, ctrl.update);
|
||||
router.delete('/:id', requireAdmin, ctrl.deactivate);
|
||||
|
||||
module.exports = router;
|
||||
@@ -64,6 +64,12 @@
|
||||
<button class="tab-btn px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap" onclick="switchTab('partners')">
|
||||
<i class="fas fa-truck mr-2"></i>협력업체
|
||||
</button>
|
||||
<button class="tab-btn px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap" onclick="switchTab('vendors')">
|
||||
<i class="fas fa-store mr-2"></i>업체
|
||||
</button>
|
||||
<button class="tab-btn px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap" onclick="switchTab('consumables')">
|
||||
<i class="fas fa-box-open mr-2"></i>소모품
|
||||
</button>
|
||||
<button class="tab-btn px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap" onclick="switchTab('notificationRecipients')">
|
||||
<i class="fas fa-bell mr-2"></i>알림 수신자
|
||||
</button>
|
||||
@@ -1482,6 +1488,70 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ============ 업체(공급업체) 탭 ============ -->
|
||||
<div id="tab-vendors" class="hidden">
|
||||
<div class="grid lg:grid-cols-5 gap-6">
|
||||
<!-- 업체 목록 -->
|
||||
<div class="lg:col-span-2 bg-white rounded-xl shadow-sm p-5">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-base font-semibold text-gray-800"><i class="fas fa-store text-indigo-500 mr-2"></i>업체 (공급업체)</h2>
|
||||
<button id="btnAddVendorTkuser" onclick="openAddVendorTkuser()" class="hidden px-3 py-1.5 bg-slate-700 text-white rounded-lg text-xs hover:bg-slate-800">
|
||||
<i class="fas fa-plus mr-1"></i>업체 등록
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex gap-2 mb-3">
|
||||
<input type="text" id="vendorSearchTkuser" class="input-field flex-1 px-3 py-1.5 rounded-lg text-sm" placeholder="업체명/사업자번호/담당자 검색">
|
||||
<select id="vendorFilterActiveTkuser" class="input-field px-2 py-1.5 rounded-lg text-sm">
|
||||
<option value="true">활성</option>
|
||||
<option value="">전체</option>
|
||||
<option value="false">비활성</option>
|
||||
</select>
|
||||
</div>
|
||||
<div id="vendorsListTkuser" class="space-y-2 max-h-[65vh] overflow-y-auto">
|
||||
<p class="text-gray-400 text-center py-4 text-sm">탭을 선택하면 데이터를 불러옵니다.</p>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 업체 상세 -->
|
||||
<div class="lg:col-span-3">
|
||||
<div id="vendorDetailTkuser" class="hidden"></div>
|
||||
<div id="vendorEmptyTkuser" class="text-center text-gray-400 py-16">
|
||||
<i class="fas fa-store text-4xl mb-3"></i>
|
||||
<p>업체를 선택하면 상세 정보를 볼 수 있습니다</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ============ 소모품 탭 ============ -->
|
||||
<div id="tab-consumables" class="hidden">
|
||||
<div class="bg-white rounded-xl shadow-sm p-5">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-base font-semibold text-gray-800"><i class="fas fa-box-open text-teal-500 mr-2"></i>소모품 마스터</h2>
|
||||
<button id="btnAddConsumableTkuser" onclick="openAddConsumableTkuser()" class="hidden px-3 py-1.5 bg-slate-700 text-white rounded-lg text-xs hover:bg-slate-800">
|
||||
<i class="fas fa-plus mr-1"></i>소모품 등록
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex gap-2 mb-4 flex-wrap">
|
||||
<input type="text" id="consumableSearchTkuser" class="input-field flex-1 min-w-[160px] px-3 py-1.5 rounded-lg text-sm" placeholder="품명/메이커 검색">
|
||||
<select id="consumableFilterCategoryTkuser" class="input-field px-2 py-1.5 rounded-lg text-sm">
|
||||
<option value="">전체 분류</option>
|
||||
<option value="consumable">소모품</option>
|
||||
<option value="safety">안전용품</option>
|
||||
<option value="repair">수선비</option>
|
||||
<option value="equipment">설비</option>
|
||||
</select>
|
||||
<select id="consumableFilterActiveTkuser" class="input-field px-2 py-1.5 rounded-lg text-sm">
|
||||
<option value="true">활성</option>
|
||||
<option value="">전체</option>
|
||||
<option value="false">비활성</option>
|
||||
</select>
|
||||
</div>
|
||||
<div id="consumablesListTkuser">
|
||||
<p class="text-gray-400 text-center py-4 text-sm">탭을 선택하면 데이터를 불러옵니다.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ============ 알림 수신자 탭 ============ -->
|
||||
<div id="tab-notificationRecipients" class="hidden">
|
||||
<div class="mb-4">
|
||||
@@ -1713,6 +1783,213 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 업체 등록 모달 -->
|
||||
<div id="addVendorModalTkuser" class="hidden fixed inset-0 bg-black bg-opacity-40 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeAddVendorTkuser()">
|
||||
<div class="bg-white rounded-xl shadow-xl max-w-lg w-full p-6">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h3 class="text-lg font-semibold">업체 등록</h3>
|
||||
<button onclick="closeAddVendorTkuser()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
|
||||
</div>
|
||||
<form id="addVendorFormTkuser">
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">업체명 <span class="text-red-400">*</span></label>
|
||||
<input type="text" id="newVendorNameTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm" required>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">사업자번호</label>
|
||||
<input type="text" id="newVendorBizNumTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm" placeholder="000-00-00000">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">대표자</label>
|
||||
<input type="text" id="newVendorRepTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">담당자명</label>
|
||||
<input type="text" id="newVendorContactNameTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">담당자 연락처</label>
|
||||
<input type="text" id="newVendorContactPhoneTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">주소</label>
|
||||
<input type="text" id="newVendorAddressTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">은행명</label>
|
||||
<input type="text" id="newVendorBankNameTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">계좌번호</label>
|
||||
<input type="text" id="newVendorBankAccountTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">비고</label>
|
||||
<input type="text" id="newVendorNotesTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end mt-4 gap-2">
|
||||
<button type="button" onclick="closeAddVendorTkuser()" class="px-4 py-2 border rounded-lg text-sm hover:bg-gray-50">취소</button>
|
||||
<button type="submit" class="px-4 py-2 bg-slate-700 text-white rounded-lg text-sm hover:bg-slate-800">등록</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 업체 수정 모달 -->
|
||||
<div id="editVendorModalTkuser" class="hidden fixed inset-0 bg-black bg-opacity-40 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeEditVendorTkuser()">
|
||||
<div class="bg-white rounded-xl shadow-xl max-w-lg w-full p-6">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h3 class="text-lg font-semibold">업체 수정</h3>
|
||||
<button onclick="closeEditVendorTkuser()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
|
||||
</div>
|
||||
<form id="editVendorFormTkuser">
|
||||
<input type="hidden" id="editVendorIdTkuser">
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">업체명 <span class="text-red-400">*</span></label>
|
||||
<input type="text" id="editVendorNameTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm" required>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">사업자번호</label>
|
||||
<input type="text" id="editVendorBizNumTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">대표자</label>
|
||||
<input type="text" id="editVendorRepTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">담당자명</label>
|
||||
<input type="text" id="editVendorContactNameTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">담당자 연락처</label>
|
||||
<input type="text" id="editVendorContactPhoneTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">주소</label>
|
||||
<input type="text" id="editVendorAddressTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">은행명</label>
|
||||
<input type="text" id="editVendorBankNameTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">계좌번호</label>
|
||||
<input type="text" id="editVendorBankAccountTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">비고</label>
|
||||
<input type="text" id="editVendorNotesTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end mt-4 gap-2">
|
||||
<button type="button" onclick="closeEditVendorTkuser()" class="px-4 py-2 border rounded-lg text-sm hover:bg-gray-50">취소</button>
|
||||
<button type="submit" class="px-4 py-2 bg-slate-700 text-white rounded-lg text-sm hover:bg-slate-800">저장</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 소모품 등록 모달 -->
|
||||
<div id="addConsumableModalTkuser" class="hidden fixed inset-0 bg-black bg-opacity-40 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeAddConsumableTkuser()">
|
||||
<div class="bg-white rounded-xl shadow-xl max-w-lg w-full p-6">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h3 class="text-lg font-semibold">소모품 등록</h3>
|
||||
<button onclick="closeAddConsumableTkuser()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
|
||||
</div>
|
||||
<form id="addConsumableFormTkuser">
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">품명 <span class="text-red-400">*</span></label>
|
||||
<input type="text" id="newConsumableNameTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm" required>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">메이커</label>
|
||||
<input type="text" id="newConsumableMakerTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">분류 <span class="text-red-400">*</span></label>
|
||||
<select id="newConsumableCategoryTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm" required>
|
||||
<option value="">선택</option>
|
||||
<option value="consumable">소모품</option>
|
||||
<option value="safety">안전용품</option>
|
||||
<option value="repair">수선비</option>
|
||||
<option value="equipment">설비</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">기준가격</label>
|
||||
<input type="number" id="newConsumablePriceTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm" min="0">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">단위</label>
|
||||
<input type="text" id="newConsumableUnitTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm" value="EA">
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">사진</label>
|
||||
<input type="file" id="newConsumablePhotoTkuser" accept="image/jpeg,image/png,image/webp" onchange="previewAddConsumablePhoto()" class="input-field w-full px-3 py-1.5 rounded-lg text-sm">
|
||||
<div id="addConsumablePhotoPreviewTkuser" class="mt-2"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end mt-4 gap-2">
|
||||
<button type="button" onclick="closeAddConsumableTkuser()" class="px-4 py-2 border rounded-lg text-sm hover:bg-gray-50">취소</button>
|
||||
<button type="submit" class="px-4 py-2 bg-slate-700 text-white rounded-lg text-sm hover:bg-slate-800">등록</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 소모품 수정 모달 -->
|
||||
<div id="editConsumableModalTkuser" class="hidden fixed inset-0 bg-black bg-opacity-40 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeEditConsumableTkuser()">
|
||||
<div class="bg-white rounded-xl shadow-xl max-w-lg w-full p-6">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h3 class="text-lg font-semibold">소모품 수정</h3>
|
||||
<button onclick="closeEditConsumableTkuser()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
|
||||
</div>
|
||||
<form id="editConsumableFormTkuser">
|
||||
<input type="hidden" id="editConsumableIdTkuser">
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">품명 <span class="text-red-400">*</span></label>
|
||||
<input type="text" id="editConsumableNameTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm" required>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">메이커</label>
|
||||
<input type="text" id="editConsumableMakerTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">분류 <span class="text-red-400">*</span></label>
|
||||
<select id="editConsumableCategoryTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm" required>
|
||||
<option value="consumable">소모품</option>
|
||||
<option value="safety">안전용품</option>
|
||||
<option value="repair">수선비</option>
|
||||
<option value="equipment">설비</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">기준가격</label>
|
||||
<input type="number" id="editConsumablePriceTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm" min="0">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">단위</label>
|
||||
<input type="text" id="editConsumableUnitTkuser" class="input-field w-full px-3 py-2 rounded-lg text-sm">
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">사진</label>
|
||||
<input type="file" id="editConsumablePhotoTkuser" accept="image/jpeg,image/png,image/webp" onchange="previewEditConsumablePhoto()" class="input-field w-full px-3 py-1.5 rounded-lg text-sm">
|
||||
<div id="editConsumablePhotoPreviewTkuser" class="mt-2"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end mt-4 gap-2">
|
||||
<button type="button" onclick="closeEditConsumableTkuser()" class="px-4 py-2 border rounded-lg text-sm hover:bg-gray-50">취소</button>
|
||||
<button type="submit" class="px-4 py-2 bg-slate-700 text-white rounded-lg text-sm hover:bg-slate-800">저장</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 사진 확대 모달 -->
|
||||
<div id="photoViewModal" class="fixed inset-0 bg-black bg-opacity-80 hidden z-[60] flex items-center justify-center p-4 cursor-pointer" onclick="this.classList.add('hidden')">
|
||||
<img id="photoViewImage" class="max-w-full max-h-[90vh] rounded-lg shadow-2xl">
|
||||
@@ -1732,6 +2009,8 @@
|
||||
<script src="/static/js/tkuser-vacations.js?v=20260224"></script>
|
||||
<script src="/static/js/tkuser-layout-map.js?v=20260305"></script>
|
||||
<script src="/static/js/tkuser-partners.js?v=20260312"></script>
|
||||
<script src="/static/js/tkuser-vendors.js?v=20260313"></script>
|
||||
<script src="/static/js/tkuser-consumables.js?v=20260313"></script>
|
||||
<script src="/static/js/tkuser-notificationRecipients.js?v=20260313b"></script>
|
||||
<!-- Boot -->
|
||||
<script>init();</script>
|
||||
|
||||
205
user-management/web/static/js/tkuser-consumables.js
Normal file
205
user-management/web/static/js/tkuser-consumables.js
Normal file
@@ -0,0 +1,205 @@
|
||||
/* ===== tkuser 소모품 마스터 CRUD ===== */
|
||||
let consumablesLoaded = false;
|
||||
let consumablesList = [];
|
||||
|
||||
const CONSUMABLE_CATEGORIES = {
|
||||
consumable: '소모품',
|
||||
safety: '안전용품',
|
||||
repair: '수선비',
|
||||
equipment: '설비'
|
||||
};
|
||||
const CONSUMABLE_CAT_COLORS = {
|
||||
consumable: 'bg-blue-50 text-blue-600',
|
||||
safety: 'bg-green-50 text-green-600',
|
||||
repair: 'bg-amber-50 text-amber-600',
|
||||
equipment: 'bg-purple-50 text-purple-600'
|
||||
};
|
||||
|
||||
async function loadConsumablesTab() {
|
||||
if (consumablesLoaded) return;
|
||||
consumablesLoaded = true;
|
||||
if (currentUser && ['admin', 'system'].includes(currentUser.role)) {
|
||||
document.getElementById('btnAddConsumableTkuser')?.classList.remove('hidden');
|
||||
}
|
||||
await loadConsumablesList();
|
||||
}
|
||||
|
||||
async function loadConsumablesList() {
|
||||
try {
|
||||
const category = document.getElementById('consumableFilterCategoryTkuser')?.value || '';
|
||||
const isActive = document.getElementById('consumableFilterActiveTkuser')?.value;
|
||||
const search = document.getElementById('consumableSearchTkuser')?.value?.trim() || '';
|
||||
const params = new URLSearchParams();
|
||||
if (category) params.set('category', category);
|
||||
if (isActive !== '' && isActive !== undefined) params.set('is_active', isActive);
|
||||
if (search) params.set('search', search);
|
||||
const r = await api('/consumable-items?' + params.toString());
|
||||
consumablesList = r.data || [];
|
||||
renderConsumablesListTkuser();
|
||||
} catch (e) {
|
||||
document.getElementById('consumablesListTkuser').innerHTML = `<div class="text-red-500 text-center py-6"><i class="fas fa-exclamation-triangle text-xl"></i><p class="text-sm mt-2">${e.message}</p></div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderConsumablesListTkuser() {
|
||||
const c = document.getElementById('consumablesListTkuser');
|
||||
if (!consumablesList.length) {
|
||||
c.innerHTML = '<p class="text-gray-400 text-center py-4 text-sm">등록된 소모품이 없습니다.</p>';
|
||||
return;
|
||||
}
|
||||
const isAdmin = currentUser && ['admin', 'system'].includes(currentUser.role);
|
||||
c.innerHTML = `<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">` +
|
||||
consumablesList.map(item => {
|
||||
const catLabel = CONSUMABLE_CATEGORIES[item.category] || item.category;
|
||||
const catColor = CONSUMABLE_CAT_COLORS[item.category] || 'bg-gray-50 text-gray-600';
|
||||
const price = item.base_price ? Number(item.base_price).toLocaleString() + '원' : '-';
|
||||
return `<div class="bg-white border rounded-lg p-3 hover:shadow-md transition-shadow">
|
||||
<div class="flex gap-3">
|
||||
${item.photo_path
|
||||
? `<img src="${item.photo_path}" class="w-16 h-16 rounded object-cover flex-shrink-0 cursor-pointer" onclick="document.getElementById('photoViewImage').src=this.src; document.getElementById('photoViewModal').classList.remove('hidden');" onerror="this.style.display='none'">`
|
||||
: `<div class="w-16 h-16 rounded bg-gray-100 flex items-center justify-center flex-shrink-0"><i class="fas fa-box text-gray-300 text-xl"></i></div>`}
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="text-sm font-medium text-gray-800 truncate">${escHtml(item.item_name)}</div>
|
||||
<div class="text-xs text-gray-500 mt-0.5">${escHtml(item.maker) || '-'}</div>
|
||||
<div class="flex items-center gap-2 mt-1">
|
||||
<span class="px-1.5 py-0.5 rounded text-xs ${catColor}">${catLabel}</span>
|
||||
<span class="text-xs text-gray-600 font-medium">${price}</span>
|
||||
<span class="text-xs text-gray-400">${escHtml(item.unit) || 'EA'}</span>
|
||||
</div>
|
||||
${!item.is_active ? '<span class="px-1.5 py-0.5 rounded text-xs bg-gray-100 text-gray-400 mt-1 inline-block">비활성</span>' : ''}
|
||||
</div>
|
||||
</div>
|
||||
${isAdmin ? `<div class="flex justify-end gap-1 mt-2 pt-2 border-t">
|
||||
<button onclick="openEditConsumableTkuser(${item.item_id})" class="px-2 py-1 text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded text-xs"><i class="fas fa-pen mr-1"></i>수정</button>
|
||||
${item.is_active ? `<button onclick="deactivateConsumableTkuser(${item.item_id}, '${escHtml(item.item_name).replace(/'/g, "\\'")}')" class="px-2 py-1 text-red-400 hover:text-red-600 hover:bg-red-50 rounded text-xs"><i class="fas fa-ban mr-1"></i>비활성화</button>` : ''}
|
||||
</div>` : ''}
|
||||
</div>`;
|
||||
}).join('') + `</div>`;
|
||||
}
|
||||
|
||||
/* ===== 소모품 등록 ===== */
|
||||
function openAddConsumableTkuser() {
|
||||
document.getElementById('addConsumablePhotoPreviewTkuser').innerHTML = '';
|
||||
document.getElementById('addConsumableModalTkuser').classList.remove('hidden');
|
||||
}
|
||||
function closeAddConsumableTkuser() { document.getElementById('addConsumableModalTkuser').classList.add('hidden'); document.getElementById('addConsumableFormTkuser').reset(); document.getElementById('addConsumablePhotoPreviewTkuser').innerHTML = ''; }
|
||||
|
||||
function previewAddConsumablePhoto() {
|
||||
const file = document.getElementById('newConsumablePhotoTkuser').files[0];
|
||||
const preview = document.getElementById('addConsumablePhotoPreviewTkuser');
|
||||
if (!file) { preview.innerHTML = ''; return; }
|
||||
const reader = new FileReader();
|
||||
reader.onload = e => { preview.innerHTML = `<img src="${e.target.result}" class="w-20 h-20 rounded object-cover">`; };
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
async function submitAddConsumableTkuser(e) {
|
||||
e.preventDefault();
|
||||
const itemName = document.getElementById('newConsumableNameTkuser').value.trim();
|
||||
const category = document.getElementById('newConsumableCategoryTkuser').value;
|
||||
if (!itemName) { showToast('품명은 필수입니다', 'error'); return; }
|
||||
if (!category) { showToast('분류는 필수입니다', 'error'); return; }
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('item_name', itemName);
|
||||
fd.append('maker', document.getElementById('newConsumableMakerTkuser').value.trim());
|
||||
fd.append('category', category);
|
||||
fd.append('base_price', document.getElementById('newConsumablePriceTkuser').value || '0');
|
||||
fd.append('unit', document.getElementById('newConsumableUnitTkuser').value.trim() || 'EA');
|
||||
const photoFile = document.getElementById('newConsumablePhotoTkuser').files[0];
|
||||
if (photoFile) fd.append('photo', photoFile);
|
||||
|
||||
try {
|
||||
const token = getToken();
|
||||
const res = await fetch('/api/consumable-items', {
|
||||
method: 'POST',
|
||||
headers: { 'Authorization': `Bearer ${token}` },
|
||||
body: fd
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || '등록 실패');
|
||||
showToast('소모품이 등록되었습니다');
|
||||
closeAddConsumableTkuser();
|
||||
await loadConsumablesList();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
/* ===== 소모품 수정 ===== */
|
||||
function openEditConsumableTkuser(id) {
|
||||
const item = consumablesList.find(x => x.item_id === id);
|
||||
if (!item) return;
|
||||
document.getElementById('editConsumableIdTkuser').value = item.item_id;
|
||||
document.getElementById('editConsumableNameTkuser').value = item.item_name;
|
||||
document.getElementById('editConsumableMakerTkuser').value = item.maker || '';
|
||||
document.getElementById('editConsumableCategoryTkuser').value = item.category;
|
||||
document.getElementById('editConsumablePriceTkuser').value = item.base_price || '';
|
||||
document.getElementById('editConsumableUnitTkuser').value = item.unit || 'EA';
|
||||
const preview = document.getElementById('editConsumablePhotoPreviewTkuser');
|
||||
preview.innerHTML = item.photo_path ? `<img src="${item.photo_path}" class="w-20 h-20 rounded object-cover">` : '';
|
||||
document.getElementById('editConsumablePhotoTkuser').value = '';
|
||||
document.getElementById('editConsumableModalTkuser').classList.remove('hidden');
|
||||
}
|
||||
function closeEditConsumableTkuser() { document.getElementById('editConsumableModalTkuser').classList.add('hidden'); }
|
||||
|
||||
function previewEditConsumablePhoto() {
|
||||
const file = document.getElementById('editConsumablePhotoTkuser').files[0];
|
||||
const preview = document.getElementById('editConsumablePhotoPreviewTkuser');
|
||||
if (!file) return;
|
||||
const reader = new FileReader();
|
||||
reader.onload = e => { preview.innerHTML = `<img src="${e.target.result}" class="w-20 h-20 rounded object-cover">`; };
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
async function submitEditConsumableTkuser(e) {
|
||||
e.preventDefault();
|
||||
const id = document.getElementById('editConsumableIdTkuser').value;
|
||||
const fd = new FormData();
|
||||
fd.append('item_name', document.getElementById('editConsumableNameTkuser').value.trim());
|
||||
fd.append('maker', document.getElementById('editConsumableMakerTkuser').value.trim());
|
||||
fd.append('category', document.getElementById('editConsumableCategoryTkuser').value);
|
||||
fd.append('base_price', document.getElementById('editConsumablePriceTkuser').value || '0');
|
||||
fd.append('unit', document.getElementById('editConsumableUnitTkuser').value.trim() || 'EA');
|
||||
const photoFile = document.getElementById('editConsumablePhotoTkuser').files[0];
|
||||
if (photoFile) fd.append('photo', photoFile);
|
||||
|
||||
try {
|
||||
const token = getToken();
|
||||
const res = await fetch(`/api/consumable-items/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Authorization': `Bearer ${token}` },
|
||||
body: fd
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || '수정 실패');
|
||||
showToast('수정되었습니다');
|
||||
closeEditConsumableTkuser();
|
||||
await loadConsumablesList();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
/* ===== 소모품 비활성화 ===== */
|
||||
async function deactivateConsumableTkuser(id, name) {
|
||||
if (!confirm(`"${name}" 소모품을 비활성화하시겠습니까?`)) return;
|
||||
try {
|
||||
await api(`/consumable-items/${id}`, { method: 'DELETE' });
|
||||
showToast('비활성화 완료');
|
||||
await loadConsumablesList();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
// 검색/필터 이벤트 + 모달 폼 이벤트
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
let searchTimeout;
|
||||
const searchEl = document.getElementById('consumableSearchTkuser');
|
||||
if (searchEl) searchEl.addEventListener('input', () => {
|
||||
clearTimeout(searchTimeout);
|
||||
searchTimeout = setTimeout(loadConsumablesList, 300);
|
||||
});
|
||||
const filterCatEl = document.getElementById('consumableFilterCategoryTkuser');
|
||||
if (filterCatEl) filterCatEl.addEventListener('change', loadConsumablesList);
|
||||
const filterActiveEl = document.getElementById('consumableFilterActiveTkuser');
|
||||
if (filterActiveEl) filterActiveEl.addEventListener('change', loadConsumablesList);
|
||||
|
||||
document.getElementById('addConsumableFormTkuser')?.addEventListener('submit', submitAddConsumableTkuser);
|
||||
document.getElementById('editConsumableFormTkuser')?.addEventListener('submit', submitEditConsumableTkuser);
|
||||
});
|
||||
@@ -29,5 +29,7 @@ function switchTab(name) {
|
||||
if (name === 'issueTypes' && !issueTypesLoaded) loadIssueTypes();
|
||||
if (name === 'permissions' && !permissionsTabLoaded) loadPermissionsTab();
|
||||
if (name === 'partners' && !partnersLoaded) loadPartnersTab();
|
||||
if (name === 'vendors' && !vendorsLoaded) loadVendorsTab();
|
||||
if (name === 'consumables' && !consumablesLoaded) loadConsumablesTab();
|
||||
if (name === 'notificationRecipients' && !nrLoaded) loadNotificationRecipientsTab();
|
||||
}
|
||||
|
||||
@@ -246,7 +246,23 @@ function openVacBalanceModal(editId) {
|
||||
// 작업자 셀렉트
|
||||
const wSel = document.getElementById('vbWorker');
|
||||
wSel.innerHTML = '<option value="">선택</option>';
|
||||
vacWorkers.forEach(w => { wSel.innerHTML += `<option value="${w.worker_id}">${escapeHtml(w.worker_name)}</option>`; });
|
||||
const byDept = {};
|
||||
vacWorkers.forEach(w => {
|
||||
const dept = w.department_name || '부서 미지정';
|
||||
if (!byDept[dept]) byDept[dept] = [];
|
||||
byDept[dept].push(w);
|
||||
});
|
||||
Object.keys(byDept).sort().forEach(dept => {
|
||||
const group = document.createElement('optgroup');
|
||||
group.label = dept;
|
||||
byDept[dept].forEach(w => {
|
||||
const o = document.createElement('option');
|
||||
o.value = w.worker_id;
|
||||
o.textContent = w.worker_name;
|
||||
group.appendChild(o);
|
||||
});
|
||||
wSel.appendChild(group);
|
||||
});
|
||||
// 유형 셀렉트
|
||||
const tSel = document.getElementById('vbType');
|
||||
tSel.innerHTML = '<option value="">선택</option>';
|
||||
|
||||
183
user-management/web/static/js/tkuser-vendors.js
Normal file
183
user-management/web/static/js/tkuser-vendors.js
Normal file
@@ -0,0 +1,183 @@
|
||||
/* ===== tkuser 업체(공급업체) CRUD ===== */
|
||||
let vendorsLoaded = false;
|
||||
let vendorsList = [];
|
||||
let selectedVendorIdTkuser = null;
|
||||
|
||||
async function loadVendorsTab() {
|
||||
if (vendorsLoaded) return;
|
||||
vendorsLoaded = true;
|
||||
if (currentUser && ['admin', 'system'].includes(currentUser.role)) {
|
||||
document.getElementById('btnAddVendorTkuser')?.classList.remove('hidden');
|
||||
}
|
||||
await loadVendorsList();
|
||||
}
|
||||
|
||||
async function loadVendorsList() {
|
||||
try {
|
||||
const isActive = document.getElementById('vendorFilterActiveTkuser')?.value;
|
||||
const search = document.getElementById('vendorSearchTkuser')?.value?.trim() || '';
|
||||
const params = new URLSearchParams();
|
||||
if (isActive !== '' && isActive !== undefined) params.set('is_active', isActive);
|
||||
if (search) params.set('search', search);
|
||||
const r = await api('/vendors?' + params.toString());
|
||||
vendorsList = r.data || [];
|
||||
renderVendorsListTkuser();
|
||||
} catch (e) {
|
||||
document.getElementById('vendorsListTkuser').innerHTML = `<div class="text-red-500 text-center py-6"><i class="fas fa-exclamation-triangle text-xl"></i><p class="text-sm mt-2">${e.message}</p></div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderVendorsListTkuser() {
|
||||
const c = document.getElementById('vendorsListTkuser');
|
||||
if (!vendorsList.length) {
|
||||
c.innerHTML = '<p class="text-gray-400 text-center py-4 text-sm">등록된 업체가 없습니다.</p>';
|
||||
return;
|
||||
}
|
||||
const isAdmin = currentUser && ['admin', 'system'].includes(currentUser.role);
|
||||
c.innerHTML = vendorsList.map(v => {
|
||||
return `<div class="flex items-center justify-between p-2.5 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer ${selectedVendorIdTkuser === v.vendor_id ? 'ring-2 ring-indigo-400' : ''}" onclick="selectVendorTkuser(${v.vendor_id})">
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="text-sm font-medium text-gray-800 truncate">
|
||||
<i class="fas fa-store mr-1.5 text-gray-400 text-xs"></i>${escHtml(v.vendor_name)}
|
||||
${!v.is_active ? '<span class="px-1.5 py-0.5 rounded text-xs bg-gray-100 text-gray-400 ml-1">비활성</span>' : ''}
|
||||
</div>
|
||||
<div class="text-xs text-gray-500 flex items-center gap-1.5 mt-0.5">
|
||||
${v.business_number ? `<span>${escHtml(v.business_number)}</span>` : ''}
|
||||
${v.contact_name ? `<span>${escHtml(v.contact_name)}</span>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
${isAdmin ? `<div class="flex gap-1 ml-2 flex-shrink-0">
|
||||
<button onclick="event.stopPropagation(); openEditVendorTkuser(${v.vendor_id})" class="p-1.5 text-slate-500 hover:text-slate-700 hover:bg-slate-200 rounded" title="수정"><i class="fas fa-pen text-xs"></i></button>
|
||||
${v.is_active ? `<button onclick="event.stopPropagation(); deactivateVendorTkuser(${v.vendor_id}, '${escHtml(v.vendor_name).replace(/'/g, "\\'")}')" class="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-100 rounded" title="비활성화"><i class="fas fa-ban text-xs"></i></button>` : ''}
|
||||
</div>` : ''}
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
async function selectVendorTkuser(id) {
|
||||
selectedVendorIdTkuser = id;
|
||||
renderVendorsListTkuser();
|
||||
try {
|
||||
const r = await api(`/vendors/${id}`);
|
||||
const v = r.data;
|
||||
renderVendorDetailTkuser(v);
|
||||
document.getElementById('vendorDetailTkuser').classList.remove('hidden');
|
||||
document.getElementById('vendorEmptyTkuser').classList.add('hidden');
|
||||
} catch (e) {
|
||||
showToast('상세 조회 실패: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function renderVendorDetailTkuser(v) {
|
||||
document.getElementById('vendorDetailTkuser').innerHTML = `
|
||||
<div class="bg-white rounded-xl shadow-sm p-5">
|
||||
<h3 class="text-lg font-semibold text-gray-800 mb-3">${escHtml(v.vendor_name)}</h3>
|
||||
<div class="grid grid-cols-2 gap-3 text-sm">
|
||||
<div><span class="text-gray-500">사업자번호:</span> <span class="font-medium">${escHtml(v.business_number) || '-'}</span></div>
|
||||
<div><span class="text-gray-500">대표자:</span> <span class="font-medium">${escHtml(v.representative) || '-'}</span></div>
|
||||
<div><span class="text-gray-500">담당자:</span> <span class="font-medium">${escHtml(v.contact_name) || '-'}</span></div>
|
||||
<div><span class="text-gray-500">연락처:</span> <span class="font-medium">${escHtml(v.contact_phone) || '-'}</span></div>
|
||||
<div class="col-span-2"><span class="text-gray-500">주소:</span> <span class="font-medium">${escHtml(v.address) || '-'}</span></div>
|
||||
<div><span class="text-gray-500">은행:</span> <span class="font-medium">${escHtml(v.bank_name) || '-'}</span></div>
|
||||
<div><span class="text-gray-500">계좌번호:</span> <span class="font-medium">${escHtml(v.bank_account) || '-'}</span></div>
|
||||
${v.notes ? `<div class="col-span-2"><span class="text-gray-500">비고:</span> ${escHtml(v.notes)}</div>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/* ===== 업체 등록 ===== */
|
||||
function openAddVendorTkuser() { document.getElementById('addVendorModalTkuser').classList.remove('hidden'); }
|
||||
function closeAddVendorTkuser() { document.getElementById('addVendorModalTkuser').classList.add('hidden'); document.getElementById('addVendorFormTkuser').reset(); }
|
||||
|
||||
async function submitAddVendorTkuser(e) {
|
||||
e.preventDefault();
|
||||
const data = {
|
||||
vendor_name: document.getElementById('newVendorNameTkuser').value.trim(),
|
||||
business_number: document.getElementById('newVendorBizNumTkuser').value.trim() || null,
|
||||
representative: document.getElementById('newVendorRepTkuser').value.trim() || null,
|
||||
contact_name: document.getElementById('newVendorContactNameTkuser').value.trim() || null,
|
||||
contact_phone: document.getElementById('newVendorContactPhoneTkuser').value.trim() || null,
|
||||
address: document.getElementById('newVendorAddressTkuser').value.trim() || null,
|
||||
bank_name: document.getElementById('newVendorBankNameTkuser').value.trim() || null,
|
||||
bank_account: document.getElementById('newVendorBankAccountTkuser').value.trim() || null,
|
||||
notes: document.getElementById('newVendorNotesTkuser').value.trim() || null,
|
||||
};
|
||||
if (!data.vendor_name) { showToast('업체명은 필수입니다', 'error'); return; }
|
||||
try {
|
||||
await api('/vendors', { method: 'POST', body: JSON.stringify(data) });
|
||||
showToast('업체가 등록되었습니다');
|
||||
closeAddVendorTkuser();
|
||||
await loadVendorsList();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
/* ===== 업체 수정 ===== */
|
||||
function openEditVendorTkuser(id) {
|
||||
const v = vendorsList.find(x => x.vendor_id === id);
|
||||
if (!v) return;
|
||||
document.getElementById('editVendorIdTkuser').value = v.vendor_id;
|
||||
document.getElementById('editVendorNameTkuser').value = v.vendor_name;
|
||||
document.getElementById('editVendorBizNumTkuser').value = v.business_number || '';
|
||||
document.getElementById('editVendorRepTkuser').value = v.representative || '';
|
||||
document.getElementById('editVendorContactNameTkuser').value = v.contact_name || '';
|
||||
document.getElementById('editVendorContactPhoneTkuser').value = v.contact_phone || '';
|
||||
document.getElementById('editVendorAddressTkuser').value = v.address || '';
|
||||
document.getElementById('editVendorBankNameTkuser').value = v.bank_name || '';
|
||||
document.getElementById('editVendorBankAccountTkuser').value = v.bank_account || '';
|
||||
document.getElementById('editVendorNotesTkuser').value = v.notes || '';
|
||||
document.getElementById('editVendorModalTkuser').classList.remove('hidden');
|
||||
}
|
||||
function closeEditVendorTkuser() { document.getElementById('editVendorModalTkuser').classList.add('hidden'); }
|
||||
|
||||
async function submitEditVendorTkuser(e) {
|
||||
e.preventDefault();
|
||||
const id = document.getElementById('editVendorIdTkuser').value;
|
||||
const data = {
|
||||
vendor_name: document.getElementById('editVendorNameTkuser').value.trim(),
|
||||
business_number: document.getElementById('editVendorBizNumTkuser').value.trim() || null,
|
||||
representative: document.getElementById('editVendorRepTkuser').value.trim() || null,
|
||||
contact_name: document.getElementById('editVendorContactNameTkuser').value.trim() || null,
|
||||
contact_phone: document.getElementById('editVendorContactPhoneTkuser').value.trim() || null,
|
||||
address: document.getElementById('editVendorAddressTkuser').value.trim() || null,
|
||||
bank_name: document.getElementById('editVendorBankNameTkuser').value.trim() || null,
|
||||
bank_account: document.getElementById('editVendorBankAccountTkuser').value.trim() || null,
|
||||
notes: document.getElementById('editVendorNotesTkuser').value.trim() || null,
|
||||
};
|
||||
try {
|
||||
await api(`/vendors/${id}`, { method: 'PUT', body: JSON.stringify(data) });
|
||||
showToast('수정되었습니다');
|
||||
closeEditVendorTkuser();
|
||||
await loadVendorsList();
|
||||
if (selectedVendorIdTkuser == id) selectVendorTkuser(id);
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
/* ===== 업체 비활성화 ===== */
|
||||
async function deactivateVendorTkuser(id, name) {
|
||||
if (!confirm(`"${name}" 업체를 비활성화하시겠습니까?`)) return;
|
||||
try {
|
||||
await api(`/vendors/${id}`, { method: 'DELETE' });
|
||||
showToast('비활성화 완료');
|
||||
await loadVendorsList();
|
||||
if (selectedVendorIdTkuser === id) {
|
||||
document.getElementById('vendorDetailTkuser').classList.add('hidden');
|
||||
document.getElementById('vendorEmptyTkuser').classList.remove('hidden');
|
||||
selectedVendorIdTkuser = null;
|
||||
}
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
// 검색/필터 이벤트 + 모달 폼 이벤트
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
let searchTimeout;
|
||||
const searchEl = document.getElementById('vendorSearchTkuser');
|
||||
if (searchEl) searchEl.addEventListener('input', () => {
|
||||
clearTimeout(searchTimeout);
|
||||
searchTimeout = setTimeout(loadVendorsList, 300);
|
||||
});
|
||||
const filterEl = document.getElementById('vendorFilterActiveTkuser');
|
||||
if (filterEl) filterEl.addEventListener('change', loadVendorsList);
|
||||
|
||||
document.getElementById('addVendorFormTkuser')?.addEventListener('submit', submitAddVendorTkuser);
|
||||
document.getElementById('editVendorFormTkuser')?.addEventListener('submit', submitEditVendorTkuser);
|
||||
});
|
||||
Reference in New Issue
Block a user