commission.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. 'use strict';
  2. const BaseService = require('./base.js');
  3. // 分佣变动服务类
  4. class CommissionService extends BaseService {
  5. /**
  6. * 佣金变化
  7. * @param order_id (64字符 为提现out_detail_no)
  8. * @return {Promise<type[]>}
  9. */
  10. async addCommissionChangeLog(params) {
  11. const that = this;
  12. let action_user = '';
  13. // -1提现失败,0提现成功;1分佣;2提现中;
  14. // eslint-disable-next-line default-case
  15. switch (params.type) {
  16. case -1:
  17. case 0:
  18. case 2:
  19. action_user = '用户提现';
  20. break;
  21. case 1:
  22. action_user = '订单分佣';
  23. break;
  24. }
  25. const createBean = await that.app.comoBean.instance({
  26. user_id: params.user_id, order_id: params.order_id, type: params.type, commission: params.commission,
  27. out_batch_no: params.out_batch_no, out_detail_no: params.out_detail_no,
  28. action_user, log_desc: params.log_desc, create_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  29. }, {});
  30. const result = await that.create(createBean, that.app.model.UsersCommissionLogs, '记录邀请用户分佣变动失败');
  31. return result;
  32. }
  33. /**
  34. * 记录邀请用户分佣变动
  35. * log_id int unsigned auto_increment comment '记录ID' primary key,
  36. * log_desc varchar(255) not null comment '变动说明',
  37. * user_id int unsigned not null comment '用户ID',
  38. * order_id int default -1 not null comment '订单ID,提现类型订单id为-1',
  39. * commission float(10, 2) not null comment '变动金额',
  40. * action_user varchar(255) not null comment '操作对象',
  41. * type int default 0 not null comment '0提现;1分佣',
  42. * create_time timestamp default CURRENT_TIMESTAMP not null comment '创建时间'
  43. * @return {Promise<type[]>}
  44. */
  45. async inviterCommissionLog(orderUserInfo = {}, inviter_id, order_id, type, commission, log_desc) {
  46. const that = this;
  47. let action_user = '';
  48. if (type === 0) {
  49. action_user = '提现';
  50. } else if (type === 1) {
  51. action_user = '分佣';
  52. }
  53. const createBean = await that.app.comoBean.instance({
  54. user_id: inviter_id,
  55. order_id,
  56. type,
  57. commission,
  58. action_user,
  59. inviter_id: orderUserInfo.user_id ? orderUserInfo.user_id : -1,
  60. inviter_name: orderUserInfo.nickname ? orderUserInfo.nickname : '',
  61. inviter_img: orderUserInfo.headimgurl ? orderUserInfo.headimgurl : '',
  62. log_desc,
  63. create_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  64. }, {});
  65. const result = await that.create(createBean, that.app.model.UsersCommissionLogs, '记录邀请用户分佣变动失败');
  66. return result;
  67. }
  68. /**
  69. * 分佣发放到用户账户 并 记录
  70. * @param order
  71. * @return {Promise<number>} commission_log_id
  72. */
  73. async dispatchCommission(order = null) {
  74. const that = this;
  75. let commission_log_id = -1;
  76. try {
  77. if (order && order.inviter_id > 0) {
  78. // 2022/11/18 获取配置分佣比例
  79. const keys = [ 'shop_commission_ratio', 'partner_commission_ratio', 'not_commission_category',
  80. 'special_sale_category', 'sale_commission_ratio' ];
  81. const config = await that.service.configs.getConfigMoreValue(keys);
  82. let ratioDefault = 0;
  83. let ratioPartner = 0;
  84. let ratioSpecialSale = 0;
  85. let saleCategoryId = 15;
  86. // 2023/4/18 邀请人餐店合伙信息
  87. const partnerInfo = await that.app.model.PartnerInfo.findOne({
  88. where: { user_id: order.inviter_id },
  89. });
  90. // 2023/4/18 : 餐店 套餐推广 category_id 分佣比例特殊处理 partner_commission_ratio
  91. ratioPartner = Number(config.partner_commission_ratio);
  92. ratioDefault = Number(config.shop_commission_ratio);
  93. ratioSpecialSale = Number(config.sale_commission_ratio);
  94. saleCategoryId = Number(config.special_sale_category);
  95. const temA = config.not_commission_category.replace('[', '');
  96. const temB = temA.replace(']', '');
  97. let notCommissionCategory = temB.split(',');
  98. notCommissionCategory = notCommissionCategory.map(Number);
  99. // 2022/11/18 计算分佣金额 排除无分佣的分类
  100. let commission = 0;
  101. if (order.orders_products.length > 0) {
  102. for (let i = 0; i < order.orders_products.length; i++) {
  103. if (!notCommissionCategory.includes(order.orders_products[i].category_id)) {
  104. if (saleCategoryId === order.orders_products[i].category_id) {
  105. // 2023/5/24 特销产品分佣
  106. commission += order.orders_products[i].total_price * ratioSpecialSale;
  107. } else if (partnerInfo && partnerInfo.category_id === order.orders_products[i].category_id) {
  108. // 2023/4/18 餐店推广自己的分类套餐 分佣比例有区别
  109. commission += order.orders_products[i].total_price * ratioPartner;
  110. } else {
  111. commission += order.orders_products[i].total_price * ratioDefault;
  112. }
  113. }
  114. }
  115. } else {
  116. commission = ratioDefault * order.order_amount;
  117. }
  118. commission = commission.toFixed(2);
  119. if (commission > 0) {
  120. // 2022/11/18 记录 并 发放到用户账户
  121. const updateBean = await that.app.comoBean.instance({
  122. commission: that.app.Sequelize.literal('commission + ' + commission),
  123. update_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  124. }, { where: { user_id: order.inviter_id } });
  125. // 2022/9/27 用户分佣余额更新 用户表szj_users
  126. await that.update(updateBean, that.app.model.Users, '用户分佣金额更新失败,请稍候重试');
  127. // 2022/12/13 当前订单的用户信息
  128. const orderUserInfo = await that.app.model.Users.findOne({
  129. where: { user_id: order.user_id },
  130. attributes: [ 'user_id', 'nickname', 'headimgurl' ],
  131. raw: true,
  132. });
  133. // 2022/11/18 记录分佣发放
  134. const logResult = await that.inviterCommissionLog(orderUserInfo, order.inviter_id, order.order_id,
  135. 1, commission, '邀请用户下单分佣');
  136. commission_log_id = logResult.log_id;
  137. }
  138. }
  139. } catch (e) {
  140. return commission_log_id;
  141. }
  142. return commission_log_id;
  143. }
  144. /**
  145. * 付款后操作检查订单及其分佣处理
  146. * @return {Promise<void>}
  147. */
  148. async orderCommissionDispatchAfterPay(order_id = -1) {
  149. const that = this;
  150. /* const order = await that.app.model.Orders.findOne({
  151. where: { order_id }, raw: true,
  152. });*/
  153. // 2022/12/24 查询订单包含商品列表详情
  154. const order = await that.selectOrderInfo(order_id);
  155. if (!order) throw new Error('订单不存在');
  156. if (order.inviter_id > 0 && order.commission_log_id === -1 && order.order_status === 1) {
  157. // 2022/11/17 发放分佣并记录
  158. const dispatchResult = that.dispatchCommission(order);
  159. let commission_log_id = -1;
  160. dispatchResult.then(log_id => {
  161. commission_log_id = log_id;
  162. if (commission_log_id >= 0) {
  163. // 2022/11/17 更新订单信息
  164. const updateBean = that.app.comoBean.instance({ commission_log_id }, {
  165. where: { order_id: order.order_id },
  166. });
  167. that.service.base.update(updateBean, that.app.model.Orders, '发放分佣后更新订单状态失败,请稍候重试');
  168. } else {
  169. that.logger.error('发放分佣记录失败,对应订单order_id: %s , 订单金额为:%s', order.order_id, order.order_amount);
  170. }
  171. });
  172. }
  173. }
  174. /**
  175. * 查询订单详情
  176. * @param order_id
  177. * @return {Promise<null|*>}
  178. */
  179. async selectOrderInfo(order_id) {
  180. const that = this;
  181. const options = {
  182. where: { order_id }, include: [
  183. {
  184. model: that.app.model.OrdersProducts, as: 'orders_products', attributes: {
  185. exclude: [ 'product_id', 'create_time', 'order_id', 'activity_name', 'activity_id', 'activity_desc' ],
  186. },
  187. },
  188. ], attributes: {
  189. exclude: [ 'seller_remarks', 'province_id', 'city_id', 'county_id', 'shipping_id', 'shipping_fee', 'activity_id', 'activity_name', 'activity_desc' ],
  190. },
  191. };
  192. const selectBean = await that.app.comoBean.instance({}, options);
  193. try {
  194. return await that.service.base.select(selectBean, that.app.model.Orders, '查询订单详情失败,请稍候重试', false, false);
  195. } catch (e) {
  196. that.logger.error('订单id:%s ;分佣查询订单详情失败', order_id);
  197. return null;
  198. }
  199. }
  200. }
  201. module.exports = CommissionService;