lrf 2 年之前
父節點
當前提交
f0dab5fcce
共有 3 個文件被更改,包括 37 次插入0 次删除
  1. 3 0
      app/controller/shop/config/.goods.js
  2. 33 0
      app/service/shop/goods.js
  3. 1 0
      app/z_router/shop/goods.js

+ 3 - 0
app/controller/shop/config/.goods.js

@@ -40,4 +40,7 @@ module.exports = {
       count: true,
     },
   },
+  toDuplicate: {
+    params: ['!id'],
+  },
 };

+ 33 - 0
app/service/shop/goods.js

@@ -3,12 +3,15 @@ const { CrudService } = require('naf-framework-mongoose-free/lib/service');
 const { BusinessError, ErrorCode } = require('naf-core').Error;
 const _ = require('lodash');
 const assert = require('assert');
+const Transaction = require('mongoose-transactions');
 
 //
 class GoodsService extends CrudService {
   constructor(ctx) {
     super(ctx, 'goods');
     this.model = this.ctx.model.Shop.Goods;
+    this.goodsSpecmodel = this.ctx.model.Shop.GoodsSpec;
+    this.tran = new Transaction();
   }
   // 标签查询
   async beforeQuery(filter) {
@@ -18,6 +21,36 @@ class GoodsService extends CrudService {
     }
     return filter;
   }
+
+  async toDuplicate({ id }) {
+    const data = await this.model.findById(id);
+    if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到数据');
+    let specList = await this.goodsSpecmodel.find({ goods: id });
+    if (specList.length > 0) specList = JSON.parse(JSON.stringify(specList));
+    const nd = JSON.parse(JSON.stringify(data));
+    delete nd.id;
+    delete nd._id;
+    delete nd.meta;
+    delete nd.__v;
+    try {
+      const id = this.tran.insert('Goods', nd);
+      specList = specList.map(i => {
+        delete i.id;
+        delete i._id;
+        delete i.meta;
+        delete i.__v;
+        i.goods = id;
+        return i;
+      });
+      for (const i of specList) this.tran.insert('GoodsSpec', i);
+      await this.tran.run();
+    } catch (error) {
+      console.log(error);
+      await this.tran.rollback();
+    } finally {
+      this.tran.clean();
+    }
+  }
 }
 
 module.exports = GoodsService;

+ 1 - 0
app/z_router/shop/goods.js

@@ -7,6 +7,7 @@ const rkey = 'goods';
 const ckey = 'shop.goods';
 const keyZh = '商品信息';
 const routes = [
+  { method: 'get', path: `${rkey}/toDuplicate/:id`, controller: `${ckey}.toDuplicate`, name: `${ckey}toDuplicate`, zh: `${keyZh}复制商品` },
   { method: 'get', path: `${rkey}`, controller: `${ckey}.index`, name: `${ckey}Query`, zh: `${keyZh}列表查询` },
   { method: 'get', path: `${rkey}/:id`, controller: `${ckey}.show`, name: `${ckey}Show`, zh: `${keyZh}查询` },
   { method: 'post', path: `${rkey}`, controller: `${ckey}.create`, name: `${ckey}Create`, zh: `创建${keyZh}` },