AgentAccount.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\Concerns\OwnedByAgentAccount;
  4. /**
  5. * AI 对话与积分里的「账号」:谁在提问、额度和积分算谁的。由 {@see AgentAccountService::resolve()} 得出。
  6. *
  7. * - 登录用户:type = user,id = 用户 uuid(user_infos.userid);
  8. * - 游客:type = guest,id = 设备匿名 uuid(客户端生成)。
  9. *
  10. * 落库是两列 `account_type` + `account_id`。**两列必须一起用**:设备 id 是客户端自己填的,
  11. * 可以故意填成某个用户的 uid,只按 account_id 查就会把游客认成那个用户。
  12. * 所以按账号查询一律走模型的 `ownedBy()` scope({@see OwnedByAgentAccount}),
  13. * 写入一律用 {@see columns()},不要手写 `where('account_id', …)`。
  14. */
  15. final readonly class AgentAccount
  16. {
  17. public const TYPES = ['user', 'guest'];
  18. /**
  19. * @param 'user'|'guest' $type
  20. */
  21. private function __construct(public string $type, public string $id) {}
  22. public static function user(string $userUid): self
  23. {
  24. return new self('user', $userUid);
  25. }
  26. public static function guest(string $deviceId): self
  27. {
  28. return new self('guest', $deviceId);
  29. }
  30. public function isUser(): bool
  31. {
  32. return $this->type === 'user';
  33. }
  34. /**
  35. * 登录用户的 uuid;游客为 null。
  36. */
  37. public function userUid(): ?string
  38. {
  39. return $this->isUser() ? $this->id : null;
  40. }
  41. /**
  42. * 写库用的两列。
  43. *
  44. * @return array{account_type: string, account_id: string}
  45. */
  46. public function columns(): array
  47. {
  48. return ['account_type' => $this->type, 'account_id' => $this->id];
  49. }
  50. /**
  51. * 同一账号的唯一字符串(advisory lock 之类需要一个键的地方用)。
  52. */
  53. public function key(): string
  54. {
  55. return $this->type.':'.$this->id;
  56. }
  57. }