ServiceTimer.php 2.6 KB

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