// 委外工单管理
(() => {
let orderList = [];
let customerOrders = [];
let currentPage = 1;
const pageSize = 20;
const statusMap = {
'pending': { text: '待发料', color: 'var(--warning)' },
'issued': { text: '已发料', color: 'var(--info)' },
'completed': { text: '已完成', color: 'var(--success)' },
'cancelled': { text: '已取消', color: 'var(--text-2)' }
};
Router.register('/outsourcing-mgmt/orders', async () => {
const html = `
`;
setTimeout(() => {
document.getElementById('add-order-btn')?.addEventListener('click', () => openModal());
document.getElementById('search-keyword')?.addEventListener('keypress', (e) => {
if (e.key === 'Enter') search();
});
loadList();
loadCustomerOrders();
}, 0);
return html;
});
async function loadList() {
try {
const res = await API.get('/api/outsourcing-orders');
orderList = res.list || [];
renderList();
} catch (e) {
console.error('加载委外工单失败:', e);
document.getElementById('order-list').innerHTML = '| 加载失败 |
';
}
}
async function loadCustomerOrders() {
try {
const res = await API.get('/api/customer-orders-for-outsourcing');
customerOrders = res.list || [];
const select = document.getElementById('customer-order-no');
if (select) {
select.innerHTML = '' +
customerOrders.map(o => ``).join('');
}
} catch (e) {
console.error('加载客户订单失败:', e);
}
}
function renderList() {
const tbody = document.getElementById('order-list');
const keyword = (document.getElementById('search-keyword')?.value || '').toLowerCase();
let filtered = orderList;
if (keyword) {
filtered = orderList.filter(item =>
(item.order_no || '').toLowerCase().includes(keyword) ||
(item.customer_order_no || '').toLowerCase().includes(keyword) ||
(item.product_code || '').toLowerCase().includes(keyword) ||
(item.product_name || '').toLowerCase().includes(keyword)
);
}
const totalPages = Math.ceil(filtered.length / pageSize);
const start = (currentPage - 1) * pageSize;
const pageData = filtered.slice(start, start + pageSize);
if (pageData.length === 0) {
tbody.innerHTML = '| 暂无数据 |
';
} else {
tbody.innerHTML = pageData.map(item => {
const status = statusMap[item.status] || { text: item.status, color: 'var(--text-2)' };
return `
| ${escapeHtml(item.order_no || '')} |
${escapeHtml(item.customer_order_no || '')} |
${escapeHtml(item.product_code || '')} |
${escapeHtml(item.product_name || '')} |
${item.production_qty || 0} |
${escapeHtml(item.outsourcing_factory || '')} |
${escapeHtml(item.delivery_date || '')} |
${status.text} |
${escapeHtml(item.created_by || '')} |
${formatTime(item.created_at)} |
|
`;
}).join('');
}
renderPagination(totalPages);
}
function renderPagination(totalPages) {
const container = document.getElementById('pagination');
if (totalPages <= 1) {
container.innerHTML = '';
return;
}
let html = '';
html += ``;
html += `第 ${currentPage} / ${totalPages} 页`;
html += ``;
container.innerHTML = html;
}
let editingId = null;
function openModal(item = null) {
editingId = item?.id || null;
document.getElementById('modal-title').textContent = item ? '编辑委外工单' : '新增委外工单';
document.getElementById('customer-order-no').value = item?.customer_order_no || '';
document.getElementById('product-code').value = item?.product_code || '';
document.getElementById('product-name').value = item?.product_name || '';
document.getElementById('production-qty').value = item?.production_qty || 1;
document.getElementById('outsourcing-factory').value = item?.outsourcing_factory || '';
document.getElementById('delivery-date').value = item?.delivery_date || '';
document.getElementById('material-list-section').style.display = 'none';
document.getElementById('order-modal').style.display = 'flex';
}
function closeModal() {
document.getElementById('order-modal').style.display = 'none';
editingId = null;
}
async function save() {
const data = {
customer_order_no: document.getElementById('customer-order-no').value.trim(),
product_code: document.getElementById('product-code').value.trim(),
product_name: document.getElementById('product-name').value.trim(),
production_qty: parseInt(document.getElementById('production-qty').value) || 0,
outsourcing_factory: document.getElementById('outsourcing-factory').value.trim(),
delivery_date: document.getElementById('delivery-date').value.trim()
};
if (!data.customer_order_no || !data.product_code || !data.product_name || !data.outsourcing_factory || !data.delivery_date) {
alert('请填写所有必填字段');
return;
}
if (data.production_qty <= 0) {
alert('生产数量必须大于0');
return;
}
try {
if (editingId) {
await API.put(`/api/outsourcing-orders/${editingId}`, data);
alert('更新成功');
} else {
const res = await API.post('/api/outsourcing-orders', data);
alert(`委外工单创建成功,工单号:${res.order_no}`);
}
closeModal();
loadList();
} catch (e) {
alert(e.message || '操作失败');
}
}
async function viewDetail(id) {
try {
const res = await API.get(`/api/outsourcing-orders/${id}`);
const order = res.order;
const materials = res.materials || [];
document.getElementById('modal-title').textContent = '查看委外工单';
document.getElementById('customer-order-no').value = order.customer_order_no || '';
document.getElementById('product-code').value = order.product_code || '';
document.getElementById('product-name').value = order.product_name || '';
document.getElementById('production-qty').value = order.production_qty || 0;
document.getElementById('outsourcing-factory').value = order.outsourcing_factory || '';
document.getElementById('delivery-date').value = order.delivery_date || '';
if (materials.length > 0) {
document.getElementById('material-list-section').style.display = 'block';
document.getElementById('material-list').innerHTML = materials.map(m => `
| ${escapeHtml(m.material_code)} |
${escapeHtml(m.material_name)} |
${m.bom_unit_qty} |
${m.need_qty} |
${escapeHtml(m.unit)} |
`).join('');
}
document.getElementById('order-modal').style.display = 'flex';
} catch (e) {
alert(e.message || '获取详情失败');
}
}
async function deleteOrder(id) {
if (!confirm('确定要删除这条委外工单吗?')) return;
try {
await API.delete(`/api/outsourcing-orders/${id}`);
alert('删除成功');
loadList();
} catch (e) {
alert(e.message || '删除失败');
}
}
function search() {
currentPage = 1;
renderList();
}
function resetSearch() {
document.getElementById('search-keyword').value = '';
currentPage = 1;
renderList();
}
function goPage(page) {
currentPage = page;
renderList();
}
function formatTime(ts) {
if (!ts) return '-';
try {
const d = new Date(ts);
return d.toLocaleString('zh-CN', { hour12: false });
} catch {
return ts;
}
}
function escapeHtml(str) {
if (!str) return '';
return String(str).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"');
}
window.OutsourcingOrders = {
search,
resetSearch,
viewDetail,
deleteOrder,
closeModal,
save,
goPage
};
})();