order.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /* eslint-disable eqeqeq */
  2. 'use strict';
  3. const ShopService = require('./shop.js');
  4. // 订单服务类
  5. class OrderService extends ShopService {
  6. /**
  7. * [statusNames 订单状态说明]
  8. * @return {[type]} [description]
  9. */
  10. get statusNames() {
  11. return [ '待付款', '待发货', '待收货', '待评价', '交易完成', '备货中(无效)', '订单已取消' ];
  12. }
  13. /**
  14. * [orderAction 订单操作记录]
  15. * @param {Object} data [description]
  16. * @return {[type]} [description]
  17. */
  18. async orderAction(data = {}, transaction = null) {
  19. const that = this;
  20. const createData = Object.assign({ create_time: that.app.szjcomo.date('Y-m-d H:i:s') }, data);
  21. const createBean = await that.app.comoBean.instance(createData, { transaction });
  22. const result = await that.service.base.create(createBean, that.app.model.OrdersAction, '订单操作记录失败,请重试');
  23. return result;
  24. }
  25. /**
  26. * [orderLogs 查询订单操作日志]
  27. * @param {[type]} order_id [description]
  28. * @return {[type]} [description]
  29. */
  30. async orderLogs(order_id) {
  31. const that = this;
  32. const seq = that.app.Sequelize;
  33. const selectBean = await that.app.comoBean.instance({}, {
  34. where: { order_id }, include: { model: that.app.model.AdminUser, as: 'admin_user', attributes: [] },
  35. attributes: {
  36. include: [ [ seq.col('admin_user.username'), 'username' ] ],
  37. exclude: [ 'admin_id', 'order_id' ],
  38. }, order: [ [ 'action_id', 'asc' ] ],
  39. });
  40. const result = await that.service.base.select(selectBean, that.app.model.OrdersAction, '操作记录查询失败,请稍候重试', false, true);
  41. return result;
  42. }
  43. /**
  44. * [caclPaymentMoney 计算用户需要支付的金额]
  45. * @param {[type]} data [description]
  46. * @param {[type]} orderAmount [description]
  47. * @param {[type]} transaction [description]
  48. * @return {[type]} [description]
  49. */
  50. async caclPaymentMoney(data, orderAmount, transaction = null) {
  51. const that = this;
  52. const userMoney = await that.getUserMoney(data.user_id, transaction);
  53. let payment_money = 0;
  54. const surplus_amout = userMoney >= orderAmount ? orderAmount : userMoney;
  55. if (surplus_amout < orderAmount) payment_money = (orderAmount - surplus_amout);
  56. return { surplus_amout, payment_money };
  57. }
  58. /**
  59. * [caclPaymentMoneyV2 计算用户需要支付的金额]
  60. * @param {[type]} data [description]
  61. * @param orderAmount
  62. * @param {[type]} transaction [description]
  63. * @param isUseMoney 是否使用余额抵扣
  64. * @return {[type]} [description]
  65. */
  66. async caclPaymentMoneyV2(data, orderAmount = {
  67. orderPriceCanDiscount: 0,
  68. orderPriceNotDiscount: 0,
  69. }, transaction = null, isUseMoney = false) {
  70. const that = this;
  71. let userMoney = 0;
  72. if (isUseMoney) {
  73. userMoney = await that.getUserMoney(data.user_id, transaction);
  74. } else {
  75. userMoney = 0;
  76. }
  77. let payment_money = 0;
  78. const surplus_amout = userMoney >= (orderAmount.orderPriceCanDiscount * 0.1) ? (orderAmount.orderPriceCanDiscount * 0.1) : userMoney;
  79. const totalAmount = orderAmount.orderPriceCanDiscount + orderAmount.orderPriceNotDiscount;
  80. if (surplus_amout < totalAmount) payment_money = (totalAmount - surplus_amout);
  81. return { surplus_amout, payment_money };
  82. }
  83. /**
  84. * [getSurplusPayParams 用户余额支付操作]
  85. * @param {Number} order_id [description]
  86. * @param {Number} user_id [description]
  87. * @return {[type]} [description]
  88. */
  89. async getSurplusPayParams(order_id, user_id = 0, surplus_amout = 0, transaction = null) {
  90. const that = this;
  91. const user = await that.app.model.Users.findOne({
  92. where: { user_id },
  93. attributes: [ 'openid' ],
  94. transaction,
  95. });
  96. const tmp = {
  97. openid: user.openid || '',
  98. total_fee: surplus_amout * 100,
  99. user_id,
  100. pay_id: 0,
  101. cash_fee: surplus_amout * 100,
  102. };
  103. const result = await that.service.shop.createPaymentLog(tmp, transaction);
  104. const updateBean = await that.app.comoBean.instance({ order_status: 1, pay_sn: result.out_trade_no }, {
  105. transaction, where: { order_id, user_id },
  106. });
  107. const res = await that.service.base.update(updateBean, that.app.model.Orders, '订单状态更新失败,请稍候重试');
  108. await that.service.shop.orderPrinter(order_id);
  109. return { payment_money: 0, params: {}, paymoney_type: 0 };
  110. }
  111. /**
  112. * [getOrederPrinterInfo 获取打印订单的详情]
  113. * @param {[type]} order_id [description]
  114. * @return {[type]} [description]
  115. */
  116. async getOrederPrinterInfo(order_id) {
  117. const that = this;
  118. const seq = that.app.Sequelize;
  119. const selectBean = await that.app.comoBean.instance({}, {
  120. where: { order_id },
  121. include: [
  122. { model: that.app.model.PaysConfig, attributes: [], as: 'pays_config' },
  123. { model: that.app.model.Users, as: 'users', attributes: [] },
  124. { model: that.app.model.Users, as: 'inviter', attributes: [] },
  125. { model: that.app.model.Payments, as: 'payments', attributes: [] },
  126. {
  127. model: that.app.model.OrdersProducts, as: 'orders_products', attributes: {
  128. exclude: [ 'product_id', 'create_time', 'order_id', 'activity_name', 'activity_id', 'activity_desc' ],
  129. },
  130. },
  131. ],
  132. attributes: [
  133. [ seq.col('pays_config.pay_name'), 'pay_name' ],
  134. [ seq.col('users.nickname'), 'userName' ],
  135. [ seq.col('inviter.nickname'), 'inviterName' ],
  136. [ seq.col('payments.total_fee'), 'total_fee' ],
  137. 'order_status', 'pay_sn', 'consignee', 'mobile', 'address',
  138. 'create_time', 'order_sn', 'order_amount', 'surplus_amout', 'user_remarks',
  139. ],
  140. });
  141. const result = await that.service.base.select(selectBean, that.app.model.Orders, '查询订单详情失败,请稍候重试', false, false);
  142. result.order_status = that.statusNames[result.order_status];
  143. result.order_amount = Number(result.order_amount)
  144. .toFixed(2);
  145. result.surplus_amout = Number(result.surplus_amout)
  146. .toFixed(2);
  147. const resultTemp1 = JSON.stringify(result);
  148. const result2 = JSON.parse(resultTemp1);
  149. result2.total_fee = result2.total_fee ? (Number(result2.total_fee) / 100).toFixed(2)
  150. .toString() : '0.00';
  151. const goods = [];
  152. result2.orders_products.forEach(item => {
  153. goods.push(`${item.product_name}${'【' + item.product_sn + '】'}${item.volume > 0 ? item.volume + 'ml' : ''}\tx\t${item.product_count}`);
  154. });
  155. result2.goods = goods.join('\n');
  156. result2.nickname = result2.inviterName ? result2.userName + '【邀请人:' + result2.inviterName + '】' : result2.userName;
  157. return result2;
  158. }
  159. /**
  160. * [orderDataCount 订单数据统计]
  161. * @return {[type]} [description]
  162. */
  163. async orderDataCount() {
  164. const that = this;
  165. const seq = that.app.Sequelize;
  166. const orderCount = await that.app.model.Orders.count({
  167. group: [ 'order_status' ],
  168. });
  169. const saleCount = await that.app.model.Orders.sum('order_amount', { where: { order_status: { [seq.Op.in]: [ 1, 2, 3, 4 ] } } });
  170. const surplusCount = await that.app.model.Orders.sum('surplus_amout', { where: { order_status: { [seq.Op.in]: [ 1, 2, 3, 4 ] } } });
  171. const result = { data_count: orderCount, sale_money: saleCount, surplus_money: surplusCount };
  172. return result;
  173. }
  174. /**
  175. * [saleDataCount 销售数量统计]
  176. * @return {[type]} [description]
  177. */
  178. async saleDataCount(day = 20) {
  179. const that = this;
  180. const curTime = that.app.szjcomo.time();
  181. const seq = that.app.Sequelize;
  182. const times = [];
  183. for (let i = 0; i < day; i++) {
  184. const tmpTime = curTime - i * 24 * 60 * 60;
  185. times.push([ `${that.app.szjcomo.date('Y-m-d', tmpTime)} 00:00:00`, `${that.app.szjcomo.date('Y-m-d', tmpTime)} 23:59:59` ]);
  186. }
  187. const orders = await that.app.model.Orders.findAll({
  188. where: {
  189. create_time: { [seq.Op.between]: [ times[day - 1][0], times[0][1] ] },
  190. order_status: { [seq.Op.gt]: 0 },
  191. },
  192. attributes: [ 'order_amount', 'create_time' ], raw: true,
  193. });
  194. const result = [];
  195. times.forEach(item => {
  196. const startTime = that.app.szjcomo.strToTime(item[0]);
  197. const endTime = that.app.szjcomo.strToTime(item[1]);
  198. const tmpData = { date: that.app.szjcomo.date('m-d', startTime), money: 0 };
  199. orders.forEach(childItem => {
  200. const tmpTime = that.app.szjcomo.strToTime(childItem.create_time);
  201. if (tmpTime >= startTime && tmpTime <= endTime) {
  202. tmpData.money += childItem.order_amount;
  203. }
  204. });
  205. result.push(tmpData);
  206. });
  207. return result;
  208. }
  209. /**
  210. * [productStockSub 发货后扣除库存]
  211. * @param {Array} products [description]
  212. * @param {[type]} transaction [description]
  213. * @return {[type]} [description]
  214. */
  215. async productStockSub(order_id, transaction = null, index = 2) {
  216. const that = this;
  217. const product_stock_subtime = await that.service.configs.getConfigValue('product_stock_subtime');
  218. if (Number(product_stock_subtime) != index) return false;
  219. const seq = that.app.Sequelize;
  220. const products = await that.app.model.OrdersProducts.findAll({
  221. where: { order_id }, attributes: [ 'product_id', 'deliver_count' ], raw: true,
  222. transaction,
  223. });
  224. if (!products.length) return false;
  225. for (let i = 0; i < products.length; i++) {
  226. const item = products[i];
  227. const updateData = {
  228. product_stock: seq.literal(`product_stock - ${item.deliver_count}`),
  229. sale_count: seq.literal(`sale_count + ${item.deliver_count}`),
  230. update_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  231. };
  232. const res = await that.app.model.Products.update(updateData, {
  233. where: { product_id: item.product_id },
  234. transaction,
  235. });
  236. if (!res) throw new Error('库存扣除失败,请稍候重试');
  237. }
  238. return true;
  239. }
  240. }
  241. module.exports = OrderService;