Files
hyperf_service/app/Service/Api/User/SiteService.php
2025-02-27 17:34:32 +08:00

119 lines
3.2 KiB
PHP

<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Service\Api\User;
use App\Cache\Redis\Api\SiteCache;
use App\Cache\Redis\Common\ConfigCache;
use App\Constants\Common\SiteCode;
use App\Constants\ConfigCode;
use App\Exception\ErrException;
use App\Model\UserSite;
use App\Service\Api\BaseService;
use Exception;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class SiteService extends BaseService
{
/**
* @var UserSite
*/
#[Inject]
protected UserSite $userSiteModel;
/**
* @var SiteCache
*/
#[Inject]
protected SiteCache $siteCache;
/**
* @var ConfigCache
*/
#[Inject]
protected ConfigCache $configCache;
/**
* @return array
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function handle(): array
{
$siteIds = $this->userSiteModel->where('user_id', $this->userId)->pluck('site_id')->toArray();
$res = [];
foreach ($siteIds as $siteId) {
$res[] = $this->siteCache->getSiteInfo($siteId);
}
return $this->return->success('success', ['list' => $res]);
}
/**
* @return array
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function add(): array
{
$id = (int)$this->request->input('site_id');
if (empty($this->siteCache->getSiteInfo($id))) throw new ErrException('该地点不存在,请联系客服');
$siteIds = $this->userSiteModel->getSiteIdsByUserId($this->userId);
if (in_array($id, $siteIds)) throw new ErrException('已添加该地点');
$poolNumber = $this->configCache->getConfigValue(ConfigCode::NUMBER_OF_USER_ADDRESS_POOLS);
if (count($siteIds) >= $poolNumber) throw new ErrException('已达到地址最大添加数量,请删除后再添加');
$insertModel = new UserSite();
$insertModel->user_id = $this->userId;
$insertModel->site_id = $id;
$insertModel->is_default = SiteCode::USER_NO_DEFAULT;
if ($this->userSiteModel->getUserDefaultIdByUserId($this->userId) == 0) {
$insertModel->is_default = SiteCode::USER_DEFAULT;
}
if (!$insertModel->save()) throw new ErrException('添加失败');
return $this->return->success();
}
/**
* @return array
*/
public function del(): array
{
$id = (int)$this->request->input('site_id');
$info = $this->userSiteModel->getInfoByUserIdAndSiteId($this->userId,$id);
Db::transaction(function () use ($info) {
if ($info->is_default == SiteCode::USER_DEFAULT) {
$updateInfo = $this->userSiteModel->getUserNoDefaultIdByUserId($this->userId);
$updateInfo->is_default = SiteCode::USER_DEFAULT;
if(!$updateInfo->save()) throw new ErrException('删除失败-修改联动数据失败');
}
if (!$info->delete()) throw new ErrException('删除失败');
});
return $this->return->success();
}
}