hospital-applets-api/app/Command/GrantUserCouponCommand.php

92 lines
2.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Command;
use App\Model\Coupon;
use App\Model\User;
use App\Model\UserCoupon;
use App\Services\CouponService;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Hyperf\DbConnection\Db;
use Psr\Container\ContainerInterface;
/**
* 发放优惠卷
*/
#[Command]
class GrantUserCouponCommand extends HyperfCommand
{
public function __construct(protected ContainerInterface $container)
{
parent::__construct('GrantUserCoupon:command');
}
public function configure()
{
parent::configure();
$this->setDescription('发放用户优惠卷');
}
public function handle()
{
$this->line("开始");
// 获取所有状态正常用户
$params = array();
$params['user_type'] = 1;
$params['user_status'] = 1;
$users = User::getList($params);
if (empty($users)){
$this->line("结束:无可执行用户");
return;
}
// 获取需要发放的优惠卷数据
$params = array();
$params['coupon_id'] = 5;
$coupon = Coupon::getOne($params);
if (empty($coupon)){
$this->line("结束:无可执行优惠卷");
return;
}
foreach ($users as $user){
// 获取用户优惠卷
$params = array();
$params['coupon_id'] = $coupon['coupon_id'];
$params['user_id'] = $user['user_id'];
$user_coupon = UserCoupon::getOne($params);
if (!empty($user_coupon)){
$this->line("用户已拥有该优惠卷");
continue;
}
Db::beginTransaction();
try {
// 发放优惠卷
$couponService = new CouponService();
$res = $couponService->GrantUserCoupon($coupon['coupon_id'],$user['user_id']);
if (!$res){
Db::rollBack();
$this->line("优惠卷发放失败");
continue;
}
}catch (\Throwable $e){
Db::rollBack();
$this->line($e->getMessage());
}
Db::commit();
$this->line("用户" . $user['user_name'] . "执行完毕");
sleep(1);
}
$this->line("发放完毕");
}
}