'use strict'; const MainService = require('../main'); /** * OpenAPI 单品服务。 * 提供商品(单品)的同步与查询能力,映射到 StockStore 底层模型。 */ class OpenapiSingleitemService extends MainService { /** * 同步(新增或更新)单品信息。 * 上下文(storeId/warehouseId/appKey/warehouseCode)已由 dispatchOpenapiMethod 统一注入。 * 将外部系统的商品数据写入 StockStore,并自动同步到库存表。 * @param {Object} payload 调用参数。 * @param {Object} payload.body 请求体数据,仅需包含 item;warehouseCode 和 ownerCode 由 app_key 自动解析,调用方不得传入。 * @param {Object} payload.query 请求 query 数据。 * @return {Promise} 同步结果,成功时返回 itemId。 */ async synchronize(payload = {}) { const { body = {} } = payload; const { item } = body; if (!item || !item.itemCode) { return this.fail('item 参数缺失或不完整(缺少 itemCode)'); } try { const { storeId, warehouseId, appKey, warehouseCode } = this.getInfo(); const ownerCode = storeId ? String(storeId) : ''; const requestData = { warehouseCode: warehouseCode || '', ownerCode: ownerCode || '', item, }; const stockData = await this.ctx.service.systems.stockStore.initQimenStockData( requestData, appKey, storeId, warehouseId ); const result = await this.ctx.service.systems.stockStore.create(stockData); return this.success('同步完成', { itemId: result.id }); } catch (error) { return this.fail(`同步失败: ${error.message}`); } } /** * 查询单品详情。 * 上下文(storeId)已由 dispatchOpenapiMethod 统一注入,查询按货主范围过滤。 * 根据 itemId 查询 StockStore 记录并转换为 OpenAPI 统一格式。 * @param {Object} payload 调用参数。 * @param {Object} payload.body 请求体数据,需包含 itemId。 * @param {Object} payload.query 请求 query 数据。 * @return {Promise} 查询结果,成功时返回商品详情。 */ async query(payload = {}) { const { body = {} } = payload; const { itemId } = body; if (!itemId) { return this.fail('itemId 参数缺失'); } try { const { storeId } = this.getInfo(); const row = await this.ctx.model.StockStore.findOne({ where: { id: itemId, store_id: storeId, }, }); if (!row) { return this.fail(`商品不存在,itemId: ${itemId}`); } const result = await this.ctx.service.systems.stockStore.convertToQimenFormat(row); return this.success('查询成功', result); } catch (error) { return this.fail(`查询失败: ${error.message}`); } } } module.exports = OpenapiSingleitemService;