122 lines
3.1 KiB
JavaScript
122 lines
3.1 KiB
JavaScript
'use strict';
|
|
const Service = require('egg').Service;
|
|
|
|
class FileService extends Service {
|
|
async getImages(data) {
|
|
const { ctx } = this;
|
|
const result = await ctx.model.FileReference.findAll({ where: {
|
|
business_type: data.type,
|
|
business_id: data.id,
|
|
}, include: [
|
|
{
|
|
model: ctx.model.File,
|
|
as: 'file',
|
|
attributes: [ 'file_url', 'file_name' ],
|
|
required: true,
|
|
},
|
|
] });
|
|
return result;
|
|
}
|
|
async ReferenceFile(data) {
|
|
const { ctx, service } = this;
|
|
const { id, type, images } = data;
|
|
const warehouseId = ctx.user.store_id;
|
|
|
|
console.log('<<<type>>>>', type);
|
|
switch (type) {
|
|
case 'stock':
|
|
const stock = await ctx.model.StockWarehouse.findOne({
|
|
where: {
|
|
warehouse_id: warehouseId,
|
|
delete_at: null,
|
|
id,
|
|
},
|
|
raw: true,
|
|
});
|
|
if (!stock) {
|
|
throw new Error('找不到商品');
|
|
}
|
|
console.log('<<<images>>>>', images.length);
|
|
|
|
if (images.length > 0) {
|
|
await ctx.model.StockWarehouse.update({ is_images: 'Y' }, {
|
|
where: {
|
|
id: stock.id,
|
|
},
|
|
});
|
|
} else {
|
|
await ctx.model.StockWarehouse.update({ is_images: 'N' }, {
|
|
where: {
|
|
id: stock.id,
|
|
},
|
|
});
|
|
}
|
|
|
|
await service.systems.operationLog.createOperationLog({
|
|
businessType: 'stock',
|
|
businessId: id,
|
|
operationCode: 'UPDATE_IMAGES',
|
|
operator: {
|
|
id: ctx.user.id,
|
|
name: ctx.user.employees_name,
|
|
},
|
|
extras: {
|
|
warehouseId,
|
|
},
|
|
beforeChanges: null,
|
|
});
|
|
break;
|
|
|
|
default:
|
|
// code
|
|
}
|
|
// 获取现有的file_id
|
|
const existingRefs = await ctx.model.FileReference.findAll({
|
|
where: { business_type: type, business_id: id, warehouse_id: warehouseId },
|
|
});
|
|
const existingFileIds = existingRefs.map(item => item.file_id);
|
|
const newFileIds = images.map(item => item.file_id);
|
|
|
|
// 需要删除的ID
|
|
const toDeleteIds = existingFileIds.filter(id => !newFileIds.includes(id));
|
|
|
|
// 需要创建的记录
|
|
const toCreate = images.filter(item => !existingFileIds.includes(item.file_id));
|
|
|
|
// 批量操作
|
|
const promises = [];
|
|
|
|
if (toDeleteIds.length > 0) {
|
|
promises.push(
|
|
ctx.model.FileReference.destroy({
|
|
where: {
|
|
business_type: type,
|
|
business_id: id,
|
|
file_id: toDeleteIds,
|
|
warehouse_id: warehouseId,
|
|
},
|
|
})
|
|
);
|
|
}
|
|
|
|
if (toCreate.length > 0) {
|
|
const refData = toCreate.map(item => ({
|
|
business_type: type,
|
|
business_id: id,
|
|
warehouse_id: warehouseId,
|
|
file_id: item.file_id,
|
|
sort_order: item.sort_order || 0,
|
|
created_by: ctx.user.employees_name,
|
|
created_at: new Date(),
|
|
updated_at: new Date(),
|
|
}));
|
|
|
|
promises.push(ctx.model.FileReference.bulkCreate(refData));
|
|
}
|
|
await Promise.all(promises);
|
|
|
|
return { success: true };
|
|
}
|
|
}
|
|
module.exports = FileService;
|