105 lines
3.5 KiB
PHP
105 lines
3.5 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\Coupon;
|
|
use App\Models\CouponSendTask;
|
|
use App\Models\CouponTaskLog;
|
|
use App\Models\UserCoupon;
|
|
use App\Services\CouponService;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Throwable;
|
|
|
|
class AdminSendCoupon extends Command
|
|
{
|
|
/**
|
|
* 单次最大条数
|
|
*
|
|
* @var integer
|
|
*/
|
|
protected $limit = 100;
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'admin-work:send-coupon';
|
|
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = '后台执行优惠券发放任务';
|
|
|
|
/**
|
|
* Create a new command instance.
|
|
*
|
|
* @return void
|
|
*/
|
|
public function __construct()
|
|
{
|
|
parent::__construct();
|
|
}
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*
|
|
* @return int
|
|
*/
|
|
public function handle()
|
|
{
|
|
while (true) {
|
|
//获取需要执行的任务数据包
|
|
$logs = CouponTaskLog::where('status', '0')->where('num', '>', 0)->orderBy('id')->limit($this->limit)->get();
|
|
$logs = $logs->groupBy('task_id');
|
|
foreach ($logs as $taskId => $taskLogs) {
|
|
$task = CouponSendTask::find($taskId);
|
|
$coupon = Coupon::find($task->coupon_id);
|
|
//如果优惠券限量,则获取优惠券余量,只发送前面的人;
|
|
$failedLogs = collect([]);
|
|
if ($coupon->limit > 0 && $coupon->stock < ($taskLogs->count() * $task->num)) {
|
|
$failedLogs = $taskLogs->slice($coupon->stock);
|
|
$taskLogs = $taskLogs->slice(0, $coupon->stock);
|
|
}
|
|
|
|
//批量插入用户优惠券
|
|
$insertUserCoupons = [];
|
|
foreach ($taskLogs as $taskLog) {
|
|
for ($i=0; $i< $taskLog->num; $i++) {
|
|
$insertUserCoupons[] = CouponService::createUserCouponData($taskLog->user_id, $coupon);
|
|
}
|
|
}
|
|
try {
|
|
DB::beginTransaction();
|
|
|
|
count($insertUserCoupons) > 0 && UserCoupon::insert($insertUserCoupons);
|
|
//更新任务日志状态;
|
|
CouponTaskLog::whereIn('id', $taskLogs->pluck('id')->toArray())->update(['status'=>2]);
|
|
$failedLogs->count() == 0 || CouponTaskLog::whereIn('id', $failedLogs->pluck('id')->toArray())->update(['status'=>3, 'remarks'=>'库存余量不足']);
|
|
//更新任务对应券发送量,余量;
|
|
$coupon->increment('sent', $taskLogs->count());
|
|
if ($coupon->limit > 0) {//限量才减少余量
|
|
$coupon->decrement('stock', $taskLogs->count());
|
|
}
|
|
|
|
//更新如果是任务最后一批,更新任务状态;
|
|
$taskTotalnum = CouponTaskLog::where('task_id', $taskId)->where('num', '>', 0)->count();
|
|
$taskDidnum = CouponTaskLog::where('task_id', $taskId)->where('num', '>', 0)->where('status', '>', 0)->count();
|
|
if ($taskTotalnum == $taskDidnum) {
|
|
$task->update(['status' => 3]);
|
|
}
|
|
DB::commit();
|
|
} catch (Throwable $th) {
|
|
DB::rollBack();
|
|
report($th);
|
|
}
|
|
}
|
|
$this->info('执行成功');
|
|
|
|
sleep(60);
|
|
}
|
|
}
|
|
}
|