goods.js 15 KB

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