|
|
@@ -4,8 +4,10 @@ namespace App\Module\UrsPromotion\Services;
|
|
|
|
|
|
use App\Module\UrsPromotion\Dtos\UrsUserMappingDto;
|
|
|
use App\Module\UrsPromotion\Models\UrsUserMapping;
|
|
|
+use App\Module\User\Services\UserService;
|
|
|
use Illuminate\Support\Facades\DB;
|
|
|
use Illuminate\Support\Facades\Log;
|
|
|
+use Illuminate\Support\Str;
|
|
|
|
|
|
/**
|
|
|
* URS用户映射服务
|
|
|
@@ -14,6 +16,9 @@ use Illuminate\Support\Facades\Log;
|
|
|
*/
|
|
|
class UrsUserMappingService
|
|
|
{
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
/**
|
|
|
* 创建用户映射关系(用户进入农场时调用)
|
|
|
*
|
|
|
@@ -76,14 +81,67 @@ class UrsUserMappingService
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
- * 根据URS用户ID获取农场用户ID
|
|
|
+ * 根据URS用户ID获取农场用户ID,不存在时自动创建新用户并绑定关系
|
|
|
*
|
|
|
* @param int $ursUserId URS用户ID
|
|
|
- * @return int|null 农场用户ID,如果未找到返回null
|
|
|
+ * @return int|null 农场用户ID,创建失败时返回null
|
|
|
*/
|
|
|
public static function getFarmUserId(int $ursUserId): ?int
|
|
|
{
|
|
|
- return UrsUserMapping::getFarmUserIdByUrsUserId($ursUserId);
|
|
|
+ // 首先尝试获取现有映射关系
|
|
|
+ $existingFarmUserId = UrsUserMapping::getFarmUserIdByUrsUserId($ursUserId);
|
|
|
+ if ($existingFarmUserId !== null) {
|
|
|
+ return $existingFarmUserId;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 不存在映射关系,自动创建新用户并建立映射
|
|
|
+ try {
|
|
|
+ DB::beginTransaction();
|
|
|
+
|
|
|
+ // 生成用户名和随机密码
|
|
|
+ $username = 'urs-' . $ursUserId;
|
|
|
+ $password = Str::random(12);
|
|
|
+
|
|
|
+ // 创建新用户
|
|
|
+ $userDto = UserService::create($username, $password);
|
|
|
+ if (is_string($userDto)) {
|
|
|
+ // 创建失败
|
|
|
+ DB::rollBack();
|
|
|
+ Log::error('自动创建URS用户失败', [
|
|
|
+ 'urs_user_id' => $ursUserId,
|
|
|
+ 'username' => $username,
|
|
|
+ 'error' => $userDto
|
|
|
+ ]);
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 创建用户映射关系
|
|
|
+ $mapping = UrsUserMapping::create([
|
|
|
+ 'urs_user_id' => $ursUserId,
|
|
|
+ 'user_id' => $userDto->id,
|
|
|
+ 'mapping_time' => now(),
|
|
|
+ 'status' => UrsUserMapping::STATUS_VALID,
|
|
|
+ ]);
|
|
|
+
|
|
|
+ DB::commit();
|
|
|
+
|
|
|
+ Log::info('自动创建URS用户映射成功', [
|
|
|
+ 'urs_user_id' => $ursUserId,
|
|
|
+ 'farm_user_id' => $userDto->id,
|
|
|
+ 'username' => $username,
|
|
|
+ 'mapping_id' => $mapping->id
|
|
|
+ ]);
|
|
|
+
|
|
|
+ return $userDto->id;
|
|
|
+
|
|
|
+ } catch (\Exception $e) {
|
|
|
+ DB::rollBack();
|
|
|
+ Log::error('自动创建URS用户映射失败', [
|
|
|
+ 'urs_user_id' => $ursUserId,
|
|
|
+ 'error' => $e->getMessage()
|
|
|
+ ]);
|
|
|
+ return null;
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
/**
|