feat(purchase): 생산소모품 구매 관리 시스템 구현
tkuser: 업체(공급업체) CRUD + 소모품 마스터 CRUD (사진 업로드 포함) tkfb: 구매신청 → 구매 처리 → 월간 분석/정산 전체 워크플로 설비(equipment) 분류 구매 시 자동 등록 + 실패 시 admin 알림 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
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;
|
||||
Reference in New Issue
Block a user