ServiceTimer.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. $orderList = Order::query()->with(['user', 'goods'])->where('status', 2)->where('is_expire', 0)->where('expire_at', '<=', date('Y-m-d H:i:s'))->get();
  36. if($orderList->isNotEmpty()){
  37. DB::beginTransaction();
  38. try{
  39. foreach($orderList as $order){
  40. // 过期本订单
  41. Order::query()->where('oid', $order->oid)->update(['is_expire' => 1]);
  42. // 过期生效中的加油包
  43. Order::query()
  44. ->with(['goods'])
  45. ->where('user_id', $order->user_id)
  46. ->where('status', 2)
  47. ->where('is_expire', 0)
  48. ->whereHas('goods', function($q){
  49. $q->where('type', 1);
  50. })->update(['is_expire' => 1]);
  51. if(empty($order->user) || empty($order->goods)){
  52. continue;
  53. }
  54. // 清理全部流量
  55. Helpers::addUserTrafficModifyLog($order->user_id, $order->oid, $order->user->transfer_enable, 0, '[定时任务]用户所购商品到期,扣减商品对应的流量');
  56. User::query()->where('id', $order->user_id)->update(['u' => 0, 'd' => 0, 'transfer_enable' => 0, 'reset_time' => NULL]);
  57. // 删除对应用户的所有标签
  58. UserLabel::query()->where('user_id', $order->user_id)->delete();
  59. // 检查该订单对应用户是否有预支付套餐
  60. $prepaidOrder = Order::query()->where('user_id', $order->user_id)->where('status', 3)->orderBy('oid', 'asc')->first();
  61. if($prepaidOrder){
  62. $this->activePrepaidOrder($prepaidOrder->oid);
  63. }
  64. }
  65. DB::commit();
  66. } catch(Exception $e){
  67. Log::error($this->description.':'.$e);
  68. DB::rollBack();
  69. }
  70. }
  71. }
  72. }