Files
hyperf_service/app/Service/Api/User/SiteService.php
2025-03-31 14:58:23 +08:00

122 lines
3.4 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)->select(['id','is_default'])->get();
if (empty($siteIds)) $this->return->success('success', ['list' => []]);
$siteIds = $siteIds->toArray();
foreach ($siteIds as &$siteId) {
$siteId = array_merge($siteId,$this->siteCache->getSiteInfo($siteId['id']));
}
return $this->return->success('success', ['list' => $siteIds]);
}
/**
* @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->getConfigValueByKey(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->getInfoByUserIdAndId($this->userId,$id);
Db::transaction(function () use ($info) {
if ($info->is_default == SiteCode::USER_DEFAULT) {
$updateInfo = $this->userSiteModel->getUserNoDefaultIdByUserId($this->userId);
if (!empty($updateInfo)) {
$updateInfo->is_default = SiteCode::USER_DEFAULT;
if(!$updateInfo->save()) throw new ErrException('删除失败-修改联动数据失败');
}
}
if (!$info->delete()) throw new ErrException('删除失败');
});
return $this->return->success();
}
}