ServiceTimer.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Components\Helpers;
  4. use App\Http\Controllers\ServiceController;
  5. use App\Http\Models\Order;
  6. use App\Http\Models\User;
  7. use App\Http\Models\UserLabel;
  8. use DB;
  9. use Exception;
  10. use Illuminate\Console\Command;
  11. use Log;
  12. class ServiceTimer extends Command {
  13. protected $signature = 'serviceTimer';
  14. protected $description = '服务计时器';
  15. public function __construct() {
  16. parent::__construct();
  17. }
  18. public function handle() {
  19. $jobStartTime = microtime(true);
  20. // 扣减用户到期商品的流量
  21. $this->decGoodsTraffic();
  22. $jobEndTime = microtime(true);
  23. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  24. Log::info('---【'.$this->description.'】完成---,耗时'.$jobUsedTime.'秒');
  25. }
  26. // 扣减用户到期商品的流量
  27. private function decGoodsTraffic() {
  28. //获取失效的套餐
  29. $orderList = Order::query()->with(['goods'])->whereStatus(2)->whereIsExpire(0)->whereHas('goods', function($q) {
  30. $q->whereType(2);
  31. })->where('expire_at', '<=', date('Y-m-d H:i:s'))->get();
  32. if($orderList->isNotEmpty()){
  33. try{
  34. DB::beginTransaction();
  35. foreach($orderList as $order){
  36. // 过期本订单
  37. Order::query()->whereOid($order->oid)->update(['is_expire' => 1]);
  38. // 过期生效中的加油包
  39. Order::query()
  40. ->with(['goods'])
  41. ->whereUserId($order->user_id)
  42. ->whereStatus(2)
  43. ->whereIsExpire(0)
  44. ->whereHas('goods', function($q) {
  45. $q->whereType(1);
  46. })
  47. ->update(['is_expire' => 1]);
  48. if(empty($order->user) || empty($order->goods)){
  49. continue;
  50. }
  51. // 清理全部流量
  52. Helpers::addUserTrafficModifyLog($order->user_id, $order->oid, $order->user->transfer_enable, 0,
  53. '[定时任务]用户所购商品到期,扣减商品对应的流量');
  54. User::query()->whereId($order->user_id)->update([
  55. 'u' => 0,
  56. 'd' => 0,
  57. 'transfer_enable' => 0,
  58. 'reset_time' => null
  59. ]);
  60. // 删除对应用户的所有标签
  61. UserLabel::query()->whereUserId($order->user_id)->delete();
  62. // 检查该订单对应用户是否有预支付套餐
  63. $prepaidOrder = Order::query()
  64. ->whereUserId($order->user_id)
  65. ->whereStatus(3)
  66. ->orderBy('oid', 'asc')
  67. ->first();
  68. if($prepaidOrder){
  69. (new ServiceController)->activePrepaidOrder($prepaidOrder->oid);
  70. }
  71. }
  72. DB::commit();
  73. }catch(Exception $e){
  74. Log::error($this->description.':'.$e);
  75. DB::rollBack();
  76. }
  77. }
  78. }
  79. }