goods.js 12 KB

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