94 lines
3.0 KiB
PHP
94 lines
3.0 KiB
PHP
<?php
|
|
/**
|
|
* This service file is part of item.
|
|
*
|
|
* @author ctexthuang
|
|
* @contact ctexthuang@qq.com
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Service\Amqp\Coupon;
|
|
|
|
use App\Constants\Common\CouponCode;
|
|
use App\Model\CouponDispenseLog;
|
|
use App\Model\CouponDispenseUser;
|
|
use App\Model\UserCoupon;
|
|
use Exception;
|
|
use Hyperf\Coroutine\Coroutine;
|
|
use Hyperf\DbConnection\Db;
|
|
use Hyperf\Di\Annotation\Inject;
|
|
|
|
class AutoDispenseService
|
|
{
|
|
|
|
const int SINGLE_MAX = 1;
|
|
|
|
/**
|
|
* @var CouponDispenseLog
|
|
*/
|
|
#[Inject]
|
|
protected CouponDispenseLog $couponDispenseLogModel;
|
|
|
|
/**
|
|
* @var CouponDispenseUser
|
|
*/
|
|
#[Inject]
|
|
protected CouponDispenseUser $couponDispenseUserModel;
|
|
|
|
/**
|
|
* @var int
|
|
*/
|
|
public int $couponDispenseId;
|
|
|
|
/**
|
|
* @return void
|
|
* @throws Exception
|
|
*/
|
|
public function handle(): void
|
|
{
|
|
$dispenseInfo = $this->couponDispenseLogModel->getInfoById($this->couponDispenseId);
|
|
|
|
if (empty($dispenseInfo)) throw new Exception('分发记录不存在');
|
|
|
|
$userIds = $this->couponDispenseUserModel->getNoSendUserListByDispenseId($this->couponDispenseId);
|
|
if (empty($userIds)) throw new Exception('该分发已发送完毕');
|
|
|
|
$partArr = array_chunk($userIds, self::SINGLE_MAX);
|
|
|
|
foreach ($partArr as $onePart) {
|
|
$insertData = [];
|
|
foreach ($onePart as $oneUser) {
|
|
//todo 模拟数据
|
|
$oneUserData = [
|
|
'user_id' => $oneUser,
|
|
'coupon_template_id' => $dispenseInfo->coupon_template_id,
|
|
'coupon_name' => $dispenseInfo->coupon_name,
|
|
'coupon_dispense_id' => $dispenseInfo->id,
|
|
'status' => CouponCode::COUPON_STATUS_UNUSED,
|
|
'validity_start_time' => $dispenseInfo->validity_start_time,
|
|
'validity_end_time' => $dispenseInfo->validity_end_time,
|
|
];
|
|
|
|
$copies = array_map(function () use ($oneUserData) {
|
|
return $oneUserData;
|
|
}, array_fill(0, $dispenseInfo->item_count, null));
|
|
|
|
$insertData = array_merge($insertData, $copies);
|
|
}
|
|
|
|
Db::transaction(function () use ($insertData,$dispenseInfo,$onePart) {
|
|
//添加优惠券信息
|
|
if (!(new UserCoupon())->insert($insertData)) throw new Exception('写入数据失败');
|
|
//修改分发用户信息
|
|
if (!(new CouponDispenseUser())->updateReceiveCountByUserIds($onePart,$dispenseInfo->item_count)) throw new Exception('修改分发用户信息失败');
|
|
|
|
//修改分发 log 信息 (修改receive_count = origin_value + count($insertData) ps : 查询还没发的用户 * item_count / total_count = 完成百分比)
|
|
if (!(new CouponDispenseLog())->updateReceiveCountById($dispenseInfo->id,count($insertData))) throw new Exception('修改分发log信息失败');
|
|
});
|
|
|
|
// 休息1秒
|
|
Coroutine::sleep(1);
|
|
}
|
|
}
|
|
} |