ActivityCalc.php 11 KB

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