goods.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. }
  182. return data;
  183. }
  184. async indexGoodsList(condition, { skip = 0, limit = 20 } = {}) {
  185. condition = this.dealFilter(condition);
  186. const pipeline = [{ $match: { status: { $ne: '0' } } }]; // { $sort: { sort: 1 } },
  187. const { view_num, sell_num, sell_money, name, shop, tags, act_tags } = condition;
  188. let sort = {};
  189. if (view_num) sort.view_num = parseInt(view_num);
  190. if (sell_num) sort.sell_num = parseInt(sell_num);
  191. if (sell_money) sort.sell_money = parseInt(sell_money);
  192. if (name) pipeline.push({ $match: { name: new RegExp(name) } });
  193. if (shop) pipeline.push({ $match: { shop } });
  194. if (tags) pipeline.push({ $match: { tags: { $elemMatch: { $elemMatch: { $eq: tags } } } } });
  195. if (act_tags) pipeline.push({ $match: { act_tags: { $elemMatch: { $eq: act_tags } } } });
  196. pipeline.push({
  197. $addFields: { goods_id: { $toString: '$_id' }, create_time: { $dateToString: { date: '$meta.createdAt', format: '%Y-%m-%d %H:%M:%S', timezone: '+08:00' } } },
  198. });
  199. // 表关联
  200. pipeline.push({
  201. $lookup: {
  202. from: 'goodsSpec',
  203. localField: 'goods_id',
  204. foreignField: 'goods',
  205. as: 'specs',
  206. },
  207. });
  208. // 按照规格平铺数据
  209. pipeline.push({ $unwind: '$specs' });
  210. // 格式化平铺后的数据
  211. pipeline.push({
  212. $project: {
  213. name: 1,
  214. view_num: 1,
  215. sell_num: 1,
  216. file: 1,
  217. sort: 1,
  218. create_time: 1,
  219. sell_money: { $toDouble: '$specs.sell_money' },
  220. flow_money: { $toDouble: '$specs.flow_money' },
  221. leader_price: { $toDouble: '$specs.leader_price' },
  222. num: '$specs.num',
  223. act_tags: 1,
  224. },
  225. });
  226. pipeline.push({
  227. $group: {
  228. _id: '$_id',
  229. data: { $min: '$$CURRENT' },
  230. },
  231. });
  232. pipeline.push({
  233. $project: {
  234. name: '$data.name',
  235. view_num: '$data.view_num',
  236. sell_num: '$data.sell_num',
  237. file: '$data.file',
  238. sell_money: '$data.sell_money',
  239. flow_money: '$data.flow_money',
  240. leader_price: '$data.leader_price',
  241. num: '$data.num',
  242. create_time: '$data.create_time',
  243. sort: '$data.sort',
  244. act_tags: '$data.act_tags',
  245. },
  246. });
  247. if (Object.keys(sort).length <= 0) sort = { sort: -1, create_time: -1 };
  248. pipeline.push({ $sort: { ...sort, sort: -1, create_time: -1 } });
  249. // 分页处理
  250. const qpipeline = _.cloneDeep(pipeline);
  251. if (parseInt(skip)) qpipeline.push({ $skip: parseInt(skip) });
  252. if (parseInt(limit)) qpipeline.push({ $limit: parseInt(limit) });
  253. let list = await this.goodsModel.aggregate(qpipeline);
  254. list = list.map(i => {
  255. const obj = _.pick(i, [ 'name', 'file', 'num', 'flow_money', 'sell_money', 'view_num', '_id', 'actTagsShow', 'act_tags', 'leader_price' ]);
  256. if (obj.leader_price) obj.leader_price = this.ctx.toNumber(obj.leader_price);
  257. return obj;
  258. });
  259. // 处理活动标签
  260. await this.getActTags(list);
  261. // 实时匹配活动
  262. // 只找: 买赠;特价;满减/折; 特价需要修改价格; 剩下的打标签
  263. const platformActList = await this.platformActModel.find({ is_use: '0', type: [ '2', '3', '5', '6' ] });
  264. await this.getAboutAct(platformActList, list);
  265. // 检查团长价格
  266. const user_id = _.get(this.ctx, 'user._id');
  267. const is_leader = await this.ctx.service.user.user.getUserIsLeader(user_id);
  268. if (!is_leader) {
  269. list = list.map(i => _.omit(i, [ 'leader_price' ]));
  270. } else {
  271. for (const i of list) {
  272. const { leader_price, _id: goods } = i;
  273. if (leader_price) continue;
  274. let specs = await this.goodsSpecModel.find({ goods, leader_price: { $gt: 0 } }, { leader_price: 1 }).lean();
  275. specs = _.orderBy(specs, [ 'leader_price' ], [ 'asc' ]);
  276. const head = _.head(specs);
  277. i.leader_price = this.ctx.toNumber(_.get(head, 'leader_price', 0));
  278. }
  279. }
  280. const tpipeline = _.cloneDeep(pipeline);
  281. tpipeline.push({ $count: 'total' });
  282. const total = await this.goodsModel.aggregate(tpipeline);
  283. return { list, total: _.get(_.head(total), 'total', 0) };
  284. }
  285. async getActTags(list) {
  286. let tags = list.map(i => i.act_tags);
  287. tags = _.flattenDeep(tags);
  288. tags = _.uniq(tags);
  289. tags = _.compact(tags);
  290. const tagsData = await this.actTagsModel.find({ value: tags, show_goods: '0' });
  291. for (const i of list) {
  292. const { act_tags = [] } = i;
  293. const actTagsShow = [];
  294. if (act_tags.length > 0) {
  295. for (const t of act_tags) {
  296. const r = tagsData.find(f => f.value === t);
  297. if (r) actTagsShow.push({ label: r.label });
  298. }
  299. }
  300. i.actTagsShow = actTagsShow;
  301. delete i.act_tags;
  302. }
  303. }
  304. /**
  305. * 处理商品有关活动部分
  306. * @param {Array} platformActList 正在进行中的活动
  307. * @param {Array} list 查询商品
  308. */
  309. async getAboutAct(platformActList, list) {
  310. const platform_act = platformActList.map(i => ObjectId(i._id).toString());
  311. for (const goods of list) {
  312. const { _id: goods_id, p_act = [], sell_money } = goods;
  313. const gjaList = await this.gjaModel.find({ platform_act, 'goods._id': ObjectId(goods_id).toString() });
  314. if (gjaList.length <= 0) continue;
  315. for (const gja of gjaList) {
  316. const { platform_act_type: type } = gja;
  317. if (type === '2' && gjaList.length > 0) p_act.push('买赠');
  318. else if (type === '3' && gjaList.length > 0) {
  319. p_act.push('特价');
  320. let sortList = JSON.parse(JSON.stringify(gjaList));
  321. sortList = sortList.map(i => ({ ...i, sp_price: _.get(i, 'config.sp_price', 0) }));
  322. sortList = _.orderBy(sortList, [ 'sp_price' ], [ 'asc' ]);
  323. sortList = sortList.filter(f => this.ctx.minus(0, f.sp_price) < 0);
  324. const lp = _.get(_.head(sortList), 'sp_price');
  325. if (lp && this.ctx.minus(lp, sell_money) < 0) goods.sell_money = lp;
  326. } else if (type === '5' && gjaList.length > 0) p_act.push('满减');
  327. else if (type === '6' && gjaList.length > 0) p_act.push('满折');
  328. goods.p_act = _.uniq(p_act);
  329. }
  330. }
  331. }
  332. async indexActTagsGoods() {
  333. // 将使用中且展示在首页的查出来排序
  334. const list = await this.ctx.model.System.ActTags.find({ status: '0', show_index: '0' }).sort({ sort: 1 });
  335. const result = [];
  336. for (const t of list) {
  337. const { label, value } = t;
  338. const list = await this.searchActTagsGoods(value);
  339. const arr = [];
  340. for (const g of list) {
  341. const obj = {
  342. url: _.get(g, 'file'),
  343. name: _.get(g, 'name'),
  344. id: _.get(g, '_id'),
  345. value,
  346. };
  347. if (arr.length === 0) {
  348. obj.title = label;
  349. }
  350. arr.push(obj);
  351. }
  352. result.push({ list: arr });
  353. }
  354. return result;
  355. }
  356. async searchActTagsGoods(act_tags, limit = 2) {
  357. const pipeline = [{ $sort: { 'meta.createdAt': -1 } }, { $match: { status: { $ne: '0' }, act_tags } }];
  358. pipeline.push({ $project: { name: 1, file: 1 } });
  359. if (parseInt(limit)) pipeline.push({ $limit: parseInt(limit) });
  360. const list = await this.goodsModel.aggregate(pipeline);
  361. return list;
  362. }
  363. // 弃用
  364. async searchLeaderPrice(list) {
  365. for (const i of list) {
  366. const { _id: goods } = i;
  367. let gcl = await this.goodsConfigModel.find({ goods }).lean();
  368. gcl = _.orderBy(gcl, [ 'leader_price' ], [ 'asc' ]);
  369. i.leader_price = _.get(_.head(gcl), 'leader_price');
  370. }
  371. return list;
  372. }
  373. }
  374. module.exports = GoodsService;