goods.js 13 KB

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