ActivityCalc.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. // 处理一个订单多件商品的情况
  83. if (!isset($orders[$oid])) {
  84. $orders[$oid] = 1;
  85. } else {
  86. $orders[$oid] += 1;
  87. }
  88. if ($ppaid <= 1.0) {
  89. Log::warning("impossible price, order: ". $p['id']);
  90. continue;
  91. }
  92. if ($pcost <= 0.1) {
  93. Log::warning("impossible cost, order: ". $p['id']);
  94. continue;
  95. }
  96. // 按一个规则, 把商品分为两份, 其中一份中奖
  97. if ($this->leaningJudge($counter, $p, $attrInfo)) {
  98. $left[] = $p;
  99. $left_spent = bcadd($left_spent, $ppaid, 2);
  100. $left_cost = bcadd($left_cost, $pcost, 2);
  101. } else {
  102. $right[] = $p;
  103. $right_spent = bcadd($right_spent, $ppaid, 2);
  104. $right_cost = bcadd($right_cost, $pcost, 2);
  105. }
  106. } // foreach
  107. // 利润
  108. $left_profit = bcsub($left_spent, $left_cost, 2);
  109. $right_profit = bcsub($right_spent, $right_cost, 2);
  110. // 定输赢
  111. $diff_money = bcsub($left_spent, $right_spent, 2);
  112. if ($diff_money < 0.0) {
  113. $diff_money = -$diff_money;
  114. }
  115. $profit = $left_profit;
  116. $winners = $left;
  117. $losers = $right;
  118. if ($left_profit > $right_profit) {
  119. $winners = $right;
  120. $losers = $left;
  121. }
  122. $result = $this->getResult($winners == $left);
  123. // 保存开奖结果
  124. SystemAwardHistory::create([
  125. 'activity' => $this->getName(),
  126. 'result' => $result,
  127. 'ts' => time(),
  128. 'order_num' => count($left) + count($right),
  129. 'winner_num' => count($winners),
  130. 'total_paid' => $left_spent + $right_spent,
  131. 'diff_paid' => $diff_money,
  132. 'profit' => $profit,
  133. 'rate' => $this->repRate(),
  134. ]);
  135. // 结果处置
  136. foreach($winners as $p) {
  137. $single = $orders[$p['id']] == 1;
  138. $this->execute($p, $single, true);
  139. }
  140. foreach($losers as $p) {
  141. $single = $orders[$p['id']] == 1;
  142. $this->execute($p, $single, false);
  143. }
  144. Log::warning('activity ' . $this->getNameCN() . ' calc finished. result:');
  145. }
  146. protected function execute($product, $single=true, $win=true) {
  147. BaseModel::beginTrans();
  148. $result = 0;
  149. $reparation = 0.0;
  150. if ($win) {
  151. $result = 1;
  152. $reparation = bcmul(bcsub($product['paid'], $product['cost'], 2), $this->repRate(), 2);
  153. }
  154. // 标记商品为已参与活动
  155. $r1 = StoreOrderCartInfo::where('oid', $product['id'])
  156. ->where('product_id', $product['product_id'])
  157. ->update([
  158. 'activity' => $this->getName(),
  159. 'result' => $result,
  160. 'reparation' => $reparation,
  161. ]);
  162. if (!$win) {
  163. BaseModel::checkTrans($r1);
  164. return;
  165. }
  166. $refund_price = bcadd($product['paid'], $reparation, 2);
  167. // 订单全部商品都中奖的退单
  168. $r2 = true;
  169. if ($single) {
  170. $r2 = StoreOrder::where('id', $product['id'])->update([
  171. 'refund_price' => $refund_price,
  172. 'refund_status' => 2,
  173. ]);
  174. }
  175. // 中奖的 退款并赔款返回到佣金
  176. $r3 = UserBill::income('活动' . $this->getNameCN(), $product['uid'], 'now_money', 'brokerage',
  177. $refund_price, $product['id'], bcadd($product['now_money'], $refund_price, 2),
  178. '订单退款' . $product['paid'] . '+' . $reparation . '元');
  179. $r4 = User::bcInc($product['uid'], 'brokerage_price', $refund_price, 'uid');
  180. $ok = $r1 && $r2 && $r3 && $r4;
  181. BaseModel::checkTrans($ok);
  182. if ($ok) {
  183. // 中奖用户发送中奖消息.
  184. UserNotice::sendNoticeTo($product['uid'], '您的订单已退款',
  185. '您好,由于活动商品库存有限,您的订单 ' . $product['store_name']
  186. . ' 未能成功分配. 该商品付款' . $product['paid'] . '元已如数退还, 并赔付您' . $reparation
  187. . '元作为补偿, 对您造成的不便我们深感抱歉. 同时感谢您对美天旺的喜爱和信任, 美天旺活动场永远等您. 顺祝生活愉快.');
  188. }
  189. }
  190. // 活动所属的 $categoryId
  191. abstract protected function getId();
  192. // 活动英文名, 长度 <8
  193. abstract protected function getName();
  194. // 活动中文名
  195. abstract protected function getNameCN();
  196. // 赔款所占商品利润的百分比
  197. abstract protected function repRate();
  198. // 获得开奖结果 int
  199. abstract protected function getResult($leftwin=true);
  200. /**
  201. * 根据此函数返回值来划分 getOrders() 返回的订单为两份, 其中一份中奖, 当本函数返回 true, $product 加入"左边"
  202. *
  203. * @param $index: $product 所在序号, 从 1 开始
  204. * @param $product: getOrders() 返回列表中的单个元素
  205. * @param $attr: 商品属性
  206. * @return boolean true 加入左边
  207. */
  208. abstract protected function leaningJudge($index, $product, $attr);
  209. }