ActivityCalc.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 think\facade\Log;
  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.pay_price, ci.product_id, ci.cart_info, u.uid, u.now_money, p.store_name')->select();
  38. $products = $products ? $products->toArray() : [];
  39. return $products;
  40. }
  41. /**
  42. * 用统一的架构来计算输赢
  43. */
  44. public function calc() {
  45. // 活动分类ID
  46. $cate_id = $this->getId();
  47. $products = self::getOrders($cate_id);
  48. if (count($products) <= 1) {
  49. Log::warning('not enough order, stop activity:' . $this->getNameCN());
  50. return;
  51. }
  52. // 按商品处理订单
  53. $counter = 0;
  54. $left = [];
  55. $right = [];
  56. $left_spent = 0;
  57. $right_spent = 0;
  58. $left_cost = 0;
  59. $right_cost = 0;
  60. // 打乱商品顺序
  61. shuffle($products);
  62. shuffle($products);
  63. // 标记有多件商品的订单, 再次统计到属于某个订单的商品时, 订单会重复
  64. $orders = [];
  65. foreach($products as &$p) {
  66. $counter += 1;
  67. $ci = json_decode($p['cart_info'], true);
  68. $num = $ci['cart_num']; // 购买个数
  69. $productInfo = isset($ci['productInfo']) ? $ci['productInfo'] : [];
  70. $attrInfo = isset($productInfo['attrInfo']) ? $productInfo['attrInfo'] : [];
  71. // 价格, 成本
  72. $price = isset($attrInfo['price']) ? $attrInfo['price'] : 0.0;
  73. $cost = isset($attrInfo['cost']) ? $attrInfo['cost'] : 0.0;
  74. // 付款总额, 总成本
  75. $ppaid = bcmul($num, $price, 2);// product paid
  76. $pcost = bcmul($num, $cost, 2);
  77. // orderId
  78. $oid = $p['id'];
  79. // 标记付款和成本
  80. $p['paid'] = $ppaid;
  81. $p['cost'] = $pcost;
  82. $p['image'] = isset($attrInfo['image']) ? $attrInfo['image'] : '';
  83. // 处理一个订单多件商品的情况
  84. if (!isset($orders[$oid])) {
  85. $orders[$oid] = 1;
  86. } else {
  87. $orders[$oid] += 1;
  88. }
  89. // if ($ppaid <= 1.0) {
  90. // Log::warning("impossible price, order: ". $p['id']);
  91. // continue;
  92. // }
  93. // if ($pcost <= 0.1) {
  94. // Log::warning("impossible cost, order: ". $p['id']);
  95. // continue;
  96. // }
  97. // 按一个规则, 把商品分为两份, 其中一份中奖
  98. if ($this->leaningJudge($counter, $p, $attrInfo)) {
  99. $left[] = $p;
  100. $left_spent = bcadd($left_spent, $ppaid, 2);
  101. $left_cost = bcadd($left_cost, $pcost, 2);
  102. } else {
  103. $right[] = $p;
  104. $right_spent = bcadd($right_spent, $ppaid, 2);
  105. $right_cost = bcadd($right_cost, $pcost, 2);
  106. }
  107. } // foreach
  108. // 利润
  109. $left_profit = bcsub($left_spent, $left_cost, 2);
  110. $right_profit = bcsub($right_spent, $right_cost, 2);
  111. // 定输赢
  112. $diff_money = bcsub($left_spent, $right_spent, 2);
  113. if ($diff_money < 0.0) {
  114. $diff_money = -$diff_money;
  115. }
  116. $profit = $left_profit;
  117. $winners = $left;
  118. $losers = $right;
  119. if ($left_profit > $right_profit) {
  120. $winners = $right;
  121. $losers = $left;
  122. $profit = $right_profit;
  123. }
  124. $result = $this->getResult($winners == $left);
  125. log::warning('products:' . json_encode($products)
  126. . ' left:' . json_encode($left) . ' left_spent:' . $left_spent
  127. . ' left_cost:' . $left_cost . ' left_profit:' . $left_profit
  128. . ' right' . json_encode($right) . ' right_spent:' . $right_spent
  129. . ' right_cost:' . $right_cost . ' right_profit:' . $right_profit
  130. . ' diff_money:' . $diff_money . ' profit:' . $profit . ' result:' . $result);
  131. // 保存开奖结果
  132. SystemAwardHistory::create([
  133. 'activity' => $this->getName(),
  134. 'result' => $result,
  135. 'ts' => time(),
  136. 'order_num' => count($left) + count($right),
  137. 'winner_num' => count($winners),
  138. 'total_paid' => $left_spent + $right_spent,
  139. 'diff_paid' => $diff_money,
  140. 'profit' => $profit,
  141. 'rate' => $this->repRate(),
  142. ]);
  143. // 结果处置
  144. foreach($winners as $p) {
  145. $single = $orders[$p['id']] == 1;
  146. $this->execute($p, $single, true);
  147. }
  148. foreach($losers as $p) {
  149. $single = $orders[$p['id']] == 1;
  150. $this->execute($p, $single, false);
  151. }
  152. Log::warning('activity ' . $this->getNameCN() . ' calc finished. result:' . $result);
  153. }
  154. protected function execute($product, $single=true, $win=true) {
  155. BaseModel::beginTrans();
  156. $result = 0;
  157. $reparation = 0.0;
  158. if ($win) {
  159. $result = 1;
  160. $reparation = bcmul(bcsub($product['paid'], $product['cost'], 2), $this->repRate(), 2);
  161. }
  162. // 标记商品为已参与活动
  163. $r1 = StoreOrderCartInfo::where('oid', $product['id'])
  164. ->where('product_id', $product['product_id'])
  165. ->update([
  166. 'activity' => $this->getName(),
  167. 'result' => $result,
  168. 'reparation' => $reparation,
  169. ]);
  170. if (!$win) {
  171. BaseModel::checkTrans($r1);
  172. return;
  173. }
  174. $refund_price = bcadd($product['paid'], $reparation, 2);
  175. // 订单全部商品都中奖的退单
  176. $r2 = true;
  177. if ($single) {
  178. $r2 = StoreOrder::where('id', $product['id'])->update([
  179. 'refund_price' => $refund_price,
  180. 'refund_status' => 2,
  181. ]);
  182. }
  183. // 中奖的 退款并赔款返回到佣金
  184. $r3 = UserBill::income('活动' . $this->getNameCN(), $product['uid'], 'now_money', 'brokerage',
  185. $refund_price, $product['id'], bcadd($product['now_money'], $refund_price, 2),
  186. '订单退款' . $product['paid'] . '+' . $reparation . '元');
  187. $r4 = User::bcInc($product['uid'], 'brokerage_price', $refund_price, 'uid');
  188. $ok = $r1 && $r2 && $r3 && $r4;
  189. BaseModel::checkTrans($ok);
  190. if ($ok) {
  191. // 中奖用户发送中奖消息.
  192. UserNotice::sendNoticeTo($product['uid'], '您的订单已退款',
  193. '您好,由于活动商品库存有限,您的订单 ' . $product['store_name']
  194. . ' 未能成功分配。 该商品付款' . $product['paid'] . '元已如数退还,并赔付您' . $reparation
  195. . '元作为补偿,对您造成的不便我们深感抱歉。同时感谢您对美天旺的信任和喜爱,祝您生活愉快。', $product['image']);
  196. }
  197. }
  198. // 活动所属的 $categoryId
  199. abstract protected function getId();
  200. // 活动英文名, 长度 <8
  201. abstract protected function getName();
  202. // 活动中文名
  203. abstract protected function getNameCN();
  204. // 赔款所占商品利润的百分比
  205. abstract protected function repRate();
  206. // 获得开奖结果 int
  207. abstract protected function getResult($leftwin=true);
  208. /**
  209. * 根据此函数返回值来划分 getOrders() 返回的订单为两份, 其中一份中奖, 当本函数返回 true, $product 加入"左边"
  210. *
  211. * @param $index: $product 所在序号, 从 1 开始
  212. * @param $product: getOrders() 返回列表中的单个元素
  213. * @param $attr: 商品属性
  214. * @return boolean true 加入左边
  215. */
  216. abstract protected function leaningJudge($index, $product, $attr);
  217. }