ActivityCalc.php 11 KB

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