ActivityCalc.php 8.2 KB

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