ServiceTimer.php 2.5 KB

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