DistributionRewardTrait.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. <?php
  2. namespace addons\Agent\common\traits;
  3. use addons\Agent\common\enums\AgentEnum;
  4. use addons\Agent\common\enums\ComputingEnum;
  5. use addons\Agent\common\models\Agent;
  6. use addons\Agent\common\models\AgentDistributionSetting;
  7. use addons\Agent\common\models\AgentGoodsRepurchase;
  8. use common\enums\GoodsTypeEnum;
  9. use common\enums\StatusEnum;
  10. use common\helpers\FormatHelper;
  11. use common\models\mall\MallAddons;
  12. use common\models\order\Order;
  13. use common\models\order\OrderDetail;
  14. use common\models\user\UserPartitionRelationship;
  15. use services\common\UserWalletService;
  16. use yii\helpers\Json;
  17. trait DistributionRewardTrait
  18. {
  19. /**
  20. * @param array $order
  21. * @return bool
  22. */
  23. public function repurchaseReward(array $order)
  24. {
  25. // 执行奖励
  26. // 开关开启以后可以设置层级的分销奖励;每个商品可以设置奖励不同,层级可以自定义设置,一二级可以单独设置分佣,三级或者三级以上设置统一。
  27. // 例如:设置15层级,达到15层以后第16个人下单以后前面的15个人都可以拿奖励;假设第17个人下单下单了,找下单的前15代拿奖励,也就是2-16层级
  28. // 可以阶梯单独设置奖励
  29. try {
  30. $mall_id = $order['mall_id'];
  31. $order_id = $order['id'];
  32. $user_id = $order['user_id'];
  33. if (MallAddons::isInstall($mall_id, AgentEnum::ADDONS_NAME) == 0) return false;
  34. $setting = \Yii::$app->services->setting->addons->get($mall_id, AgentEnum::ADDONS_NAME, 'basic');
  35. if (empty($setting['is_enable'])) throw new \Exception('没开启渠道分红');
  36. $params['where'] = [['order_id' => $order_id], ['user_id' => $user_id], ['mall_id' => $mall_id]];
  37. $order_detail_list = OrderDetail::lists($params);
  38. if (empty($order_detail_list)) throw new \Exception('订单详情不存在');
  39. $parent_id_arr = UserPartitionRelationship::getParentIdArr($user_id);
  40. $parent_id_arr = array_reverse($parent_id_arr);
  41. $where = ['user_id' => $parent_id_arr, 'mall_id' => $mall_id, 'status' => StatusEnum::ENABLED];
  42. $addons_agent_list = Agent::find()->where($where)->indexBy('user_id')->all();//查询经销商列表
  43. $agent_list = [];
  44. // 如果中间有非渠道长的那么就直接断掉后面的奖励
  45. foreach ($parent_id_arr as $parent_id) {
  46. if (empty($addons_agent_list[$parent_id])) break;
  47. $agent_list[] = $addons_agent_list[$parent_id];//按照关系排序
  48. }
  49. // 需要判断是否为复购 - 只有复购的情况下才会有
  50. // 非复购情况下那么就给上级
  51. $enable_repurchase_reward = (int) $setting['enable_repurchase_reward'];
  52. $agent = Agent::findOne(['user_id' => $user_id, 'mall_id' => $mall_id, 'status' => StatusEnum::ENABLED]);// 查询购买者身份
  53. if ($enable_repurchase_reward) {
  54. $enable_repurchase_reward = Order::find()
  55. ->where(['mall_id' => $mall_id])
  56. ->andWhere(['user_id' => $user_id])
  57. ->andWhere(['<>', 'id', $order_id])
  58. ->andWhere(['pay_status' => StatusEnum::ENABLED])
  59. ->count();
  60. }
  61. // 如果本人是渠道长且有开启复购且当前订单是复购订单那么当前用户就拿第一代奖励
  62. // if ($enable_repurchase_reward == StatusEnum::ENABLED && !empty($agent)) {
  63. // array_unshift($agent_list, $agent);
  64. // }
  65. $wallet_insert = [];
  66. // 如果没有代理商,那么就不做分佣处理
  67. if (!empty($agent_list)) {
  68. $is_frozen = $setting['compute_type'] == ComputingEnum::ORDER_FINISH;
  69. foreach ($order_detail_list as $order_detail) {
  70. $distribution_settings = AgentDistributionSetting::find()
  71. ->where(['mall_id' => $mall_id])
  72. ->andWhere(['item_id' => $order_detail['goods_id']])
  73. ->andWhere(['status' => StatusEnum::ENABLED])
  74. ->select('value')
  75. ->column();
  76. // 判断配置了没
  77. if (empty($distribution_settings)) continue;
  78. if($order_detail['is_virtual'] == StatusEnum::ENABLED){
  79. //虚拟商品,支付后-直接订单完成,所以直接结算
  80. $is_frozen = false;
  81. }
  82. $tmp_agent_list = $agent_list;
  83. $tmp_enable_repurchase_reward = $enable_repurchase_reward;
  84. if (!empty($agent)) {
  85. // 独立设置
  86. if (AgentGoodsRepurchase::isAloneSetting($mall_id, $order_detail['goods_id'])) {
  87. // 判断当前用户是否买过, 如果当前用户没有买过当前商品那么就将自己剔除
  88. $tmp_enable_repurchase_reward =
  89. AgentGoodsRepurchase::isBuyCurrentGoods($mall_id, $user_id, $order_id, $order_detail['goods_id']) ?
  90. StatusEnum::ENABLED : StatusEnum::DISABLED;
  91. }
  92. if ($tmp_enable_repurchase_reward == StatusEnum::ENABLED) {
  93. array_unshift($tmp_agent_list, $agent); // 将自己排在第一位
  94. }
  95. }
  96. foreach ($distribution_settings as $distribution_setting) {
  97. $distribution_setting = Json::decode($distribution_setting);
  98. // 判断启用了没 - 如果有启用单独设置 那么也是可以执行的
  99. if (empty($distribution_setting['enable_repurchase_reward'])) continue;
  100. if (empty($distribution_setting['item_type']) || $distribution_setting['item_type'] != 'goods') continue;
  101. // 判断层级及分佣方式
  102. $rewards = $this->execReward($order_detail, $distribution_setting, $tmp_agent_list, $order['order_no'], $setting, $is_frozen);
  103. if (!empty($rewards)) {
  104. array_push($wallet_insert, ...$rewards);
  105. }
  106. }
  107. }
  108. if (!empty($wallet_insert)) {
  109. $res = UserWalletService::batchHandleByQueue($wallet_insert);
  110. if (empty($res)) {
  111. throw new \Exception(UserWalletService::getStaticError());
  112. }
  113. // 累加数据
  114. foreach ($wallet_insert as $user) {
  115. $agent = Agent::findOne(['user_id' => $user['user_id'], 'status'=>[StatusEnum::DISABLED, StatusEnum::ENABLED], 'mall_id' => $user['mall_id']]);
  116. if(empty($agent)) continue;
  117. $field = 'total_' . $user['wallet_type'];
  118. $agent->$field += $user['money'];
  119. if (!$agent->save()) throw new \Exception(Agent::getStaticError());
  120. }
  121. }
  122. }
  123. } catch (\Exception $e) {
  124. \Yii::error(FormatHelper::exception($e, __CLASS__ . "->" . __METHOD__));
  125. }
  126. return true;
  127. }
  128. /**
  129. * @param array $orderDetail
  130. * @param array $config
  131. * @param array $parentIds
  132. * @param string $order_no
  133. * @param array $setting
  134. * @param bool $is_frozen
  135. * @return array
  136. */
  137. protected function execReward(array $orderDetail, array $config, array $parentIds, string $order_no, array $setting, bool $is_frozen)
  138. {
  139. $insert_wallet = [];
  140. // 遍历所有上级
  141. foreach ($parentIds as $key => $agent) {
  142. // 控制在范围内
  143. if ($config['distribution_level_max'] < $key+1) break;
  144. $reward_amount = 0;
  145. // 需要判断是否独立设置 - 独立设置后 最终奖励那么就按独立设置的来处理
  146. switch ($key) {
  147. case 0:
  148. if ($config['distribution_level1'] > 0) {
  149. $reward_amount = $config['distribution_level1']; // 固定金额
  150. if ($config['distribution_type'] == 0) { // 百分比
  151. switch ($setting['computing_method']) {
  152. case 0: // 支付价格
  153. $reward_amount = $this->calcByPayAmount($orderDetail['goods_price'], $config['distribution_level1'] * 0.01);
  154. break;
  155. case 1: // 商品售价
  156. $reward_amount = $this->calcByGoodsSalePrice($orderDetail['price'], $orderDetail['num'], $config['distribution_level1'] * 0.01);
  157. break;
  158. case 2: // 商品利润
  159. $reward_amount = $this->calcByGoodsProfit($orderDetail['price'], $orderDetail['cost_price'],
  160. $orderDetail['num'], $config['distribution_level1'] * 0.01);
  161. break;
  162. }
  163. }
  164. }
  165. break;
  166. case 1:
  167. if ($config['distribution_level2'] > 0 && $config['distribution_level_max'] > 1) {
  168. $reward_amount = $config['distribution_level2']; // 固定金额
  169. if ($config['distribution_type'] == 0) { // 百分比
  170. switch ($setting['computing_method']) {
  171. case 0: // 支付价格
  172. $reward_amount = $this->calcByPayAmount($orderDetail['goods_price'], $config['distribution_level2'] * 0.01);
  173. break;
  174. case 1: // 商品售价
  175. $reward_amount = $this->calcByGoodsSalePrice($orderDetail['price'], $orderDetail['num'], $config['distribution_level2'] * 0.01);
  176. break;
  177. case 2: // 商品利润
  178. $reward_amount = $this->calcByGoodsProfit($orderDetail['price'], $orderDetail['cost_price'],
  179. $orderDetail['num'], $config['distribution_level2'] * 0.01);
  180. break;
  181. }
  182. }
  183. }
  184. break;
  185. default:
  186. // 必须保持在指定层级内
  187. if ($config['distribution_level3'] > 0 && $config['distribution_level_max'] > 2) {
  188. $reward_amount = $config['distribution_level3']; // 固定金额
  189. if ($config['distribution_type'] == 0) { // 百分比
  190. switch ($setting['computing_method']) {
  191. case 0: // 支付价格
  192. $reward_amount = $this->calcByPayAmount($orderDetail['goods_price'], $config['distribution_level3'] * 0.01);
  193. break;
  194. case 1: // 商品售价
  195. $reward_amount = $this->calcByGoodsSalePrice($orderDetail['price'], $orderDetail['num'], $config['distribution_level3'] * 0.01);
  196. break;
  197. case 2: // 商品利润
  198. $reward_amount = $this->calcByGoodsProfit($orderDetail['price'], $orderDetail['cost_price'],
  199. $orderDetail['num'], $config['distribution_level3'] * 0.01);
  200. break;
  201. }
  202. }
  203. }
  204. }
  205. if ($reward_amount > 0) {
  206. // ComputingEnum::AGENT_DISTRIBUTION_PREFIX . ($key + 1)
  207. $capital_type = ComputingEnum::AGENT_DISTRIBUTION_REWARD;
  208. $insert_wallet[] = $this->pack($agent->user_id, $orderDetail,
  209. $config['commission_type'], $reward_amount, $capital_type,
  210. $order_no, ComputingEnum::AGENT_DISTRIBUTION_REWARD_TXT, $is_frozen);
  211. }
  212. }
  213. return $insert_wallet;
  214. }
  215. /**
  216. * @param int $user_id
  217. * @param array $orderDetail
  218. * @param string $commission_type
  219. * @param string $amount
  220. * @param string $capital_type
  221. * @param string $order_no
  222. * @param string $reward_type
  223. * @param bool $is_frozen
  224. * @return array
  225. */
  226. protected function pack(int $user_id, array $orderDetail, string $commission_type, string $amount,
  227. string $capital_type, string $order_no, string $reward_type, bool $is_frozen)
  228. {
  229. // 获取奖励名称
  230. $commission_name = \Yii::$app->services->setting->mall->get($orderDetail['mall_id'], "{$commission_type}.{$commission_type}_name");
  231. if (empty($commission_name)) {
  232. switch ($commission_type) {
  233. case UserWalletService::WALLET_TYPE_COMMISSION:
  234. $commission_name = '佣金';
  235. break;
  236. default:
  237. $commission_name = '';
  238. }
  239. }
  240. $desc = "用户($user_id),获得订单({$orderDetail['order_id']})奖励,奖励类型: $reward_type, 奖励: $amount $commission_name";
  241. return [
  242. 'mall_id' => $orderDetail['mall_id'],
  243. 'user_id' => $user_id,
  244. 'is_frozen' => $is_frozen,
  245. 'wallet_type' => $commission_type,
  246. 'money' => $amount,
  247. 'desc' => $desc,
  248. 'source_table' => 'order_detail',
  249. 'source_table_id' => $orderDetail['id'], // 取出订单ID?
  250. 'from_type' => AgentEnum::ADDONS_NAME,
  251. 'capital_type' => $capital_type,
  252. 'order_no' => $order_no, // 这里需要订单号
  253. 'contributor_name' => $orderDetail['goods_name'],
  254. 'contributor_id' => $orderDetail['user_id'],
  255. 'contributor_money' => $orderDetail['goods_price'],
  256. ];
  257. }
  258. /**
  259. * @param $goods_price
  260. * @param $cardinality
  261. * @return string
  262. */
  263. protected function calcByPayAmount($goods_price, $cardinality)
  264. {
  265. return bcmul($goods_price, $cardinality, 2);
  266. }
  267. /**
  268. * @param $goods_price
  269. * @param $num
  270. * @param $cardinality
  271. * @return string
  272. */
  273. protected function calcByGoodsSalePrice($goods_price, $num, $cardinality)
  274. {
  275. return bcmul(bcmul($goods_price, $num, 2), $cardinality, 2);
  276. }
  277. /**
  278. * @param $goods_price
  279. * @param $goods_const_price
  280. * @param $num
  281. * @param $cardinality
  282. * @return string
  283. */
  284. protected function calcByGoodsProfit($goods_price, $goods_const_price, $num, $cardinality)
  285. {
  286. return bcmul(bcmul(bcsub($goods_price, $goods_const_price, 2), $num, 2),
  287. $cardinality, 2);
  288. }
  289. protected function traitUnshiftAgentList(int $enable_repurchase_reward, array $agent_list, array $orders, Agent $agent)
  290. {
  291. }
  292. }