feat(purchase): 소모품 신청 시스템 v2 — 모바일 최적화, 스마트 검색, 그룹화, 입고 알림
- 4단계 상태 플로우: pending → grouped → purchased → received - 한국어 스마트 검색: 초성 매칭(ㅁㅈㄱ→면장갑), 별칭 테이블, 인메모리 캐시 - 모바일 전용 신청 페이지: 바텀시트 UI, FAB, 카드 리스트, 스크롤 페이지네이션 - 인라인 품목 등록: 미등록 품목 검색→등록→신청 단일 트랜잭션 - 관리자 그룹화: 체크박스 다중 선택, 구매 그룹(batch) 생성/일괄 구매/입고 - 입고 처리: 사진+보관위치 등록, 부분 입고 허용, batch 자동 상태 전환 - 알림: notifyHelper에 target_user_ids 추가, 구매진행중/입고완료 시 신청자 ntfy+push Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -9,13 +9,14 @@ const notifyHelper = {
|
||||
/**
|
||||
* 알림 전송
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.type - 알림 유형 (safety, maintenance, repair, system)
|
||||
* @param {string} opts.type - 알림 유형 (safety, maintenance, repair, system, purchase)
|
||||
* @param {string} opts.title - 알림 제목
|
||||
* @param {string} [opts.message] - 알림 내용
|
||||
* @param {string} [opts.link_url] - 클릭 시 이동 URL
|
||||
* @param {string} [opts.reference_type] - 연관 테이블명
|
||||
* @param {number} [opts.reference_id] - 연관 레코드 ID
|
||||
* @param {number} [opts.created_by] - 생성자 user_id
|
||||
* @param {number[]} [opts.target_user_ids] - 특정 사용자 직접 알림 (생략 시 type 기반 브로드캐스트)
|
||||
*/
|
||||
async send(opts) {
|
||||
try {
|
||||
|
||||
@@ -53,6 +53,8 @@ function setupRoutes(app) {
|
||||
const purchaseRequestRoutes = require('../routes/purchaseRequestRoutes');
|
||||
const purchaseRoutes = require('../routes/purchaseRoutes');
|
||||
const settlementRoutes = require('../routes/settlementRoutes');
|
||||
const itemAliasRoutes = require('../routes/itemAliasRoutes');
|
||||
const purchaseBatchRoutes = require('../routes/purchaseBatchRoutes');
|
||||
const scheduleRoutes = require('../routes/scheduleRoutes');
|
||||
const meetingRoutes = require('../routes/meetingRoutes');
|
||||
const proxyInputRoutes = require('../routes/proxyInputRoutes');
|
||||
@@ -166,6 +168,8 @@ function setupRoutes(app) {
|
||||
app.use('/api/purchase-requests', purchaseRequestRoutes); // 구매신청
|
||||
app.use('/api/purchases', purchaseRoutes); // 구매 내역
|
||||
app.use('/api/settlements', settlementRoutes); // 월간 정산
|
||||
app.use('/api/item-aliases', itemAliasRoutes); // 품목 별칭
|
||||
app.use('/api/purchase-batches', purchaseBatchRoutes); // 구매 그룹
|
||||
app.use('/api/schedule', scheduleRoutes); // 공정표
|
||||
app.use('/api/meetings', meetingRoutes); // 생산회의록
|
||||
app.use('/api/proxy-input', proxyInputRoutes); // 대리입력 + 일별현황
|
||||
|
||||
47
system1-factory/api/controllers/itemAliasController.js
Normal file
47
system1-factory/api/controllers/itemAliasController.js
Normal file
@@ -0,0 +1,47 @@
|
||||
const ItemAliasModel = require('../models/itemAliasModel');
|
||||
const koreanSearch = require('../utils/koreanSearch');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
const ItemAliasController = {
|
||||
getAll: async (req, res) => {
|
||||
try {
|
||||
const rows = await ItemAliasModel.getAll();
|
||||
res.json({ success: true, data: rows });
|
||||
} catch (err) {
|
||||
logger.error('ItemAlias getAll error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
create: async (req, res) => {
|
||||
try {
|
||||
const { item_id, alias_name } = req.body;
|
||||
if (!item_id || !alias_name || !alias_name.trim()) {
|
||||
return res.status(400).json({ success: false, message: '품목 ID와 별칭을 입력해주세요.' });
|
||||
}
|
||||
const id = await ItemAliasModel.create(item_id, alias_name);
|
||||
koreanSearch.clearCache();
|
||||
res.status(201).json({ success: true, data: { alias_id: id }, message: '별칭이 등록되었습니다.' });
|
||||
} catch (err) {
|
||||
if (err.code === 'ER_DUP_ENTRY') {
|
||||
return res.status(400).json({ success: false, message: '이미 등록된 별칭입니다.' });
|
||||
}
|
||||
logger.error('ItemAlias create error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
delete: async (req, res) => {
|
||||
try {
|
||||
const deleted = await ItemAliasModel.delete(req.params.id);
|
||||
if (!deleted) return res.status(404).json({ success: false, message: '별칭을 찾을 수 없습니다.' });
|
||||
koreanSearch.clearCache();
|
||||
res.json({ success: true, message: '별칭이 삭제되었습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('ItemAlias delete error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = ItemAliasController;
|
||||
175
system1-factory/api/controllers/purchaseBatchController.js
Normal file
175
system1-factory/api/controllers/purchaseBatchController.js
Normal file
@@ -0,0 +1,175 @@
|
||||
const PurchaseBatchModel = require('../models/purchaseBatchModel');
|
||||
const PurchaseRequestModel = require('../models/purchaseRequestModel');
|
||||
const { saveBase64Image } = require('../services/imageUploadService');
|
||||
const logger = require('../utils/logger');
|
||||
const notifyHelper = require('../../../shared/utils/notifyHelper');
|
||||
|
||||
const PurchaseBatchController = {
|
||||
getAll: async (req, res) => {
|
||||
try {
|
||||
const { status } = req.query;
|
||||
const rows = await PurchaseBatchModel.getAll({ status });
|
||||
res.json({ success: true, data: rows });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseBatch getAll error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
getById: async (req, res) => {
|
||||
try {
|
||||
const batch = await PurchaseBatchModel.getById(req.params.id);
|
||||
if (!batch) return res.status(404).json({ success: false, message: '그룹을 찾을 수 없습니다.' });
|
||||
// 포함된 요청 목록도 함께 반환
|
||||
const requests = await PurchaseRequestModel.getAll({ batch_id: req.params.id });
|
||||
res.json({ success: true, data: { ...batch, requests } });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseBatch getById error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 그룹 생성 + 요청 포함
|
||||
create: async (req, res) => {
|
||||
try {
|
||||
const { batch_name, category, vendor_id, notes, request_ids } = req.body;
|
||||
if (!request_ids || !request_ids.length) {
|
||||
return res.status(400).json({ success: false, message: '그룹에 포함할 신청 건을 선택해주세요.' });
|
||||
}
|
||||
|
||||
const batchId = await PurchaseBatchModel.create({
|
||||
batchName: batch_name,
|
||||
category,
|
||||
vendorId: vendor_id,
|
||||
notes,
|
||||
createdBy: req.user.id
|
||||
});
|
||||
|
||||
await PurchaseBatchModel.addRequests(batchId, request_ids);
|
||||
|
||||
// 신청자들에게 알림
|
||||
const requesterIds = await PurchaseRequestModel.getRequesterIdsByBatch(batchId);
|
||||
if (requesterIds.length > 0) {
|
||||
notifyHelper.send({
|
||||
type: 'purchase',
|
||||
title: '구매 진행 안내',
|
||||
message: '신청하신 소모품 구매가 진행됩니다.',
|
||||
link_url: '/pages/purchase/request-mobile.html',
|
||||
target_user_ids: requesterIds,
|
||||
created_by: req.user.id
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
const batch = await PurchaseBatchModel.getById(batchId);
|
||||
res.status(201).json({ success: true, data: batch, message: '그룹이 생성되었습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseBatch create error:', err);
|
||||
res.status(400).json({ success: false, message: err.message || '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
update: async (req, res) => {
|
||||
try {
|
||||
const { batch_name, category, vendor_id, notes, add_request_ids, remove_request_ids } = req.body;
|
||||
const batch = await PurchaseBatchModel.getById(req.params.id);
|
||||
if (!batch) return res.status(404).json({ success: false, message: '그룹을 찾을 수 없습니다.' });
|
||||
|
||||
if (batch_name !== undefined || category !== undefined || vendor_id !== undefined || notes !== undefined) {
|
||||
await PurchaseBatchModel.update(req.params.id, {
|
||||
batchName: batch_name !== undefined ? batch_name : batch.batch_name,
|
||||
category: category !== undefined ? category : batch.category,
|
||||
vendorId: vendor_id !== undefined ? vendor_id : batch.vendor_id,
|
||||
notes: notes !== undefined ? notes : batch.notes
|
||||
});
|
||||
}
|
||||
|
||||
if (add_request_ids && add_request_ids.length) {
|
||||
await PurchaseBatchModel.addRequests(req.params.id, add_request_ids);
|
||||
}
|
||||
if (remove_request_ids && remove_request_ids.length) {
|
||||
await PurchaseBatchModel.removeRequests(req.params.id, remove_request_ids);
|
||||
}
|
||||
|
||||
const updated = await PurchaseBatchModel.getById(req.params.id);
|
||||
res.json({ success: true, data: updated, message: '그룹이 수정되었습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseBatch update error:', err);
|
||||
res.status(400).json({ success: false, message: err.message || '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
delete: async (req, res) => {
|
||||
try {
|
||||
const deleted = await PurchaseBatchModel.delete(req.params.id);
|
||||
if (!deleted) return res.status(400).json({ success: false, message: '대기 상태의 그룹만 삭제할 수 있습니다.' });
|
||||
res.json({ success: true, message: '그룹이 삭제되었습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseBatch delete error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 그룹 일괄 구매 처리
|
||||
purchase: async (req, res) => {
|
||||
try {
|
||||
const batch = await PurchaseBatchModel.getById(req.params.id);
|
||||
if (!batch) return res.status(404).json({ success: false, message: '그룹을 찾을 수 없습니다.' });
|
||||
if (batch.status !== 'pending') {
|
||||
return res.status(400).json({ success: false, message: '대기 상태의 그룹만 구매 처리할 수 있습니다.' });
|
||||
}
|
||||
|
||||
// batch 내 모든 요청 purchased 전환
|
||||
await PurchaseRequestModel.markBatchPurchased(req.params.id);
|
||||
await PurchaseBatchModel.markPurchased(req.params.id, req.user.id);
|
||||
|
||||
res.json({ success: true, message: '일괄 구매 처리가 완료되었습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseBatch purchase error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 그룹 일괄 입고 처리
|
||||
receive: async (req, res) => {
|
||||
try {
|
||||
const batch = await PurchaseBatchModel.getById(req.params.id);
|
||||
if (!batch) return res.status(404).json({ success: false, message: '그룹을 찾을 수 없습니다.' });
|
||||
if (batch.status !== 'purchased') {
|
||||
return res.status(400).json({ success: false, message: '구매완료 상태의 그룹만 입고 처리할 수 있습니다.' });
|
||||
}
|
||||
|
||||
const { received_location, photo } = req.body;
|
||||
let receivedPhotoPath = null;
|
||||
if (photo) {
|
||||
receivedPhotoPath = await saveBase64Image(photo, 'received', 'purchase_received');
|
||||
}
|
||||
|
||||
await PurchaseRequestModel.receiveBatch(req.params.id, {
|
||||
receivedPhotoPath,
|
||||
receivedLocation: received_location,
|
||||
receivedBy: req.user.id
|
||||
});
|
||||
await PurchaseBatchModel.markReceived(req.params.id, req.user.id);
|
||||
|
||||
// 신청자들에게 입고 알림
|
||||
const requesterIds = await PurchaseRequestModel.getRequesterIdsByBatch(req.params.id);
|
||||
if (requesterIds.length > 0) {
|
||||
notifyHelper.send({
|
||||
type: 'purchase',
|
||||
title: '소모품 입고 완료',
|
||||
message: `소모품이 입고되었습니다.${received_location ? ' 보관위치: ' + received_location : ''}`,
|
||||
link_url: '/pages/purchase/request-mobile.html',
|
||||
target_user_ids: requesterIds,
|
||||
created_by: req.user.id
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
res.json({ success: true, message: '일괄 입고 처리가 완료되었습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseBatch receive error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = PurchaseBatchController;
|
||||
@@ -2,14 +2,16 @@ const PurchaseRequestModel = require('../models/purchaseRequestModel');
|
||||
const PurchaseModel = require('../models/purchaseModel');
|
||||
const { saveBase64Image } = require('../services/imageUploadService');
|
||||
const logger = require('../utils/logger');
|
||||
const notifyHelper = require('../../../shared/utils/notifyHelper');
|
||||
const koreanSearch = require('../utils/koreanSearch');
|
||||
|
||||
const PurchaseRequestController = {
|
||||
// 구매신청 목록
|
||||
getAll: async (req, res) => {
|
||||
try {
|
||||
const { status, category, from_date, to_date } = req.query;
|
||||
const { status, category, from_date, to_date, batch_id } = req.query;
|
||||
const isAdmin = req.user && ['admin', 'system'].includes(req.user.access_level);
|
||||
const filters = { status, category, from_date, to_date };
|
||||
const filters = { status, category, from_date, to_date, batch_id };
|
||||
if (!isAdmin) filters.requester_id = req.user.id;
|
||||
const rows = await PurchaseRequestModel.getAll(filters);
|
||||
res.json({ success: true, data: rows });
|
||||
@@ -113,6 +115,83 @@ const PurchaseRequestController = {
|
||||
}
|
||||
},
|
||||
|
||||
// 품목 등록 + 신청 동시 처리 (단일 트랜잭션)
|
||||
registerAndRequest: async (req, res) => {
|
||||
const { getDb } = require('../dbPool');
|
||||
let conn;
|
||||
try {
|
||||
const { item_name, spec, maker, category, quantity, notes, photo } = req.body;
|
||||
if (!item_name || !item_name.trim()) {
|
||||
return res.status(400).json({ success: false, message: '품목명을 입력해주세요.' });
|
||||
}
|
||||
if (!quantity || quantity < 1) {
|
||||
return res.status(400).json({ success: false, message: '수량은 1 이상이어야 합니다.' });
|
||||
}
|
||||
|
||||
const db = await getDb();
|
||||
conn = await db.getConnection();
|
||||
await conn.beginTransaction();
|
||||
|
||||
// 1. 소모품 마스터 등록 (중복 확인)
|
||||
const [existing] = await conn.query(
|
||||
`SELECT item_id FROM consumable_items
|
||||
WHERE item_name = ? AND (spec = ? OR (spec IS NULL AND ? IS NULL))
|
||||
AND (maker = ? OR (maker IS NULL AND ? IS NULL))`,
|
||||
[item_name.trim(), spec || null, spec || null, maker || null, maker || null]
|
||||
);
|
||||
|
||||
let itemId;
|
||||
if (existing.length > 0) {
|
||||
itemId = existing[0].item_id;
|
||||
} else {
|
||||
const [insertResult] = await conn.query(
|
||||
`INSERT INTO consumable_items (item_name, spec, maker, category, is_active) VALUES (?, ?, ?, ?, 1)`,
|
||||
[item_name.trim(), spec || null, maker || null, category || 'consumable']
|
||||
);
|
||||
itemId = insertResult.insertId;
|
||||
}
|
||||
|
||||
// 2. 사진 업로드 (트랜잭션 외부 — 파일 저장은 DB 롤백 불가이므로 마지막에)
|
||||
let photo_path = null;
|
||||
if (photo) {
|
||||
photo_path = await saveBase64Image(photo, 'pr', 'purchase_requests');
|
||||
}
|
||||
|
||||
// 3. 구매 신청 생성
|
||||
const [reqResult] = await conn.query(
|
||||
`INSERT INTO purchase_requests (item_id, quantity, requester_id, request_date, notes, photo_path)
|
||||
VALUES (?, ?, ?, CURDATE(), ?, ?)`,
|
||||
[itemId, quantity, req.user.id, notes || null, photo_path]
|
||||
);
|
||||
|
||||
await conn.commit();
|
||||
|
||||
// 검색 캐시 무효화
|
||||
koreanSearch.clearCache();
|
||||
|
||||
const request = await PurchaseRequestModel.getById(reqResult.insertId);
|
||||
res.status(201).json({ success: true, data: request, message: '품목 등록 및 신청이 완료되었습니다.' });
|
||||
} catch (err) {
|
||||
if (conn) await conn.rollback().catch(() => {});
|
||||
logger.error('registerAndRequest error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
} finally {
|
||||
if (conn) conn.release();
|
||||
}
|
||||
},
|
||||
|
||||
// 스마트 검색 (초성 + 별칭 + substring)
|
||||
search: async (req, res) => {
|
||||
try {
|
||||
const { q } = req.query;
|
||||
const results = await koreanSearch.search(q || '');
|
||||
res.json({ success: true, data: results });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseRequest search error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 소모품 목록 (select용)
|
||||
getConsumableItems: async (req, res) => {
|
||||
try {
|
||||
@@ -133,6 +212,71 @@ const PurchaseRequestController = {
|
||||
logger.error('Vendors get error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 내 신청 목록 (모바일용, 페이지네이션)
|
||||
getMyRequests: async (req, res) => {
|
||||
try {
|
||||
const page = parseInt(req.query.page) || 1;
|
||||
const limit = parseInt(req.query.limit) || 20;
|
||||
const { status } = req.query;
|
||||
const result = await PurchaseRequestModel.getMyRequests(req.user.id, { page, limit, status });
|
||||
res.json({ success: true, ...result });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseRequest getMyRequests error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
},
|
||||
|
||||
// 개별 입고 처리 (admin)
|
||||
receive: async (req, res) => {
|
||||
try {
|
||||
const existing = await PurchaseRequestModel.getById(req.params.id);
|
||||
if (!existing) return res.status(404).json({ success: false, message: '신청 건을 찾을 수 없습니다.' });
|
||||
if (existing.status !== 'purchased') {
|
||||
return res.status(400).json({ success: false, message: '구매완료 상태의 신청만 입고 처리할 수 있습니다.' });
|
||||
}
|
||||
|
||||
const { received_location, photo } = req.body;
|
||||
let receivedPhotoPath = null;
|
||||
if (photo) {
|
||||
receivedPhotoPath = await saveBase64Image(photo, 'received', 'purchase_received');
|
||||
}
|
||||
|
||||
const updated = await PurchaseRequestModel.receive(req.params.id, {
|
||||
receivedPhotoPath,
|
||||
receivedLocation: received_location || null,
|
||||
receivedBy: req.user.id
|
||||
});
|
||||
|
||||
// batch 내 전체 입고 완료 시 batch.status 자동 전환
|
||||
if (existing.batch_id) {
|
||||
const allReceived = await PurchaseRequestModel.checkBatchAllReceived(existing.batch_id);
|
||||
if (allReceived) {
|
||||
const { getDb } = require('../dbPool');
|
||||
const db = await getDb();
|
||||
await db.query(
|
||||
`UPDATE purchase_batches SET status = 'received', received_at = NOW(), received_by = ? WHERE batch_id = ?`,
|
||||
[req.user.id, existing.batch_id]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 신청자에게 입고 알림
|
||||
notifyHelper.send({
|
||||
type: 'purchase',
|
||||
title: '소모품 입고 완료',
|
||||
message: `${existing.item_name || existing.custom_item_name} 입고 완료${received_location ? '. 보관위치: ' + received_location : ''}`,
|
||||
link_url: '/pages/purchase/request-mobile.html?view=' + req.params.id,
|
||||
target_user_ids: [existing.requester_id],
|
||||
created_by: req.user.id
|
||||
}).catch(() => {});
|
||||
|
||||
res.json({ success: true, data: updated, message: '입고 처리가 완료되었습니다.' });
|
||||
} catch (err) {
|
||||
logger.error('PurchaseRequest receive error:', err);
|
||||
res.status(500).json({ success: false, message: '서버 오류가 발생했습니다.' });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
-- 소모품 구매 관리 시스템 v2: 상태 확장 + 그룹화 + 별칭 + 입고
|
||||
|
||||
-- 1. purchase_requests.status ENUM 확장
|
||||
ALTER TABLE purchase_requests
|
||||
MODIFY COLUMN status ENUM('pending','grouped','purchased','received','hold') DEFAULT 'pending'
|
||||
COMMENT '대기, 구매진행중, 구매완료, 입고완료, 보류';
|
||||
|
||||
-- 2. 입고/그룹 관련 컬럼 추가
|
||||
ALTER TABLE purchase_requests
|
||||
ADD COLUMN batch_id INT NULL COMMENT '구매 묶음 ID' AFTER photo_path,
|
||||
ADD COLUMN received_photo_path VARCHAR(255) NULL COMMENT '입고 사진' AFTER batch_id,
|
||||
ADD COLUMN received_location VARCHAR(200) NULL COMMENT '입고 보관 위치' AFTER received_photo_path,
|
||||
ADD COLUMN received_at TIMESTAMP NULL COMMENT '입고 확인 시각' AFTER received_location,
|
||||
ADD COLUMN received_by INT NULL COMMENT '입고 확인자' AFTER received_at,
|
||||
ADD CONSTRAINT fk_pr_received_by FOREIGN KEY (received_by) REFERENCES sso_users(user_id);
|
||||
|
||||
-- 3. 구매 묶음(그룹) 테이블
|
||||
CREATE TABLE IF NOT EXISTS purchase_batches (
|
||||
batch_id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
batch_name VARCHAR(100) COMMENT '묶음 이름',
|
||||
category ENUM('consumable','safety','repair','equipment') NULL COMMENT '분류',
|
||||
vendor_id INT NULL COMMENT '예정 업체',
|
||||
status ENUM('pending','purchased','received') DEFAULT 'pending'
|
||||
COMMENT '진행중, 구매완료, 입고완료',
|
||||
notes TEXT,
|
||||
created_by INT NOT NULL COMMENT '생성자',
|
||||
purchased_at TIMESTAMP NULL COMMENT '구매 처리 시점',
|
||||
purchased_by INT NULL COMMENT '구매 처리자',
|
||||
received_at TIMESTAMP NULL COMMENT '입고 확인 시점',
|
||||
received_by INT NULL COMMENT '입고 확인자',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (vendor_id) REFERENCES vendors(vendor_id),
|
||||
FOREIGN KEY (created_by) REFERENCES sso_users(user_id),
|
||||
FOREIGN KEY (purchased_by) REFERENCES sso_users(user_id),
|
||||
FOREIGN KEY (received_by) REFERENCES sso_users(user_id)
|
||||
);
|
||||
|
||||
-- 4. batch FK
|
||||
ALTER TABLE purchase_requests
|
||||
ADD CONSTRAINT fk_pr_batch FOREIGN KEY (batch_id)
|
||||
REFERENCES purchase_batches(batch_id) ON DELETE SET NULL;
|
||||
|
||||
-- 5. 품목 별칭 테이블 (한국어 동의어/약어 매핑)
|
||||
CREATE TABLE IF NOT EXISTS item_aliases (
|
||||
alias_id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
item_id INT NOT NULL COMMENT 'FK → consumable_items',
|
||||
alias_name VARCHAR(100) NOT NULL COMMENT '별칭/축약어',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (item_id) REFERENCES consumable_items(item_id) ON DELETE CASCADE,
|
||||
UNIQUE KEY uq_item_alias (item_id, alias_name),
|
||||
INDEX idx_alias_name (alias_name)
|
||||
);
|
||||
|
||||
-- 6. notification_recipients ENUM에 'purchase' 추가
|
||||
ALTER TABLE notification_recipients
|
||||
MODIFY COLUMN notification_type
|
||||
ENUM('repair','safety','nonconformity','equipment','maintenance','system','purchase')
|
||||
NOT NULL COMMENT '알림 유형';
|
||||
|
||||
-- 7. 페이지 키 등록
|
||||
INSERT IGNORE INTO pages (page_key, page_name, page_path, category, is_admin_only, display_order) VALUES
|
||||
('purchase.request_mobile', '소모품 신청 (모바일)', '/pages/purchase/request-mobile.html', 'purchase', 0, 42);
|
||||
35
system1-factory/api/models/itemAliasModel.js
Normal file
35
system1-factory/api/models/itemAliasModel.js
Normal file
@@ -0,0 +1,35 @@
|
||||
// models/itemAliasModel.js
|
||||
const { getDb } = require('../dbPool');
|
||||
|
||||
const ItemAliasModel = {
|
||||
async getAll() {
|
||||
const db = await getDb();
|
||||
const [rows] = await db.query(
|
||||
`SELECT ia.*, ci.item_name, ci.spec, ci.maker, ci.category
|
||||
FROM item_aliases ia
|
||||
JOIN consumable_items ci ON ia.item_id = ci.item_id
|
||||
ORDER BY ci.item_name, ia.alias_name`
|
||||
);
|
||||
return rows;
|
||||
},
|
||||
|
||||
async create(itemId, aliasName) {
|
||||
const db = await getDb();
|
||||
const [result] = await db.query(
|
||||
`INSERT INTO item_aliases (item_id, alias_name) VALUES (?, ?)`,
|
||||
[itemId, aliasName.trim()]
|
||||
);
|
||||
return result.insertId;
|
||||
},
|
||||
|
||||
async delete(aliasId) {
|
||||
const db = await getDb();
|
||||
const [result] = await db.query(
|
||||
`DELETE FROM item_aliases WHERE alias_id = ?`,
|
||||
[aliasId]
|
||||
);
|
||||
return result.affectedRows > 0;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = ItemAliasModel;
|
||||
117
system1-factory/api/models/purchaseBatchModel.js
Normal file
117
system1-factory/api/models/purchaseBatchModel.js
Normal file
@@ -0,0 +1,117 @@
|
||||
// models/purchaseBatchModel.js
|
||||
const { getDb } = require('../dbPool');
|
||||
|
||||
const PurchaseBatchModel = {
|
||||
async getAll(filters = {}) {
|
||||
const db = await getDb();
|
||||
let sql = `
|
||||
SELECT pb.*, su.name AS created_by_name,
|
||||
v.vendor_name,
|
||||
(SELECT COUNT(*) FROM purchase_requests WHERE batch_id = pb.batch_id) AS request_count
|
||||
FROM purchase_batches pb
|
||||
LEFT JOIN sso_users su ON pb.created_by = su.user_id
|
||||
LEFT JOIN vendors v ON pb.vendor_id = v.vendor_id
|
||||
WHERE 1=1
|
||||
`;
|
||||
const params = [];
|
||||
if (filters.status) { sql += ' AND pb.status = ?'; params.push(filters.status); }
|
||||
sql += ' ORDER BY pb.created_at DESC';
|
||||
const [rows] = await db.query(sql, params);
|
||||
return rows;
|
||||
},
|
||||
|
||||
async getById(batchId) {
|
||||
const db = await getDb();
|
||||
const [rows] = await db.query(`
|
||||
SELECT pb.*, su.name AS created_by_name, v.vendor_name
|
||||
FROM purchase_batches pb
|
||||
LEFT JOIN sso_users su ON pb.created_by = su.user_id
|
||||
LEFT JOIN vendors v ON pb.vendor_id = v.vendor_id
|
||||
WHERE pb.batch_id = ?
|
||||
`, [batchId]);
|
||||
return rows[0] || null;
|
||||
},
|
||||
|
||||
async create({ batchName, category, vendorId, notes, createdBy }) {
|
||||
const db = await getDb();
|
||||
const [result] = await db.query(
|
||||
`INSERT INTO purchase_batches (batch_name, category, vendor_id, notes, created_by)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
[batchName || null, category || null, vendorId || null, notes || null, createdBy]
|
||||
);
|
||||
return result.insertId;
|
||||
},
|
||||
|
||||
async update(batchId, { batchName, category, vendorId, notes }) {
|
||||
const db = await getDb();
|
||||
await db.query(
|
||||
`UPDATE purchase_batches SET batch_name = ?, category = ?, vendor_id = ?, notes = ?
|
||||
WHERE batch_id = ? AND status = 'pending'`,
|
||||
[batchName || null, category || null, vendorId || null, notes || null, batchId]
|
||||
);
|
||||
return this.getById(batchId);
|
||||
},
|
||||
|
||||
async delete(batchId) {
|
||||
const db = await getDb();
|
||||
// pending 상태만 삭제 가능
|
||||
const [batch] = await db.query('SELECT status FROM purchase_batches WHERE batch_id = ?', [batchId]);
|
||||
if (!batch.length || batch[0].status !== 'pending') return false;
|
||||
|
||||
// 포함된 요청 복원
|
||||
await db.query(
|
||||
`UPDATE purchase_requests SET batch_id = NULL, status = 'pending' WHERE batch_id = ?`,
|
||||
[batchId]
|
||||
);
|
||||
await db.query('DELETE FROM purchase_batches WHERE batch_id = ?', [batchId]);
|
||||
return true;
|
||||
},
|
||||
|
||||
async markPurchased(batchId, purchasedBy) {
|
||||
const db = await getDb();
|
||||
await db.query(
|
||||
`UPDATE purchase_batches SET status = 'purchased', purchased_at = NOW(), purchased_by = ?
|
||||
WHERE batch_id = ? AND status = 'pending'`,
|
||||
[purchasedBy, batchId]
|
||||
);
|
||||
},
|
||||
|
||||
async markReceived(batchId, receivedBy) {
|
||||
const db = await getDb();
|
||||
await db.query(
|
||||
`UPDATE purchase_batches SET status = 'received', received_at = NOW(), received_by = ?
|
||||
WHERE batch_id = ? AND status = 'purchased'`,
|
||||
[receivedBy, batchId]
|
||||
);
|
||||
},
|
||||
|
||||
// batch에 요청 추가 (검증: pending이고 다른 batch에 속하지 않음)
|
||||
async addRequests(batchId, requestIds) {
|
||||
const db = await getDb();
|
||||
const [existing] = await db.query(
|
||||
`SELECT request_id, batch_id, status FROM purchase_requests WHERE request_id IN (?)`,
|
||||
[requestIds]
|
||||
);
|
||||
const invalid = existing.filter(r => r.status !== 'pending' || r.batch_id !== null);
|
||||
if (invalid.length > 0) {
|
||||
const ids = invalid.map(r => r.request_id);
|
||||
throw new Error(`다음 요청은 추가할 수 없습니다 (이미 그룹 소속이거나 대기 상태가 아님): ${ids.join(', ')}`);
|
||||
}
|
||||
|
||||
const PurchaseRequestModel = require('./purchaseRequestModel');
|
||||
await PurchaseRequestModel.groupIntoBatch(requestIds, batchId);
|
||||
},
|
||||
|
||||
// batch에서 요청 제거
|
||||
async removeRequests(batchId, requestIds) {
|
||||
const db = await getDb();
|
||||
const [batch] = await db.query('SELECT status FROM purchase_batches WHERE batch_id = ?', [batchId]);
|
||||
if (!batch.length || batch[0].status !== 'pending') {
|
||||
throw new Error('진행중인 그룹에서만 요청을 제거할 수 있습니다.');
|
||||
}
|
||||
const PurchaseRequestModel = require('./purchaseRequestModel');
|
||||
await PurchaseRequestModel.removeFromBatch(requestIds);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = PurchaseBatchModel;
|
||||
@@ -2,17 +2,19 @@
|
||||
const { getDb } = require('../dbPool');
|
||||
|
||||
const PurchaseRequestModel = {
|
||||
// 구매신청 목록 (소모품 정보 LEFT JOIN — item_id NULL 허용)
|
||||
// 구매신청 목록 (소모품 정보 LEFT JOIN — item_id NULL 허용, batch 정보 포함)
|
||||
async getAll(filters = {}) {
|
||||
const db = await getDb();
|
||||
let sql = `
|
||||
SELECT pr.*, ci.item_name, ci.spec, ci.maker, ci.category, ci.base_price, ci.unit,
|
||||
ci.photo_path AS ci_photo_path, pr.photo_path AS pr_photo_path,
|
||||
pr.custom_item_name, pr.custom_category,
|
||||
su.name AS requester_name
|
||||
su.name AS requester_name,
|
||||
pb.batch_name, pb.status AS batch_status, pb.category AS batch_category
|
||||
FROM purchase_requests pr
|
||||
LEFT JOIN consumable_items ci ON pr.item_id = ci.item_id
|
||||
LEFT JOIN sso_users su ON pr.requester_id = su.user_id
|
||||
LEFT JOIN purchase_batches pb ON pr.batch_id = pb.batch_id
|
||||
WHERE 1=1
|
||||
`;
|
||||
const params = [];
|
||||
@@ -25,23 +27,28 @@ const PurchaseRequestModel = {
|
||||
}
|
||||
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); }
|
||||
if (filters.batch_id) { sql += ' AND pr.batch_id = ?'; params.push(filters.batch_id); }
|
||||
|
||||
sql += ' ORDER BY pr.created_at DESC';
|
||||
const [rows] = await db.query(sql, params);
|
||||
return rows;
|
||||
},
|
||||
|
||||
// 단건 조회
|
||||
// 단건 조회 (batch 정보 포함)
|
||||
async getById(requestId) {
|
||||
const db = await getDb();
|
||||
const [rows] = await db.query(`
|
||||
SELECT pr.*, ci.item_name, ci.spec, ci.maker, ci.category, ci.base_price, ci.unit,
|
||||
ci.photo_path AS ci_photo_path, pr.photo_path AS pr_photo_path,
|
||||
pr.custom_item_name, pr.custom_category,
|
||||
su.name AS requester_name
|
||||
su.name AS requester_name,
|
||||
pb.batch_name, pb.status AS batch_status, pb.category AS batch_category,
|
||||
rsu.name AS received_by_name
|
||||
FROM purchase_requests pr
|
||||
LEFT JOIN consumable_items ci ON pr.item_id = ci.item_id
|
||||
LEFT JOIN sso_users su ON pr.requester_id = su.user_id
|
||||
LEFT JOIN purchase_batches pb ON pr.batch_id = pb.batch_id
|
||||
LEFT JOIN sso_users rsu ON pr.received_by = rsu.user_id
|
||||
WHERE pr.request_id = ?
|
||||
`, [requestId]);
|
||||
return rows[0] || null;
|
||||
@@ -105,6 +112,127 @@ const PurchaseRequestModel = {
|
||||
[requestId]
|
||||
);
|
||||
return result.affectedRows > 0;
|
||||
},
|
||||
|
||||
// 내 신청 목록 (모바일용, 페이지네이션)
|
||||
async getMyRequests(userId, { page = 1, limit = 20, status } = {}) {
|
||||
const db = await getDb();
|
||||
const offset = (page - 1) * limit;
|
||||
let where = 'WHERE pr.requester_id = ?';
|
||||
const params = [userId];
|
||||
|
||||
if (status) { where += ' AND pr.status = ?'; params.push(status); }
|
||||
|
||||
const [[{ total }]] = await db.query(
|
||||
`SELECT COUNT(*) AS total FROM purchase_requests pr ${where}`, params
|
||||
);
|
||||
|
||||
const [rows] = await db.query(`
|
||||
SELECT pr.*, ci.item_name, ci.spec, ci.maker, ci.category, ci.base_price, ci.unit,
|
||||
ci.photo_path AS ci_photo_path, pr.photo_path AS pr_photo_path,
|
||||
pr.custom_item_name, pr.custom_category,
|
||||
pb.batch_name, pb.status AS batch_status,
|
||||
rsu.name AS received_by_name
|
||||
FROM purchase_requests pr
|
||||
LEFT JOIN consumable_items ci ON pr.item_id = ci.item_id
|
||||
LEFT JOIN purchase_batches pb ON pr.batch_id = pb.batch_id
|
||||
LEFT JOIN sso_users rsu ON pr.received_by = rsu.user_id
|
||||
${where}
|
||||
ORDER BY pr.created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, [...params, limit, offset]);
|
||||
|
||||
return {
|
||||
data: rows,
|
||||
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) }
|
||||
};
|
||||
},
|
||||
|
||||
// batch에 요청 그룹화 (status → grouped)
|
||||
async groupIntoBatch(requestIds, batchId) {
|
||||
const db = await getDb();
|
||||
await db.query(
|
||||
`UPDATE purchase_requests SET batch_id = ?, status = 'grouped'
|
||||
WHERE request_id IN (?) AND status = 'pending' AND batch_id IS NULL`,
|
||||
[batchId, requestIds]
|
||||
);
|
||||
},
|
||||
|
||||
// batch에서 제거 (status → pending 복원)
|
||||
async removeFromBatch(requestIds) {
|
||||
const db = await getDb();
|
||||
await db.query(
|
||||
`UPDATE purchase_requests SET batch_id = NULL, status = 'pending'
|
||||
WHERE request_id IN (?) AND status = 'grouped'`,
|
||||
[requestIds]
|
||||
);
|
||||
},
|
||||
|
||||
// batch 내 전체 요청 purchased 전환
|
||||
async markBatchPurchased(batchId) {
|
||||
const db = await getDb();
|
||||
await db.query(
|
||||
`UPDATE purchase_requests SET status = 'purchased' WHERE batch_id = ? AND status = 'grouped'`,
|
||||
[batchId]
|
||||
);
|
||||
},
|
||||
|
||||
// 개별 입고 처리
|
||||
async receive(requestId, { receivedPhotoPath, receivedLocation, receivedBy }) {
|
||||
const db = await getDb();
|
||||
await db.query(
|
||||
`UPDATE purchase_requests
|
||||
SET status = 'received', received_photo_path = ?, received_location = ?,
|
||||
received_at = NOW(), received_by = ?
|
||||
WHERE request_id = ? AND status = 'purchased'`,
|
||||
[receivedPhotoPath || null, receivedLocation || null, receivedBy, requestId]
|
||||
);
|
||||
return this.getById(requestId);
|
||||
},
|
||||
|
||||
// batch 내 전체 입고 처리
|
||||
async receiveBatch(batchId, { receivedPhotoPath, receivedLocation, receivedBy }) {
|
||||
const db = await getDb();
|
||||
await db.query(
|
||||
`UPDATE purchase_requests
|
||||
SET status = 'received', received_photo_path = ?, received_location = ?,
|
||||
received_at = NOW(), received_by = ?
|
||||
WHERE batch_id = ? AND status = 'purchased'`,
|
||||
[receivedPhotoPath || null, receivedLocation || null, receivedBy, batchId]
|
||||
);
|
||||
},
|
||||
|
||||
// batch 내 모든 요청이 received인지 확인
|
||||
async checkBatchAllReceived(batchId) {
|
||||
const db = await getDb();
|
||||
const [[{ total, received }]] = await db.query(
|
||||
`SELECT COUNT(*) AS total,
|
||||
SUM(CASE WHEN status = 'received' THEN 1 ELSE 0 END) AS received
|
||||
FROM purchase_requests WHERE batch_id = ?`,
|
||||
[batchId]
|
||||
);
|
||||
return total > 0 && total === received;
|
||||
},
|
||||
|
||||
// grouped 상태에서 hold (batch에서 자동 제거)
|
||||
async holdFromGrouped(requestId, holdReason) {
|
||||
const db = await getDb();
|
||||
await db.query(
|
||||
`UPDATE purchase_requests SET status = 'hold', hold_reason = ?, batch_id = NULL
|
||||
WHERE request_id = ? AND status = 'grouped'`,
|
||||
[holdReason || null, requestId]
|
||||
);
|
||||
return this.getById(requestId);
|
||||
},
|
||||
|
||||
// batch 내 신청자 ID 목록 조회
|
||||
async getRequesterIdsByBatch(batchId) {
|
||||
const db = await getDb();
|
||||
const [rows] = await db.query(
|
||||
`SELECT DISTINCT requester_id FROM purchase_requests WHERE batch_id = ?`,
|
||||
[batchId]
|
||||
);
|
||||
return rows.map(r => r.requester_id);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
12
system1-factory/api/routes/itemAliasRoutes.js
Normal file
12
system1-factory/api/routes/itemAliasRoutes.js
Normal file
@@ -0,0 +1,12 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const ctrl = require('../controllers/itemAliasController');
|
||||
const { createRequirePage } = require('../../../shared/middleware/pagePermission');
|
||||
const { getDb } = require('../dbPool');
|
||||
const requirePage = createRequirePage(getDb);
|
||||
|
||||
router.get('/', requirePage('factory_purchases'), ctrl.getAll);
|
||||
router.post('/', requirePage('factory_purchases'), ctrl.create);
|
||||
router.delete('/:id', requirePage('factory_purchases'), ctrl.delete);
|
||||
|
||||
module.exports = router;
|
||||
16
system1-factory/api/routes/purchaseBatchRoutes.js
Normal file
16
system1-factory/api/routes/purchaseBatchRoutes.js
Normal file
@@ -0,0 +1,16 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const ctrl = require('../controllers/purchaseBatchController');
|
||||
const { createRequirePage } = require('../../../shared/middleware/pagePermission');
|
||||
const { getDb } = require('../dbPool');
|
||||
const requirePage = createRequirePage(getDb);
|
||||
|
||||
router.get('/', requirePage('factory_purchases'), ctrl.getAll);
|
||||
router.get('/:id', requirePage('factory_purchases'), ctrl.getById);
|
||||
router.post('/', requirePage('factory_purchases'), ctrl.create);
|
||||
router.put('/:id', requirePage('factory_purchases'), ctrl.update);
|
||||
router.delete('/:id', requirePage('factory_purchases'), ctrl.delete);
|
||||
router.post('/:id/purchase', requirePage('factory_purchases'), ctrl.purchase);
|
||||
router.put('/:id/receive', requirePage('factory_purchases'), ctrl.receive);
|
||||
|
||||
module.exports = router;
|
||||
@@ -8,6 +8,13 @@ const requirePage = createRequirePage(getDb);
|
||||
// 보조 데이터
|
||||
router.get('/consumable-items', ctrl.getConsumableItems);
|
||||
router.get('/vendors', ctrl.getVendors);
|
||||
router.get('/search', ctrl.search);
|
||||
|
||||
// 내 신청 (모바일용 페이지네이션) — /:id 보다 먼저 등록
|
||||
router.get('/my-requests', ctrl.getMyRequests);
|
||||
|
||||
// 품목 등록 + 신청 동시 (트랜잭션)
|
||||
router.post('/register-and-request', ctrl.registerAndRequest);
|
||||
|
||||
// 구매신청 CRUD
|
||||
router.get('/', ctrl.getAll);
|
||||
@@ -15,6 +22,7 @@ router.get('/:id', ctrl.getById);
|
||||
router.post('/', ctrl.create);
|
||||
router.put('/:id/hold', requirePage('factory_purchases'), ctrl.hold);
|
||||
router.put('/:id/revert', requirePage('factory_purchases'), ctrl.revert);
|
||||
router.put('/:id/receive', requirePage('factory_purchases'), ctrl.receive);
|
||||
router.delete('/:id', ctrl.delete);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -23,7 +23,8 @@ try {
|
||||
const UPLOAD_DIRS = {
|
||||
issues: path.join(__dirname, '../uploads/issues'),
|
||||
equipments: path.join(__dirname, '../uploads/equipments'),
|
||||
purchase_requests: path.join(__dirname, '../uploads/purchase_requests')
|
||||
purchase_requests: path.join(__dirname, '../uploads/purchase_requests'),
|
||||
purchase_received: path.join(__dirname, '../uploads/purchase_received')
|
||||
};
|
||||
const UPLOAD_DIR = UPLOAD_DIRS.issues; // 기존 호환성 유지
|
||||
const MAX_SIZE = { width: 1920, height: 1920 };
|
||||
|
||||
156
system1-factory/api/utils/koreanSearch.js
Normal file
156
system1-factory/api/utils/koreanSearch.js
Normal file
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* 한국어 스마트 검색 유틸리티
|
||||
* - 초성 추출 및 매칭
|
||||
* - 별칭(alias) 매칭
|
||||
* - 인메모리 캐시 (5분 TTL)
|
||||
*/
|
||||
const { getDb } = require('../dbPool');
|
||||
|
||||
// 초성 목록 (19개)
|
||||
const CHOSUNG = [
|
||||
'ㄱ','ㄲ','ㄴ','ㄷ','ㄸ','ㄹ','ㅁ','ㅂ','ㅃ','ㅅ',
|
||||
'ㅆ','ㅇ','ㅈ','ㅉ','ㅊ','ㅋ','ㅌ','ㅍ','ㅎ'
|
||||
];
|
||||
|
||||
// 자음 문자 집합 (초성 판별용)
|
||||
const JAMO_SET = new Set([
|
||||
'ㄱ','ㄲ','ㄴ','ㄷ','ㄸ','ㄹ','ㅁ','ㅂ','ㅃ','ㅅ',
|
||||
'ㅆ','ㅇ','ㅈ','ㅉ','ㅊ','ㅋ','ㅌ','ㅍ','ㅎ'
|
||||
]);
|
||||
|
||||
// 캐시
|
||||
let cache = null;
|
||||
let cacheTime = 0;
|
||||
const CACHE_TTL = 5 * 60 * 1000; // 5분
|
||||
|
||||
/**
|
||||
* 한글 완성형 문자에서 초성 추출
|
||||
* @param {string} str
|
||||
* @returns {string} 초성 문자열
|
||||
*/
|
||||
function extractChosung(str) {
|
||||
let result = '';
|
||||
for (const ch of str) {
|
||||
const code = ch.charCodeAt(0);
|
||||
if (code >= 0xAC00 && code <= 0xD7A3) {
|
||||
const idx = Math.floor((code - 0xAC00) / (21 * 28));
|
||||
result += CHOSUNG[idx];
|
||||
} else {
|
||||
result += ch;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검색어가 모두 자음(초성)인지 판별
|
||||
* @param {string} query
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isChosungOnly(query) {
|
||||
if (query.length < 2) return false;
|
||||
for (const ch of query) {
|
||||
if (!JAMO_SET.has(ch)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 로드 (consumable_items + item_aliases)
|
||||
*/
|
||||
async function loadCache() {
|
||||
if (cache && (Date.now() - cacheTime < CACHE_TTL)) return cache;
|
||||
|
||||
const db = await getDb();
|
||||
const [items] = await db.query(
|
||||
`SELECT item_id, item_name, spec, maker, category, base_price, unit, photo_path
|
||||
FROM consumable_items WHERE is_active = 1`
|
||||
);
|
||||
const [aliases] = await db.query(
|
||||
`SELECT alias_id, item_id, alias_name FROM item_aliases`
|
||||
);
|
||||
|
||||
// 아이템별 별칭 맵 생성
|
||||
const aliasMap = {};
|
||||
for (const a of aliases) {
|
||||
if (!aliasMap[a.item_id]) aliasMap[a.item_id] = [];
|
||||
aliasMap[a.item_id].push(a.alias_name);
|
||||
}
|
||||
|
||||
// 초성 미리 계산
|
||||
const enriched = items.map(item => ({
|
||||
...item,
|
||||
aliases: aliasMap[item.item_id] || [],
|
||||
chosung_name: extractChosung(item.item_name),
|
||||
chosung_aliases: (aliasMap[item.item_id] || []).map(a => extractChosung(a))
|
||||
}));
|
||||
|
||||
cache = enriched;
|
||||
cacheTime = Date.now();
|
||||
return cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 무효화
|
||||
*/
|
||||
function clearCache() {
|
||||
cache = null;
|
||||
cacheTime = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 스마트 검색
|
||||
* @param {string} query - 검색어
|
||||
* @returns {Promise<Array>} 스코어 기준 상위 20건
|
||||
*/
|
||||
async function search(query) {
|
||||
if (!query || query.trim().length === 0) return [];
|
||||
const items = await loadCache();
|
||||
const q = query.trim().toLowerCase();
|
||||
const qChosung = isChosungOnly(q) ? q : null;
|
||||
|
||||
const scored = [];
|
||||
for (const item of items) {
|
||||
let score = 0;
|
||||
let matchType = '';
|
||||
|
||||
const nameLower = item.item_name.toLowerCase();
|
||||
const specLower = (item.spec || '').toLowerCase();
|
||||
const makerLower = (item.maker || '').toLowerCase();
|
||||
|
||||
// exact match (이름 완전 일치)
|
||||
if (nameLower === q) {
|
||||
score = 100; matchType = 'exact';
|
||||
}
|
||||
// substring match (이름)
|
||||
else if (nameLower.includes(q)) {
|
||||
score = 80; matchType = 'name';
|
||||
}
|
||||
// alias match
|
||||
else if (item.aliases.some(a => a.toLowerCase().includes(q))) {
|
||||
score = 75; matchType = 'alias';
|
||||
}
|
||||
// spec/maker match
|
||||
else if (specLower.includes(q) || makerLower.includes(q)) {
|
||||
score = 70; matchType = 'spec';
|
||||
}
|
||||
// 초성 매칭 (이름)
|
||||
else if (qChosung && item.chosung_name.includes(qChosung)) {
|
||||
score = 50; matchType = 'chosung';
|
||||
}
|
||||
// 초성 매칭 (별칭)
|
||||
else if (qChosung && item.chosung_aliases.some(ca => ca.includes(qChosung))) {
|
||||
score = 40; matchType = 'chosung_alias';
|
||||
}
|
||||
|
||||
if (score > 0) {
|
||||
scored.push({ ...item, _score: score, _matchType: matchType });
|
||||
}
|
||||
}
|
||||
|
||||
// 점수 높은 순, 같은 점수면 이름 짧은 순 (더 구체적)
|
||||
scored.sort((a, b) => b._score - a._score || a.item_name.length - b.item_name.length);
|
||||
return scored.slice(0, 20);
|
||||
}
|
||||
|
||||
module.exports = { search, clearCache, extractChosung, isChosungOnly };
|
||||
317
system1-factory/web/css/purchase-mobile.css
Normal file
317
system1-factory/web/css/purchase-mobile.css
Normal file
@@ -0,0 +1,317 @@
|
||||
/* purchase-mobile.css — 소모품 신청 모바일 전용 */
|
||||
|
||||
/* 메인 컨텐츠 (하단 네비 여유) */
|
||||
.pm-content {
|
||||
padding-bottom: calc(76px + env(safe-area-inset-bottom));
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* 상태 탭 */
|
||||
.pm-tabs {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: none;
|
||||
padding: 8px 16px;
|
||||
background: white;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
.pm-tabs::-webkit-scrollbar { display: none; }
|
||||
.pm-tab {
|
||||
flex-shrink: 0;
|
||||
padding: 6px 14px;
|
||||
border-radius: 20px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
background: #f3f4f6;
|
||||
color: #6b7280;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.pm-tab.active {
|
||||
background: #ea580c;
|
||||
color: white;
|
||||
}
|
||||
.pm-tab .tab-count {
|
||||
margin-left: 4px;
|
||||
font-size: 11px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
/* 카드 리스트 */
|
||||
.pm-cards {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
.pm-card {
|
||||
background: white;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 12px;
|
||||
padding: 14px;
|
||||
cursor: pointer;
|
||||
transition: box-shadow 0.15s;
|
||||
}
|
||||
.pm-card:active { box-shadow: 0 0 0 2px rgba(234,88,12,0.2); }
|
||||
.pm-card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
}
|
||||
.pm-card-name {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: #1f2937;
|
||||
line-height: 1.3;
|
||||
}
|
||||
.pm-card-custom { font-size: 11px; color: #ea580c; margin-left: 4px; }
|
||||
.pm-card-meta {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: #9ca3af;
|
||||
}
|
||||
.pm-card-qty { color: #374151; font-weight: 600; }
|
||||
|
||||
/* FAB */
|
||||
.pm-fab {
|
||||
position: fixed;
|
||||
bottom: calc(84px + env(safe-area-inset-bottom));
|
||||
right: 20px;
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
border-radius: 50%;
|
||||
background: #ea580c;
|
||||
color: white;
|
||||
border: none;
|
||||
box-shadow: 0 4px 12px rgba(234,88,12,0.35);
|
||||
font-size: 24px;
|
||||
cursor: pointer;
|
||||
z-index: 30;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
.pm-fab:active { transform: scale(0.92); }
|
||||
|
||||
/* 바텀시트 */
|
||||
.pm-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0,0,0,0.4);
|
||||
z-index: 100;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.25s;
|
||||
}
|
||||
.pm-overlay.open { opacity: 1; pointer-events: auto; }
|
||||
|
||||
.pm-sheet {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: white;
|
||||
border-radius: 16px 16px 0 0;
|
||||
z-index: 101;
|
||||
max-height: 92vh;
|
||||
overflow-y: auto;
|
||||
transform: translateY(100%);
|
||||
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
}
|
||||
.pm-sheet.open { transform: translateY(0); }
|
||||
.pm-sheet-handle {
|
||||
width: 36px;
|
||||
height: 4px;
|
||||
background: #d1d5db;
|
||||
border-radius: 2px;
|
||||
margin: 8px auto;
|
||||
}
|
||||
.pm-sheet-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 20px 8px;
|
||||
}
|
||||
.pm-sheet-title { font-size: 17px; font-weight: 700; color: #1f2937; }
|
||||
.pm-sheet-close {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: none;
|
||||
background: #f3f4f6;
|
||||
border-radius: 50%;
|
||||
font-size: 16px;
|
||||
color: #6b7280;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.pm-sheet-body { padding: 0 20px 20px; }
|
||||
|
||||
/* 검색 */
|
||||
.pm-search-wrap { position: relative; margin-bottom: 12px; }
|
||||
.pm-search-input {
|
||||
width: 100%;
|
||||
padding: 12px 40px 12px 14px;
|
||||
border: 1.5px solid #e5e7eb;
|
||||
border-radius: 10px;
|
||||
font-size: 16px;
|
||||
outline: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.pm-search-input:focus { border-color: #ea580c; }
|
||||
.pm-search-spinner {
|
||||
position: absolute;
|
||||
right: 12px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
display: none;
|
||||
}
|
||||
.pm-search-spinner.show { display: block; }
|
||||
.pm-search-results {
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
display: none;
|
||||
}
|
||||
.pm-search-results.open { display: block; }
|
||||
.pm-search-item {
|
||||
padding: 10px 12px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
border-bottom: 1px solid #f3f4f6;
|
||||
}
|
||||
.pm-search-item:last-child { border-bottom: none; }
|
||||
.pm-search-item:active { background: #fff7ed; }
|
||||
.pm-search-item .match-type {
|
||||
font-size: 10px;
|
||||
padding: 1px 5px;
|
||||
border-radius: 4px;
|
||||
background: #f3f4f6;
|
||||
color: #9ca3af;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.pm-search-register {
|
||||
padding: 10px 12px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
color: #ea580c;
|
||||
font-weight: 500;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.pm-search-register:active { background: #fff7ed; }
|
||||
|
||||
/* 폼 필드 */
|
||||
.pm-field { margin-bottom: 12px; }
|
||||
.pm-label { display: block; font-size: 12px; font-weight: 600; color: #6b7280; margin-bottom: 4px; }
|
||||
.pm-input {
|
||||
width: 100%;
|
||||
padding: 10px 12px;
|
||||
border: 1.5px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
outline: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.pm-input:focus { border-color: #ea580c; }
|
||||
.pm-select {
|
||||
width: 100%;
|
||||
padding: 10px 12px;
|
||||
border: 1.5px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
background: white;
|
||||
outline: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* 사진 */
|
||||
.pm-photo-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 14px;
|
||||
border: 1.5px dashed #d1d5db;
|
||||
border-radius: 8px;
|
||||
background: #fafafa;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
color: #6b7280;
|
||||
min-height: 44px;
|
||||
}
|
||||
.pm-photo-preview {
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
border-radius: 8px;
|
||||
object-fit: cover;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
/* 제출 */
|
||||
.pm-submit {
|
||||
width: 100%;
|
||||
padding: 14px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
background: #ea580c;
|
||||
color: white;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
margin-top: 16px;
|
||||
min-height: 48px;
|
||||
}
|
||||
.pm-submit:active { background: #c2410c; }
|
||||
.pm-submit:disabled { background: #d1d5db; cursor: not-allowed; }
|
||||
|
||||
/* 상세 시트 */
|
||||
.pm-detail-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 8px 0;
|
||||
font-size: 14px;
|
||||
border-bottom: 1px solid #f3f4f6;
|
||||
}
|
||||
.pm-detail-label { color: #9ca3af; }
|
||||
.pm-detail-value { color: #1f2937; font-weight: 500; }
|
||||
.pm-received-photo {
|
||||
width: 100%;
|
||||
max-height: 200px;
|
||||
object-fit: cover;
|
||||
border-radius: 10px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
/* 빈 상태 */
|
||||
.pm-empty {
|
||||
text-align: center;
|
||||
padding: 48px 16px;
|
||||
color: #9ca3af;
|
||||
}
|
||||
.pm-empty i { font-size: 32px; margin-bottom: 8px; display: block; }
|
||||
|
||||
/* 로딩 */
|
||||
.pm-loading {
|
||||
text-align: center;
|
||||
padding: 24px;
|
||||
color: #9ca3af;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
/* 스피너 애니메이션 */
|
||||
@keyframes pm-spin { to { transform: translateY(-50%) rotate(360deg); } }
|
||||
.pm-search-spinner.show i { animation: pm-spin 0.8s linear infinite; }
|
||||
147
system1-factory/web/pages/purchase/request-mobile.html
Normal file
147
system1-factory/web/pages/purchase/request-mobile.html
Normal file
@@ -0,0 +1,147 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||||
<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?v=2026040101">
|
||||
<link rel="stylesheet" href="/css/purchase-mobile.css?v=2026040101">
|
||||
<script src="https://cdn.jsdelivr.net/npm/heic2any@0.0.4/dist/heic2any.min.js"></script>
|
||||
</head>
|
||||
<body class="bg-gray-50">
|
||||
<!-- 헤더 -->
|
||||
<header class="bg-orange-700 text-white sticky top-0 z-50">
|
||||
<div class="px-4 flex justify-between items-center h-12">
|
||||
<div class="flex items-center gap-3">
|
||||
<button id="mobileMenuBtn" class="text-orange-200 hover:text-white"><i class="fas fa-bars text-lg"></i></button>
|
||||
<h1 class="text-base font-semibold">소모품 신청</h1>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<span id="headerUserName" class="text-sm text-orange-200"></span>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- 사이드 네비 -->
|
||||
<nav id="sideNav" class="fixed inset-y-0 left-0 w-64 bg-white shadow-xl z-40 transform -translate-x-full transition-transform duration-200" style="top:48px"></nav>
|
||||
<div id="mobileOverlay" class="fixed inset-0 bg-black/40 z-30 hidden" onclick="toggleMobileMenu()"></div>
|
||||
|
||||
<div class="pm-content">
|
||||
<!-- 상태 탭 -->
|
||||
<div class="pm-tabs" id="statusTabs">
|
||||
<button class="pm-tab active" data-status="" onclick="filterByStatus(this)">전체</button>
|
||||
<button class="pm-tab" data-status="pending" onclick="filterByStatus(this)">대기</button>
|
||||
<button class="pm-tab" data-status="grouped" onclick="filterByStatus(this)">구매진행중</button>
|
||||
<button class="pm-tab" data-status="purchased" onclick="filterByStatus(this)">구매완료</button>
|
||||
<button class="pm-tab" data-status="received" onclick="filterByStatus(this)">입고완료</button>
|
||||
</div>
|
||||
|
||||
<!-- 카드 리스트 -->
|
||||
<div class="pm-cards" id="requestCards"></div>
|
||||
<div class="pm-loading hidden" id="loadingMore">더 불러오는 중...</div>
|
||||
</div>
|
||||
|
||||
<!-- FAB -->
|
||||
<button class="pm-fab" onclick="openRequestSheet()"><i class="fas fa-plus"></i></button>
|
||||
|
||||
<!-- 신청 바텀시트 -->
|
||||
<div class="pm-overlay" id="requestOverlay" onclick="closeRequestSheet()"></div>
|
||||
<div class="pm-sheet" id="requestSheet">
|
||||
<div class="pm-sheet-handle"></div>
|
||||
<div class="pm-sheet-header">
|
||||
<span class="pm-sheet-title">소모품 신청</span>
|
||||
<button class="pm-sheet-close" onclick="closeRequestSheet()"><i class="fas fa-times"></i></button>
|
||||
</div>
|
||||
<div class="pm-sheet-body">
|
||||
<!-- 검색 -->
|
||||
<div class="pm-search-wrap">
|
||||
<input type="text" id="searchInput" class="pm-search-input" placeholder="품목 검색 (이름, 초성, 별칭)">
|
||||
<div class="pm-search-spinner" id="searchSpinner"><i class="fas fa-spinner text-orange-500"></i></div>
|
||||
</div>
|
||||
<div class="pm-search-results" id="searchResults"></div>
|
||||
|
||||
<!-- 선택된 품목 표시 -->
|
||||
<div id="selectedItemWrap" class="hidden mb-3">
|
||||
<div class="flex items-center gap-2 p-3 bg-orange-50 rounded-lg">
|
||||
<div class="flex-1">
|
||||
<div id="selectedItemName" class="font-medium text-sm text-gray-800"></div>
|
||||
<div id="selectedItemMeta" class="text-xs text-gray-500 mt-1"></div>
|
||||
</div>
|
||||
<button onclick="clearSelectedItem()" class="text-gray-400 hover:text-red-500"><i class="fas fa-times-circle"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
<input type="hidden" id="selectedItemId">
|
||||
<input type="hidden" id="selectedCustomName">
|
||||
|
||||
<!-- 신규 품목 등록 영역 (Phase 4에서 활성화) -->
|
||||
<div id="newItemForm" class="hidden">
|
||||
<div class="p-3 bg-yellow-50 border border-yellow-200 rounded-lg mb-3">
|
||||
<div class="text-sm font-medium text-yellow-800 mb-2"><i class="fas fa-plus-circle mr-1"></i>새 품목 등록</div>
|
||||
<div class="pm-field">
|
||||
<label class="pm-label">품목명 *</label>
|
||||
<input type="text" id="newItemName" class="pm-input" readonly>
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<div class="pm-field">
|
||||
<label class="pm-label">규격</label>
|
||||
<input type="text" id="newItemSpec" class="pm-input" placeholder="예: 300mm">
|
||||
</div>
|
||||
<div class="pm-field">
|
||||
<label class="pm-label">제조사</label>
|
||||
<input type="text" id="newItemMaker" class="pm-input" placeholder="예: 3M">
|
||||
</div>
|
||||
</div>
|
||||
<div class="pm-field">
|
||||
<label class="pm-label">분류 (선택)</label>
|
||||
<select id="newItemCategory" class="pm-select">
|
||||
<option value="">나중에 분류</option>
|
||||
<option value="consumable">소모품</option>
|
||||
<option value="safety">안전용품</option>
|
||||
<option value="repair">수선비</option>
|
||||
<option value="equipment">설비</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 수량/메모/사진 -->
|
||||
<div class="pm-field">
|
||||
<label class="pm-label">수량 *</label>
|
||||
<input type="number" id="reqQuantity" class="pm-input" value="1" min="1" inputmode="numeric">
|
||||
</div>
|
||||
<div class="pm-field">
|
||||
<label class="pm-label">메모</label>
|
||||
<input type="text" id="reqNotes" class="pm-input" placeholder="요청 사항">
|
||||
</div>
|
||||
<div class="pm-field">
|
||||
<label class="pm-label">사진 첨부</label>
|
||||
<label class="pm-photo-btn">
|
||||
<i class="fas fa-camera"></i>
|
||||
<span id="photoLabel">사진 촬영/선택</span>
|
||||
<input type="file" id="reqPhotoInput" accept="image/*,.heic,.heif" capture="environment" class="hidden" onchange="onMobilePhotoSelected(this)">
|
||||
</label>
|
||||
<img id="reqPhotoPreview" class="pm-photo-preview hidden">
|
||||
</div>
|
||||
|
||||
<button id="submitBtn" class="pm-submit" onclick="submitRequest()">신청하기</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 상세 바텀시트 -->
|
||||
<div class="pm-overlay" id="detailOverlay" onclick="closeDetailSheet()"></div>
|
||||
<div class="pm-sheet" id="detailSheet">
|
||||
<div class="pm-sheet-handle"></div>
|
||||
<div class="pm-sheet-header">
|
||||
<span class="pm-sheet-title">신청 상세</span>
|
||||
<button class="pm-sheet-close" onclick="closeDetailSheet()"><i class="fas fa-times"></i></button>
|
||||
</div>
|
||||
<div class="pm-sheet-body" id="detailContent"></div>
|
||||
</div>
|
||||
|
||||
<script src="/static/js/tkfb-core.js?v=2026040101"></script>
|
||||
<script src="/static/js/purchase-request-mobile.js?v=2026040101"></script>
|
||||
<script src="/static/js/shared-bottom-nav.js?v=2026040101"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -114,7 +114,9 @@
|
||||
<select id="prFilterStatus" class="px-3 py-2 border rounded-lg text-sm" onchange="loadRequests()">
|
||||
<option value="">전체 상태</option>
|
||||
<option value="pending">대기</option>
|
||||
<option value="grouped">구매진행중</option>
|
||||
<option value="purchased">구매완료</option>
|
||||
<option value="received">입고완료</option>
|
||||
<option value="hold">보류</option>
|
||||
</select>
|
||||
<select id="prFilterCategory" class="px-3 py-2 border rounded-lg text-sm" onchange="loadRequests()">
|
||||
@@ -127,6 +129,27 @@
|
||||
<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>
|
||||
<!-- 그룹 액션 (admin only) -->
|
||||
<div id="batchActions" class="hidden ml-auto flex items-center gap-2">
|
||||
<span id="selectedCount" class="text-sm text-gray-500">0건 선택</span>
|
||||
<button onclick="openBatchCreateModal()" class="px-3 py-2 bg-blue-600 text-white rounded-lg text-sm hover:bg-blue-700">
|
||||
<i class="fas fa-layer-group mr-1"></i>그룹 생성
|
||||
</button>
|
||||
</div>
|
||||
<button id="batchViewBtn" class="hidden ml-2 px-3 py-2 border border-blue-300 text-blue-600 rounded-lg text-sm hover:bg-blue-50" onclick="toggleBatchView()">
|
||||
<i class="fas fa-layer-group mr-1"></i>그룹 보기
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 그룹 목록 (토글) -->
|
||||
<div id="batchView" class="hidden mb-4">
|
||||
<div class="bg-white rounded-xl shadow-sm p-4">
|
||||
<div class="flex justify-between items-center mb-3">
|
||||
<h3 class="font-semibold text-gray-700"><i class="fas fa-layer-group mr-1 text-blue-500"></i>구매 그룹</h3>
|
||||
<button onclick="loadBatches()" class="text-xs text-gray-400 hover:text-gray-600"><i class="fas fa-sync-alt"></i></button>
|
||||
</div>
|
||||
<div id="batchList" class="space-y-2 text-sm"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 신청 목록 -->
|
||||
@@ -135,6 +158,7 @@
|
||||
<table class="w-full text-sm">
|
||||
<thead class="bg-gray-50 text-gray-600 text-xs uppercase">
|
||||
<tr>
|
||||
<th class="px-2 py-3 text-center" id="thCheckbox" style="display:none"><input type="checkbox" id="selectAllCb" onchange="toggleSelectAll(this)"></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-right">수량</th>
|
||||
@@ -218,10 +242,75 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 그룹 생성 모달 -->
|
||||
<div id="batchCreateModal" class="hidden fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeBatchCreateModal()">
|
||||
<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 text-blue-700"><i class="fas fa-layer-group mr-2"></i>구매 그룹 <20><><EFBFBD>성</h3>
|
||||
<button onclick="closeBatchCreateModal()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
|
||||
</div>
|
||||
<div id="batchSelectedInfo" class="mb-3 text-sm text-gray-600"></div>
|
||||
<div class="mb-3">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">그룹명</label>
|
||||
<input type="text" id="bcName" class="w-full px-3 py-2 border rounded-lg text-sm" placeholder="예: 4월 소모품 1차">
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-3 mb-3">
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">분류</label>
|
||||
<select id="bcCategory" class="w-full px-3 py-2 border rounded-lg text-sm">
|
||||
<option value="">자동 분류</option>
|
||||
<option value="consumable">소모품</option>
|
||||
<option value="safety">안전<EFBFBD><EFBFBD><EFBFBD>품</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>
|
||||
<select id="bcVendor" class="w-full px-3 py-2 border rounded-lg text-sm"></select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">메모</label>
|
||||
<input type="text" id="bcNotes" class="w-full px-3 py-2 border rounded-lg text-sm" placeholder="메모">
|
||||
</div>
|
||||
<div class="flex justify-end gap-2">
|
||||
<button type="button" onclick="closeBatchCreateModal()" class="px-4 py-2 border rounded-lg text-sm hover:bg-gray-50">취소</button>
|
||||
<button type="button" onclick="submitBatchCreate()" class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm hover:bg-blue-700">생성</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 입고 처리 <20><>달 -->
|
||||
<div id="receiveModal" class="hidden fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)closeReceiveModal()">
|
||||
<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 text-teal-700"><i class="fas fa-box-open mr-2"></i>입고 처리</h3>
|
||||
<button onclick="closeReceiveModal()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
|
||||
</div>
|
||||
<div id="receiveModalInfo" class="mb-4 p-3 bg-gray-50 rounded-lg"></div>
|
||||
<div class="mb-3">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">보관 위치</label>
|
||||
<input type="text" id="rcLocation" class="w-full px-3 py-2 border rounded-lg text-sm" placeholder="예: 1층 자재창고 A-3선반">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="block text-xs font-medium text-gray-600 mb-1">입고 사진 (선택)</label>
|
||||
<input type="file" id="rcPhotoInput" accept="image/*,.heic,.heif" onchange="onReceivePhotoSelected(this)" class="text-sm">
|
||||
<div id="rcPhotoPreview" class="hidden mt-2">
|
||||
<img id="rcPhotoPreviewImg" class="w-24 h-24 rounded object-cover">
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end mt-4 gap-2">
|
||||
<button type="button" onclick="closeReceiveModal()" class="px-4 py-2 border rounded-lg text-sm hover:bg-gray-50">취소</button>
|
||||
<button type="button" onclick="submitReceive()" class="px-4 py-2 bg-teal-600 text-white rounded-lg text-sm hover:bg-teal-700">입고 확인</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/static/js/tkfb-core.js?v=2026033108"></script>
|
||||
<script src="/static/js/purchase-request.js?v=2026031602"></script>
|
||||
<script src="/static/js/tkfb-core.js?v=2026040101"></script>
|
||||
<script src="/static/js/purchase-request.js?v=2026040101"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -42,6 +42,7 @@ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; b
|
||||
.badge-gray { background: #f3f4f6; color: #6b7280; }
|
||||
.badge-orange { background: #fff7ed; color: #c2410c; }
|
||||
.badge-purple { background: #faf5ff; color: #7c3aed; }
|
||||
.badge-teal { background: #f0fdfa; color: #0d9488; }
|
||||
|
||||
/* Collapsible */
|
||||
.collapsible-content { max-height: 0; overflow: hidden; transition: max-height 0.3s ease; }
|
||||
|
||||
393
system1-factory/web/static/js/purchase-request-mobile.js
Normal file
393
system1-factory/web/static/js/purchase-request-mobile.js
Normal file
@@ -0,0 +1,393 @@
|
||||
/* ===== 소모품 신청 모바일 ===== */
|
||||
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 STATUS_LABELS = { pending: '대기', grouped: '구매진행중', purchased: '구매완료', received: '입고완료', hold: '보류' };
|
||||
const STATUS_COLORS = { pending: 'badge-amber', grouped: 'badge-blue', purchased: 'badge-green', received: 'badge-teal', hold: 'badge-gray' };
|
||||
const MATCH_LABELS = { exact: '정확', name: '이름', alias: '별칭', spec: '규격', chosung: '초성', chosung_alias: '초성' };
|
||||
|
||||
let currentPage = 1;
|
||||
let currentStatus = '';
|
||||
let totalPages = 1;
|
||||
let isLoadingMore = false;
|
||||
let requestsList = [];
|
||||
let photoBase64 = null;
|
||||
let searchTimer = null;
|
||||
let isRegisterMode = false;
|
||||
|
||||
/* ===== 상태 탭 필터 ===== */
|
||||
function filterByStatus(btn) {
|
||||
document.querySelectorAll('.pm-tab').forEach(t => t.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
currentStatus = btn.dataset.status;
|
||||
currentPage = 1;
|
||||
requestsList = [];
|
||||
loadRequests();
|
||||
}
|
||||
|
||||
/* ===== 신청 목록 로드 ===== */
|
||||
async function loadRequests(append = false) {
|
||||
try {
|
||||
if (!append) {
|
||||
document.getElementById('requestCards').innerHTML = '<div class="pm-loading">불러오는 중...</div>';
|
||||
}
|
||||
const params = new URLSearchParams({ page: currentPage, limit: 20 });
|
||||
if (currentStatus) params.set('status', currentStatus);
|
||||
|
||||
const res = await api('/purchase-requests/my-requests?' + params.toString());
|
||||
const items = res.data || [];
|
||||
totalPages = res.pagination?.totalPages || 1;
|
||||
|
||||
if (append) {
|
||||
requestsList = requestsList.concat(items);
|
||||
} else {
|
||||
requestsList = items;
|
||||
}
|
||||
renderCards();
|
||||
} catch (e) {
|
||||
document.getElementById('requestCards').innerHTML = `<div class="pm-empty"><i class="fas fa-exclamation-circle"></i>${escapeHtml(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderCards() {
|
||||
const container = document.getElementById('requestCards');
|
||||
if (!requestsList.length) {
|
||||
container.innerHTML = '<div class="pm-empty"><i class="fas fa-box-open"></i>신청 내역이 없습니다.</div>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = requestsList.map(r => {
|
||||
const itemName = r.item_name || r.custom_item_name || '-';
|
||||
const category = r.category || r.custom_category;
|
||||
const catLabel = CAT_LABELS[category] || category || '';
|
||||
const statusLabel = STATUS_LABELS[r.status] || r.status;
|
||||
const statusColor = STATUS_COLORS[r.status] || 'badge-gray';
|
||||
const isCustom = !r.item_id && r.custom_item_name;
|
||||
|
||||
return `<div class="pm-card" onclick="openDetail(${r.request_id})">
|
||||
<div class="pm-card-header">
|
||||
<div>
|
||||
<div class="pm-card-name">${escapeHtml(itemName)}${isCustom ? '<span class="pm-card-custom">(직접입력)</span>' : ''}</div>
|
||||
${catLabel ? `<span class="badge ${STATUS_COLORS[category] || 'badge-gray'} mt-1" style="font-size:11px">${catLabel}</span>` : ''}
|
||||
</div>
|
||||
<span class="badge ${statusColor}">${statusLabel}</span>
|
||||
</div>
|
||||
<div class="pm-card-meta">
|
||||
<span>수량: <span class="pm-card-qty">${r.quantity}</span></span>
|
||||
<span>${formatDate(r.request_date)}</span>
|
||||
${r.batch_name ? `<span><i class="fas fa-layer-group"></i> ${escapeHtml(r.batch_name)}</span>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
/* ===== 무한 스크롤 ===== */
|
||||
window.addEventListener('scroll', () => {
|
||||
if (isLoadingMore || currentPage >= totalPages) return;
|
||||
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 200) {
|
||||
isLoadingMore = true;
|
||||
currentPage++;
|
||||
document.getElementById('loadingMore').classList.remove('hidden');
|
||||
loadRequests(true).finally(() => {
|
||||
isLoadingMore = false;
|
||||
document.getElementById('loadingMore').classList.add('hidden');
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/* ===== 상세 바텀시트 ===== */
|
||||
function openDetail(requestId) {
|
||||
const r = requestsList.find(x => x.request_id === requestId);
|
||||
if (!r) return;
|
||||
|
||||
const itemName = r.item_name || r.custom_item_name || '-';
|
||||
const category = r.category || r.custom_category;
|
||||
const catLabel = CAT_LABELS[category] || category || '-';
|
||||
const statusLabel = STATUS_LABELS[r.status] || r.status;
|
||||
const statusColor = STATUS_COLORS[r.status] || 'badge-gray';
|
||||
|
||||
let html = `
|
||||
<div class="text-center mb-4">
|
||||
<div class="text-lg font-bold">${escapeHtml(itemName)}</div>
|
||||
<span class="badge ${statusColor} mt-2">${statusLabel}</span>
|
||||
</div>
|
||||
<div class="pm-detail-row"><span class="pm-detail-label">분류</span><span class="pm-detail-value">${catLabel}</span></div>
|
||||
<div class="pm-detail-row"><span class="pm-detail-label">수량</span><span class="pm-detail-value">${r.quantity}</span></div>
|
||||
<div class="pm-detail-row"><span class="pm-detail-label">신청일</span><span class="pm-detail-value">${formatDate(r.request_date)}</span></div>
|
||||
`;
|
||||
if (r.notes) {
|
||||
html += `<div class="pm-detail-row"><span class="pm-detail-label">메모</span><span class="pm-detail-value">${escapeHtml(r.notes)}</span></div>`;
|
||||
}
|
||||
if (r.batch_name) {
|
||||
html += `<div class="pm-detail-row"><span class="pm-detail-label">구매 그룹</span><span class="pm-detail-value">${escapeHtml(r.batch_name)}</span></div>`;
|
||||
}
|
||||
if (r.hold_reason) {
|
||||
html += `<div class="pm-detail-row"><span class="pm-detail-label">보류 사유</span><span class="pm-detail-value text-red-600">${escapeHtml(r.hold_reason)}</span></div>`;
|
||||
}
|
||||
|
||||
// 입고 정보
|
||||
if (r.status === 'received') {
|
||||
html += `<div class="mt-4 p-3 bg-teal-50 rounded-lg">
|
||||
<div class="text-sm font-semibold text-teal-700 mb-2"><i class="fas fa-box-open mr-1"></i>입고 완료</div>`;
|
||||
if (r.received_location) {
|
||||
html += `<div class="text-sm text-gray-700"><i class="fas fa-map-marker-alt mr-1 text-teal-500"></i>보관위치: ${escapeHtml(r.received_location)}</div>`;
|
||||
}
|
||||
if (r.received_at) {
|
||||
html += `<div class="text-xs text-gray-500 mt-1">${formatDateTime(r.received_at)}${r.received_by_name ? ' · ' + escapeHtml(r.received_by_name) : ''}</div>`;
|
||||
}
|
||||
if (r.received_photo_path) {
|
||||
html += `<img src="${r.received_photo_path}" class="pm-received-photo" onerror="this.style.display='none'">`;
|
||||
}
|
||||
html += `</div>`;
|
||||
}
|
||||
|
||||
// 신청 사진
|
||||
if (r.pr_photo_path) {
|
||||
html += `<div class="mt-3"><div class="text-xs text-gray-500 mb-1">첨부 사진</div><img src="${r.pr_photo_path}" class="pm-received-photo" onerror="this.style.display='none'"></div>`;
|
||||
}
|
||||
|
||||
document.getElementById('detailContent').innerHTML = html;
|
||||
document.getElementById('detailOverlay').classList.add('open');
|
||||
document.getElementById('detailSheet').classList.add('open');
|
||||
}
|
||||
|
||||
function closeDetailSheet() {
|
||||
document.getElementById('detailOverlay').classList.remove('open');
|
||||
document.getElementById('detailSheet').classList.remove('open');
|
||||
}
|
||||
|
||||
/* ===== 신청 바텀시트 ===== */
|
||||
function openRequestSheet() {
|
||||
document.getElementById('requestOverlay').classList.add('open');
|
||||
document.getElementById('requestSheet').classList.add('open');
|
||||
document.getElementById('searchInput').focus();
|
||||
}
|
||||
|
||||
function closeRequestSheet() {
|
||||
document.getElementById('requestOverlay').classList.remove('open');
|
||||
document.getElementById('requestSheet').classList.remove('open');
|
||||
resetRequestForm();
|
||||
}
|
||||
|
||||
function resetRequestForm() {
|
||||
document.getElementById('searchInput').value = '';
|
||||
document.getElementById('searchResults').classList.remove('open');
|
||||
document.getElementById('selectedItemWrap').classList.add('hidden');
|
||||
document.getElementById('selectedItemId').value = '';
|
||||
document.getElementById('selectedCustomName').value = '';
|
||||
document.getElementById('newItemForm').classList.add('hidden');
|
||||
document.getElementById('reqQuantity').value = '1';
|
||||
document.getElementById('reqNotes').value = '';
|
||||
document.getElementById('reqPhotoInput').value = '';
|
||||
document.getElementById('reqPhotoPreview').classList.add('hidden');
|
||||
document.getElementById('photoLabel').textContent = '사진 촬영/선택';
|
||||
photoBase64 = null;
|
||||
isRegisterMode = false;
|
||||
}
|
||||
|
||||
/* ===== 서버 스마트 검색 ===== */
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const input = document.getElementById('searchInput');
|
||||
input.addEventListener('input', () => {
|
||||
clearTimeout(searchTimer);
|
||||
const q = input.value.trim();
|
||||
if (q.length === 0) {
|
||||
document.getElementById('searchResults').classList.remove('open');
|
||||
document.getElementById('searchSpinner').classList.remove('show');
|
||||
return;
|
||||
}
|
||||
document.getElementById('searchSpinner').classList.add('show');
|
||||
searchTimer = setTimeout(async () => {
|
||||
try {
|
||||
const res = await api('/purchase-requests/search?q=' + encodeURIComponent(q));
|
||||
renderSearchResults(res.data || [], q);
|
||||
} catch (e) {
|
||||
console.error('검색 오류:', e);
|
||||
} finally {
|
||||
document.getElementById('searchSpinner').classList.remove('show');
|
||||
}
|
||||
}, 300);
|
||||
});
|
||||
});
|
||||
|
||||
function renderSearchResults(items, query) {
|
||||
const container = document.getElementById('searchResults');
|
||||
let html = '';
|
||||
|
||||
items.forEach(item => {
|
||||
const catLabel = CAT_LABELS[item.category] || '';
|
||||
const matchLabel = MATCH_LABELS[item._matchType] || '';
|
||||
const spec = item.spec ? ' [' + escapeHtml(item.spec) + ']' : '';
|
||||
const maker = item.maker ? ' (' + escapeHtml(item.maker) + ')' : '';
|
||||
html += `<div class="pm-search-item" onclick="selectSearchItem(${item.item_id})">
|
||||
<div class="flex-1">
|
||||
<div class="text-sm font-medium">${escapeHtml(item.item_name)}${spec}${maker}</div>
|
||||
${catLabel ? `<div class="text-xs text-gray-400 mt-0.5">${catLabel}</div>` : ''}
|
||||
</div>
|
||||
${matchLabel ? `<span class="match-type">${matchLabel}</span>` : ''}
|
||||
</div>`;
|
||||
});
|
||||
|
||||
// 새 품목 등록 옵션
|
||||
html += `<div class="pm-search-register" onclick="selectNewItem()">
|
||||
<i class="fas fa-plus-circle"></i>
|
||||
<span>"${escapeHtml(query)}" 새 품목으로 등록 후 신청</span>
|
||||
</div>`;
|
||||
|
||||
container.innerHTML = html;
|
||||
container.classList.add('open');
|
||||
}
|
||||
|
||||
/* ===== 품목 선택 ===== */
|
||||
let searchItemsCache = [];
|
||||
|
||||
function selectSearchItem(itemId) {
|
||||
// API 검색 결과에서 선택 — searchResults에서 데이터 가져오기
|
||||
api('/purchase-requests/search?q=' + encodeURIComponent(document.getElementById('searchInput').value.trim()))
|
||||
.then(res => {
|
||||
const item = (res.data || []).find(i => i.item_id === itemId);
|
||||
if (!item) return;
|
||||
document.getElementById('selectedItemId').value = item.item_id;
|
||||
document.getElementById('selectedCustomName').value = '';
|
||||
document.getElementById('selectedItemName').textContent = item.item_name + (item.spec ? ' [' + item.spec + ']' : '') + (item.maker ? ' (' + item.maker + ')' : '');
|
||||
document.getElementById('selectedItemMeta').textContent = (CAT_LABELS[item.category] || '') + (item.base_price ? ' · ' + Number(item.base_price).toLocaleString() + '원' : '');
|
||||
document.getElementById('selectedItemWrap').classList.remove('hidden');
|
||||
document.getElementById('searchResults').classList.remove('open');
|
||||
document.getElementById('newItemForm').classList.add('hidden');
|
||||
isRegisterMode = false;
|
||||
});
|
||||
}
|
||||
|
||||
function selectNewItem() {
|
||||
const query = document.getElementById('searchInput').value.trim();
|
||||
if (!query) return;
|
||||
document.getElementById('selectedItemId').value = '';
|
||||
document.getElementById('selectedCustomName').value = query;
|
||||
document.getElementById('selectedItemName').textContent = query;
|
||||
document.getElementById('selectedItemMeta').textContent = '직접 입력';
|
||||
document.getElementById('selectedItemWrap').classList.remove('hidden');
|
||||
document.getElementById('searchResults').classList.remove('open');
|
||||
|
||||
// 신규 등록 폼 표시
|
||||
document.getElementById('newItemForm').classList.remove('hidden');
|
||||
document.getElementById('newItemName').value = query;
|
||||
isRegisterMode = true;
|
||||
}
|
||||
|
||||
function clearSelectedItem() {
|
||||
document.getElementById('selectedItemWrap').classList.add('hidden');
|
||||
document.getElementById('selectedItemId').value = '';
|
||||
document.getElementById('selectedCustomName').value = '';
|
||||
document.getElementById('newItemForm').classList.add('hidden');
|
||||
document.getElementById('searchInput').value = '';
|
||||
isRegisterMode = false;
|
||||
}
|
||||
|
||||
/* ===== 사진 ===== */
|
||||
async function onMobilePhotoSelected(inputEl) {
|
||||
const file = inputEl.files[0];
|
||||
if (!file) return;
|
||||
let processFile = file;
|
||||
|
||||
const isHeic = file.type === 'image/heic' || file.type === 'image/heif' ||
|
||||
file.name.toLowerCase().endsWith('.heic') || file.name.toLowerCase().endsWith('.heif');
|
||||
if (isHeic && typeof heic2any !== 'undefined') {
|
||||
document.getElementById('photoLabel').textContent = '변환 중...';
|
||||
try {
|
||||
const blob = await heic2any({ blob: file, toType: 'image/jpeg', quality: 0.85 });
|
||||
processFile = new File([blob], file.name.replace(/\.hei[cf]$/i, '.jpg'), { type: 'image/jpeg' });
|
||||
} catch (e) {
|
||||
console.warn('HEIC 변환 실패, 원본 사용:', e);
|
||||
// 폴백: 원본 파일 그대로 사용
|
||||
}
|
||||
}
|
||||
|
||||
if (processFile.size > 10 * 1024 * 1024) {
|
||||
showToast('파일 크기는 10MB 이하만 가능합니다.', 'error');
|
||||
document.getElementById('photoLabel').textContent = '사진 촬영/선택';
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
photoBase64 = e.target.result;
|
||||
document.getElementById('reqPhotoPreview').src = photoBase64;
|
||||
document.getElementById('reqPhotoPreview').classList.remove('hidden');
|
||||
document.getElementById('photoLabel').textContent = '사진 변경';
|
||||
};
|
||||
reader.readAsDataURL(processFile);
|
||||
}
|
||||
|
||||
/* ===== 신청 제출 ===== */
|
||||
async function submitRequest() {
|
||||
const itemId = document.getElementById('selectedItemId').value;
|
||||
const customName = document.getElementById('selectedCustomName').value;
|
||||
const quantity = parseInt(document.getElementById('reqQuantity').value) || 0;
|
||||
|
||||
if (!itemId && !customName) { showToast('품목을 선택하거나 검색해주세요.', 'error'); return; }
|
||||
if (quantity < 1) { showToast('수량은 1 이상이어야 합니다.', 'error'); return; }
|
||||
|
||||
const btn = document.getElementById('submitBtn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = '처리 중...';
|
||||
|
||||
try {
|
||||
if (isRegisterMode && customName) {
|
||||
// Phase 4: 인라인 등록 + 신청
|
||||
const body = {
|
||||
item_name: customName,
|
||||
spec: document.getElementById('newItemSpec').value.trim() || null,
|
||||
maker: document.getElementById('newItemMaker').value.trim() || null,
|
||||
category: document.getElementById('newItemCategory').value || null,
|
||||
quantity,
|
||||
notes: document.getElementById('reqNotes').value.trim() || null
|
||||
};
|
||||
if (photoBase64) body.photo = photoBase64;
|
||||
await api('/purchase-requests/register-and-request', {
|
||||
method: 'POST', body: JSON.stringify(body)
|
||||
});
|
||||
} else {
|
||||
// 기존 방식
|
||||
const body = { quantity, notes: document.getElementById('reqNotes').value.trim() };
|
||||
if (itemId) {
|
||||
body.item_id = parseInt(itemId);
|
||||
} else {
|
||||
body.custom_item_name = customName;
|
||||
body.custom_category = document.getElementById('newItemCategory')?.value || null;
|
||||
}
|
||||
if (photoBase64) body.photo = photoBase64;
|
||||
await api('/purchase-requests', {
|
||||
method: 'POST', body: JSON.stringify(body)
|
||||
});
|
||||
}
|
||||
|
||||
showToast('소모품 신청이 등록되었습니다.');
|
||||
closeRequestSheet();
|
||||
currentPage = 1;
|
||||
requestsList = [];
|
||||
await loadRequests();
|
||||
} catch (e) {
|
||||
showToast(e.message, 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = '신청하기';
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== URL 파라미터로 상세 열기 ===== */
|
||||
function checkViewParam() {
|
||||
const urlParams = new URLSearchParams(location.search);
|
||||
const viewId = urlParams.get('view');
|
||||
if (viewId) {
|
||||
// 데이터 로드 후 상세 열기
|
||||
setTimeout(() => openDetail(parseInt(viewId)), 500);
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== Init ===== */
|
||||
(async function() {
|
||||
if (!await initAuth()) return;
|
||||
await loadRequests();
|
||||
checkViewParam();
|
||||
})();
|
||||
@@ -7,8 +7,8 @@ const CAT_LABELS = { consumable: '소모품', safety: '안전용품', repair: '
|
||||
const CAT_COLORS = { consumable: 'badge-blue', safety: 'badge-green', repair: 'badge-amber', equipment: 'badge-purple' };
|
||||
const CAT_BG = { consumable: '#dbeafe', safety: '#dcfce7', repair: '#fef3c7', equipment: '#f3e8ff' };
|
||||
const CAT_FG = { consumable: '#1e40af', safety: '#166534', repair: '#92400e', equipment: '#7e22ce' };
|
||||
const STATUS_LABELS = { pending: '대기', purchased: '구매완료', hold: '보류' };
|
||||
const STATUS_COLORS = { pending: 'badge-amber', purchased: 'badge-green', hold: 'badge-gray' };
|
||||
const STATUS_LABELS = { pending: '대기', grouped: '구매진행중', purchased: '구매완료', received: '입고완료', hold: '보류' };
|
||||
const STATUS_COLORS = { pending: 'badge-amber', grouped: 'badge-blue', purchased: 'badge-green', received: 'badge-teal', hold: 'badge-gray' };
|
||||
|
||||
function _fmtSpec(spec) { return spec ? ' [' + spec + ']' : ''; }
|
||||
|
||||
@@ -21,6 +21,8 @@ let isAdmin = false;
|
||||
let photoBase64 = null;
|
||||
let searchDebounceTimer = null;
|
||||
let dropdownActiveIndex = -1;
|
||||
let selectedRequestIds = new Set();
|
||||
let batchesVisible = false;
|
||||
|
||||
async function loadInitialData() {
|
||||
try {
|
||||
@@ -310,8 +312,18 @@ async function loadRequests() {
|
||||
|
||||
function renderRequests() {
|
||||
const tbody = document.getElementById('prRequestList');
|
||||
selectedRequestIds.clear();
|
||||
updateSelectedCount();
|
||||
|
||||
// admin이면 체크박스 열 보이기, 그룹 버튼 보이기
|
||||
if (isAdmin) {
|
||||
document.getElementById('thCheckbox').style.display = '';
|
||||
document.getElementById('batchActions').classList.remove('hidden');
|
||||
document.getElementById('batchViewBtn').classList.remove('hidden');
|
||||
}
|
||||
|
||||
if (!requestsList.length) {
|
||||
tbody.innerHTML = '<tr><td colspan="7" class="px-4 py-8 text-center text-gray-400">소모품 신청 내역이 없습니다.</td></tr>';
|
||||
tbody.innerHTML = `<tr><td colspan="${isAdmin ? 8 : 7}" class="px-4 py-8 text-center text-gray-400">소모품 신청 내역이 없습니다.</td></tr>`;
|
||||
return;
|
||||
}
|
||||
tbody.innerHTML = requestsList.map(r => {
|
||||
@@ -336,6 +348,11 @@ function renderRequests() {
|
||||
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 === 'grouped') {
|
||||
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 === 'purchased') {
|
||||
actions = `<button onclick="openReceiveModal(${r.request_id})" class="px-2 py-1 bg-teal-500 text-white rounded text-xs hover:bg-teal-600" title="입고 처리"><i class="fas fa-box-open"></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>`;
|
||||
}
|
||||
@@ -343,13 +360,18 @@ function renderRequests() {
|
||||
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>`;
|
||||
}
|
||||
|
||||
const cbCell = isAdmin && r.status === 'pending'
|
||||
? `<td class="px-2 py-3 text-center" style="${isAdmin ? '' : 'display:none'}"><input type="checkbox" class="request-cb h-4 w-4" data-id="${r.request_id}" onchange="onRequestChecked()"></td>`
|
||||
: `<td class="px-2 py-3" style="${isAdmin ? '' : 'display:none'}"></td>`;
|
||||
|
||||
return `<tr class="hover:bg-gray-50">
|
||||
${cbCell}
|
||||
<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(itemName)}${r.spec ? ' <span class="text-gray-400">[' + escapeHtml(r.spec) + ']</span>' : ''}${isCustom ? ' <span class="text-xs text-orange-500">(직접입력)</span>' : ''}</div>
|
||||
<div class="text-xs text-gray-500">${escapeHtml(r.maker || '')}</div>
|
||||
<div class="text-xs text-gray-500">${escapeHtml(r.maker || '')}${r.batch_name ? ' <span class="text-blue-500"><i class="fas fa-layer-group"></i> ' + escapeHtml(r.batch_name) + '</span>' : ''}</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
@@ -508,6 +530,197 @@ async function deleteRequest(requestId) {
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
/* ===== 그룹화 기능 ===== */
|
||||
function onRequestChecked() {
|
||||
selectedRequestIds.clear();
|
||||
document.querySelectorAll('.request-cb:checked').forEach(cb => {
|
||||
selectedRequestIds.add(parseInt(cb.dataset.id));
|
||||
});
|
||||
updateSelectedCount();
|
||||
}
|
||||
|
||||
function updateSelectedCount() {
|
||||
const el = document.getElementById('selectedCount');
|
||||
if (el) el.textContent = selectedRequestIds.size + '건 선택';
|
||||
}
|
||||
|
||||
function toggleSelectAll(masterCb) {
|
||||
document.querySelectorAll('.request-cb').forEach(cb => {
|
||||
cb.checked = masterCb.checked;
|
||||
});
|
||||
onRequestChecked();
|
||||
}
|
||||
|
||||
function openBatchCreateModal() {
|
||||
if (selectedRequestIds.size === 0) { showToast('그룹에 포함할 신청 건을 선택해주세요.', 'error'); return; }
|
||||
document.getElementById('batchSelectedInfo').textContent = `${selectedRequestIds.size}건의 신청을 그룹으로 묶습니다.`;
|
||||
document.getElementById('bcName').value = '';
|
||||
document.getElementById('bcCategory').value = '';
|
||||
document.getElementById('bcNotes').value = '';
|
||||
// 업체 셀렉트 채우기
|
||||
const sel = document.getElementById('bcVendor');
|
||||
sel.innerHTML = '<option value="">업체 선택</option>' +
|
||||
vendorsList.map(v => `<option value="${v.vendor_id}">${escapeHtml(v.vendor_name)}</option>`).join('');
|
||||
document.getElementById('batchCreateModal').classList.remove('hidden');
|
||||
}
|
||||
|
||||
function closeBatchCreateModal() {
|
||||
document.getElementById('batchCreateModal').classList.add('hidden');
|
||||
}
|
||||
|
||||
async function submitBatchCreate() {
|
||||
const body = {
|
||||
batch_name: document.getElementById('bcName').value.trim() || null,
|
||||
category: document.getElementById('bcCategory').value || null,
|
||||
vendor_id: parseInt(document.getElementById('bcVendor').value) || null,
|
||||
notes: document.getElementById('bcNotes').value.trim() || null,
|
||||
request_ids: Array.from(selectedRequestIds)
|
||||
};
|
||||
try {
|
||||
await api('/purchase-batches', { method: 'POST', body: JSON.stringify(body) });
|
||||
showToast('구매 그룹이 생성되었습니다.');
|
||||
closeBatchCreateModal();
|
||||
selectedRequestIds.clear();
|
||||
await loadRequests();
|
||||
if (batchesVisible) await loadBatches();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
function toggleBatchView() {
|
||||
batchesVisible = !batchesVisible;
|
||||
document.getElementById('batchView').classList.toggle('hidden', !batchesVisible);
|
||||
if (batchesVisible) loadBatches();
|
||||
}
|
||||
|
||||
async function loadBatches() {
|
||||
try {
|
||||
const res = await api('/purchase-batches');
|
||||
const batches = res.data || [];
|
||||
const container = document.getElementById('batchList');
|
||||
if (!batches.length) {
|
||||
container.innerHTML = '<div class="text-gray-400 text-center py-4">생성된 그룹이 없습니다.</div>';
|
||||
return;
|
||||
}
|
||||
const BATCH_STATUS = { pending: { label: '진행중', color: 'badge-blue' }, purchased: { label: '구매완료', color: 'badge-green' }, received: { label: '입고완료', color: 'badge-teal' } };
|
||||
container.innerHTML = batches.map(b => {
|
||||
const s = BATCH_STATUS[b.status] || { label: b.status, color: 'badge-gray' };
|
||||
return `<div class="flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50">
|
||||
<div>
|
||||
<span class="font-medium">${escapeHtml(b.batch_name || '그룹 #' + b.batch_id)}</span>
|
||||
<span class="badge ${s.color} ml-2">${s.label}</span>
|
||||
<span class="text-xs text-gray-400 ml-2">${b.request_count || 0}건</span>
|
||||
${b.vendor_name ? `<span class="text-xs text-gray-400 ml-1">· ${escapeHtml(b.vendor_name)}</span>` : ''}
|
||||
</div>
|
||||
<div class="flex gap-1">
|
||||
${b.status === 'pending' ? `<button onclick="batchPurchase(${b.batch_id})" class="px-2 py-1 bg-orange-500 text-white rounded text-xs hover:bg-orange-600" title="일괄 구매"><i class="fas fa-shopping-cart"></i></button>
|
||||
<button onclick="batchDelete(${b.batch_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>` : ''}
|
||||
${b.status === 'purchased' ? `<button onclick="batchReceive(${b.batch_id})" class="px-2 py-1 bg-teal-500 text-white rounded text-xs hover:bg-teal-600" title="일괄 입고"><i class="fas fa-box-open"></i></button>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
} catch (e) { console.error('그룹 목록 로드 실패:', e); }
|
||||
}
|
||||
|
||||
async function batchPurchase(batchId) {
|
||||
if (!confirm('이 그룹의 모든 신청을 구매완료 처리하시겠습니까?')) return;
|
||||
try {
|
||||
await api(`/purchase-batches/${batchId}/purchase`, { method: 'POST' });
|
||||
showToast('일괄 구매 처리 완료.');
|
||||
await Promise.all([loadRequests(), loadBatches()]);
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
async function batchDelete(batchId) {
|
||||
if (!confirm('이 그룹을 삭제하시겠습니까? 포함된 신청은 대기 상태로 복원됩니다.')) return;
|
||||
try {
|
||||
await api(`/purchase-batches/${batchId}`, { method: 'DELETE' });
|
||||
showToast('그룹이 삭제되었습니다.');
|
||||
await Promise.all([loadRequests(), loadBatches()]);
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
async function batchReceive(batchId) {
|
||||
// 간단한 입고 — 위치만 입력
|
||||
const location = prompt('보관 위치를 입력하세요 (선택):');
|
||||
if (location === null) return; // 취소
|
||||
try {
|
||||
await api(`/purchase-batches/${batchId}/receive`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ received_location: location || null })
|
||||
});
|
||||
showToast('일괄 입고 처리 완료.');
|
||||
await Promise.all([loadRequests(), loadBatches()]);
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
/* ===== 입고 처리 모달 ===== */
|
||||
let currentRequestForReceive = null;
|
||||
let receivePhotoBase64 = null;
|
||||
|
||||
function openReceiveModal(requestId) {
|
||||
const r = requestsList.find(x => x.request_id === requestId);
|
||||
if (!r) return;
|
||||
currentRequestForReceive = r;
|
||||
const itemName = r.item_name || r.custom_item_name || '-';
|
||||
document.getElementById('receiveModalInfo').innerHTML = `
|
||||
<div class="font-medium">${escapeHtml(itemName)}</div>
|
||||
<div class="text-xs text-gray-500 mt-1">수량: ${r.quantity} | 신청자: ${escapeHtml(r.requester_name || '')}</div>
|
||||
`;
|
||||
document.getElementById('rcLocation').value = '';
|
||||
receivePhotoBase64 = null;
|
||||
document.getElementById('rcPhotoPreview').classList.add('hidden');
|
||||
document.getElementById('rcPhotoInput').value = '';
|
||||
document.getElementById('receiveModal').classList.remove('hidden');
|
||||
}
|
||||
|
||||
function closeReceiveModal() {
|
||||
document.getElementById('receiveModal').classList.add('hidden');
|
||||
currentRequestForReceive = null;
|
||||
receivePhotoBase64 = null;
|
||||
}
|
||||
|
||||
async function onReceivePhotoSelected(inputEl) {
|
||||
const file = inputEl.files[0];
|
||||
if (!file) return;
|
||||
let processFile = file;
|
||||
const isHeic = file.type === 'image/heic' || file.type === 'image/heif' ||
|
||||
file.name.toLowerCase().endsWith('.heic') || file.name.toLowerCase().endsWith('.heif');
|
||||
if (isHeic && typeof heic2any !== 'undefined') {
|
||||
try {
|
||||
const blob = await heic2any({ blob: file, toType: 'image/jpeg', quality: 0.85 });
|
||||
processFile = new File([blob], file.name.replace(/\.hei[cf]$/i, '.jpg'), { type: 'image/jpeg' });
|
||||
} catch (e) {
|
||||
// 변환 실패 시 원본 시도
|
||||
console.warn('HEIC 변환 실패, 원본 사용:', e);
|
||||
}
|
||||
}
|
||||
if (processFile.size > 10 * 1024 * 1024) { showToast('파일 크기는 10MB 이하만 가능합니다.', 'error'); return; }
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
receivePhotoBase64 = e.target.result;
|
||||
document.getElementById('rcPhotoPreviewImg').src = receivePhotoBase64;
|
||||
document.getElementById('rcPhotoPreview').classList.remove('hidden');
|
||||
};
|
||||
reader.readAsDataURL(processFile);
|
||||
}
|
||||
|
||||
async function submitReceive() {
|
||||
if (!currentRequestForReceive) return;
|
||||
const received_location = document.getElementById('rcLocation').value.trim();
|
||||
const body = { received_location };
|
||||
if (receivePhotoBase64) body.photo = receivePhotoBase64;
|
||||
|
||||
try {
|
||||
await api(`/purchase-requests/${currentRequestForReceive.request_id}/receive`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
showToast('입고 처리가 완료되었습니다.');
|
||||
closeReceiveModal();
|
||||
await loadRequests();
|
||||
} catch (e) { showToast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
/* ===== Init ===== */
|
||||
(async function() {
|
||||
if (!await initAuth()) return;
|
||||
|
||||
@@ -20,6 +20,11 @@
|
||||
label: '작업보고',
|
||||
icon: '<svg ' + SVG_ATTR + '><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>'
|
||||
},
|
||||
{
|
||||
href: '/pages/purchase/request-mobile.html',
|
||||
label: '소모품',
|
||||
icon: '<svg ' + SVG_ATTR + '><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>'
|
||||
},
|
||||
{
|
||||
href: '/pages/attendance/my-vacation-info.html',
|
||||
label: '연차관리',
|
||||
|
||||
@@ -133,7 +133,8 @@ const NAV_MENU = [
|
||||
{ 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/purchase/request-mobile.html', icon: 'fa-shopping-cart', label: '소모품 신청', key: 'purchase.request_mobile' },
|
||||
{ href: '/pages/purchase/request.html', icon: 'fa-clipboard-list', label: '소모품 관리', key: 'purchase.request' },
|
||||
{ href: '/pages/admin/purchase-analysis.html', icon: 'fa-chart-line', label: '소모품 분석', key: 'purchase.analysis', admin: true },
|
||||
]},
|
||||
{ cat: '근태 관리', items: [
|
||||
|
||||
@@ -169,21 +169,36 @@ const notificationController = {
|
||||
return res.status(403).json({ success: false, message: '권한이 없습니다.' });
|
||||
}
|
||||
|
||||
const { type, title, message, link_url, reference_type, reference_id, created_by } = req.body;
|
||||
const { type, title, message, link_url, reference_type, reference_id, created_by, target_user_ids } = req.body;
|
||||
|
||||
if (!title) {
|
||||
return res.status(400).json({ success: false, message: '알림 제목은 필수입니다.' });
|
||||
}
|
||||
|
||||
const results = await notificationModel.createTypedNotification({
|
||||
type: type || 'system',
|
||||
title,
|
||||
message,
|
||||
link_url,
|
||||
reference_type,
|
||||
reference_id,
|
||||
created_by
|
||||
});
|
||||
let results;
|
||||
if (target_user_ids && Array.isArray(target_user_ids) && target_user_ids.length > 0) {
|
||||
// 특정 사용자 직접 알림 (type 기반 브로드캐스트 대신)
|
||||
results = await notificationModel.createTargetedNotification({
|
||||
type: type || 'system',
|
||||
title,
|
||||
message,
|
||||
link_url,
|
||||
reference_type,
|
||||
reference_id,
|
||||
created_by,
|
||||
target_user_ids
|
||||
});
|
||||
} else {
|
||||
results = await notificationModel.createTypedNotification({
|
||||
type: type || 'system',
|
||||
title,
|
||||
message,
|
||||
link_url,
|
||||
reference_type,
|
||||
reference_id,
|
||||
created_by
|
||||
});
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
|
||||
@@ -304,6 +304,31 @@ const notificationModel = {
|
||||
|
||||
sendPushToUsers(recipientIds, { title, body: message || '', url: link_url || '/' });
|
||||
|
||||
return results;
|
||||
},
|
||||
|
||||
// 특정 사용자 직접 알림 (target_user_ids 기반, type 브로드캐스트 아님)
|
||||
async createTargetedNotification(notificationData) {
|
||||
const { type, title, message, link_url, reference_type, reference_id, created_by, target_user_ids } = notificationData;
|
||||
|
||||
const results = [];
|
||||
for (const userId of target_user_ids) {
|
||||
const notificationId = await this.create({
|
||||
user_id: userId,
|
||||
type,
|
||||
title,
|
||||
message,
|
||||
link_url,
|
||||
reference_type,
|
||||
reference_id,
|
||||
created_by
|
||||
});
|
||||
results.push(notificationId);
|
||||
}
|
||||
|
||||
// ntfy + WebPush 발송
|
||||
sendPushToUsers(target_user_ids, { title, body: message || '', url: link_url || '/' });
|
||||
|
||||
return results;
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user