ActivityCalc.php 7.7 KB

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