order.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. 'use strict';
  2. const shopController = require('./shop.js');
  3. // 订单控制器
  4. module.exports = class OrderController extends shopController {
  5. /**
  6. * [useModel 使用模型]
  7. * @return {[type]} [description]
  8. */
  9. get useModel() {
  10. const that = this;
  11. return that.app.model.Orders;
  12. }
  13. /**
  14. * [addressModel 用户地址模型]
  15. * @return {[type]} [description]
  16. */
  17. get useAddressModel() {
  18. const that = this;
  19. return that.app.model.Address;
  20. }
  21. /**
  22. * [useCartModel 使用购物车模型]
  23. * @return {[type]} [description]
  24. */
  25. get useCartModel() {
  26. const that = this;
  27. return that.app.model.Carts;
  28. }
  29. /**
  30. * [usePaysConfigModel 使用支付模型]
  31. * @return {[type]} [description]
  32. */
  33. get usePaysConfigModel() {
  34. const that = this;
  35. return that.app.model.PaysConfig;
  36. }
  37. /**
  38. * [useOrdersProductsModel 订单商品模型]
  39. * @return {[type]} [description]
  40. */
  41. get useOrdersProductsModel() {
  42. const that = this;
  43. return that.app.model.OrdersProducts;
  44. }
  45. /**
  46. * [createValidate 用户下单验证器]
  47. * @return {[type]} [description]
  48. */
  49. get createValidate() {
  50. const that = this;
  51. return {
  52. pay_id: that.ctx.rules.name('支付方式')
  53. .required()
  54. .notEmpty()
  55. .number(),
  56. pid: that.ctx.rules.name('家具分类父级ID')
  57. .required()
  58. .notEmpty()
  59. .number(),
  60. user_id: that.ctx.rules.default(that.service.shop.getWebUserId())
  61. .number(),
  62. user_remarks: that.ctx.rules.default('')
  63. .required(),
  64. order_source: that.ctx.rules.default(1)
  65. .number(),
  66. order_sn: that.ctx.rules.default(`W${that.app.szjcomo.date('YmdHis')}${that.app.szjcomo.mt_rand(100000, 999999)}`)
  67. .required(),
  68. create_time: that.ctx.rules.default(that.app.szjcomo.date('Y-m-d H:i:s'))
  69. .required(),
  70. };
  71. }
  72. /**
  73. * [selectValidate 获取订单列表]
  74. * @return {[type]} [description]
  75. */
  76. get selectValidate() {
  77. const that = this;
  78. return {
  79. page: that.ctx.rules.default(1)
  80. .number(),
  81. limit: that.ctx.rules.default(20)
  82. .number(),
  83. user_id: that.ctx.rules.default(that.service.shop.getWebUserId())
  84. .number(),
  85. order_status: that.ctx.rules.default(-1)
  86. .number(),
  87. order_id: that.ctx.rules.default(0)
  88. .number(),
  89. comment_id: that.ctx.rules.default(0)
  90. .number(),
  91. };
  92. }
  93. /**
  94. * [selectInfoValidate 订单详情验证器]
  95. * @return {[type]} [description]
  96. */
  97. get selectInfoValidate() {
  98. const that = this;
  99. return {
  100. order_id: that.ctx.rules.name('订单ID')
  101. .required()
  102. .notEmpty()
  103. .number(),
  104. };
  105. }
  106. /**
  107. * [orderCountValidate 获取订单数量统计]
  108. * @return {[type]} [description]
  109. */
  110. get orderCountValidate() {
  111. const that = this;
  112. return {
  113. user_id: that.ctx.rules.default(that.service.shop.getWebUserId())
  114. .number(),
  115. };
  116. }
  117. /**
  118. * [cancelValidate 用户取消订单]
  119. * @return {[type]} [description]
  120. */
  121. get cancelValidate() {
  122. const that = this;
  123. return {
  124. user_id: that.ctx.rules.default(that.service.shop.getWebUserId())
  125. .number(),
  126. order_id: that.ctx.rules.name('订单ID')
  127. .required()
  128. .notEmpty()
  129. .number(),
  130. };
  131. }
  132. /**
  133. * [deliverValidate 查看物流配送信息]
  134. * @return {[type]} [description]
  135. */
  136. get deliverValidate() {
  137. const that = this;
  138. return {
  139. order_id: that.ctx.rules.name('订单ID')
  140. .required()
  141. .notEmpty()
  142. .number(),
  143. user_id: that.ctx.rules.default(that.service.shop.getWebUserId())
  144. .number(),
  145. };
  146. }
  147. /**
  148. * [orderCount 订单数量统计]
  149. * @return {[type]} [description]
  150. */
  151. async orderCount() {
  152. const that = this;
  153. try {
  154. const data = await that.ctx.validate(that.orderCountValidate, await that.ctx.getParse());
  155. const seq = that.app.Sequelize;
  156. const options = {
  157. where: {
  158. user_id: data.user_id, order_status: {
  159. [seq.Op.in]: [ 0, 1, 2, 3 ],
  160. },
  161. }, group: [ 'order_status' ],
  162. };
  163. const result = await that.useModel.count(options);
  164. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  165. } catch (err) {
  166. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  167. }
  168. }
  169. /**
  170. * [select 查询订单]
  171. * @return {[type]} [description]
  172. */
  173. async select() {
  174. const that = this;
  175. try {
  176. const data = await that.ctx.validate(that.selectValidate, await that.ctx.getParse());
  177. let result;
  178. if (data.order_id) {
  179. result = await that.orderInfo(data);
  180. } else {
  181. result = await that.orderList(data);
  182. }
  183. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  184. } catch (err) {
  185. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  186. }
  187. }
  188. /**
  189. * [selectInfo 查询订单详情]
  190. * @return {[type]} [description]
  191. */
  192. async selectInfo() {
  193. const that = this;
  194. try {
  195. const data = await that.ctx.validate(that.selectInfoValidate, await that.ctx.getParse());
  196. const result = await that.orderInfo(data);
  197. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  198. } catch (err) {
  199. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  200. }
  201. }
  202. /**
  203. * [orderInfo 订单详情]
  204. * @return {[type]} [description]
  205. */
  206. async orderInfo(data = {}) {
  207. const that = this;
  208. const seq = that.app.Sequelize;
  209. let commentInclude = [];
  210. if (data.comment_id) {
  211. commentInclude = [{
  212. model: that.app.model.ProductComment,
  213. as: 'product_comment',
  214. attributes: [ 'comment' ],
  215. where: { order_id: data.order_id },
  216. required: false,
  217. }];
  218. }
  219. const options = {
  220. where: { order_id: data.order_id },
  221. include: [
  222. {
  223. model: that.app.model.OrdersProducts,
  224. as: 'orders_products',
  225. attributes: [ 'product_count', 'product_name', 'product_image', 'product_id', 'category_id', 'shop_price', 'volume', 'price' ],
  226. include: commentInclude,
  227. },
  228. { model: that.app.model.PaysConfig, as: 'pays_config', attributes: [] },
  229. ],
  230. attributes: [ 'order_sn', 'create_time', 'order_status', 'order_amount', 'order_id', [ seq.col('pays_config.pay_name'), 'pay_name' ], 'consignee', 'mobile', 'address', 'is_urge', 'pay_id', 'surplus_amout' ],
  231. };
  232. const selectBean = await that.app.comoBean.instance(data, options);
  233. const result = await that.service.base.select(selectBean, that.useModel, '订单详情查询失败,请稍候重试', false);
  234. return result;
  235. }
  236. /**
  237. * [orderList 订单列表]
  238. * @param {Object} data [description]
  239. * @return {[type]} [description]
  240. */
  241. async orderList(data = {}) {
  242. const that = this;
  243. // const seq = that.app.Sequelize;
  244. const options = {
  245. offset: (data.page - 1) * data.limit, limit: data.limit, where: { user_id: data.user_id },
  246. include: [
  247. {
  248. model: that.app.model.OrdersProducts,
  249. as: 'orders_products',
  250. attributes: [ 'product_count', 'product_name', 'product_image', 'product_id', 'category_id', 'shop_price', 'volume', 'price' ],
  251. order: [[ 'rec_id', 'asc' ]],
  252. },
  253. ],
  254. attributes: [ 'order_sn', 'create_time', 'order_status', 'order_amount', 'surplus_amout', 'order_id', 'is_urge' ],
  255. order: [[ 'order_id', 'desc' ]],
  256. };
  257. if (data.order_status > -1) options.where.order_status = data.order_status;
  258. const selectBean = await that.app.comoBean.instance(data, options);
  259. const result = await that.service.base.select(selectBean, that.useModel, '订单列表查询失败,请稍候重试', true);
  260. return result;
  261. }
  262. /**
  263. * [cancel 用户取消订单]
  264. * @return {[type]} [description]
  265. */
  266. async cancel() {
  267. const that = this;
  268. let transaction;
  269. try {
  270. const data = await that.ctx.validate(that.cancelValidate, await that.ctx.anyParse());
  271. transaction = await that.app.model.transaction();
  272. const info = await that.useModel.findOne({
  273. where: { order_id: data.order_id, user_id: data.user_id },
  274. attributes: [ 'surplus_amout', 'order_sn' ],
  275. transaction,
  276. raw: true,
  277. });
  278. if (!info) throw new Error('订单信息不存在,请勿非法操作');
  279. const opts = { where: { user_id: data.user_id, order_id: data.order_id }, transaction };
  280. const updateBean = await that.app.comoBean.instance({ order_status: 6, surplus_amout: 0 }, opts);
  281. const result = await that.service.base.update(updateBean, that.useModel, '取消订单操作失败,请重试');
  282. if (Number(info.surplus_amout) > 0) await that.service.shop.userMoneyAdd(data.user_id, Number(info.surplus_amout), transaction, `订单取消,退回订单抵扣的余额,订单编号是:${info.order_sn}`);
  283. await that.service.order.orderAction({
  284. admin_id: 0,
  285. order_id: data.order_id,
  286. action_desc: '用户取消订单',
  287. }, transaction);
  288. await transaction.commit();
  289. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  290. } catch (err) {
  291. if (transaction) await transaction.rollback();
  292. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  293. }
  294. }
  295. /**
  296. * [urge 用户催发货]
  297. * @return {[type]} [description]
  298. */
  299. async urge() {
  300. const that = this;
  301. let transaction;
  302. try {
  303. const data = await that.ctx.validate(that.cancelValidate, await that.ctx.anyParse());
  304. transaction = await that.app.model.transaction();
  305. const opts = { where: { user_id: data.user_id, order_id: data.order_id }, transaction };
  306. const updateBean = await that.app.comoBean.instance({ is_urge: that.app.Sequelize.literal('is_urge + 1') }, opts);
  307. const result = await that.service.base.update(updateBean, that.useModel, '催发货失败,请稍候重试');
  308. await that.service.order.orderAction({
  309. admin_id: 0,
  310. order_id: data.order_id,
  311. action_desc: '用户催发货',
  312. }, transaction);
  313. await transaction.commit();
  314. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  315. } catch (err) {
  316. if (transaction) await transaction.rollback();
  317. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  318. }
  319. }
  320. /**
  321. * [confirm 用户确认收货]
  322. * @return {[type]} [description]
  323. */
  324. async confirm() {
  325. const that = this;
  326. let transaction;
  327. try {
  328. const data = await that.ctx.validate(that.cancelValidate, await that.ctx.anyParse());
  329. transaction = await that.app.model.transaction();
  330. const opts = { where: { user_id: data.user_id, order_id: data.order_id }, transaction };
  331. const updateBean = await that.app.comoBean.instance({
  332. order_status: 3,
  333. query_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  334. }, opts);
  335. const result = await that.service.base.update(updateBean, that.useModel, '确认收货更新失败,请稍候重试');
  336. await that.service.order.orderAction({
  337. admin_id: 0,
  338. order_id: data.order_id,
  339. action_desc: '用户已收货',
  340. }, transaction);
  341. await transaction.commit();
  342. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  343. } catch (err) {
  344. if (transaction) await transaction.rollback();
  345. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  346. }
  347. }
  348. // ======================以下为用户下单所需要方法==============================
  349. /**
  350. * [create 用户下单]
  351. * @return {[type]} [description]
  352. *
  353. */
  354. /* async create() {
  355. const that = this;
  356. let transaction;
  357. try {
  358. const data = await that.ctx.validate(that.createValidate, await that.ctx.postParse());
  359. const inviteCode = data.inviteCode ? Number(data.inviteCode) : -1;
  360. that.logger.error('用户下单绑定的邀请码: %s ', inviteCode);
  361. transaction = await that.app.model.transaction();
  362. const products = await that.getCartProducts(data.user_id, transaction);
  363. const orderAmount = await that.caclOrderAmount(products);
  364. const result = await that.orderCreateBefore(data, orderAmount, transaction, inviteCode);
  365. const cartIds = await that.orderProductsAfter(result.order.order_id, products, data, transaction);
  366. await that.clearCartProducts(cartIds, transaction);
  367. await transaction.commit();
  368. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result.payParmas, false));
  369. } catch (err) {
  370. if (transaction) await transaction.rollback();
  371. await that.logs('order.js', err);
  372. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  373. }
  374. }*/
  375. /**
  376. * [createV2 用户下单]
  377. * @return {[type]} [description]
  378. *
  379. */
  380. async createV2() {
  381. const that = this;
  382. let transaction;
  383. try {
  384. const data = await that.ctx.validate(that.createValidate, await that.ctx.postParse());
  385. const inviteCode = data.inviteCode ? Number(data.inviteCode) : -1;
  386. const isUseMoney = data.isUseMoney ? data.isUseMoney : false;
  387. that.logger.error('用户下单绑定的邀请码: %s ', inviteCode);
  388. transaction = await that.app.model.transaction();
  389. const products = await that.getCartProducts(data.user_id, data.pid, transaction);
  390. const orderAmount = await that.caclOrderAmountV2(products, data.pid);
  391. const result = await that.orderCreateBeforeV2(data, orderAmount, transaction, inviteCode, isUseMoney);
  392. const cartIds = await that.orderProductsAfter(result.order.order_id, products, data, transaction);
  393. await that.clearCartProducts(cartIds, transaction);
  394. await transaction.commit();
  395. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result.payParmas, false));
  396. } catch (err) {
  397. if (transaction) await transaction.rollback();
  398. await that.logs('order.js', err);
  399. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  400. }
  401. }
  402. /**
  403. * [caclOrderAmount 计算订单总价]
  404. * @param {[type]} products [description]
  405. * @param {Object} data [description]
  406. * @return {[type]} [description]
  407. */
  408. // eslint-disable-next-line no-unused-vars
  409. /* async caclOrderAmount(products, data = {}) {
  410. // const that = this;
  411. let order_amount = 0;
  412. products.forEach(item => {
  413. order_amount += (Number(item.shop_price) * item.product_count);
  414. });
  415. return order_amount;
  416. }*/
  417. async caclOrderAmountV2(products, pid = 4) {
  418. const that = this;
  419. const keys = [ 'can_discount_category' ];
  420. const config = await that.service.configs.getConfigMoreValue(keys);
  421. const temA = config.can_discount_category.replace('[', '');
  422. const temB = temA.replace(']', '');
  423. let canDiscountCategory = temB.split(',');
  424. canDiscountCategory = canDiscountCategory.map(Number);
  425. const orderAmount = { orderPriceCanDiscount: 0, orderPriceNotDiscount: 0 };
  426. // 2023/10/12 todo 订单价格办公家具全场八折
  427. products.forEach(item => {
  428. if (!canDiscountCategory.includes(item.category_id)) {
  429. orderAmount.orderPriceNotDiscount += ((Number(item.price > 0 ? item.price : item.shop_price) * item.product_count) * (pid === 1 ? 0.8 : 1));
  430. } else {
  431. orderAmount.orderPriceCanDiscount += ((Number(item.price > 0 ? item.price : item.shop_price) * item.product_count) * (pid === 1 ? 0.8 : 1));
  432. }
  433. });
  434. /* console.log('orderAmount');
  435. console.log(orderAmount);
  436. console.log('pid');
  437. console.log(pid);
  438. console.log('item');
  439. console.log(products);*/
  440. return orderAmount;
  441. }
  442. /**
  443. * [orderCreateBefore 用户下单前置]
  444. * @param {Object} data [description]
  445. * @param order_amount
  446. * @param transaction
  447. * @param inviteCode
  448. * @return {[type]} [description]
  449. */
  450. /* async orderCreateBefore(data = {}, order_amount = 0, transaction = null, inviteCode = -1) {
  451. const that = this;
  452. const address = await that.getUserAddress(data.user_id, transaction);
  453. if (!address) throw new Error('您还没有完善收货信息,请完善后再下单吧!');
  454. // 计算用户需要支付的金额
  455. const tmpPayMentMoney = await that.service.order.caclPaymentMoney(data, order_amount, transaction);
  456. const opts = {
  457. order_sn: data.order_sn, user_id: data.user_id, order_status: 0, order_source: data.order_source,
  458. surplus_amout: tmpPayMentMoney.surplus_amout, consignee: address.uname, mobile: address.mobile,
  459. order_amount, province_id: address.province_id, city_id: address.city_id,
  460. user_remarks: data.user_remarks, county_id: address.county_id,
  461. address: [ address.province_name, address.city_name, address.county_name, address.address ].join(''),
  462. create_time: data.create_time,
  463. pay_id: data.pay_id, shipping_fee: 0, is_urge: 0, inviter_id: inviteCode,
  464. };
  465. const orderBean = await that.app.comoBean.instance(opts, { transaction });
  466. // 2022/11/11 创建订单
  467. const order = await that.service.base.create(orderBean, that.useModel, '订单提交失败,请重试');
  468. if (tmpPayMentMoney.surplus_amout) await that.service.shop.userMoneySub(data.user_id, tmpPayMentMoney.surplus_amout, transaction, `商品下单时余额抵扣,订单编号是:${data.order_sn}`);
  469. // 用户全部使用余额支付
  470. if (!tmpPayMentMoney.payment_money) {
  471. const payParmas = await that.service.order.getSurplusPayParams(order.order_id, data.user_id, tmpPayMentMoney.surplus_amout, transaction);
  472. // 订单发货时扣除库存,受控于后台配置的扣除时机
  473. await that.service.order.productStockSub(order.order_id, transaction, 1);
  474. return { order, payParmas };
  475. }
  476. let payParmas = {};
  477. const userInfo = await that.app.model.Users.findOne({
  478. where: { user_id: data.user_id },
  479. attributes: [ 'openid' ],
  480. transaction,
  481. raw: true,
  482. });
  483. if (data.order_source === 1) {
  484. payParmas = await that.service.wechat.wechatAccountJsApiPay({
  485. body: '订单支付',
  486. openid: userInfo.openid,
  487. total_fee: (tmpPayMentMoney.payment_money * 100),
  488. trade_type: 'JSAPI',
  489. attach: that.app.szjcomo.base64_encode(that.app.szjcomo.json_encode({
  490. user_id: data.user_id,
  491. order_id: order.order_id,
  492. pay_id: data.pay_id,
  493. })),
  494. });
  495. }
  496. return {
  497. order,
  498. payParmas: { payment_money: tmpPayMentMoney.payment_money, params: payParmas, order_id: order.order_id },
  499. };
  500. }*/
  501. async orderCreateBeforeV2(data = {}, orderAmount = {
  502. orderPriceCanDiscount: 0,
  503. orderPriceNotDiscount: 0,
  504. }, transaction = null, inviteCode = -1, isUseMoney = false) {
  505. const that = this;
  506. const address = await that.getUserAddress(data.user_id, transaction);
  507. if (!address && !data.isSelfPickUp) throw new Error('您还没有完善收货信息,请完善收货地址或者选择门店自提再下单吧!');
  508. // 计算用户需要支付的金额
  509. const tmpPayMentMoney = await that.service.order.caclPaymentMoneyV2(data, orderAmount, transaction, isUseMoney);
  510. const opts = {
  511. order_sn: data.order_sn,
  512. user_id: data.user_id,
  513. order_status: 0,
  514. order_source: data.order_source,
  515. surplus_amout: tmpPayMentMoney.surplus_amout,
  516. consignee: address ? address.uname : '门店自提',
  517. mobile: address ? address.mobile : '',
  518. order_amount: orderAmount.orderPriceCanDiscount + orderAmount.orderPriceNotDiscount,
  519. province_id: address ? address.province_id : '',
  520. city_id: address ? address.city_id : '',
  521. user_remarks: data.user_remarks,
  522. county_id: address ? address.county_id : '',
  523. address: address ? [ address.province_name, address.city_name, address.county_name, address.address ].join('') : '门店自提',
  524. create_time: data.create_time,
  525. pay_id: data.pay_id,
  526. shipping_fee: 0,
  527. is_urge: 0,
  528. inviter_id: inviteCode,
  529. };
  530. const orderBean = await that.app.comoBean.instance(opts, { transaction });
  531. // 2022/11/11 创建订单
  532. const order = await that.service.base.create(orderBean, that.useModel, '订单提交失败,请重试');
  533. if (tmpPayMentMoney.surplus_amout) await that.service.shop.userMoneySub(data.user_id, tmpPayMentMoney.surplus_amout, transaction, `商品下单时余额抵扣,订单编号是:${data.order_sn}`);
  534. // 用户全部使用余额支付
  535. if (!tmpPayMentMoney.payment_money) {
  536. const payParmas = await that.service.order.getSurplusPayParams(order.order_id, data.user_id, tmpPayMentMoney.surplus_amout, transaction);
  537. // 订单发货时扣除库存,受控于后台配置的扣除时机
  538. await that.service.order.productStockSub(order.order_id, transaction, 1);
  539. return { order, payParmas };
  540. }
  541. let payParmas = {};
  542. const userInfo = await that.app.model.Users.findOne({
  543. where: { user_id: data.user_id },
  544. attributes: [ 'openid' ],
  545. transaction,
  546. raw: true,
  547. });
  548. if (data.order_source === 1) {
  549. payParmas = await that.service.wechat.wechatAccountJsApiPay({
  550. body: '订单支付',
  551. openid: userInfo.openid,
  552. total_fee: (tmpPayMentMoney.payment_money * 100),
  553. trade_type: 'JSAPI',
  554. attach: that.app.szjcomo.base64_encode(that.app.szjcomo.json_encode({
  555. user_id: data.user_id,
  556. order_id: order.order_id,
  557. pay_id: data.pay_id,
  558. })),
  559. });
  560. }
  561. return {
  562. order,
  563. payParmas: { payment_money: tmpPayMentMoney.payment_money, params: payParmas, order_id: order.order_id },
  564. };
  565. }
  566. /**
  567. * [orderProductsAfter description]
  568. * @param {[type]} order_id [description]
  569. * @param {Array} products [description]
  570. * @param data
  571. * @param {[type]} transaction [description]
  572. * @return {[type]} [description]
  573. */
  574. async orderProductsAfter(order_id, products = [], data = {}, transaction = null) {
  575. const that = this;
  576. const cartIds = [];
  577. // const seq = that.app.Sequelize;
  578. const orderProducts = products.map(item => {
  579. const tmp = Object.assign({
  580. order_id, total_price: Number(item.price > 0 ? item.price : item.shop_price) * item.product_count,
  581. // 2023/1/9 默认出货数量是订单商品的购买数量
  582. deliver_count: Number(item.product_count),
  583. create_time: data.create_time,
  584. }, item);
  585. cartIds.push(item.cart_id);
  586. return tmp;
  587. });
  588. const result = await that.useOrdersProductsModel.bulkCreate(orderProducts, { transaction });
  589. if (!result) throw new Error('订单商品写入失败,请重试');
  590. return cartIds;
  591. }
  592. /**
  593. * [clearCartProducts 清除购物车商品]
  594. * @param {Array} cartIds [description]
  595. * @return {[type]} [description]
  596. */
  597. async clearCartProducts(cartIds = [], transaction = null) {
  598. const that = this;
  599. const seq = that.app.Sequelize;
  600. const deleteBean = await that.app.comoBean.instance({}, {
  601. where: { cart_id: { [seq.Op.in]: cartIds } },
  602. transaction,
  603. });
  604. await that.service.base.delete(deleteBean, that.useCartModel, '订单提交成功,清除购物车失败,请重试');
  605. }
  606. /**
  607. * [getCartProducts 下单时获取购物车商品]
  608. * @param {Number} user_id [description]
  609. * @return {[type]} [description]
  610. */
  611. async getCartProducts(user_id = 0, pid = 4, transaction = null) {
  612. const that = this;
  613. const seq = that.app.Sequelize;
  614. const options = {
  615. where: { user_id, is_select: 1, pid }, transaction, raw: true,
  616. include: [
  617. { model: that.app.model.Products, as: 'products', attributes: [] },
  618. ],
  619. attributes: [
  620. [ seq.col('products.product_id'), 'product_id' ],
  621. [ seq.col('products.category_id'), 'category_id' ],
  622. [ seq.col('products.product_name'), 'product_name' ],
  623. [ seq.col('products.product_sn'), 'product_sn' ],
  624. [ seq.col('products.product_image'), 'product_image' ],
  625. [ seq.col('products.shop_price'), 'shop_price' ],
  626. [ seq.col('products.dinning_coin_amount'), 'dinning_coin_amount' ],
  627. [ seq.col('products.dining_partner_id'), 'dining_partner_id' ],
  628. [ seq.col('products.goods_type'), 'goods_type' ],
  629. [ seq.col('products.activity_id'), 'activity_id' ], 'product_count', 'cart_id', 'volume', 'price',
  630. ],
  631. };
  632. const res = await that.useCartModel.findAll(options);
  633. return res;
  634. }
  635. /**
  636. * [getUserAddress 获取收货地址]
  637. * @param {Number} user_id [description]
  638. * @return {[type]} [description]
  639. */
  640. async getUserAddress(user_id = 0, transaction = null) {
  641. const that = this;
  642. const options = {
  643. where: { user_id, is_use: 1 }, raw: true, transaction, attributes: {
  644. exclude: [ 'user_id', 'address_id', 'is_use', 'update_time', 'create_time' ],
  645. },
  646. };
  647. const res = await that.useAddressModel.findOne(options);
  648. return res;
  649. }
  650. /**
  651. * [orderDeliver 查看物流配送信息]
  652. * @return {[type]} [description]
  653. */
  654. async orderDeliver() {
  655. const that = this;
  656. try {
  657. const data = await that.ctx.validate(that.deliverValidate, await that.ctx.getParse());
  658. const selectBean = await that.app.comoBean.instance(data, {
  659. where: { order_id: data.order_id, user_id: data.user_id },
  660. include: [
  661. {
  662. model: that.app.model.OrdersProducts,
  663. as: 'orders_products',
  664. attributes: [ 'product_count', 'product_name', 'product_image', 'product_id', 'category_id', 'shop_price', 'deliver_count', 'is_deliver', 'volume', 'price' ],
  665. },
  666. ],
  667. attributes: [ 'order_sn', 'create_time', 'order_status', 'order_amount', 'order_id', 'consignee', 'mobile', 'address', 'is_urge', 'pay_id', 'surplus_amout', 'is_express', 'express_sn', 'express_id', 'deliver_desc', 'deliver_time' ],
  668. });
  669. const result = await that.service.base.select(selectBean, that.useModel, '查询订单详情失败,请稍候重试', false, false);
  670. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  671. } catch (err) {
  672. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  673. }
  674. }
  675. /**
  676. * [orderPayFind 查询验证订单是否已经支付]
  677. * @return {[type]} [description]
  678. */
  679. async orderPayFind() {
  680. const that = this;
  681. try {
  682. const data = await that.ctx.validate(that.cancelValidate, await that.ctx.getParse());
  683. const selectBean = await that.app.comoBean.instance(data, {
  684. where: {
  685. order_id: data.order_id,
  686. user_id: data.user_id,
  687. }, attributes: [ 'order_status' ],
  688. });
  689. const result = await that.service.base.select(selectBean, that.useModel, '查询订单信息失败,请勿非法操作', false, false);
  690. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  691. } catch (err) {
  692. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  693. }
  694. }
  695. /**
  696. * [orderAgainPay 订单继续支付]
  697. * @return {[type]} [description]
  698. */
  699. async orderAgainPay() {
  700. const that = this;
  701. try {
  702. const data = await that.ctx.validate(that.cancelValidate, await that.ctx.getParse());
  703. const seq = that.app.Sequelize;
  704. const info = await that.useModel.findOne({
  705. include: [{ model: that.app.model.Users, as: 'users', attributes: [] }],
  706. where: { order_id: data.order_id }, raw: true,
  707. attributes: [ 'order_amount', 'surplus_amout', 'pay_id', [ seq.col('users.openid'), 'openid' ]],
  708. });
  709. if (!info) throw new Error('订单信息不存在,请勿非法操作');
  710. const result = await that.service.wechat.wechatAccountJsApiPay({
  711. body: '订单支付',
  712. openid: info.openid,
  713. total_fee: ((Number(info.order_amount) - Number(info.surplus_amout)) * 100),
  714. trade_type: 'JSAPI',
  715. attach: that.app.szjcomo.base64_encode(that.app.szjcomo.json_encode({
  716. user_id: data.user_id,
  717. order_id: data.order_id,
  718. pay_id: data.pay_id,
  719. })),
  720. });
  721. return that.ctx.appJson(that.app.szjcomo.appResult('SUCCESS', result, false));
  722. } catch (err) {
  723. return that.ctx.appJson(that.app.szjcomo.appResult(err.message));
  724. }
  725. }
  726. };