goods.js 15 KB

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