ActivityCalc.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. <?php
  2. namespace crmeb\services\async;
  3. use app\admin\model\user\User;
  4. use app\admin\model\user\UserBill;
  5. use app\models\store\StoreOrder;
  6. use app\models\store\StoreOrderCartInfo;
  7. use app\models\system\SystemAwardHistory;
  8. use app\models\user\UserNotice;
  9. use crmeb\basic\BaseModel;
  10. use crmeb\utils\Redis;
  11. use think\facade\Log;
  12. /**
  13. * 活动基类
  14. *
  15. * 活动设计为:一个活动有一个商品分类,该分类下的商品为该活动商品
  16. */
  17. abstract class ActivityCalc {
  18. protected $ctx = [];
  19. public function __construct() {
  20. }
  21. /**
  22. * 根据分类 ID 来获取该分类下已被购买的单件商品,及其订单,用户信息
  23. * @param $cate_id
  24. * @return array
  25. */
  26. protected static function getOrders($cate_id) {
  27. $products = StoreOrderCartInfo::alias('ci')
  28. ->join('store_order o', 'o.id=ci.oid')
  29. ->join('store_product p', 'ci.product_id=p.id')
  30. ->join('user u', 'u.uid = o.uid')
  31. ->where('o.paid', 1)
  32. ->where('o.status', '>=', 0)
  33. ->where('o.refund_status', 0)
  34. ->where('o.is_del', 0)
  35. ->where('o.is_system_del', 0)
  36. ->where('p.cate_id', $cate_id)
  37. ->where('ci.activity', '')
  38. ->field('o.id, o.pay_price, ci.product_id, ci.cart_info, u.uid, u.now_money, u.pay_count, p.store_name')
  39. ->select();
  40. $products = $products ? $products->toArray() : [];
  41. return $products;
  42. }
  43. /**
  44. * 用统一的架构来计算输赢
  45. */
  46. public function calc() {
  47. // 活动分类ID
  48. $cate_id = $this->getId();
  49. $products = self::getOrders($cate_id);
  50. $pNum = count($products);
  51. $minNum = $this->getMinimalProductNum();
  52. if ($pNum < $minNum) {
  53. Log::warning("not enough order. product num: $pNum, $minNum needed, stop activity: $this->getNameCN()");
  54. return;
  55. }
  56. // 按商品处理订单
  57. $counter = 0; // 订单中商品计数器
  58. $left = []; // 左侧商品
  59. $right = []; // 右侧商品
  60. $left_spent = 0; // 左侧总价
  61. $right_spent = 0; // 右侧总价
  62. $left_cost = 0; // 左侧总成本
  63. $right_cost = 0; // 右侧总成本
  64. // 打乱商品顺序
  65. shuffle($products);
  66. shuffle($products);
  67. // 标记有多件商品的订单, 再次统计到属于某个订单的商品时, 订单会重复
  68. $orders = [];
  69. foreach($products as &$p) {
  70. $counter += 1;
  71. $ci = json_decode($p['cart_info'], true);
  72. $num = $ci['cart_num']; // 购买个数
  73. $productInfo = isset($ci['productInfo']) ? $ci['productInfo'] : [];
  74. $attrInfo = isset($productInfo['attrInfo']) ? $productInfo['attrInfo'] : [];
  75. // 价格, 成本
  76. $price = isset($attrInfo['price']) ? $attrInfo['price'] : 0.0;
  77. $cost = isset($attrInfo['cost']) ? $attrInfo['cost'] : 0.0;
  78. // 付款总额, 总成本
  79. $ppaid = bcmul($num, $price, 2);// product paid
  80. $pcost = bcmul($num, $cost, 2);
  81. // orderId
  82. $oid = $p['id'];
  83. // 标记付款和成本
  84. $p['paid'] = $ppaid;
  85. $p['cost'] = $pcost;
  86. $p['image'] = isset($attrInfo['image']) ? $attrInfo['image'] : '';
  87. // 处理一个订单多件商品的情况
  88. if (!isset($orders[$oid])) {
  89. $orders[$oid] = 1;
  90. } else {
  91. $orders[$oid] += 1;
  92. }
  93. // if ($ppaid <= 1.0) {
  94. // Log::warning("impossible price, order: ". $p['id']);
  95. // continue;
  96. // }
  97. // if ($pcost <= 0.1) {
  98. // Log::warning("impossible cost, order: ". $p['id']);
  99. // continue;
  100. // }
  101. // 按一个规则, 把商品分为两份, 其中一份中奖
  102. if ($this->leaningJudge($counter, $p, $attrInfo)) {
  103. $left[] = $p;
  104. $left_spent = bcadd($left_spent, $ppaid, 2);
  105. $left_cost = bcadd($left_cost, $pcost, 2);
  106. } else {
  107. $right[] = $p;
  108. $right_spent = bcadd($right_spent, $ppaid, 2);
  109. $right_cost = bcadd($right_cost, $pcost, 2);
  110. }
  111. } // foreach
  112. // 利润
  113. $left_profit = bcsub($left_spent, $left_cost, 2);
  114. $right_profit = bcsub($right_spent, $right_cost, 2);
  115. // 定输赢
  116. $diff_money = abs(bcsub($left_spent, $right_spent, 2));
  117. // if ($diff_money < 0.0) {
  118. // $diff_money = -$diff_money;
  119. // }
  120. // 假定左边胜利
  121. $profit = $right_profit;
  122. $winners = $left;
  123. $losers = $right;
  124. // 左边利润高则右边胜利
  125. if ($left_profit > $right_profit) {
  126. $winners = $right;
  127. $losers = $left;
  128. $profit = $left_profit;
  129. }
  130. // 如果只有 1 件商品
  131. if ($pNum == 1) {
  132. $KEY = 'activity:pool';
  133. // 此时,订单必为 loser
  134. // 40% 概率胜
  135. $itWin = false; // 这单胜了 ?
  136. $dice = mt_rand(0, 100);
  137. if ( $dice < 40) {
  138. $itWin = true;
  139. }
  140. $remain = intval(Redis::hGet($KEY, $this->getName()));
  141. if (!$itWin) {
  142. // 如果为新用户,且池子有钱,让他胜
  143. if ($remain > $profit && $products[0]['pay_count'] <= 1) {
  144. $itWin = true;
  145. }
  146. }
  147. if ($itWin) {
  148. $profit = -$profit;
  149. list($winners, $losers) = [$losers, $winners];
  150. }
  151. Redis::hSet($KEY, $this->getName(), $remain + $profit);
  152. Log::warning("$this->getName(): single order[product]. dice:$dice, remain:$remain, pay_count:$products[0]['pay_count']");
  153. }
  154. $result = $this->getResult($winners == $left);
  155. log::warning('products:' . json_encode($products)
  156. . ' left:' . json_encode($left) . ' left_spent:' . $left_spent
  157. . ' left_cost:' . $left_cost . ' left_profit:' . $left_profit
  158. . ' right' . json_encode($right) . ' right_spent:' . $right_spent
  159. . ' right_cost:' . $right_cost . ' right_profit:' . $right_profit
  160. . ' diff_money:' . $diff_money . ' profit:' . $profit . ' result:' . $result);
  161. // 保存开奖结果
  162. SystemAwardHistory::create([
  163. 'activity' => $this->getName(),
  164. 'result' => $result,
  165. 'ts' => time(),
  166. 'order_num' => count($left) + count($right),
  167. 'winner_num' => count($winners),
  168. 'total_paid' => $left_spent + $right_spent,
  169. 'diff_paid' => $diff_money,
  170. 'profit' => $profit,
  171. 'rate' => $this->repRate(),
  172. ]);
  173. // 结果处置 胜方退款,败方发货
  174. foreach($winners as $p) {
  175. $single = $orders[$p['id']] == 1;
  176. $this->execute($p, $single, true);
  177. }
  178. foreach($losers as $p) {
  179. $single = $orders[$p['id']] == 1;
  180. $this->execute($p, $single, false);
  181. }
  182. Log::warning("activity $this->getNameCN() calc finished. result: $result");
  183. }
  184. protected function execute($product, $single=true, $win=true) {
  185. BaseModel::beginTrans();
  186. $result = 0;
  187. $reparation = 0.0;
  188. if ($win) {
  189. $result = 1;
  190. $reparation = bcmul(bcsub($product['paid'], $product['cost'], 2), $this->repRate(), 2);
  191. }
  192. if ($reparation < 0.0) {
  193. log::warning("reparation = $reparation, orderId=" . $product['id']);
  194. $reparation = 0.0;
  195. }
  196. // 标记商品为已参与活动
  197. $r1 = StoreOrderCartInfo::where('oid', $product['id'])
  198. ->where('product_id', $product['product_id'])
  199. ->update([
  200. 'activity' => $this->getName(),
  201. 'result' => $result,
  202. 'reparation' => $reparation,
  203. ]);
  204. if (!$win) {
  205. BaseModel::checkTrans($r1);
  206. return;
  207. }
  208. $refund_price = bcadd($product['paid'], $reparation, 2);
  209. // 订单全部商品都中奖的退单
  210. $r2 = true;
  211. if ($single) {
  212. $r2 = StoreOrder::where('id', $product['id'])->update([
  213. 'refund_price' => $refund_price,
  214. 'refund_status' => 2,
  215. ]);
  216. }
  217. // 中奖的 退款并赔款返回到佣金
  218. $r3 = UserBill::income('活动' . $this->getNameCN(), $product['uid'], 'now_money', 'brokerage',
  219. $refund_price, $product['id'], bcadd($product['now_money'], $refund_price, 2),
  220. '订单退款' . $product['paid'] . '+' . $reparation . '元');
  221. $r4 = User::bcInc($product['uid'], 'brokerage_price', $refund_price, 'uid');
  222. $ok = $r1 && $r2 && $r3 && $r4;
  223. BaseModel::checkTrans($ok);
  224. if ($ok) {
  225. // 中奖用户发送中奖消息.
  226. UserNotice::sendNoticeTo($product['uid'], '您的订单已退款',
  227. '您好,由于活动商品库存有限,您的订单 ' . $product['store_name']
  228. . ' 未能成功发货。 该商品付款' . $product['paid'] . '元已如数退还,并赔付您' . $reparation
  229. . '元作为补偿,请在“我的佣金”中核实。对您造成的不便我们深感抱歉。感谢您对我们的信任和喜爱,美天旺祝您生活愉快。', $product['image']);
  230. }
  231. }
  232. // 活动所属的 $categoryId
  233. abstract protected function getId();
  234. // 活动英文名, 长度 <8
  235. abstract protected function getName();
  236. // 活动中文名
  237. abstract protected function getNameCN();
  238. // 赔款所占商品利润的百分比
  239. abstract protected function repRate();
  240. // 满足开奖的最小订单数
  241. abstract protected function getMinimalProductNum();
  242. // 获得开奖结果 int
  243. abstract protected function getResult($leftwin=true);
  244. /**
  245. * 根据此函数返回值来划分 getOrders() 返回的订单为两份, 其中一份中奖, 当本函数返回 true, $product 加入"左边"
  246. *
  247. * @param $index: $product 所在序号, 从 1 开始
  248. * @param $product: getOrders() 返回列表中的单个元素
  249. * @param $attr: 商品属性
  250. * @return boolean true 加入左边
  251. */
  252. abstract protected function leaningJudge($index, $product, $attr);
  253. }