goods.js 13 KB

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