ActivityCalc.php 11 KB

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