goods.js 12 KB

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