'use strict'; const Service = require('egg').Service; const { parseWhereConditions } = require('../../../lib/query_condition_parser'); class EntryService extends Service { /** * 灏嗚垂鐢ㄨ褰曠瓫閫夊€煎綊涓€鍖栦负 0/1銆? * @param {unknown} rawValue 鍘熷绛涢€夊€? * @return {number|null} 褰掍竴鍖栫粨鏋滐紝鏃犳硶璇嗗埆鏃惰繑鍥?null */ normalizeExpenseRecordValue(rawValue) { if (rawValue === true) return 1; if (rawValue === false) return 0; if (rawValue === 1 || rawValue === '1') return 1; if (rawValue === 0 || rawValue === '0') return 0; if (typeof rawValue === 'string') { const normalized = rawValue.trim().toLowerCase(); if ([ 'true', 'yes', 'y' ].includes(normalized)) return 1; if ([ 'false', 'no', 'n' ].includes(normalized)) return 0; } return null; } /** * 褰掍竴鍖?expense_record 鏉′欢锛屽吋瀹?eq/in/甯冨皵鍊煎啓娉曘€? * @param {Object|number|string|boolean} condition 鍘熷鏉′欢 * @return {Object|null} 鏍囧噯鍖栧悗鐨勬潯浠讹紝鏃犳硶璇嗗埆鏃惰繑鍥?null */ normalizeExpenseRecordCondition(condition) { const isObjectCondition = condition && typeof condition === 'object' && !Array.isArray(condition); if (!isObjectCondition) { const normalizedValue = this.normalizeExpenseRecordValue(condition); if (normalizedValue === null) { return null; } return { operator: 'eq', value: normalizedValue, }; } const operator = String(condition.operator || 'eq').trim().toLowerCase(); const values = this.normalizeFilterValues(condition) .map(item => this.normalizeExpenseRecordValue(item)) .filter(item => item !== null); if (values.length === 0) { return null; } if (operator === 'in') { return { operator: 'in', value: [ ...new Set(values) ], }; } return { operator: 'eq', value: values[0], }; } /** * 灏嗙瓫閫夊€煎綊涓€鍖栦负鏁扮粍銆? * @param {Object} condition 鏉′欢瀵硅薄 * @return {Array} 褰掍竴鍖栧悗鐨勫€兼暟缁? */ normalizeFilterValues(condition = {}) { const value = condition && Object.prototype.hasOwnProperty.call(condition, 'value') ? condition.value : undefined; if (Array.isArray(value)) { return value; } if (value === undefined || value === null) { return []; } return [ value ]; } /** * 鏋勫缓鍏ュ簱鍗?搴撳瓨娴佹按 EXISTS 瀛愭煡璇㈡潯浠躲€? * @param {string} fieldName 娴佹按瀛楁鍚? * @param {Object} condition 鏉′欢瀵硅薄 * @return {Object|null} Sequelize.where 鏉′欢锛屾棤娉曟瀯寤烘椂杩斿洖 null */ buildEntryStockTransactionExistsCondition(fieldName, condition = {}) { const { app } = this; const values = this.normalizeFilterValues(condition) .map(item => (typeof item === 'string' ? item.trim() : item)) .filter(item => item !== '' && item !== undefined && item !== null); if (values.length === 0) { return null; } const operator = String(condition.operator || 'eq').trim().toLowerCase(); const escapedColumn = `st.${fieldName}`; const escapedValues = values.map(item => app.Sequelize.escape(item)); let valueClause = ''; if (operator === 'in') { valueClause = `${escapedColumn} IN (${escapedValues.join(',')})`; } else if (operator === 'like' || operator === 'contains') { const likeClauses = values.map(item => `${escapedColumn} LIKE ${app.Sequelize.escape(`%${String(item)}%`)}`); valueClause = likeClauses.length === 1 ? likeClauses[0] : `(${likeClauses.join(' OR ')})`; } else { valueClause = `${escapedColumn} = ${escapedValues[0]}`; } const sql = `EXISTS ( SELECT 1 FROM wms_stock_transaction st WHERE st.entry_order_id = wms_entry_order.id AND ${valueClause} )`; return app.Sequelize.where(app.Sequelize.literal(sql), 1); } /** * 棰勫鐞嗗叆搴撳崟鍒楄〃绛涢€夋潯浠讹紝鍏煎鍘嗗彶鍒悕骞舵瀯寤烘墿灞曠瓫閫夈€? * @param {Object} normalizedWhere 鏍囧噯鍖栧悗鐨?where 鏉′欢 * @return {{where: Object, extraConditions: Array, errorMessage: string}} 棰勫鐞嗙粨鏋? */ preprocessEntryListWhere(normalizedWhere = {}) { const { ctx } = this; const whereForParse = normalizedWhere && typeof normalizedWhere === 'object' ? { ...normalizedWhere } : {}; const extraConditions = []; if (whereForParse.erp_remark && !whereForParse.remark) { whereForParse.remark = whereForParse.erp_remark; } delete whereForParse.erp_remark; const batchCondition = whereForParse.batch_no || whereForParse.batch; if (batchCondition) { const existsCondition = this.buildEntryStockTransactionExistsCondition('batch_no', batchCondition); if (existsCondition) { extraConditions.push(existsCondition); } } delete whereForParse.batch_no; delete whereForParse.batch; if (whereForParse.operator_id) { const existsCondition = this.buildEntryStockTransactionExistsCondition('operator_id', whereForParse.operator_id); if (existsCondition) { extraConditions.push(existsCondition); } } delete whereForParse.operator_id; if (Object.prototype.hasOwnProperty.call(whereForParse, 'expense_record')) { const hasExpenseRecordField = Boolean( ctx.model && ctx.model.EntryOrder && ctx.model.EntryOrder.rawAttributes && ctx.model.EntryOrder.rawAttributes.expense_record ); if (!hasExpenseRecordField) { return { where: {}, extraConditions: [], errorMessage: '褰撳墠鐜鏈彁渚?expense_record 瀛楁锛屾殏涓嶆敮鎸佽绛涢€夋潯浠讹紝璇峰厛瀹屾垚琛ㄧ粨鏋勫崌绾?, }; } const normalizedExpenseRecord = this.normalizeExpenseRecordCondition(whereForParse.expense_record); if (normalizedExpenseRecord) { whereForParse.expense_record = normalizedExpenseRecord; } else { delete whereForParse.expense_record; } } return { where: whereForParse, extraConditions, errorMessage: '', }; } /** * 鍏ュ簱鍗曞垪琛ㄦ煡璇紝澶嶇敤 where 瑙f瀯宸ュ叿銆? * @param {Object} where 绛涢€夋潯浠跺璞? * @param {Object} pageParams 鍒嗛〉鍙傛暟 * @param {Object} sortParams 鎺掑簭鍙傛暟 * @return {Promise} code/data/message 缁撴瀯 */ async list(where = {}, pageParams = {}, sortParams = {}) { const { ctx, app } = this; const { Sequelize } = app; const { Op } = Sequelize; const page = Math.max(Number(pageParams.page) || 1, 1); const pageSize = Math.max(Number(pageParams.pageSize) || 20, 1); const sortField = sortParams.sortField || 'created_at'; const sortOrder = String(sortParams.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; const validSortFields = [ 'id', 'entry_order_code', 'order_type', 'order_status', 'order_create_time', 'created_at', 'updated_at', 'total_order_lines', ]; const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at'; const baseWhere = { warehouse_id: ctx.user.store_id, is_enabled: 1, deleted_at: null, }; const normalizedWhere = ctx.where && typeof ctx.where === 'object' ? { ...ctx.where } : (where && typeof where === 'object' ? { ...where } : {}); const { where: parsedSourceWhere, extraConditions, errorMessage, } = this.preprocessEntryListWhere(normalizedWhere); if (errorMessage) { return { code: 400, message: errorMessage, data: { list: [], pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false, }, summary: { total: 0, pending: 0, creating: 0, created: 0, completed: 0, cancelled: 0, }, }, }; } const parsed = parseWhereConditions({ where: parsedSourceWhere, app, specialFieldMap: { quickWhere: { bucket: 'quick', }, }, }); if (!parsed.ok) { return { code: 400, message: `绛涢€夋潯浠惰В鏋愬け璐? ${parsed.reason}`, data: { list: [], pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false, }, summary: { total: 0, pending: 0, creating: 0, created: 0, completed: 0, cancelled: 0, }, }, }; } const parsedResult = parsed.result; const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) || parsedSourceWhere.quickWhere || null; const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' ? quickWhereInput.value : null; const andConditions = [ baseWhere ]; if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { const kw = String(quickWhereValue).trim(); andConditions.push({ [Op.or]: [ { entry_order_code: { [Op.like]: `%${kw}%` } }, { purchase_order_code: { [Op.like]: `%${kw}%` } }, { supplier_name: { [Op.like]: `%${kw}%` } }, { store_name: { [Op.like]: `%${kw}%` } }, { warehouse_name: { [Op.like]: `%${kw}%` } }, ], }); } const dynamicConditions = parsedResult.dynamicConditions || []; if (dynamicConditions.length > 0) { andConditions.push({ [Op.and]: dynamicConditions }); } if (extraConditions.length > 0) { andConditions.push({ [Op.and]: extraConditions }); } const finalWhere = { [Op.and]: andConditions }; const include = [ { model: ctx.model.Store, as: 'warehouse', attributes: [ 'id', 'company_name' ], required: false, }, { model: ctx.model.Store, as: 'store', attributes: [ 'id', 'company_name' ], required: false, }, ]; const { count, rows } = await ctx.model.EntryOrder.findAndCountAll({ where: finalWhere, include, order: [[ actualSortField, sortOrder ]], limit: pageSize, offset: (page - 1) * pageSize, distinct: true, }); const statusRows = await ctx.model.EntryOrder.findAll({ attributes: [ 'order_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ], ], where: finalWhere, group: [ 'order_status' ], raw: true, }); const summary = { total: count, pending: 0, creating: 0, created: 0, completed: 0, cancelled: 0, }; statusRows.forEach(item => { const statusKey = String(item.order_status || '').toLowerCase(); if (Object.prototype.hasOwnProperty.call(summary, statusKey)) { summary[statusKey] = Number(item.count) || 0; } }); return { code: 200, message: '鏌ヨ鎴愬姛', data: { list: rows, pagination: { page, pageSize, total: count, totalPages: Math.ceil(count / pageSize), hasPrevious: page > 1, hasNext: page < Math.ceil(count / pageSize), }, summary, }, }; } /** * 鏌ヨ鍏ュ簱鍗曡鎯呫€? * @param {Object} data 璇锋眰浣? * @return {Promise} code/data/message 缁撴瀯 */ async get(data = {}) { const { ctx } = this; const id = Number(data.id || 0); const entryOrderCode = data.entry_order_code ? String(data.entry_order_code).trim() : ''; if (!id && !entryOrderCode) { return { code: 400, message: 'id 鎴?entry_order_code 鑷冲皯浼犱竴涓?, data: null, }; } const where = { warehouse_id: ctx.user.store_id, is_enabled: 1, deleted_at: null, }; if (id) { where.id = id; } else { where.entry_order_code = entryOrderCode; } const entryOrder = await ctx.model.EntryOrder.findOne({ where, include: [ { model: ctx.model.Store, as: 'warehouse', attributes: [ 'id', 'company_name' ], required: false, }, { model: ctx.model.Store, as: 'store', attributes: [ 'id', 'company_name' ], required: false, }, { model: ctx.model.EntryItems, as: 'items', include: [ { model: ctx.model.StockWarehouse, as: 'stock', attributes: [ 'id', 'item_code', 'item_name' ], required: false, }, ], required: false, }, ], }); if (!entryOrder) { return { code: 0, message: '鍏ュ簱鍗曚笉瀛樺湪鎴栨棤鏉冭闂?, data: null, }; } return { code: 200, message: '鏌ヨ鎴愬姛', data: { entryOrder, }, }; } generateOrderCode() { const randomPart = Math.floor(Math.random() * 1000).toString().padStart(3, '0'); return `ENT${Date.now()}${randomPart}`; } /** * 鍒涘缓鍏ュ簱鍗曘€? * @param {Object} data 璇锋眰浣? * @return {Promise} code/data/message 缁撴瀯 */ async create(data = {}) { const { ctx } = this; const allowedOrderTypes = new Set([ 'SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK', 'B2BRK', 'XNRK' ]); const orderType = String(data.order_type || '').trim(); const storeId = Number(data.store_id || ctx.user.store_id || 0); if (!orderType) { return { code: 400, message: 'order_type 蹇呭~', data: null, }; } if (!allowedOrderTypes.has(orderType)) { return { code: 400, message: 'order_type 涓嶅悎娉?, data: null, }; } if (!storeId) { return { code: 400, message: 'store_id 蹇呭~', data: null, }; } const entryOrderCode = data.entry_order_code && String(data.entry_order_code).trim() !== '' ? String(data.entry_order_code).trim() : this.generateOrderCode(); const exists = await ctx.model.EntryOrder.findOne({ where: { entry_order_code: entryOrderCode, warehouse_id: ctx.user.store_id, store_id: storeId, deleted_at: null, }, }); if (exists) { return { code: 409, message: '鍏ュ簱鍗曞彿宸插瓨鍦?, data: { id: exists.id, entry_order_code: exists.entry_order_code, }, }; } const order = await ctx.model.EntryOrder.create({ entry_order_code: entryOrderCode, order_type: orderType, purchase_order_code: data.purchase_order_code || '', total_order_lines: Number(data.total_order_lines || 0), order_create_time: data.order_create_time ? new Date(data.order_create_time) : new Date(), expect_start_time: data.expect_start_time ? new Date(data.expect_start_time) : null, expect_end_time: data.expect_end_time ? new Date(data.expect_end_time) : null, logistics_code: data.logistics_code || '', logistics_name: data.logistics_name || '', express_code: data.express_code || '', supplier_code: data.supplier_code || '', supplier_name: data.supplier_name || '', source_type: 'API', order_status: 'PENDING', sync_status: 'PENDING', sync_message: '', is_enabled: 1, warehouse_id: ctx.user.store_id, store_id: storeId, remark: data.remark || '', created_at: new Date(), updated_at: new Date(), }); return { code: 200, message: '鍒涘缓鎴愬姛', data: { id: order.id, entry_order_code: order.entry_order_code, }, }; } /** * 褰掍竴鍖栦綔搴熷叆鍙備腑鐨勫叆搴撳崟 ID 鍒楄〃銆? * 浼樺厛浣跨敤 ids锛涙湭浼?ids 鏃跺洖閫€鍒?id銆? * @param {Object} data 璇锋眰浣? * @return {{ ok: boolean, ids?: number[], code?: number, message?: string }} 褰掍竴鍖栫粨鏋? */ normalizeCancelEntryOrderIds(data = {}) { const hasIdsField = Object.prototype.hasOwnProperty.call(data, 'ids'); const hasIdField = Object.prototype.hasOwnProperty.call(data, 'id'); if (!hasIdsField && !hasIdField) { return { ok: false, code: 400, message: 'id 鎴?ids 蹇呭~', }; } const rawIds = hasIdsField ? data.ids : [ data.id ]; if (hasIdsField) { if (!Array.isArray(rawIds) || rawIds.length === 0) { return { ok: false, code: 400, message: 'ids 蹇呴』鏄潪绌烘暟缁?, }; } } else if (!Number.isInteger(Number(rawIds[0])) || Number(rawIds[0]) <= 0) { return { ok: false, code: 400, message: 'id 蹇呭~涓斿繀椤讳负姝f暣鏁?, }; } const normalizedIds = []; for (const rawId of rawIds) { const normalizedId = Number(rawId); if (!Number.isInteger(normalizedId) || normalizedId <= 0) { return { ok: false, code: 400, message: 'ids 蹇呴』涓烘鏁存暟鏁扮粍', }; } normalizedIds.push(normalizedId); } return { ok: true, ids: [ ...new Set(normalizedIds) ], }; } /** * 鏌ヨ褰撳墠浠撳簱鍙闂殑鍏ュ簱鍗曘€? * @param {number} id 鍏ュ簱鍗旾D * @return {Promise} 鍏ュ簱鍗曞疄渚? */ async getOwnedEntryOrderById(id) { const { ctx } = this; return await ctx.model.EntryOrder.findOne({ where: { id, warehouse_id: ctx.user.store_id, is_enabled: 1, deleted_at: null, }, }); } /** * 鏂板鍏ュ簱鏄庣粏銆? * @param {Object} data 璇锋眰浣? * @return {Promise} code/data/message 缁撴瀯 */ async addDetail(data = {}) { const { ctx } = this; const orderId = Number(data.order_id || 0); const count = Number(data.count || 0); if (!orderId) { return { code: 400, message: 'order_id 蹇呭~', data: null, }; } if (!count || count <= 0) { return { code: 400, message: 'count 蹇呴』澶т簬 0', data: null, }; } const entryOrder = await this.getOwnedEntryOrderById(orderId); if (!entryOrder) { return { code: 404, message: '鍏ュ簱鍗曚笉瀛樺湪鎴栨棤鏉冭闂?, data: null, }; } if (entryOrder.order_status === 'CANCELLED' || entryOrder.order_status === 'COMPLETED') { return { code: 400, message: '褰撳墠鐘舵€佷笉鍏佽鏂板鏄庣粏', data: null, }; } const maxLineNo = Number(await ctx.model.EntryItems.max('order_line_no', { where: { order_id: orderId }, })) || 0; const detail = await ctx.model.EntryItems.create({ order_id: orderId, order_line_no: maxLineNo + 1, item_code: data.item_code || '', item_id: data.item_id || null, stock_id: data.stock_id || data.item_id || null, count, inventory_type: data.inventory_type || 'ZP', received_quantity: 0, confirm_quantity: 0, owner_code: data.owner_code || '', out_biz_code: data.out_biz_code || '', }); await entryOrder.update({ total_order_lines: maxLineNo + 1, updated_at: new Date(), }); return { code: 200, message: '鏂板鏄庣粏鎴愬姛', data: { id: detail.id, order_id: orderId, }, }; } /** * 鍒犻櫎鍏ュ簱鏄庣粏銆? * @param {Object} data 璇锋眰浣? * @return {Promise} code/data/message 缁撴瀯 */ async deleteDetail(data = {}) { const { ctx } = this; const detailId = Number(data.id || 0); if (!detailId) { return { code: 400, message: 'id 蹇呭~', data: null, }; } const detail = await ctx.model.EntryItems.findByPk(detailId); if (!detail) { return { code: 404, message: '鏄庣粏涓嶅瓨鍦?, data: null, }; } const entryOrder = await this.getOwnedEntryOrderById(detail.order_id); if (!entryOrder) { return { code: 404, message: '鍏ュ簱鍗曚笉瀛樺湪鎴栨棤鏉冭闂?, data: null, }; } if (Number(detail.received_quantity || 0) > 0) { return { code: 400, message: '宸叉湁鏀惰揣鏁伴噺鐨勬槑缁嗕笉鍏佽鍒犻櫎', data: null, }; } await detail.destroy(); const lineCount = await ctx.model.EntryItems.count({ where: { order_id: entryOrder.id } }); await entryOrder.update({ total_order_lines: lineCount, updated_at: new Date(), }); return { code: 200, message: '鍒犻櫎鏄庣粏鎴愬姛', data: { id: detailId, }, }; } /** * 淇敼鍏ュ簱鏄庣粏銆? * @param {Object} data 璇锋眰浣? * @return {Promise} code/data/message 缁撴瀯 */ async detailChange(data = {}) { const { ctx } = this; const detailId = Number(data.id || 0); if (!detailId) { return { code: 400, message: 'id 蹇呭~', data: null, }; } const detail = await ctx.model.EntryItems.findByPk(detailId); if (!detail) { return { code: 404, message: '鏄庣粏涓嶅瓨鍦?, data: null, }; } const entryOrder = await this.getOwnedEntryOrderById(detail.order_id); if (!entryOrder) { return { code: 404, message: '鍏ュ簱鍗曚笉瀛樺湪鎴栨棤鏉冭闂?, data: null, }; } const updateData = {}; const mutableFields = [ 'item_code', 'item_id', 'inventory_type', 'stock_id', 'out_biz_code', 'owner_code' ]; for (const field of mutableFields) { if (Object.prototype.hasOwnProperty.call(data, field)) { updateData[field] = data[field]; } } if (Object.prototype.hasOwnProperty.call(data, 'count')) { const count = Number(data.count); if (!count || count <= 0) { return { code: 400, message: 'count 蹇呴』澶т簬 0', data: null, }; } if (Number(detail.received_quantity || 0) > count) { return { code: 400, message: 'count 涓嶈兘灏忎簬宸叉敹璐ф暟閲?, data: null, }; } updateData.count = count; } if (Object.keys(updateData).length === 0) { return { code: 400, message: '娌℃湁鍙洿鏂板瓧娈?, data: null, }; } await detail.update(updateData); return { code: 200, message: '淇敼鏄庣粏鎴愬姛', data: { id: detail.id, }, }; } /** * 浣滃簾鍏ュ簱鍗曘€? * @param {Object} data 璇锋眰浣? * @return {Promise} code/data/message 缁撴瀯 */ async cancel(data = {}) { const { ctx } = this; const normalizedResult = this.normalizeCancelEntryOrderIds(data); if (!normalizedResult.ok) { return { code: normalizedResult.code || 400, message: normalizedResult.message || '鍙傛暟閿欒', data: null, }; } const orderIds = normalizedResult.ids || []; const entryOrders = []; for (const orderId of orderIds) { const entryOrder = await this.getOwnedEntryOrderById(orderId); if (!entryOrder) { return { code: 404, message: '鍏ュ簱鍗曚笉瀛樺湪鎴栨棤鏉冭闂?, data: null, }; } if (entryOrder.order_status === 'COMPLETED') { return { code: 400, message: '宸插畬鎴愬叆搴撳崟涓嶅厑璁镐綔搴?, data: null, }; } entryOrders.push(entryOrder); } const transaction = ctx.model && typeof ctx.model.transaction === 'function' ? await ctx.model.transaction() : null; try { const updatedAt = new Date(); for (const entryOrder of entryOrders) { await entryOrder.update({ order_status: 'CANCELLED', updated_at: updatedAt, }, transaction ? { transaction, } : undefined); } if (transaction && typeof transaction.commit === 'function') { await transaction.commit(); } } catch (error) { if (transaction && typeof transaction.rollback === 'function') { await transaction.rollback(); } throw error; } return { code: 200, message: '浣滃簾鎴愬姛', data: { [orderIds.length === 1 ? 'id' : 'ids']: orderIds.length === 1 ? entryOrders[0].id : orderIds, }, }; } /** * 瀹屾垚鍏ュ簱鍗曘€? * @param {Object} data 璇锋眰浣? * @return {Promise} code/data/message 缁撴瀯 */ async completeEntry(data = {}) { const { ctx } = this; const orderId = Number(data.id || 0); if (!orderId) { return { code: 400, message: 'id 蹇呭~', data: null, }; } const entryOrder = await this.getOwnedEntryOrderById(orderId); if (!entryOrder) { return { code: 404, message: '鍏ュ簱鍗曚笉瀛樺湪鎴栨棤鏉冭闂?, data: null, }; } if (entryOrder.order_status === 'CANCELLED') { return { code: 400, message: '宸蹭綔搴熷叆搴撳崟涓嶅厑璁稿畬鎴?, data: null, }; } const detailCount = await ctx.model.EntryItems.count({ where: { order_id: orderId } }); if (detailCount <= 0) { return { code: 400, message: '璇峰厛娣诲姞鍏ュ簱鏄庣粏', data: null, }; } await entryOrder.update({ order_status: 'COMPLETED', updated_at: new Date(), }); return { code: 200, message: '瀹屾垚鎴愬姛', data: { id: entryOrder.id, }, }; } } module.exports = EntryService;