order.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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 ? orderAmount.orderPriceCanDiscount : 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.Payments, as: 'payments', attributes: [] },
  125. {
  126. model: that.app.model.OrdersProducts, as: 'orders_products', attributes: {
  127. exclude: [ 'product_id', 'create_time', 'order_id', 'activity_name', 'activity_id', 'activity_desc' ],
  128. },
  129. },
  130. ],
  131. attributes: [
  132. [ seq.col('pays_config.pay_name'), 'pay_name' ],
  133. [ seq.col('users.nickname'), 'nickname' ],
  134. [ seq.col('payments.total_fee'), 'total_fee' ],
  135. 'order_status', 'pay_sn', 'consignee', 'mobile', 'address',
  136. 'create_time', 'order_sn', 'order_amount', 'surplus_amout', 'user_remarks',
  137. ],
  138. });
  139. const result = await that.service.base.select(selectBean, that.app.model.Orders, '查询订单详情失败,请稍候重试', false, false);
  140. result.order_status = that.statusNames[result.order_status];
  141. result.order_amount = Number(result.order_amount)
  142. .toFixed(2);
  143. result.surplus_amout = Number(result.surplus_amout)
  144. .toFixed(2);
  145. const resultTemp1 = JSON.stringify(result);
  146. const result2 = JSON.parse(resultTemp1);
  147. result2.total_fee = result2.total_fee ? (Number(result2.total_fee) / 100).toFixed(2)
  148. .toString() : '0.00';
  149. const goods = [];
  150. result2.orders_products.forEach(item => {
  151. goods.push(`${item.product_name}${item.volume > 0 ? item.volume + 'ml' : ''}\tx\t${item.product_count}`);
  152. });
  153. result2.goods = goods.join('\n');
  154. return result2;
  155. }
  156. /**
  157. * [orderDataCount 订单数据统计]
  158. * @return {[type]} [description]
  159. */
  160. async orderDataCount() {
  161. const that = this;
  162. const seq = that.app.Sequelize;
  163. const orderCount = await that.app.model.Orders.count({
  164. group: [ 'order_status' ],
  165. });
  166. const saleCount = await that.app.model.Orders.sum('order_amount', { where: { order_status: { [seq.Op.gt]: 0 } } });
  167. const surplusCount = await that.app.model.Orders.sum('surplus_amout', { where: { order_status: { [seq.Op.gt]: 0 } } });
  168. const result = { data_count: orderCount, sale_money: saleCount, surplus_money: surplusCount };
  169. return result;
  170. }
  171. /**
  172. * [saleDataCount 销售数量统计]
  173. * @return {[type]} [description]
  174. */
  175. async saleDataCount(day = 20) {
  176. const that = this;
  177. const curTime = that.app.szjcomo.time();
  178. const seq = that.app.Sequelize;
  179. const times = [];
  180. for (let i = 0; i < day; i++) {
  181. const tmpTime = curTime - i * 24 * 60 * 60;
  182. times.push([ `${that.app.szjcomo.date('Y-m-d', tmpTime)} 00:00:00`, `${that.app.szjcomo.date('Y-m-d', tmpTime)} 23:59:59` ]);
  183. }
  184. const orders = await that.app.model.Orders.findAll({
  185. where: {
  186. create_time: { [seq.Op.between]: [ times[day - 1][0], times[0][1] ] },
  187. order_status: { [seq.Op.gt]: 0 },
  188. },
  189. attributes: [ 'order_amount', 'create_time' ], raw: true,
  190. });
  191. const result = [];
  192. times.forEach(item => {
  193. const startTime = that.app.szjcomo.strToTime(item[0]);
  194. const endTime = that.app.szjcomo.strToTime(item[1]);
  195. const tmpData = { date: that.app.szjcomo.date('m-d', startTime), money: 0 };
  196. orders.forEach(childItem => {
  197. const tmpTime = that.app.szjcomo.strToTime(childItem.create_time);
  198. if (tmpTime >= startTime && tmpTime <= endTime) {
  199. tmpData.money += childItem.order_amount;
  200. }
  201. });
  202. result.push(tmpData);
  203. });
  204. return result;
  205. }
  206. /**
  207. * [productStockSub 发货后扣除库存]
  208. * @param {Array} products [description]
  209. * @param {[type]} transaction [description]
  210. * @return {[type]} [description]
  211. */
  212. async productStockSub(order_id, transaction = null, index = 2) {
  213. const that = this;
  214. const product_stock_subtime = await that.service.configs.getConfigValue('product_stock_subtime');
  215. if (Number(product_stock_subtime) != index) return false;
  216. const seq = that.app.Sequelize;
  217. const products = await that.app.model.OrdersProducts.findAll({
  218. where: { order_id }, attributes: [ 'product_id', 'deliver_count' ], raw: true,
  219. transaction,
  220. });
  221. if (!products.length) return false;
  222. for (let i = 0; i < products.length; i++) {
  223. const item = products[i];
  224. const updateData = {
  225. product_stock: seq.literal(`product_stock - ${item.deliver_count}`),
  226. sale_count: seq.literal(`sale_count + ${item.deliver_count}`),
  227. update_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  228. };
  229. const res = await that.app.model.Products.update(updateData, {
  230. where: { product_id: item.product_id },
  231. transaction,
  232. });
  233. if (!res) throw new Error('库存扣除失败,请稍候重试');
  234. }
  235. return true;
  236. }
  237. }
  238. module.exports = OrderService;