goods.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const { ObjectId } = require('mongoose').Types;
  7. //
  8. class GoodsService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'goods');
  11. this.goodsModel = this.ctx.model.Shop.Goods;
  12. this.goodsSpecModel = this.ctx.model.Shop.GoodsSpec;
  13. this.gjaModel = this.ctx.model.Shop.GoodsJoinAct;
  14. this.goodsTagsModel = this.ctx.model.System.GoodsTags;
  15. this.platformActModel = this.ctx.model.System.PlatformAct;
  16. this.gjaModel = this.ctx.model.Shop.GoodsJoinAct;
  17. this.actTagsModel = this.ctx.model.System.ActTags;
  18. this.goodsConfigModel = this.ctx.model.Shop.GoodsConfig;
  19. this.userModel = this.ctx.model.User.User;
  20. this.setModel = this.ctx.model.Shop.GoodsSet;
  21. }
  22. /**
  23. *
  24. * @param {Object} query 查询条件
  25. * @param query.id 商品数据id
  26. */
  27. async goodsDetail({ id }) {
  28. assert(id, '缺少商品信息');
  29. const pipeline = [{ $match: { _id: ObjectId(id) } }];
  30. const goodsProject = { file: 1, tags: 1, name: 1, shot_brief: 1, brief: 1, send_time: 1, shop: 1, view_num: 1, act_tags: 1, sell_num: 1 };
  31. // 将 活动标签都进行数据替换
  32. pipeline.push({
  33. $lookup: {
  34. from: 'actTags',
  35. localField: 'act_tags',
  36. foreignField: 'value',
  37. pipeline: [{ $match: { show_goods: '0' } }, { $project: { label: 1 } }],
  38. as: 'act_tags',
  39. },
  40. });
  41. // 找店铺信息
  42. pipeline.push({ $addFields: { shop_id: { $toObjectId: '$shop' } } });
  43. pipeline.push({
  44. $lookup: {
  45. from: 'shop',
  46. localField: 'shop_id',
  47. foreignField: '_id',
  48. pipeline: [
  49. { $addFields: { shop_id: { $toString: '$_id' } } },
  50. // 计算店铺商品总数
  51. {
  52. $lookup: {
  53. from: 'goods',
  54. localField: 'shop_id',
  55. foreignField: 'shop',
  56. pipeline: [{ $match: { status: '1' } }, { $count: 'gn' }],
  57. as: 'gn',
  58. },
  59. },
  60. { $project: { logo: 1, name: 1, person: 1, phone: 1, _id: 1, goods_score: 1, send_score: 1, service_score: 1, goods_num: { $first: '$gn.gn' } } },
  61. ],
  62. as: 'shopInfo',
  63. },
  64. });
  65. pipeline.push({ $project: { ...goodsProject, shopInfo: { $first: '$shopInfo' } } });
  66. // 找规格
  67. pipeline.push({ $addFields: { goods_id: { $toString: '$_id' } } });
  68. pipeline.push({
  69. $lookup: {
  70. from: 'goodsSpec',
  71. localField: 'goods_id',
  72. foreignField: 'goods',
  73. pipeline: [
  74. {
  75. $project: {
  76. sell_money: { $toDouble: '$sell_money' },
  77. flow_money: { $toDouble: '$flow_money' },
  78. freight: { $toDouble: '$freight' },
  79. name: 1,
  80. num: 1,
  81. buy_limit: 1,
  82. limit_num: 1,
  83. file: 1,
  84. leader_price: 1,
  85. },
  86. },
  87. ],
  88. as: 'specs',
  89. },
  90. });
  91. pipeline.push({ $project: { ...goodsProject, goods_id: 1, specs: 1, shopInfo: 1 } });
  92. // 找到商品是否参与活动,且该活动是否正在进行
  93. pipeline.push({
  94. $lookup: {
  95. from: 'goodsJoinAct',
  96. localField: 'goods_id',
  97. foreignField: 'goods._id',
  98. pipeline: [
  99. { $addFields: { pa: { $toObjectId: '$platform_act' } } },
  100. {
  101. $lookup: {
  102. from: 'platformAct',
  103. localField: 'pa',
  104. foreignField: '_id',
  105. pipeline: [{ $match: { is_use: '0' } }],
  106. as: 'act',
  107. },
  108. },
  109. { $unwind: '$act' },
  110. { $replaceRoot: { newRoot: '$act' } },
  111. { $project: { act_time: 1, config: 1, type: 1 } },
  112. ],
  113. as: 'act',
  114. },
  115. });
  116. // 整理数据
  117. pipeline.push({
  118. $project: {
  119. _id: 0,
  120. goods: {
  121. _id: '$$CURRENT._id',
  122. brief: '$$CURRENT.brief',
  123. file: '$$CURRENT.file',
  124. name: '$$CURRENT.name',
  125. send_time: '$$CURRENT.send_time',
  126. tags: '$$CURRENT.tags',
  127. act_tags: '$$CURRENT.act_tags',
  128. shot_brief: '$$CURRENT.shot_brief',
  129. view_num: '$$CURRENT.view_num',
  130. sell_num: '$$CURRENT.sell_num',
  131. },
  132. shop: '$shopInfo',
  133. specs: '$specs',
  134. act: '$act',
  135. },
  136. });
  137. const res = await this.goodsModel.aggregate(pipeline);
  138. let data = _.head(res);
  139. if (data) data = JSON.parse(JSON.stringify(data));
  140. if (data.goods.tags.length > 0) {
  141. const nt = [];
  142. for (const t of data.goods.tags) {
  143. const code = _.last(t);
  144. const data = await this.goodsTagsModel.findOne({ code }, 'label');
  145. nt.push(data);
  146. }
  147. data.goods.tags = nt;
  148. }
  149. for (const d of data.act) {
  150. const { tag, text, aboutList } = await this.ctx.service.system.platformAct.getActText(d, data.goods);
  151. d.text = text;
  152. d.tag = tag;
  153. d.list = aboutList;
  154. if (d.type === '2') {
  155. // 处理赠品与规格的显示问题
  156. for (const i of d.list) {
  157. const spec = data.specs.find(f => f._id === i.spec);
  158. if (spec) i.spec_name = _.get(spec, 'name');
  159. }
  160. }
  161. }
  162. data.act = _.uniqBy(data.act, '_id');
  163. const user_id = _.get(this.ctx, 'user._id');
  164. if (user_id) {
  165. // 检查团长价格
  166. const is_leader = await this.ctx.service.user.user.getUserIsLeader(user_id);
  167. if (is_leader) {
  168. data.specs = data.specs.map(i => {
  169. const { sell_money, leader_price } = i;
  170. const sm = this.ctx.toNumber(sell_money);
  171. const obj = { o_sell_money: sm };
  172. if (leader_price) {
  173. const lp = this.ctx.toNumber(leader_price);
  174. obj.leader_price = lp;
  175. obj.sell_money = lp;
  176. }
  177. return { ...i, ...obj };
  178. });
  179. } else {
  180. data.specs = data.specs.map(i => _.omit(i, [ 'leader_price' ]));
  181. }
  182. } else {
  183. data.specs = data.specs.map(i => _.omit(i, [ 'leader_price' ]));
  184. }
  185. const sets = await this.getGoodsSetList(data);
  186. data.sets = sets;
  187. return data;
  188. }
  189. /**
  190. * 套装查询
  191. * @param data
  192. */
  193. async getGoodsSetList(data) {
  194. const goods = _.get(data, 'goods');
  195. if (!goods) return [];
  196. const goodsSetList = await this.setModel.find({ goods: goods._id, is_use: '0' }).lean();
  197. const arr = [];
  198. for (const sd of goodsSetList) {
  199. const { _id, set = [], sell_money, name } = sd;
  200. const obj = { _id, name, sell_money, goods_total: set.length };
  201. const newSet = [];
  202. for (const s of set) {
  203. const { goods, goods_name, spec, spec_name } = s;
  204. const goodsData = await this.goodsModel.findById(goods, { file: 1 }).lean();
  205. const specData = await this.goodsSpecModel.findById(spec, { file: 1 }).lean();
  206. const file = [ ..._.get(specData, 'file', []), ..._.get(goodsData, 'file', []) ];
  207. const newSetData = { goods, goods_name, spec_name, file };
  208. newSet.push(newSetData);
  209. }
  210. obj.set = newSet;
  211. arr.push(obj);
  212. }
  213. return arr;
  214. }
  215. async indexGoodsList(condition, { skip = 0, limit = 20 } = {}) {
  216. condition = this.dealFilter(condition);
  217. const pipeline = [{ $match: { status: { $ne: '0' } } }]; // { $sort: { sort: 1 } },
  218. const { view_num, sell_num, sell_money, name, shop, tags, act_tags } = condition;
  219. let sort = {};
  220. if (view_num) sort.view_num = parseInt(view_num);
  221. if (sell_num) sort.sell_num = parseInt(sell_num);
  222. if (sell_money) sort.sell_money = parseInt(sell_money);
  223. if (name) pipeline.push({ $match: { name: new RegExp(name) } });
  224. if (shop) pipeline.push({ $match: { shop } });
  225. if (tags) pipeline.push({ $match: { tags: { $elemMatch: { $elemMatch: { $eq: tags } } } } });
  226. if (act_tags) pipeline.push({ $match: { act_tags: { $elemMatch: { $eq: act_tags } } } });
  227. pipeline.push({
  228. $addFields: { goods_id: { $toString: '$_id' }, create_time: { $dateToString: { date: '$meta.createdAt', format: '%Y-%m-%d %H:%M:%S', timezone: '+08:00' } } },
  229. });
  230. // 表关联
  231. pipeline.push({
  232. $lookup: {
  233. from: 'goodsSpec',
  234. localField: 'goods_id',
  235. foreignField: 'goods',
  236. as: 'specs',
  237. },
  238. });
  239. // 按照规格平铺数据
  240. pipeline.push({ $unwind: '$specs' });
  241. // 格式化平铺后的数据
  242. pipeline.push({
  243. $project: {
  244. name: 1,
  245. view_num: 1,
  246. sell_num: 1,
  247. file: 1,
  248. sort: 1,
  249. create_time: 1,
  250. sell_money: { $toDouble: '$specs.sell_money' },
  251. flow_money: { $toDouble: '$specs.flow_money' },
  252. leader_price: { $toDouble: '$specs.leader_price' },
  253. num: '$specs.num',
  254. act_tags: 1,
  255. },
  256. });
  257. pipeline.push({
  258. $group: {
  259. _id: '$_id',
  260. data: { $min: '$$CURRENT' },
  261. },
  262. });
  263. pipeline.push({
  264. $project: {
  265. name: '$data.name',
  266. view_num: '$data.view_num',
  267. sell_num: '$data.sell_num',
  268. file: '$data.file',
  269. sell_money: '$data.sell_money',
  270. flow_money: '$data.flow_money',
  271. leader_price: '$data.leader_price',
  272. num: '$data.num',
  273. create_time: '$data.create_time',
  274. sort: '$data.sort',
  275. act_tags: '$data.act_tags',
  276. },
  277. });
  278. if (Object.keys(sort).length <= 0) sort = { sort: -1, create_time: -1 };
  279. pipeline.push({ $sort: { ...sort, sort: -1, create_time: -1 } });
  280. // 分页处理
  281. const qpipeline = _.cloneDeep(pipeline);
  282. if (parseInt(skip)) qpipeline.push({ $skip: parseInt(skip) });
  283. if (parseInt(limit)) qpipeline.push({ $limit: parseInt(limit) });
  284. let list = await this.goodsModel.aggregate(qpipeline);
  285. list = list.map(i => {
  286. const obj = _.pick(i, [ 'name', 'file', 'num', 'flow_money', 'sell_money', 'view_num', '_id', 'actTagsShow', 'act_tags', 'leader_price' ]);
  287. if (obj.leader_price) obj.leader_price = this.ctx.toNumber(obj.leader_price);
  288. return obj;
  289. });
  290. // 处理活动标签
  291. await this.getActTags(list);
  292. // 实时匹配活动
  293. // 只找: 买赠;特价;满减/折; 特价需要修改价格; 剩下的打标签
  294. const platformActList = await this.platformActModel.find({ is_use: '0', type: [ '2', '3', '5', '6' ] });
  295. await this.getAboutAct(platformActList, list);
  296. // 检查团长价格
  297. const user_id = _.get(this.ctx, 'user._id');
  298. const is_leader = await this.ctx.service.user.user.getUserIsLeader(user_id);
  299. if (!is_leader) {
  300. list = list.map(i => _.omit(i, [ 'leader_price' ]));
  301. } else {
  302. for (const i of list) {
  303. const { leader_price, _id: goods } = i;
  304. if (leader_price) continue;
  305. let specs = await this.goodsSpecModel.find({ goods, leader_price: { $gt: 0 } }, { leader_price: 1 }).lean();
  306. specs = _.orderBy(specs, [ 'leader_price' ], [ 'asc' ]);
  307. const head = _.head(specs);
  308. i.leader_price = this.ctx.toNumber(_.get(head, 'leader_price', 0));
  309. }
  310. }
  311. const tpipeline = _.cloneDeep(pipeline);
  312. tpipeline.push({ $count: 'total' });
  313. const total = await this.goodsModel.aggregate(tpipeline);
  314. return { list, total: _.get(_.head(total), 'total', 0) };
  315. }
  316. async getActTags(list) {
  317. let tags = list.map(i => i.act_tags);
  318. tags = _.flattenDeep(tags);
  319. tags = _.uniq(tags);
  320. tags = _.compact(tags);
  321. const tagsData = await this.actTagsModel.find({ value: tags, show_goods: '0' });
  322. for (const i of list) {
  323. const { act_tags = [] } = i;
  324. const actTagsShow = [];
  325. if (act_tags.length > 0) {
  326. for (const t of act_tags) {
  327. const r = tagsData.find(f => f.value === t);
  328. if (r) actTagsShow.push({ label: r.label });
  329. }
  330. }
  331. i.actTagsShow = actTagsShow;
  332. delete i.act_tags;
  333. }
  334. }
  335. /**
  336. * 处理商品有关活动部分
  337. * @param {Array} platformActList 正在进行中的活动
  338. * @param {Array} list 查询商品
  339. */
  340. async getAboutAct(platformActList, list) {
  341. const platform_act = platformActList.map(i => ObjectId(i._id).toString());
  342. for (const goods of list) {
  343. const { _id: goods_id, p_act = [], sell_money } = goods;
  344. const gjaList = await this.gjaModel.find({ platform_act, 'goods._id': ObjectId(goods_id).toString() });
  345. if (gjaList.length <= 0) continue;
  346. for (const gja of gjaList) {
  347. const { platform_act_type: type } = gja;
  348. if (type === '2' && gjaList.length > 0) p_act.push('买赠');
  349. else if (type === '3' && gjaList.length > 0) {
  350. p_act.push('特价');
  351. let sortList = JSON.parse(JSON.stringify(gjaList));
  352. sortList = sortList.map(i => ({ ...i, sp_price: _.get(i, 'config.sp_price', 0) }));
  353. sortList = _.orderBy(sortList, [ 'sp_price' ], [ 'asc' ]);
  354. sortList = sortList.filter(f => this.ctx.minus(0, f.sp_price) < 0);
  355. const lp = _.get(_.head(sortList), 'sp_price');
  356. if (lp && this.ctx.minus(lp, sell_money) < 0) goods.sell_money = lp;
  357. } else if (type === '5' && gjaList.length > 0) p_act.push('满减');
  358. else if (type === '6' && gjaList.length > 0) p_act.push('满折');
  359. goods.p_act = _.uniq(p_act);
  360. }
  361. }
  362. }
  363. async indexActTagsGoods() {
  364. // 将使用中且展示在首页的查出来排序
  365. const list = await this.ctx.model.System.ActTags.find({ status: '0', show_index: '0' }).sort({ sort: 1 });
  366. const result = [];
  367. for (const t of list) {
  368. const { label, value } = t;
  369. const list = await this.searchActTagsGoods(value);
  370. const arr = [];
  371. for (const g of list) {
  372. const obj = {
  373. url: _.get(g, 'file'),
  374. name: _.get(g, 'name'),
  375. id: _.get(g, '_id'),
  376. value,
  377. };
  378. if (arr.length === 0) {
  379. obj.title = label;
  380. }
  381. arr.push(obj);
  382. }
  383. result.push({ list: arr });
  384. }
  385. return result;
  386. }
  387. async searchActTagsGoods(act_tags, limit = 2) {
  388. const pipeline = [{ $sort: { 'meta.createdAt': -1 } }, { $match: { status: { $ne: '0' }, act_tags } }];
  389. pipeline.push({ $project: { name: 1, file: 1 } });
  390. if (parseInt(limit)) pipeline.push({ $limit: parseInt(limit) });
  391. const list = await this.goodsModel.aggregate(pipeline);
  392. return list;
  393. }
  394. // 弃用
  395. async searchLeaderPrice(list) {
  396. for (const i of list) {
  397. const { _id: goods } = i;
  398. let gcl = await this.goodsConfigModel.find({ goods }).lean();
  399. gcl = _.orderBy(gcl, [ 'leader_price' ], [ 'asc' ]);
  400. i.leader_price = _.get(_.head(gcl), 'leader_price');
  401. }
  402. return list;
  403. }
  404. }
  405. module.exports = GoodsService;