fix and update

This commit is contained in:
lendry
2026-06-25 16:01:41 +03:00
parent ce58e6f4c1
commit 3880c68d59
40 changed files with 1715 additions and 215 deletions

View File

@@ -3,7 +3,7 @@ import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiTags } from '@nestjs
import { map } from 'rxjs'; import { map } from 'rxjs';
import { CoreGrpcService } from '../core-grpc.service'; import { CoreGrpcService } from '../core-grpc.service';
import { CurrentAdmin } from '../decorators/current-admin.decorator'; import { CurrentAdmin } from '../decorators/current-admin.decorator';
import { ListUsersQueryDto, ResetPasswordDto, SetSuperAdminDto, UpdateUserDto } from '../dto/admin.dto'; import { ListUsersQueryDto, ResetPasswordDto, SetSuperAdminDto, SetUserVerificationDto, UpdateUserDto } from '../dto/admin.dto';
import { AdminGuard, AdminRequestUser, assertAdminPermission, SuperAdminGuard } from '../guards/admin.guard'; import { AdminGuard, AdminRequestUser, assertAdminPermission, SuperAdminGuard } from '../guards/admin.guard';
@ApiTags('Администрирование') @ApiTags('Администрирование')
@@ -32,6 +32,15 @@ export class AdminController {
); );
} }
@Get('verification-icons')
@ApiOperation({ summary: 'Список значков верификации', description: 'Доступные значки для выбора при верификации пользователя.' })
listVerificationIcons(@CurrentAdmin() admin: AdminRequestUser) {
if (!admin.canVerifyUsers) {
throw new ForbiddenException('Недостаточно прав для верификации пользователей');
}
return this.core.admin.ListVerificationIcons({});
}
@Patch(':userId') @Patch(':userId')
@ApiOperation({ summary: 'Обновить профиль пользователя', description: 'Обновляет основные и резервные контакты пользователя.' }) @ApiOperation({ summary: 'Обновить профиль пользователя', description: 'Обновляет основные и резервные контакты пользователя.' })
@ApiParam({ name: 'userId', description: 'ID пользователя' }) @ApiParam({ name: 'userId', description: 'ID пользователя' })
@@ -66,4 +75,20 @@ export class AdminController {
setSuperAdmin(@Param('userId') userId: string, @Body() dto: SetSuperAdminDto, @CurrentAdmin() admin: AdminRequestUser) { setSuperAdmin(@Param('userId') userId: string, @Body() dto: SetSuperAdminDto, @CurrentAdmin() admin: AdminRequestUser) {
return this.core.admin.SetSuperAdmin({ actorUserId: admin.id, userId, isSuperAdmin: dto.isSuperAdmin }); return this.core.admin.SetSuperAdmin({ actorUserId: admin.id, userId, isSuperAdmin: dto.isSuperAdmin });
} }
@Patch(':userId/verification')
@ApiOperation({ summary: 'Верифицировать или снять верификацию', description: 'Требуется право users.verify.' })
@ApiParam({ name: 'userId', description: 'ID пользователя' })
@ApiBody({ type: SetUserVerificationDto })
setUserVerification(@Param('userId') userId: string, @Body() dto: SetUserVerificationDto, @CurrentAdmin() admin: AdminRequestUser) {
if (!admin.canVerifyUsers) {
throw new ForbiddenException('Недостаточно прав для верификации пользователей');
}
return this.core.admin.SetUserVerification({
actorUserId: admin.id,
userId,
isVerified: dto.isVerified,
verificationIcon: dto.verificationIcon
});
}
} }

View File

@@ -58,3 +58,14 @@ export class SetSuperAdminDto {
@IsBoolean({ message: 'isSuperAdmin должно быть boolean' }) @IsBoolean({ message: 'isSuperAdmin должно быть boolean' })
isSuperAdmin!: boolean; isSuperAdmin!: boolean;
} }
export class SetUserVerificationDto {
@ApiProperty({ description: 'Верифицировать или снять верификацию' })
@IsBoolean({ message: 'isVerified должно быть boolean' })
isVerified!: boolean;
@ApiPropertyOptional({ description: 'Slug значка из списка (badge-check, star, moon и т.д.)' })
@IsOptional()
@IsString({ message: 'Значок должен быть строкой' })
verificationIcon?: string;
}

View File

@@ -16,6 +16,7 @@ export interface AdminRequestUser {
canManageAllUsers: boolean; canManageAllUsers: boolean;
canViewUsers: boolean; canViewUsers: boolean;
canManageSettings: boolean; canManageSettings: boolean;
canVerifyUsers: boolean;
roles: string[]; roles: string[];
permissions: string[]; permissions: string[];
} }
@@ -58,6 +59,7 @@ export class AdminGuard implements CanActivate {
canManageAllUsers: Boolean(profile.canManageAllUsers), canManageAllUsers: Boolean(profile.canManageAllUsers),
canManageSettings: Boolean(profile.canManageSettings), canManageSettings: Boolean(profile.canManageSettings),
canViewUsers: Boolean(profile.canViewUsers), canViewUsers: Boolean(profile.canViewUsers),
canVerifyUsers: Boolean(profile.canVerifyUsers),
roles: profile.roles ?? [], roles: profile.roles ?? [],
permissions: profile.permissions ?? [] permissions: profile.permissions ?? []
}; };

View File

@@ -2,7 +2,8 @@
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { Ban, Crown, FileText, KeyRound, Loader2, Search, ShieldPlus, UserCheck, UserCog } from 'lucide-react'; import { Ban, BadgeCheck, Crown, FileText, KeyRound, Loader2, Search, ShieldPlus, UserCheck, UserCog } from 'lucide-react';
import { VerificationBadge } from '@/components/id/verification-badge';
import { UserDocumentsDialog } from '@/components/documents/user-documents-dialog'; import { UserDocumentsDialog } from '@/components/documents/user-documents-dialog';
import { AdminShell } from '@/components/id/admin-shell'; import { AdminShell } from '@/components/id/admin-shell';
import { useAuth } from '@/components/id/auth-provider'; import { useAuth } from '@/components/id/auth-provider';
@@ -13,6 +14,7 @@ import { Input } from '@/components/ui/input';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { AdminPermission, AdminRole, AdminUser, apiFetch } from '@/lib/api'; import { AdminPermission, AdminRole, AdminUser, apiFetch } from '@/lib/api';
import { getAdminLandingPath } from '@/lib/admin-access'; import { getAdminLandingPath } from '@/lib/admin-access';
import { DEFAULT_VERIFICATION_ICON, VERIFICATION_ICON_OPTIONS } from '@/lib/verification-icons';
const statusLabels: Record<string, string> = { const statusLabels: Record<string, string> = {
ACTIVE: 'Активен', ACTIVE: 'Активен',
@@ -42,8 +44,9 @@ export default function AdminUsersPage() {
const [selectedUser, setSelectedUser] = useState<AdminUser | null>(null); const [selectedUser, setSelectedUser] = useState<AdminUser | null>(null);
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const [actionLoading, setActionLoading] = useState(false); const [actionLoading, setActionLoading] = useState(false);
const [dialog, setDialog] = useState<'password' | 'roles' | null>(null); const [dialog, setDialog] = useState<'password' | 'roles' | 'verification' | null>(null);
const [documentsUser, setDocumentsUser] = useState<AdminUser | null>(null); const [documentsUser, setDocumentsUser] = useState<AdminUser | null>(null);
const [verificationIcon, setVerificationIcon] = useState(DEFAULT_VERIFICATION_ICON);
const loadUsers = useCallback(async () => { const loadUsers = useCallback(async () => {
if (!token) return; if (!token) return;
@@ -224,6 +227,53 @@ export default function AdminUsersPage() {
} }
} }
async function handleSaveVerification() {
if (!token || !selectedUser) return;
setActionLoading(true);
try {
const updated = await apiFetch<AdminUser>(`/admin/users/${selectedUser.id}/verification`, {
method: 'PATCH',
body: JSON.stringify({
isVerified: true,
verificationIcon
})
}, token);
showToast('Пользователь верифицирован');
setSelectedUser(updated);
setDialog(null);
await loadUsers();
} catch (error) {
showToast(error instanceof Error ? error.message : 'Не удалось верифицировать пользователя');
} finally {
setActionLoading(false);
}
}
async function handleRemoveVerification() {
if (!token || !selectedUser) return;
setActionLoading(true);
try {
await apiFetch<AdminUser>(`/admin/users/${selectedUser.id}/verification`, {
method: 'PATCH',
body: JSON.stringify({ isVerified: false })
}, token);
showToast('Верификация снята');
setSelectedUser({ ...selectedUser, isVerified: false, verificationIcon: undefined });
setDialog(null);
await loadUsers();
} catch (error) {
showToast(error instanceof Error ? error.message : 'Не удалось снять верификацию');
} finally {
setActionLoading(false);
}
}
function openVerificationDialog(user: AdminUser) {
setSelectedUser(user);
setVerificationIcon(user.verificationIcon ?? DEFAULT_VERIFICATION_ICON);
setDialog('verification');
}
function renderRoles(user: AdminUser) { function renderRoles(user: AdminUser) {
const userRoles = user.roles ?? []; const userRoles = user.roles ?? [];
const extraRoles = userRoles.filter((role) => role !== DEFAULT_USER_ROLE); const extraRoles = userRoles.filter((role) => role !== DEFAULT_USER_ROLE);
@@ -271,7 +321,10 @@ export default function AdminUsersPage() {
{users.map((user) => ( {users.map((user) => (
<TableRow key={user.id}> <TableRow key={user.id}>
<TableCell> <TableCell>
<div className="font-medium">{user.displayName}</div> <div className="flex items-center gap-2">
<span className="font-medium">{user.displayName}</span>
{user.isVerified ? <VerificationBadge verificationIcon={user.verificationIcon} size="xs" /> : null}
</div>
<div className="text-sm text-[#667085]">{user.email ?? user.username ?? '—'}</div> <div className="text-sm text-[#667085]">{user.email ?? user.username ?? '—'}</div>
</TableCell> </TableCell>
<TableCell>{user.phone ?? '—'}</TableCell> <TableCell>{user.phone ?? '—'}</TableCell>
@@ -315,6 +368,17 @@ export default function AdminUsersPage() {
<FileText className="h-4 w-4" /> <FileText className="h-4 w-4" />
</Button> </Button>
) : null} ) : null}
{currentUser?.canVerifyUsers ? (
<Button
variant={user.isVerified ? 'default' : 'secondary'}
size="icon"
aria-label="Верификация"
disabled={actionLoading}
onClick={() => openVerificationDialog(user)}
>
<BadgeCheck className="h-4 w-4" />
</Button>
) : null}
{currentUser?.canManageRoles ? ( {currentUser?.canManageRoles ? (
<> <>
<Button <Button
@@ -432,6 +496,49 @@ export default function AdminUsersPage() {
</DialogContent> </DialogContent>
</Dialog> </Dialog>
<Dialog open={dialog === 'verification'} onOpenChange={(open) => !open && setDialog(null)}>
<DialogContent className="max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Верификация пользователя</DialogTitle>
</DialogHeader>
<p className="mb-4 text-sm text-[#667085]">{selectedUser?.displayName}</p>
{selectedUser?.isVerified ? (
<div className="mb-4 flex items-center gap-2 rounded-xl bg-[#eef4ff] px-3 py-2 text-sm">
<VerificationBadge verificationIcon={selectedUser.verificationIcon} size="sm" />
<span>Пользователь уже верифицирован</span>
</div>
) : null}
<div className="space-y-3">
<p className="text-sm font-medium">Выберите значок</p>
<div className="grid grid-cols-5 gap-2">
{VERIFICATION_ICON_OPTIONS.map((option) => (
<button
key={option.slug}
type="button"
className={`flex flex-col items-center gap-1 rounded-xl border px-2 py-3 text-xs transition ${
verificationIcon === option.slug ? 'border-[#3390ec] bg-[#eef4ff]' : 'border-[#eceef4] bg-[#fafbfd] hover:bg-[#f4f5f8]'
}`}
onClick={() => setVerificationIcon(option.slug)}
>
<option.Icon className="h-5 w-5 text-[#3390ec]" />
<span className="text-center leading-tight">{option.name}</span>
</button>
))}
</div>
</div>
<div className="mt-4 flex flex-col gap-2">
<Button className="w-full" disabled={actionLoading} onClick={() => void handleSaveVerification()}>
{actionLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : selectedUser?.isVerified ? 'Обновить значок' : 'Верифицировать'}
</Button>
{selectedUser?.isVerified ? (
<Button variant="secondary" className="w-full text-red-600" disabled={actionLoading} onClick={() => void handleRemoveVerification()}>
Снять верификацию
</Button>
) : null}
</div>
</DialogContent>
</Dialog>
{documentsUser ? ( {documentsUser ? (
<UserDocumentsDialog <UserDocumentsDialog
open={Boolean(documentsUser)} open={Boolean(documentsUser)}

View File

@@ -235,7 +235,17 @@ export default function DataPage() {
<IdShell active="/data"> <IdShell active="/data">
<div className="mb-8 flex items-center gap-4 rounded-[24px] border border-[#20212b] p-4"> <div className="mb-8 flex items-center gap-4 rounded-[24px] border border-[#20212b] p-4">
{user ? ( {user ? (
<AvatarUpload userId={user.id} displayName={user.displayName} hasAvatar={user.hasAvatar} token={token} onUpdated={refreshProfile} /> <AvatarUpload
userId={user.id}
displayName={user.displayName}
hasAvatar={user.hasAvatar}
token={token}
isVerified={user.isVerified}
verificationIcon={user.verificationIcon}
className="h-14 w-14"
badgeSize="sm"
onUpdated={refreshProfile}
/>
) : ( ) : (
<AvatarDisplay userId="" displayName="" hasAvatar={false} token={null} className="h-14 w-14" /> <AvatarDisplay userId="" displayName="" hasAvatar={false} token={null} className="h-14 w-14" />
)} )}

View File

@@ -1,11 +1,18 @@
'use client'; 'use client';
import { use } from 'react'; import { use, useEffect } from 'react';
import { IdShell } from '@/components/id/shell';
import { FamilyGroupView } from '@/components/family/family-group-view'; import { FamilyGroupView } from '@/components/family/family-group-view';
import { useFamilyOverlay } from '@/components/family/family-overlay-provider';
import { IdShell } from '@/components/id/shell';
export default function FamilyGroupPage({ params }: { params: Promise<{ groupId: string }> }) { export default function FamilyGroupPage({ params }: { params: Promise<{ groupId: string }> }) {
const { groupId } = use(params); const { groupId } = use(params);
const { setSelectedGroupId } = useFamilyOverlay();
useEffect(() => {
setSelectedGroupId(groupId);
}, [groupId, setSelectedGroupId]);
return ( return (
<IdShell active="/family" wide> <IdShell active="/family" wide>
<FamilyGroupView groupId={groupId} /> <FamilyGroupView groupId={groupId} />

View File

@@ -10,6 +10,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { useRequireAuth } from '@/hooks/use-require-auth'; import { useRequireAuth } from '@/hooks/use-require-auth';
import { apiFetch, FamilyGroup, fetchFamilyGroups, getApiErrorMessage } from '@/lib/api'; import { apiFetch, FamilyGroup, fetchFamilyGroups, getApiErrorMessage } from '@/lib/api';
import { defaultFamilyGroupName } from '@/lib/family-defaults';
export default function FamilyPage() { export default function FamilyPage() {
const router = useRouter(); const router = useRouter();
@@ -17,9 +18,15 @@ export default function FamilyPage() {
const { isReady, isPinLocked } = useRequireAuth(); const { isReady, isPinLocked } = useRequireAuth();
const { showToast } = useToast(); const { showToast } = useToast();
const [groups, setGroups] = useState<FamilyGroup[]>([]); const [groups, setGroups] = useState<FamilyGroup[]>([]);
const [name, setName] = useState('Моя семья'); const [name, setName] = useState('');
const [creating, setCreating] = useState(false); const [creating, setCreating] = useState(false);
useEffect(() => {
if (user?.displayName) {
setName(defaultFamilyGroupName(user.displayName));
}
}, [user?.displayName]);
useEffect(() => { useEffect(() => {
if (!user || !token || isPinLocked) return; if (!user || !token || isPinLocked) return;
fetchFamilyGroups(user.id, token) fetchFamilyGroups(user.id, token)
@@ -63,7 +70,7 @@ export default function FamilyPage() {
<div className="mt-8 flex gap-3"> <div className="mt-8 flex gap-3">
<Input value={name} onChange={(event) => setName(event.target.value)} placeholder="Название семьи" /> <Input value={name} onChange={(event) => setName(event.target.value)} placeholder="Название семьи" />
<Button onClick={() => void createGroup()} disabled={creating}> <Button onClick={() => void createGroup()} disabled={creating || !name.trim()}>
{creating ? 'Создаём...' : (<><Plus className="h-4 w-4" />Создать</>)} {creating ? 'Создаём...' : (<><Plus className="h-4 w-4" />Создать</>)}
</Button> </Button>
</div> </div>

View File

@@ -7,7 +7,7 @@ import { AddressQuickSection } from '@/components/addresses/address-quick-sectio
import { DocumentFormDialog } from '@/components/documents/document-form-dialog'; import { DocumentFormDialog } from '@/components/documents/document-form-dialog';
import { ActionTile, SectionTitle } from '@/components/id/action-tile'; import { ActionTile, SectionTitle } from '@/components/id/action-tile';
import { AdminBadge } from '@/components/id/admin-badge'; import { AdminBadge } from '@/components/id/admin-badge';
import { AvatarUpload } from '@/components/id/avatar-upload'; import { AvatarDisplay } from '@/components/id/avatar-upload';
import { useAuth } from '@/components/id/auth-provider'; import { useAuth } from '@/components/id/auth-provider';
import { IdShell } from '@/components/id/shell'; import { IdShell } from '@/components/id/shell';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -17,7 +17,7 @@ import { apiFetch, UserDocument } from '@/lib/api';
export default function HomePage() { export default function HomePage() {
const router = useRouter(); const router = useRouter();
const { user, token, refreshProfile, isPinLocked } = useAuth(); const { user, token, isPinLocked } = useAuth();
const { isReady } = useRequireAuth(); const { isReady } = useRequireAuth();
const contactLine = [user?.phone, user?.username ?? user?.email].filter(Boolean).join(' · '); const contactLine = [user?.phone, user?.username ?? user?.email].filter(Boolean).join(' · ');
const [documents, setDocuments] = useState<UserDocument[]>([]); const [documents, setDocuments] = useState<UserDocument[]>([]);
@@ -55,12 +55,15 @@ export default function HomePage() {
<IdShell active="/" wide> <IdShell active="/" wide>
<div className="flex flex-col items-center"> <div className="flex flex-col items-center">
{user ? ( {user ? (
<AvatarUpload <AvatarDisplay
userId={user.id} userId={user.id}
displayName={user.displayName} displayName={user.displayName}
hasAvatar={user.hasAvatar} hasAvatar={user.hasAvatar}
token={token} token={token}
onUpdated={refreshProfile} isVerified={user.isVerified}
verificationIcon={user.verificationIcon}
className="h-24 w-24 border-4 border-white shadow-xl"
badgeSize="md"
/> />
) : ( ) : (
<div className="h-24 w-24 rounded-full bg-[#f4f5f8]" /> <div className="h-24 w-24 rounded-full bg-[#f4f5f8]" />

View File

@@ -0,0 +1,55 @@
'use client';
import { UserAvatar } from '@/components/id/user-avatar';
import { cn } from '@/lib/utils';
export function OnlineDot({ online, className }: { online?: boolean; className?: string }) {
if (!online) return null;
return (
<span
className={cn(
'absolute bottom-0 right-0 z-10 h-3 w-3 rounded-full border-2 border-white bg-emerald-500 shadow-sm',
className
)}
aria-hidden
/>
);
}
export function AvatarWithPresence({
userId,
displayName,
hasAvatar,
token,
isVerified,
verificationIcon,
online,
className = 'h-9 w-9',
badgeSize = 'xs'
}: {
userId: string;
displayName?: string;
hasAvatar?: boolean;
token: string | null;
isVerified?: boolean;
verificationIcon?: string | null;
online?: boolean;
className?: string;
badgeSize?: 'xs' | 'sm' | 'md' | 'lg';
}) {
return (
<div className="relative inline-flex shrink-0">
<UserAvatar
userId={userId}
displayName={displayName}
hasAvatar={hasAvatar}
token={token}
isVerified={isVerified}
verificationIcon={verificationIcon}
className={className}
badgeSize={badgeSize}
/>
<OnlineDot online={online} />
</div>
);
}

View File

@@ -0,0 +1,76 @@
'use client';
import Link from 'next/link';
import { ChevronDown } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';
import { cn } from '@/lib/utils';
type FamilyGroupOption = {
id: string;
name: string;
};
export function FamilyGroupSelector({
groups,
selectedGroupId,
onSelect,
href,
className,
nameClassName
}: {
groups: FamilyGroupOption[];
selectedGroupId: string | null;
onSelect: (groupId: string) => void;
href?: string;
className?: string;
nameClassName?: string;
}) {
const selected = groups.find((group) => group.id === selectedGroupId) ?? groups[0];
if (!selected) return null;
const nameElement = href ? (
<Link href={href} className={cn('truncate hover:underline', nameClassName)} onClick={(event) => event.stopPropagation()}>
{selected.name}
</Link>
) : (
<span className={cn('truncate', nameClassName)}>{selected.name}</span>
);
if (groups.length <= 1) {
return <div className={cn('min-w-0', className)}>{nameElement}</div>;
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className={cn(
'flex min-w-0 max-w-full items-center gap-0.5 rounded-lg text-left transition hover:bg-[#f4f5f8]',
className
)}
>
{nameElement}
<ChevronDown className="h-3 w-3 shrink-0 text-[#667085]" aria-hidden />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="max-w-[220px] rounded-xl">
{groups.map((group) => (
<DropdownMenuItem
key={group.id}
className={cn('truncate rounded-lg', group.id === selected.id && 'font-medium text-[#3390ec]')}
onClick={() => onSelect(group.id)}
>
{group.name}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -23,7 +23,10 @@ import {
Volume2, Volume2,
VolumeX VolumeX
} from 'lucide-react'; } from 'lucide-react';
import { AvatarWithPresence } from '@/components/family/avatar-with-presence';
import { FamilyInviteDialog } from '@/components/family/family-invite-dialog';
import { VoiceMessagePlayer } from '@/components/chat/voice-message-player'; import { VoiceMessagePlayer } from '@/components/chat/voice-message-player';
import { UserAvatar } from '@/components/id/user-avatar';
import { useAuth } from '@/components/id/auth-provider'; import { useAuth } from '@/components/id/auth-provider';
import { useToast } from '@/components/id/toast-provider'; import { useToast } from '@/components/id/toast-provider';
import { useRealtime } from '@/components/notifications/realtime-provider'; import { useRealtime } from '@/components/notifications/realtime-provider';
@@ -48,7 +51,6 @@ import {
deleteFamilyGroup, deleteFamilyGroup,
editChatMessage, editChatMessage,
FamilyGroup, FamilyGroup,
FamilyInviteCandidate,
FamilyPresenceMember, FamilyPresenceMember,
fetchChatMessages, fetchChatMessages,
fetchChatRooms, fetchChatRooms,
@@ -58,9 +60,7 @@ import {
markChatRoomRead, markChatRoomRead,
removeChatRoomMember, removeChatRoomMember,
removeFamilyMember, removeFamilyMember,
searchFamilyInviteUsers,
sendChatMessage, sendChatMessage,
sendFamilyInvite,
setChatRoomMuted, setChatRoomMuted,
updateFamilyGroup, updateFamilyGroup,
uploadMediaObject, uploadMediaObject,
@@ -132,18 +132,6 @@ function messagePreview(message?: ChatMessage) {
return message.content ?? ''; return message.content ?? '';
} }
function OnlineDot({ online, className }: { online?: boolean; className?: string }) {
if (!online) return null;
return (
<span
className={cn(
'absolute bottom-0 right-0 h-3 w-3 rounded-full border-2 border-white bg-emerald-500 shadow-sm',
className
)}
/>
);
}
function FamilyAvatar({ groupId, name, hasAvatar, token }: { groupId: string; name: string; hasAvatar?: boolean; token: string | null }) { function FamilyAvatar({ groupId, name, hasAvatar, token }: { groupId: string; name: string; hasAvatar?: boolean; token: string | null }) {
const [url, setUrl] = useState<string | null>(null); const [url, setUrl] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
@@ -206,10 +194,6 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
const [membersOpen, setMembersOpen] = useState(false); const [membersOpen, setMembersOpen] = useState(false);
const [familyMembersOpen, setFamilyMembersOpen] = useState(false); const [familyMembersOpen, setFamilyMembersOpen] = useState(false);
const [addMembersOpen, setAddMembersOpen] = useState(false); const [addMembersOpen, setAddMembersOpen] = useState(false);
const [inviteQuery, setInviteQuery] = useState('');
const [inviteResults, setInviteResults] = useState<FamilyInviteCandidate[]>([]);
const [selectedInviteUser, setSelectedInviteUser] = useState<FamilyInviteCandidate | null>(null);
const [inviteSearching, setInviteSearching] = useState(false);
const [renameValue, setRenameValue] = useState(''); const [renameValue, setRenameValue] = useState('');
const [newRoomName, setNewRoomName] = useState(''); const [newRoomName, setNewRoomName] = useState('');
const [selectedMembers, setSelectedMembers] = useState<string[]>([]); const [selectedMembers, setSelectedMembers] = useState<string[]>([]);
@@ -579,39 +563,6 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
} }
} }
async function submitInvite() {
if (!token || !selectedInviteUser) return;
try {
await sendFamilyInvite(groupId, { inviteeUserId: selectedInviteUser.id }, token);
setInviteOpen(false);
setInviteQuery('');
setInviteResults([]);
setSelectedInviteUser(null);
showToast('Приглашение отправлено');
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось отправить приглашение') ?? 'Ошибка');
}
}
useEffect(() => {
if (!inviteOpen || !token || selectedInviteUser) {
return;
}
const query = inviteQuery.trim();
if (query.length < 2) {
setInviteResults([]);
return;
}
const timer = window.setTimeout(() => {
setInviteSearching(true);
void searchFamilyInviteUsers(groupId, query, token)
.then((response) => setInviteResults(response.users ?? []))
.catch(() => setInviteResults([]))
.finally(() => setInviteSearching(false));
}, 300);
return () => window.clearTimeout(timer);
}, [groupId, inviteOpen, inviteQuery, selectedInviteUser, token]);
async function submitCreateRoom() { async function submitCreateRoom() {
if (!token || !newRoomName.trim()) return; if (!token || !newRoomName.trim()) return;
try { try {
@@ -941,7 +892,19 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
const isEditing = editingMessageId === message.id; const isEditing = editingMessageId === message.id;
const canEdit = mine && !message.isDeleted && (message.type === 'TEXT' || message.type === 'EMOJI'); const canEdit = mine && !message.isDeleted && (message.type === 'TEXT' || message.type === 'EMOJI');
return ( return (
<div key={message.id} className={cn('group flex', mine ? 'justify-end' : 'justify-start')}> <div key={message.id} className={cn('group flex gap-2', mine ? 'justify-end' : 'justify-start')}>
{!mine ? (
<UserAvatar
userId={message.senderId}
displayName={message.senderName}
hasAvatar={message.senderHasAvatar}
token={token}
isVerified={message.senderIsVerified}
verificationIcon={message.senderVerificationIcon}
className="h-8 w-8 self-end"
badgeSize="xs"
/>
) : null}
<div <div
className={cn( className={cn(
'relative max-w-[78%] rounded-[18px] px-3 py-2 shadow-sm', 'relative max-w-[78%] rounded-[18px] px-3 py-2 shadow-sm',
@@ -1176,74 +1139,12 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
event.target.value = ''; event.target.value = '';
}} /> }} />
<Dialog open={inviteOpen} onOpenChange={(open) => { <FamilyInviteDialog
setInviteOpen(open); groupId={groupId}
if (!open) { open={inviteOpen}
setInviteQuery(''); onOpenChange={setInviteOpen}
setInviteResults([]); onInvited={() => void loadGroup()}
setSelectedInviteUser(null);
}
}}>
<DialogContent className="rounded-[28px] sm:max-w-[420px]">
<DialogHeader><DialogTitle>Пригласить в семью</DialogTitle></DialogHeader>
{selectedInviteUser ? (
<div className="rounded-2xl bg-[#f4f5f8] px-4 py-3">
<p className="font-medium">{selectedInviteUser.displayName}</p>
<p className="text-sm text-[#667085]">
{selectedInviteUser.email ?? selectedInviteUser.phone ?? selectedInviteUser.username ?? 'Контакт не указан'}
</p>
<button type="button" className="mt-2 text-sm text-[#667085] underline" onClick={() => setSelectedInviteUser(null)}>
Выбрать другого пользователя
</button>
</div>
) : (
<>
<Input
placeholder="ФИО, почта, телефон или логин"
value={inviteQuery}
onChange={(event) => setInviteQuery(event.target.value)}
/> />
<div className="mt-2 max-h-56 overflow-y-auto rounded-2xl border border-[#eceef4]">
{inviteSearching ? (
<div className="flex items-center gap-2 px-4 py-3 text-sm text-[#667085]">
<Loader2 className="h-4 w-4 animate-spin" />
Ищем пользователей...
</div>
) : inviteQuery.trim().length < 2 ? (
<p className="px-4 py-3 text-sm text-[#667085]">Введите минимум 2 символа для поиска</p>
) : inviteResults.length ? (
inviteResults.map((candidate) => (
<button
key={candidate.id}
type="button"
className="flex w-full items-center gap-3 border-b border-[#eceef4] px-4 py-3 text-left last:border-b-0 hover:bg-[#fafbfd]"
onClick={() => {
setSelectedInviteUser(candidate);
setInviteResults([]);
}}
>
<Avatar className="h-9 w-9">
<AvatarFallback>{candidate.displayName.slice(0, 1)}</AvatarFallback>
</Avatar>
<div className="min-w-0">
<p className="truncate font-medium">{candidate.displayName}</p>
<p className="truncate text-sm text-[#667085]">
{candidate.email ?? candidate.phone ?? candidate.username ?? 'Без контактов'}
</p>
</div>
</button>
))
) : (
<p className="px-4 py-3 text-sm text-[#667085]">Пользователи не найдены</p>
)}
</div>
</>
)}
<Button className="mt-4 w-full rounded-xl" disabled={!selectedInviteUser} onClick={() => void submitInvite()}>
Отправить приглашение
</Button>
</DialogContent>
</Dialog>
<Dialog open={familyMembersOpen} onOpenChange={setFamilyMembersOpen}> <Dialog open={familyMembersOpen} onOpenChange={setFamilyMembersOpen}>
<DialogContent className="rounded-[28px] sm:max-w-[480px]"> <DialogContent className="rounded-[28px] sm:max-w-[480px]">
@@ -1262,21 +1163,27 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
return ( return (
<div key={member.id} className="flex items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3"> <div key={member.id} className="flex items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3">
<div className="relative shrink-0"> <AvatarWithPresence
<Avatar className="h-10 w-10"> userId={member.userId}
<AvatarFallback>{member.displayName.slice(0, 1)}</AvatarFallback> displayName={member.displayName}
</Avatar> hasAvatar={member.hasAvatar}
<OnlineDot online={presence?.online} /> token={token}
</div> isVerified={member.isVerified}
verificationIcon={member.verificationIcon}
online={isSelf ? undefined : presence?.online}
className="h-10 w-10"
/>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="truncate font-medium"> <p className="truncate font-medium">
{member.displayName} {member.displayName}
{isSelf ? <span className="ml-1 text-xs font-normal text-[#667085]">(Вы)</span> : null} {isSelf ? <span className="ml-1 text-xs font-normal text-[#667085]">(Вы)</span> : null}
</p> </p>
<p className="text-xs text-[#667085]">{familyMemberRoleLabel(member.role)}</p> <p className="text-xs text-[#667085]">{familyMemberRoleLabel(member.role)}</p>
{!isSelf ? (
<p className={cn('text-xs', presence?.online ? 'font-medium text-emerald-600' : 'text-[#a8adbc]')}> <p className={cn('text-xs', presence?.online ? 'font-medium text-emerald-600' : 'text-[#a8adbc]')}>
{presence ? formatPresenceStatus(presence) : 'Статус неизвестен'} {presence ? formatPresenceStatus(presence) : 'Статус неизвестен'}
</p> </p>
) : null}
</div> </div>
{canRemove ? ( {canRemove ? (
<Button <Button
@@ -1357,12 +1264,16 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
return ( return (
<div key={member.id} className="flex items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3"> <div key={member.id} className="flex items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3">
<div className="relative shrink-0"> <AvatarWithPresence
<Avatar className="h-10 w-10"> userId={member.userId}
<AvatarFallback>{member.displayName.slice(0, 1)}</AvatarFallback> displayName={member.displayName}
</Avatar> hasAvatar={member.hasAvatar}
<OnlineDot online={presence?.online} /> token={token}
</div> isVerified={member.isVerified}
verificationIcon={member.verificationIcon}
online={presence?.online}
className="h-10 w-10"
/>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="truncate font-medium">{member.displayName}</p> <p className="truncate font-medium">{member.displayName}</p>
<p className="text-xs text-[#667085]">{memberRoleLabel(member)}</p> <p className="text-xs text-[#667085]">{memberRoleLabel(member)}</p>
@@ -1404,22 +1315,32 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
<DialogHeader><DialogTitle>Добавить в чат</DialogTitle></DialogHeader> <DialogHeader><DialogTitle>Добавить в чат</DialogTitle></DialogHeader>
<div className="space-y-2"> <div className="space-y-2">
{familyMembersNotInRoom.length ? ( {familyMembersNotInRoom.length ? (
familyMembersNotInRoom.map((member) => ( familyMembersNotInRoom.map((member) => {
const presence = presenceByUserId.get(member.userId);
return (
<button <button
key={member.id} key={member.id}
type="button" type="button"
className="flex w-full items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3 text-left transition hover:bg-[#eceef4]" className="flex w-full items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3 text-left transition hover:bg-[#eceef4]"
onClick={() => void handleAddRoomMember(member.userId)} onClick={() => void handleAddRoomMember(member.userId)}
> >
<Avatar className="h-9 w-9"> <AvatarWithPresence
<AvatarFallback>{member.displayName.slice(0, 1)}</AvatarFallback> userId={member.userId}
</Avatar> displayName={member.displayName}
hasAvatar={member.hasAvatar}
token={token}
isVerified={member.isVerified}
verificationIcon={member.verificationIcon}
online={presence?.online}
className="h-9 w-9"
/>
<div> <div>
<p className="font-medium">{member.displayName}</p> <p className="font-medium">{member.displayName}</p>
<p className="text-xs text-[#667085]">{member.role === 'owner' ? 'Создатель семьи' : 'Участник семьи'}</p> <p className="text-xs text-[#667085]">{member.role === 'owner' ? 'Создатель семьи' : 'Участник семьи'}</p>
</div> </div>
</button> </button>
)) );
})
) : ( ) : (
<p className="py-6 text-center text-sm text-[#667085]">Все участники семьи уже в этом чате</p> <p className="py-6 text-center text-sm text-[#667085]">Все участники семьи уже в этом чате</p>
)} )}

View File

@@ -0,0 +1,141 @@
'use client';
import { useEffect, useState } from 'react';
import { Loader2 } from 'lucide-react';
import { AvatarWithPresence } from '@/components/family/avatar-with-presence';
import { useAuth } from '@/components/id/auth-provider';
import { useToast } from '@/components/id/toast-provider';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { FamilyInviteCandidate, getApiErrorMessage, searchFamilyInviteUsers, sendFamilyInvite } from '@/lib/api';
export function FamilyInviteDialog({
groupId,
open,
onOpenChange,
onInvited
}: {
groupId: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onInvited?: () => void;
}) {
const { token } = useAuth();
const { showToast } = useToast();
const [inviteQuery, setInviteQuery] = useState('');
const [inviteResults, setInviteResults] = useState<FamilyInviteCandidate[]>([]);
const [inviteSearching, setInviteSearching] = useState(false);
const [selectedInviteUser, setSelectedInviteUser] = useState<FamilyInviteCandidate | null>(null);
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (!open) {
setInviteQuery('');
setInviteResults([]);
setSelectedInviteUser(null);
return;
}
if (!token || inviteQuery.trim().length < 2) {
setInviteResults([]);
return;
}
const timer = window.setTimeout(() => {
setInviteSearching(true);
searchFamilyInviteUsers(groupId, inviteQuery.trim(), token)
.then((response) => setInviteResults(response.users ?? []))
.catch(() => setInviteResults([]))
.finally(() => setInviteSearching(false));
}, 300);
return () => window.clearTimeout(timer);
}, [groupId, inviteQuery, open, token]);
async function submitInvite() {
if (!token || !selectedInviteUser) return;
setSubmitting(true);
try {
await sendFamilyInvite(groupId, { inviteeUserId: selectedInviteUser.id }, token);
showToast('Приглашение отправлено');
onOpenChange(false);
onInvited?.();
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось отправить приглашение') ?? 'Ошибка');
} finally {
setSubmitting(false);
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="rounded-[28px] sm:max-w-[420px]">
<DialogHeader>
<DialogTitle>Пригласить в семью</DialogTitle>
</DialogHeader>
{selectedInviteUser ? (
<div className="rounded-2xl bg-[#f4f5f8] px-4 py-3">
<p className="font-medium">{selectedInviteUser.displayName}</p>
<p className="text-sm text-[#667085]">
{selectedInviteUser.email ?? selectedInviteUser.phone ?? selectedInviteUser.username ?? 'Контакт не указан'}
</p>
<button type="button" className="mt-2 text-sm text-[#667085] underline" onClick={() => setSelectedInviteUser(null)}>
Выбрать другого пользователя
</button>
</div>
) : (
<>
<Input
placeholder="ФИО, почта, телефон или логин"
value={inviteQuery}
onChange={(event) => setInviteQuery(event.target.value)}
/>
<div className="mt-2 max-h-56 overflow-y-auto rounded-2xl border border-[#eceef4]">
{inviteSearching ? (
<div className="flex items-center gap-2 px-4 py-3 text-sm text-[#667085]">
<Loader2 className="h-4 w-4 animate-spin" />
Ищем пользователей...
</div>
) : inviteQuery.trim().length < 2 ? (
<p className="px-4 py-3 text-sm text-[#667085]">Введите минимум 2 символа для поиска</p>
) : inviteResults.length ? (
inviteResults.map((candidate) => (
<button
key={candidate.id}
type="button"
className="flex w-full items-center gap-3 border-b border-[#eceef4] px-4 py-3 text-left last:border-b-0 hover:bg-[#fafbfd]"
onClick={() => {
setSelectedInviteUser(candidate);
setInviteResults([]);
}}
>
<AvatarWithPresence
userId={candidate.id}
displayName={candidate.displayName}
hasAvatar={candidate.hasAvatar}
token={token}
isVerified={candidate.isVerified}
verificationIcon={candidate.verificationIcon}
className="h-9 w-9"
/>
<div className="min-w-0">
<p className="truncate font-medium">{candidate.displayName}</p>
<p className="truncate text-sm text-[#667085]">
{candidate.email ?? candidate.phone ?? candidate.username ?? 'Без контактов'}
</p>
</div>
</button>
))
) : (
<p className="px-4 py-3 text-sm text-[#667085]">Пользователи не найдены</p>
)}
</div>
</>
)}
<Button className="mt-4 w-full rounded-xl" disabled={!selectedInviteUser || submitting} onClick={() => void submitInvite()}>
{submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Отправить приглашение'}
</Button>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,111 @@
'use client';
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
const SELECTED_FAMILY_STORAGE_KEY = 'id-selected-family-group-id';
type FamilyOverlayContextValue = {
openMiniChat: () => void;
openChatRoom: (roomId: string) => void;
openChatWithMember: (memberUserId: string, memberName: string) => void;
closeMiniChat: () => void;
miniChatOpen: boolean;
pendingRoomId: string | null;
pendingMember: { userId: string; name: string } | null;
clearPending: () => void;
selectedGroupId: string | null;
setSelectedGroupId: (groupId: string | null) => void;
};
const FamilyOverlayContext = createContext<FamilyOverlayContextValue | null>(null);
export function FamilyOverlayProvider({ children }: { children: React.ReactNode }) {
const [miniChatOpen, setMiniChatOpen] = useState(false);
const [pendingRoomId, setPendingRoomId] = useState<string | null>(null);
const [pendingMember, setPendingMember] = useState<{ userId: string; name: string } | null>(null);
const [selectedGroupId, setSelectedGroupIdState] = useState<string | null>(null);
const pendingMemberRef = useRef<{ userId: string; name: string } | null>(null);
const selectionHydratedRef = useRef(false);
useEffect(() => {
if (selectionHydratedRef.current) return;
selectionHydratedRef.current = true;
const stored = window.localStorage.getItem(SELECTED_FAMILY_STORAGE_KEY);
if (stored) setSelectedGroupIdState(stored);
}, []);
const setSelectedGroupId = useCallback((groupId: string | null) => {
setSelectedGroupIdState(groupId);
if (groupId) {
window.localStorage.setItem(SELECTED_FAMILY_STORAGE_KEY, groupId);
} else {
window.localStorage.removeItem(SELECTED_FAMILY_STORAGE_KEY);
}
}, []);
const openMiniChat = useCallback(() => {
setMiniChatOpen(true);
}, []);
const closeMiniChat = useCallback(() => {
setMiniChatOpen(false);
}, []);
const openChatRoom = useCallback((roomId: string) => {
setPendingRoomId(roomId);
setPendingMember(null);
pendingMemberRef.current = null;
setMiniChatOpen(true);
}, []);
const openChatWithMember = useCallback((memberUserId: string, memberName: string) => {
const payload = { userId: memberUserId, name: memberName };
setPendingMember(payload);
pendingMemberRef.current = payload;
setPendingRoomId(null);
setMiniChatOpen(true);
}, []);
const clearPending = useCallback(() => {
setPendingRoomId(null);
setPendingMember(null);
pendingMemberRef.current = null;
}, []);
const value = useMemo(
() => ({
openMiniChat,
openChatRoom,
openChatWithMember,
closeMiniChat,
miniChatOpen,
pendingRoomId,
pendingMember,
clearPending,
selectedGroupId,
setSelectedGroupId
}),
[
clearPending,
closeMiniChat,
miniChatOpen,
openChatRoom,
openChatWithMember,
openMiniChat,
pendingMember,
pendingRoomId,
selectedGroupId,
setSelectedGroupId
]
);
return <FamilyOverlayContext.Provider value={value}>{children}</FamilyOverlayContext.Provider>;
}
export function useFamilyOverlay() {
const context = useContext(FamilyOverlayContext);
if (!context) {
throw new Error('useFamilyOverlay must be used within FamilyOverlayProvider');
}
return context;
}

View File

@@ -0,0 +1,130 @@
'use client';
import Link from 'next/link';
import { useState } from 'react';
import { Loader2, Search, UsersRound } from 'lucide-react';
import { AvatarWithPresence } from '@/components/family/avatar-with-presence';
import { FamilyGroupSelector } from '@/components/family/family-group-selector';
import { FamilyInviteDialog } from '@/components/family/family-invite-dialog';
import { useFamilyOverlay } from '@/components/family/family-overlay-provider';
import { useAuth } from '@/components/id/auth-provider';
import { useSelectedFamily } from '@/hooks/use-primary-family';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
export function FamilySidebarPanel() {
const { user, token } = useAuth();
const {
group,
groupSummaries,
loading,
hasFamily,
selectedGroupId,
setSelectedGroupId,
presenceByUserId,
refresh
} = useSelectedFamily(Boolean(user && token));
const { openChatWithMember } = useFamilyOverlay();
const [inviteOpen, setInviteOpen] = useState(false);
if (!user || !token) return null;
return (
<>
<div className="mt-5 border-t border-[#eceef4] pt-4">
<div className="mb-2 flex items-center justify-between gap-1">
<div className="min-w-0">
<p className="truncate text-[11px] font-semibold uppercase tracking-wide text-[#667085]">Семья</p>
{hasFamily ? (
<FamilyGroupSelector
groups={groupSummaries}
selectedGroupId={selectedGroupId}
onSelect={setSelectedGroupId}
href={`/family/${group!.id}`}
nameClassName="text-xs font-medium text-[#1f2430]"
/>
) : (
<Link href="/family" className="text-xs font-medium text-[#3390ec] hover:underline">
Создать семью
</Link>
)}
</div>
{hasFamily ? (
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7 shrink-0 rounded-lg"
aria-label="Найти и пригласить"
onClick={() => setInviteOpen(true)}
>
<Search className="h-3.5 w-3.5" />
</Button>
) : null}
</div>
{loading ? (
<div className="flex items-center gap-2 py-2 text-[11px] text-[#667085]">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
Загрузка...
</div>
) : hasFamily ? (
<div className="max-h-[220px] space-y-1 overflow-y-auto pr-1">
{(group?.members ?? []).map((member) => {
const presence = presenceByUserId.get(member.userId);
const isSelf = member.userId === user.id;
return (
<button
key={member.id}
type="button"
className={cn(
'flex w-full items-center gap-2 rounded-xl px-2 py-1.5 text-left transition hover:bg-[#f4f5f8]',
isSelf && 'bg-[#fafbfd]'
)}
onClick={() => openChatWithMember(member.userId, member.displayName)}
title={isSelf ? 'Вы' : `Написать ${member.displayName}`}
>
<AvatarWithPresence
userId={member.userId}
displayName={member.displayName}
hasAvatar={member.hasAvatar}
token={token}
isVerified={member.isVerified}
verificationIcon={member.verificationIcon}
online={isSelf ? undefined : presence?.online}
className="h-8 w-8"
/>
<div className="min-w-0 flex-1">
<p className="truncate text-[12px] font-medium leading-tight">
{member.displayName}
{isSelf ? ' (Вы)' : ''}
</p>
{!isSelf ? (
<p className={cn('truncate text-[10px]', presence?.online ? 'text-emerald-600' : 'text-[#a8adbc]')}>
{presence?.online ? 'В сети' : 'Не в сети'}
</p>
) : null}
</div>
</button>
);
})}
</div>
) : (
<div className="rounded-xl bg-[#f4f5f8] px-2 py-3 text-[11px] text-[#667085]">
<UsersRound className="mb-1 h-4 w-4" />
Приглашайте близких и общайтесь в чатах
</div>
)}
</div>
{hasFamily ? (
<FamilyInviteDialog
groupId={group!.id}
open={inviteOpen}
onOpenChange={setInviteOpen}
onInvited={() => void refresh()}
/>
) : null}
</>
);
}

View File

@@ -0,0 +1,394 @@
'use client';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import Link from 'next/link';
import { ArrowLeft, Loader2, MessageCircle, Send, X } from 'lucide-react';
import { AvatarWithPresence } from '@/components/family/avatar-with-presence';
import { useFamilyOverlay } from '@/components/family/family-overlay-provider';
import { useAuth } from '@/components/id/auth-provider';
import { useToast } from '@/components/id/toast-provider';
import { useRealtime } from '@/components/notifications/realtime-provider';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useSelectedFamily } from '@/hooks/use-primary-family';
import { FamilyGroupSelector } from '@/components/family/family-group-selector';
import {
ChatMessage,
ChatRoom,
fetchChatMessages,
fetchChatRooms,
getApiErrorMessage,
markChatRoomRead,
sendChatMessage
} from '@/lib/api';
import { findOrCreateMemberChat, roomDisplayLabel } from '@/lib/family-chat';
import { cn } from '@/lib/utils';
function formatMessageTime(value: string) {
return new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' }).format(new Date(value));
}
export function MiniFamilyChat() {
const { user, token, isPinLocked } = useAuth();
const { showToast } = useToast();
const { subscribe } = useRealtime();
const {
group,
groupSummaries,
hasFamily,
selectedGroupId,
setSelectedGroupId,
presenceByUserId
} = useSelectedFamily(Boolean(user && token && !isPinLocked));
const {
miniChatOpen,
openMiniChat,
closeMiniChat,
pendingRoomId,
pendingMember,
clearPending
} = useFamilyOverlay();
const [view, setView] = useState<'picker' | 'chat'>('picker');
const [rooms, setRooms] = useState<ChatRoom[]>([]);
const [activeRoom, setActiveRoom] = useState<ChatRoom | null>(null);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [draft, setDraft] = useState('');
const [loadingRooms, setLoadingRooms] = useState(false);
const [loadingMessages, setLoadingMessages] = useState(false);
const [sending, setSending] = useState(false);
const [openingMemberId, setOpeningMemberId] = useState<string | null>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const previousGroupIdRef = useRef<string | null>(null);
const loadRooms = useCallback(async () => {
if (!group || !token) return;
setLoadingRooms(true);
try {
const response = await fetchChatRooms(group.id, token);
setRooms(response.rooms ?? []);
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось загрузить чаты') ?? 'Ошибка');
} finally {
setLoadingRooms(false);
}
}, [group, showToast, token]);
const openRoom = useCallback(
async (room: ChatRoom) => {
setActiveRoom(room);
setView('chat');
setLoadingMessages(true);
try {
const response = await fetchChatMessages(room.id, token);
setMessages(response.messages ?? []);
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось загрузить сообщения') ?? 'Ошибка');
} finally {
setLoadingMessages(false);
}
},
[showToast, token]
);
const openMemberChat = useCallback(
async (memberUserId: string, memberName: string) => {
if (!group || !token || !user) return;
setOpeningMemberId(memberUserId);
try {
const room = await findOrCreateMemberChat(group.id, memberUserId, memberName, user.id, token);
await loadRooms();
await openRoom(room);
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось открыть чат') ?? 'Ошибка');
} finally {
setOpeningMemberId(null);
}
},
[group, loadRooms, openRoom, showToast, token, user]
);
useEffect(() => {
if (!miniChatOpen || !hasFamily) return;
void loadRooms();
}, [group?.id, hasFamily, loadRooms, miniChatOpen]);
useEffect(() => {
if (!group?.id) return;
if (previousGroupIdRef.current && previousGroupIdRef.current !== group.id && miniChatOpen) {
setView('picker');
setActiveRoom(null);
setMessages([]);
setDraft('');
}
previousGroupIdRef.current = group.id;
}, [group?.id, miniChatOpen]);
useEffect(() => {
if (!miniChatOpen) {
setView('picker');
setActiveRoom(null);
setMessages([]);
setDraft('');
clearPending();
return;
}
if (pendingRoomId && rooms.length) {
const room = rooms.find((item) => item.id === pendingRoomId);
if (room) {
void openRoom(room);
clearPending();
}
} else if (pendingMember && user) {
void openMemberChat(pendingMember.userId, pendingMember.name);
clearPending();
}
}, [clearPending, miniChatOpen, openMemberChat, openRoom, pendingMember, pendingRoomId, rooms, user]);
useEffect(() => {
if (!activeRoom) return;
return subscribe((event) => {
const payload = event.payload;
if (payload?.roomId && payload.roomId !== activeRoom.id) return;
if (event.type === 'chat_message' && payload?.message) {
const message = payload.message as ChatMessage;
setMessages((current) => {
if (current.some((item) => item.id === message.id)) return current;
return [...current, message];
});
}
if (event.type === 'chat_message_updated' || event.type === 'chat_message_deleted') {
const updated = payload?.message;
if (updated) {
setMessages((current) => current.map((item) => (item.id === updated.id ? updated : item)));
}
}
});
}, [activeRoom, subscribe]);
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
useEffect(() => {
if (!activeRoom || !token || !messages.length) return;
const last = messages[messages.length - 1];
const timer = window.setTimeout(() => {
void markChatRoomRead(activeRoom.id, last.id, token).catch(() => {});
}, 400);
return () => window.clearTimeout(timer);
}, [activeRoom, messages, token]);
async function handleSend() {
if (!token || !activeRoom || !draft.trim()) return;
setSending(true);
try {
const message = await sendChatMessage(activeRoom.id, { type: 'TEXT', content: draft.trim() }, token);
setMessages((current) => [...current, message]);
setDraft('');
void loadRooms();
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось отправить сообщение') ?? 'Ошибка');
} finally {
setSending(false);
}
}
const otherMembers = useMemo(
() => (group?.members ?? []).filter((member) => member.userId !== user?.id),
[group?.members, user?.id]
);
if (!user || !token || isPinLocked) return null;
return (
<>
<button
type="button"
onClick={() => (miniChatOpen ? closeMiniChat() : openMiniChat())}
className={cn(
'fixed bottom-5 right-5 z-50 flex h-12 w-12 items-center justify-center rounded-full bg-[#3390ec] text-white shadow-lg transition hover:bg-[#2b7fd4] lg:bottom-6 lg:right-6',
miniChatOpen && 'scale-95'
)}
aria-label={miniChatOpen ? 'Закрыть чат семьи' : 'Открыть чат семьи'}
>
{miniChatOpen ? <X className="h-5 w-5" /> : <MessageCircle className="h-5 w-5" />}
</button>
{miniChatOpen ? (
<div className="fixed bottom-20 right-5 z-50 flex w-[min(92vw,380px)] flex-col overflow-hidden rounded-[24px] border border-[#eceef4] bg-white shadow-2xl lg:bottom-[5.5rem] lg:right-6">
<div className="flex items-center gap-2 border-b border-[#eceef4] px-4 py-3">
{view === 'chat' ? (
<Button type="button" variant="ghost" size="icon" className="h-8 w-8 shrink-0" onClick={() => setView('picker')}>
<ArrowLeft className="h-4 w-4" />
</Button>
) : null}
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold">
{view === 'chat' && activeRoom && user ? roomDisplayLabel(activeRoom, user.id) : 'Чат семьи'}
</p>
{hasFamily ? (
<FamilyGroupSelector
groups={groupSummaries}
selectedGroupId={selectedGroupId}
onSelect={setSelectedGroupId}
href={`/family/${group!.id}`}
nameClassName="text-xs text-[#667085]"
/>
) : (
<p className="text-xs text-[#667085]">Семья не создана</p>
)}
</div>
<Button type="button" variant="ghost" size="icon" className="h-8 w-8 shrink-0" onClick={closeMiniChat}>
<X className="h-4 w-4" />
</Button>
</div>
{!hasFamily ? (
<div className="space-y-3 p-5 text-sm text-[#667085]">
<p>Создайте семейную группу, чтобы общаться с близкими из любого раздела.</p>
<Link href="/family" className="inline-flex text-[#3390ec] hover:underline" onClick={closeMiniChat}>
Перейти к созданию семьи
</Link>
</div>
) : view === 'picker' ? (
<div className="max-h-[min(60vh,460px)] overflow-y-auto p-3">
<section className="mb-4">
<p className="mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-[#667085]">Чаты</p>
{loadingRooms ? (
<div className="flex items-center gap-2 px-2 py-3 text-sm text-[#667085]">
<Loader2 className="h-4 w-4 animate-spin" />
Загрузка...
</div>
) : rooms.length ? (
<div className="space-y-1">
{rooms.map((room) => (
<button
key={room.id}
type="button"
className="flex w-full items-center gap-3 rounded-xl px-2 py-2 text-left transition hover:bg-[#f4f5f8]"
onClick={() => void openRoom(room)}
>
<div className="flex h-9 w-9 items-center justify-center rounded-full bg-[#eef4ff] text-xs font-semibold text-[#3390ec]">
{room.type === 'GENERAL' ? 'В' : room.name.slice(0, 2).toUpperCase()}
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{user ? roomDisplayLabel(room, user.id) : room.name}</p>
<p className="truncate text-xs text-[#667085]">
{room.lastMessage?.isDeleted
? 'Сообщение удалено'
: room.lastMessage?.content ?? 'Нет сообщений'}
</p>
</div>
</button>
))}
</div>
) : (
<p className="px-2 py-2 text-sm text-[#667085]">Чаты пока не созданы</p>
)}
</section>
<section>
<p className="mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-[#667085]">Написать участнику</p>
<div className="space-y-1">
{otherMembers.map((member) => {
const presence = presenceByUserId.get(member.userId);
return (
<button
key={member.id}
type="button"
disabled={openingMemberId === member.userId}
className="flex w-full items-center gap-3 rounded-xl px-2 py-2 text-left transition hover:bg-[#f4f5f8] disabled:opacity-60"
onClick={() => void openMemberChat(member.userId, member.displayName)}
>
<AvatarWithPresence
userId={member.userId}
displayName={member.displayName}
hasAvatar={member.hasAvatar}
token={token}
isVerified={member.isVerified}
verificationIcon={member.verificationIcon}
online={presence?.online}
className="h-9 w-9"
/>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{member.displayName}</p>
<p className={cn('text-xs', presence?.online ? 'text-emerald-600' : 'text-[#667085]')}>
{presence?.online ? 'В сети' : 'Личный чат'}
</p>
</div>
{openingMemberId === member.userId ? <Loader2 className="h-4 w-4 animate-spin text-[#667085]" /> : null}
</button>
);
})}
{!otherMembers.length ? (
<p className="px-2 py-2 text-sm text-[#667085]">Пригласите участников в семью</p>
) : null}
</div>
</section>
<Link
href={`/family/${group!.id}`}
className="mt-3 block rounded-xl bg-[#f4f5f8] px-3 py-2 text-center text-xs font-medium text-[#3390ec] hover:bg-[#eceef4]"
onClick={closeMiniChat}
>
Открыть семью полностью
</Link>
</div>
) : (
<>
<div className="flex-1 space-y-2 overflow-y-auto bg-[#eef1f6] p-3" style={{ maxHeight: 'min(50vh,380px)' }}>
{loadingMessages ? (
<div className="flex items-center justify-center gap-2 py-8 text-sm text-[#667085]">
<Loader2 className="h-4 w-4 animate-spin" />
Загрузка...
</div>
) : messages.length ? (
messages.map((message) => {
const mine = message.senderId === user.id;
return (
<div key={message.id} className={cn('flex', mine ? 'justify-end' : 'justify-start')}>
<div
className={cn(
'max-w-[85%] rounded-[16px] px-3 py-2 text-sm shadow-sm',
mine ? 'bg-[#effdde]' : 'bg-white',
message.isDeleted && 'italic text-[#667085]'
)}
>
{!mine ? <p className="mb-0.5 text-[11px] font-semibold text-[#3390ec]">{message.senderName}</p> : null}
<p>{message.isDeleted ? 'Сообщение удалено' : message.content ?? '…'}</p>
<p className="mt-1 text-[10px] text-[#a8adbc]">{formatMessageTime(message.createdAt)}</p>
</div>
</div>
);
})
) : (
<p className="py-8 text-center text-sm text-[#667085]">Сообщений пока нет</p>
)}
<div ref={messagesEndRef} />
</div>
<div className="flex items-center gap-2 border-t border-[#eceef4] p-3">
<Input
value={draft}
onChange={(event) => setDraft(event.target.value)}
placeholder="Сообщение"
className="rounded-xl"
onKeyDown={(event) => {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
void handleSend();
}
}}
/>
<Button className="h-10 w-10 shrink-0 rounded-full p-0" disabled={sending || !draft.trim()} onClick={() => void handleSend()}>
{sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
</Button>
</div>
</>
)}
</div>
) : null}
</>
);
}

View File

@@ -3,10 +3,11 @@
import { useRef, useState } from 'react'; import { useRef, useState } from 'react';
import { Camera, Loader2 } from 'lucide-react'; import { Camera, Loader2 } from 'lucide-react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/id/toast-provider'; import { useToast } from '@/components/id/toast-provider';
import { useAvatarUrl } from '@/hooks/use-avatar-url'; import { useAvatarUrl } from '@/hooks/use-avatar-url';
import { apiFetch, getApiErrorMessage, uploadMediaObject } from '@/lib/api'; import { apiFetch, getApiErrorMessage, uploadMediaObject } from '@/lib/api';
import { VerificationBadge } from '@/components/id/verification-badge';
import { cn } from '@/lib/utils';
interface PresignedUploadResponse { interface PresignedUploadResponse {
uploadUrl: string; uploadUrl: string;
@@ -20,13 +21,21 @@ export function AvatarUpload({
displayName, displayName,
hasAvatar, hasAvatar,
token, token,
onUpdated onUpdated,
isVerified,
verificationIcon,
className = 'h-24 w-24',
badgeSize = 'md'
}: { }: {
userId: string; userId: string;
displayName?: string; displayName?: string;
hasAvatar?: boolean; hasAvatar?: boolean;
token: string | null; token: string | null;
onUpdated: () => Promise<void>; onUpdated: () => Promise<void>;
isVerified?: boolean;
verificationIcon?: string | null;
className?: string;
badgeSize?: 'xs' | 'sm' | 'md' | 'lg';
}) { }) {
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const { showToast } = useToast(); const { showToast } = useToast();
@@ -73,24 +82,45 @@ export function AvatarUpload({
} }
} }
function openFilePicker() {
if (isUploading || !token) return;
inputRef.current?.click();
}
return ( return (
<div className="relative inline-flex"> <div className="relative inline-flex shrink-0">
<Avatar className="h-24 w-24 border-4 border-white shadow-xl"> <button
type="button"
className={cn('group relative rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#3390ec] focus-visible:ring-offset-2', className)}
disabled={isUploading || !token}
aria-label="Изменить фото профиля"
onClick={openFilePicker}
>
<Avatar className={cn('border-4 border-white shadow-xl', className)}>
{avatarUrl ? <AvatarImage src={avatarUrl} alt={displayName ?? 'Аватар'} /> : null} {avatarUrl ? <AvatarImage src={avatarUrl} alt={displayName ?? 'Аватар'} /> : null}
<AvatarFallback className="bg-[linear-gradient(135deg,#6f58ff,#ffd2a8)] text-2xl">{initials}</AvatarFallback> <AvatarFallback className="bg-[linear-gradient(135deg,#6f58ff,#ffd2a8)] text-2xl">{initials}</AvatarFallback>
</Avatar> </Avatar>
<input ref={inputRef} type="file" accept="image/jpeg,image/png,image/webp,image/gif" className="hidden" onChange={handleFileChange} /> <span
<Button className={cn(
type="button" 'absolute inset-0 flex items-center justify-center rounded-full transition',
size="sm" isUploading ? 'bg-black/45 opacity-100' : 'bg-black/0 opacity-0 group-hover:bg-black/40 group-hover:opacity-100 group-focus-visible:bg-black/40 group-focus-visible:opacity-100'
variant="secondary" )}
className="absolute -bottom-2 left-1/2 -translate-x-1/2 rounded-full px-3 shadow"
disabled={isUploading || !token}
onClick={() => inputRef.current?.click()}
> >
{isUploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Camera className="h-4 w-4" />} {isUploading ? (
{isUploading ? 'Загрузка...' : 'Фото'} <Loader2 className="h-5 w-5 animate-spin text-white" />
</Button> ) : (
<Camera className="h-5 w-5 text-white" />
)}
</span>
</button>
{isVerified ? (
<VerificationBadge
verificationIcon={verificationIcon}
size={badgeSize}
className="pointer-events-none absolute top-0 right-0 z-20"
/>
) : null}
<input ref={inputRef} type="file" accept="image/jpeg,image/png,image/webp,image/gif" className="hidden" onChange={handleFileChange} />
</div> </div>
); );
} }
@@ -100,21 +130,36 @@ export function AvatarDisplay({
displayName, displayName,
hasAvatar, hasAvatar,
token, token,
className className,
isVerified,
verificationIcon,
badgeSize = 'sm'
}: { }: {
userId: string; userId: string;
displayName?: string; displayName?: string;
hasAvatar?: boolean; hasAvatar?: boolean;
token: string | null; token: string | null;
className?: string; className?: string;
isVerified?: boolean;
verificationIcon?: string | null;
badgeSize?: 'xs' | 'sm' | 'md' | 'lg';
}) { }) {
const { avatarUrl } = useAvatarUrl(userId, hasAvatar, token); const { avatarUrl } = useAvatarUrl(userId, hasAvatar, token);
const initials = (displayName ?? '').slice(0, 2).toUpperCase() || 'ID'; const initials = (displayName ?? '').slice(0, 2).toUpperCase() || 'ID';
return ( return (
<div className="relative inline-flex shrink-0">
<Avatar className={className}> <Avatar className={className}>
{avatarUrl ? <AvatarImage src={avatarUrl} alt={displayName ?? 'Аватар'} /> : null} {avatarUrl ? <AvatarImage src={avatarUrl} alt={displayName ?? 'Аватар'} /> : null}
<AvatarFallback className="bg-[linear-gradient(135deg,#6f58ff,#ffd2a8)]">{initials}</AvatarFallback> <AvatarFallback className="bg-[linear-gradient(135deg,#6f58ff,#ffd2a8)]">{initials}</AvatarFallback>
</Avatar> </Avatar>
{isVerified ? (
<VerificationBadge
verificationIcon={verificationIcon}
size={badgeSize}
className="absolute -top-0.5 -right-0.5 z-20"
/>
) : null}
</div>
); );
} }

View File

@@ -3,18 +3,23 @@
import { Sidebar } from './sidebar'; import { Sidebar } from './sidebar';
import { UserMenu } from './user-menu'; import { UserMenu } from './user-menu';
import { NotificationBell } from '@/components/notifications/notification-bell'; import { NotificationBell } from '@/components/notifications/notification-bell';
import { FamilyOverlayProvider } from '@/components/family/family-overlay-provider';
import { MiniFamilyChat } from '@/components/family/mini-family-chat';
export function IdShell({ active, children, wide = false }: { active: string; children: React.ReactNode; wide?: boolean }) { export function IdShell({ active, children, wide = false }: { active: string; children: React.ReactNode; wide?: boolean }) {
return ( return (
<FamilyOverlayProvider>
<div className="min-h-screen bg-white"> <div className="min-h-screen bg-white">
<Sidebar active={active} /> <Sidebar active={active} />
<div className="fixed right-4 top-4 z-40 flex items-center gap-2 lg:right-8 lg:top-6"> <div className="fixed right-4 top-4 z-40 flex items-center gap-2 lg:right-8 lg:top-6">
<NotificationBell /> <NotificationBell />
<UserMenu /> <UserMenu />
</div> </div>
<main className="px-5 py-8 lg:pl-[170px] lg:pr-8"> <main className="px-5 py-8 lg:pl-[220px] lg:pr-8">
<div className={wide ? 'mx-auto max-w-[920px]' : 'mx-auto max-w-[560px]'}>{children}</div> <div className={wide ? 'mx-auto max-w-[920px]' : 'mx-auto max-w-[560px]'}>{children}</div>
</main> </main>
<MiniFamilyChat />
</div> </div>
</FamilyOverlayProvider>
); );
} }

View File

@@ -2,6 +2,7 @@
import Link from 'next/link'; import Link from 'next/link';
import { FileText, Heart, Home, LockKeyhole, LogOut, ShieldCheck, UserRound } from 'lucide-react'; import { FileText, Heart, Home, LockKeyhole, LogOut, ShieldCheck, UserRound } from 'lucide-react';
import { FamilySidebarPanel } from '@/components/family/family-sidebar-panel';
import { BrandLogo } from '@/components/id/brand-logo'; import { BrandLogo } from '@/components/id/brand-logo';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { getAdminLandingPath } from '@/lib/admin-access'; import { getAdminLandingPath } from '@/lib/admin-access';
@@ -22,8 +23,8 @@ export function Sidebar({ active }: { active: string }) {
: baseItems; : baseItems;
return ( return (
<aside className="fixed left-0 top-0 hidden h-screen w-[150px] flex-col justify-between border-r border-transparent bg-white px-3 py-7 text-[13px] lg:flex"> <aside className="fixed left-0 top-0 hidden h-screen w-[200px] flex-col justify-between border-r border-[#eceef4] bg-white px-3 py-7 text-[13px] lg:flex">
<div> <div className="flex min-h-0 flex-1 flex-col">
<Link href="/" className="mb-7 block"> <Link href="/" className="mb-7 block">
<BrandLogo size="lg" variant="dark" /> <BrandLogo size="lg" variant="dark" />
</Link> </Link>
@@ -42,6 +43,9 @@ export function Sidebar({ active }: { active: string }) {
</Link> </Link>
))} ))}
</nav> </nav>
<div className="min-h-0 flex-1 overflow-hidden">
<FamilySidebarPanel />
</div>
</div> </div>
<div className="space-y-2 text-[11px] text-[#667085]"> <div className="space-y-2 text-[11px] text-[#667085]">
{user ? <p className="truncate font-medium text-[#1f2430]">{user.displayName}</p> : null} {user ? <p className="truncate font-medium text-[#1f2430]">{user.displayName}</p> : null}

View File

@@ -0,0 +1,54 @@
'use client';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { VerificationBadge } from '@/components/id/verification-badge';
import { useAvatarUrl } from '@/hooks/use-avatar-url';
import { cn } from '@/lib/utils';
export function UserAvatar({
userId,
displayName,
hasAvatar,
token,
isVerified,
verificationIcon,
className,
badgeSize = 'sm',
fallbackClassName
}: {
userId: string;
displayName?: string;
hasAvatar?: boolean;
token: string | null;
isVerified?: boolean;
verificationIcon?: string | null;
className?: string;
badgeSize?: 'xs' | 'sm' | 'md' | 'lg';
fallbackClassName?: string;
}) {
const { avatarUrl } = useAvatarUrl(userId, hasAvatar, token);
const initials = (displayName ?? '')
.split(' ')
.map((part) => part[0])
.join('')
.slice(0, 2)
.toUpperCase() || 'ID';
return (
<div className="relative inline-flex shrink-0">
<Avatar className={className}>
{avatarUrl ? <AvatarImage src={avatarUrl} alt={displayName ?? 'Аватар'} /> : null}
<AvatarFallback className={cn('bg-[linear-gradient(135deg,#6f58ff,#ffd2a8)] text-xs font-semibold', fallbackClassName)}>
{initials.slice(0, 2)}
</AvatarFallback>
</Avatar>
{isVerified ? (
<VerificationBadge
verificationIcon={verificationIcon}
size={badgeSize}
className="absolute -top-0.5 -right-0.5 z-20"
/>
) : null}
</div>
);
}

View File

@@ -13,10 +13,9 @@ import {
UserRound UserRound
} from 'lucide-react'; } from 'lucide-react';
import { AdminBadge } from '@/components/id/admin-badge'; import { AdminBadge } from '@/components/id/admin-badge';
import { UserAvatar } from '@/components/id/user-avatar';
import { useAuth } from '@/components/id/auth-provider'; import { useAuth } from '@/components/id/auth-provider';
import { useAvatarUrl } from '@/hooks/use-avatar-url';
import { getAdminLandingPath } from '@/lib/admin-access'; import { getAdminLandingPath } from '@/lib/admin-access';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
@@ -38,17 +37,10 @@ const menuItems = [
export function UserMenu({ className }: { className?: string }) { export function UserMenu({ className }: { className?: string }) {
const router = useRouter(); const router = useRouter();
const { user, token, logout } = useAuth(); const { user, token, logout } = useAuth();
const { avatarUrl } = useAvatarUrl(user?.id, user?.hasAvatar, token);
if (!user) return null; if (!user) return null;
const contactLine = [maskPhone(user.phone), user.username ?? user.email].filter(Boolean).join(' · '); const contactLine = [maskPhone(user.phone), user.username ?? user.email].filter(Boolean).join(' · ');
const initials = user.displayName
.split(' ')
.map((part) => part[0])
.join('')
.slice(0, 2)
.toUpperCase();
return ( return (
<Popover> <Popover>
@@ -58,19 +50,31 @@ export function UserMenu({ className }: { className?: string }) {
className={cn('flex items-center gap-2 rounded-full border border-[#eceef4] bg-white py-1 pl-1 pr-3 shadow-sm transition hover:bg-[#fafbfd]', className)} className={cn('flex items-center gap-2 rounded-full border border-[#eceef4] bg-white py-1 pl-1 pr-3 shadow-sm transition hover:bg-[#fafbfd]', className)}
aria-label="Меню пользователя" aria-label="Меню пользователя"
> >
<Avatar className="h-9 w-9"> <UserAvatar
{avatarUrl ? <AvatarImage src={avatarUrl} alt={user.displayName} /> : null} userId={user.id}
<AvatarFallback className="text-xs font-semibold">{initials}</AvatarFallback> displayName={user.displayName}
</Avatar> hasAvatar={user.hasAvatar}
token={token}
isVerified={user.isVerified}
verificationIcon={user.verificationIcon}
className="h-9 w-9"
badgeSize="xs"
/>
<span className="hidden max-w-[120px] truncate text-sm font-medium md:inline">{user.displayName}</span> <span className="hidden max-w-[120px] truncate text-sm font-medium md:inline">{user.displayName}</span>
</button> </button>
</PopoverTrigger> </PopoverTrigger>
<PopoverContent align="end" className="w-[min(92vw,360px)] rounded-[28px] border-[#eceef4] p-0 shadow-2xl"> <PopoverContent align="end" className="w-[min(92vw,360px)] rounded-[28px] border-[#eceef4] p-0 shadow-2xl">
<div className="border-b border-[#eceef4] px-5 pb-5 pt-5 text-center"> <div className="border-b border-[#eceef4] px-5 pb-5 pt-5 text-center">
<Avatar className="mx-auto h-20 w-20"> <UserAvatar
{avatarUrl ? <AvatarImage src={avatarUrl} alt={user.displayName} /> : null} userId={user.id}
<AvatarFallback className="text-lg font-semibold">{initials}</AvatarFallback> displayName={user.displayName}
</Avatar> hasAvatar={user.hasAvatar}
token={token}
isVerified={user.isVerified}
verificationIcon={user.verificationIcon}
className="mx-auto h-20 w-20"
badgeSize="md"
/>
<div className="mt-3 flex items-center justify-center gap-2"> <div className="mt-3 flex items-center justify-center gap-2">
<p className="text-lg font-semibold">{user.displayName}</p> <p className="text-lg font-semibold">{user.displayName}</p>
<AdminBadge user={user} /> <AdminBadge user={user} />

View File

@@ -0,0 +1,42 @@
'use client';
import { cn } from '@/lib/utils';
import { VerificationIconGlyph } from '@/lib/verification-icons';
const sizeClasses = {
xs: 'h-3.5 w-3.5 border',
sm: 'h-4 w-4 border',
md: 'h-5 w-5 border-2',
lg: 'h-6 w-6 border-2'
} as const;
const iconSizeClasses = {
xs: 'h-2 w-2',
sm: 'h-2.5 w-2.5',
md: 'h-3 w-3',
lg: 'h-3.5 w-3.5'
} as const;
export function VerificationBadge({
verificationIcon,
size = 'sm',
className
}: {
verificationIcon?: string | null;
size?: keyof typeof sizeClasses;
className?: string;
}) {
return (
<span
className={cn(
'inline-flex items-center justify-center rounded-full border-white bg-[#3390ec] text-white shadow-sm',
sizeClasses[size],
className
)}
title="Верифицированный пользователь"
aria-label="Верифицированный пользователь"
>
<VerificationIconGlyph slug={verificationIcon} className={iconSizeClasses[size]} />
</span>
);
}

View File

@@ -0,0 +1,102 @@
'use client';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useFamilyOverlay } from '@/components/family/family-overlay-provider';
import { useAuth } from '@/components/id/auth-provider';
import {
FamilyGroup,
FamilyPresenceMember,
fetchFamilyGroup,
fetchFamilyGroups,
fetchFamilyPresence
} from '@/lib/api';
export function useSelectedFamily(enabled = true) {
const { user, token, isPinLocked } = useAuth();
const { selectedGroupId, setSelectedGroupId } = useFamilyOverlay();
const [groups, setGroups] = useState<FamilyGroup[]>([]);
const [group, setGroup] = useState<FamilyGroup | null>(null);
const [presenceMembers, setPresenceMembers] = useState<FamilyPresenceMember[]>([]);
const [loading, setLoading] = useState(true);
const refresh = useCallback(async () => {
if (!enabled || !user || !token || isPinLocked) {
setGroups([]);
setGroup(null);
setPresenceMembers([]);
setLoading(false);
return;
}
try {
const groupsResponse = await fetchFamilyGroups(user.id, token);
const list = groupsResponse.groups ?? [];
setGroups(list);
if (!list.length) {
setGroup(null);
setPresenceMembers([]);
if (selectedGroupId) setSelectedGroupId(null);
return;
}
const effectiveId =
selectedGroupId && list.some((item) => item.id === selectedGroupId) ? selectedGroupId : list[0]!.id;
if (effectiveId !== selectedGroupId) {
setSelectedGroupId(effectiveId);
}
const [groupResponse, presenceResponse] = await Promise.all([
fetchFamilyGroup(effectiveId, token),
fetchFamilyPresence(effectiveId, token)
]);
setGroup(groupResponse);
setPresenceMembers(presenceResponse.members ?? []);
} catch {
setGroups([]);
setGroup(null);
setPresenceMembers([]);
} finally {
setLoading(false);
}
}, [enabled, isPinLocked, selectedGroupId, setSelectedGroupId, token, user]);
useEffect(() => {
setLoading(true);
void refresh();
}, [refresh]);
useEffect(() => {
if (!enabled || !token || isPinLocked || !group) return;
const timer = window.setInterval(() => void refresh(), 25_000);
return () => window.clearInterval(timer);
}, [enabled, group, isPinLocked, refresh, token]);
const presenceByUserId = useMemo(
() => new Map(presenceMembers.map((member) => [member.userId, member])),
[presenceMembers]
);
const groupSummaries = useMemo(
() => groups.map((item) => ({ id: item.id, name: item.name })),
[groups]
);
return {
groups,
groupSummaries,
group,
loading,
hasFamily: Boolean(group),
selectedGroupId: group?.id ?? selectedGroupId,
setSelectedGroupId,
presenceByUserId,
refresh
};
}
/** @deprecated Используйте useSelectedFamily */
export function usePrimaryFamily(enabled = true) {
return useSelectedFamily(enabled);
}

View File

@@ -79,6 +79,9 @@ export interface PublicUser {
canViewUsers?: boolean; canViewUsers?: boolean;
canViewUserDocuments?: boolean; canViewUserDocuments?: boolean;
hasPassword?: boolean; hasPassword?: boolean;
isVerified?: boolean;
verificationIcon?: string | null;
canVerifyUsers?: boolean;
} }
export interface AdminUser { export interface AdminUser {
@@ -92,6 +95,8 @@ export interface AdminUser {
createdAt: string; createdAt: string;
roles: string[]; roles: string[];
directPermissions?: string[]; directPermissions?: string[];
isVerified?: boolean;
verificationIcon?: string | null;
} }
export interface AdminRole { export interface AdminRole {
@@ -230,6 +235,8 @@ export interface FamilyInviteCandidate {
phone?: string | null; phone?: string | null;
username?: string | null; username?: string | null;
hasAvatar?: boolean; hasAvatar?: boolean;
isVerified?: boolean;
verificationIcon?: string | null;
} }
export async function searchFamilyInviteUsers(groupId: string, query: string, token?: string | null) { export async function searchFamilyInviteUsers(groupId: string, query: string, token?: string | null) {
@@ -653,6 +660,8 @@ export interface FamilyMember {
role: string; role: string;
displayName: string; displayName: string;
hasAvatar: boolean; hasAvatar: boolean;
isVerified?: boolean;
verificationIcon?: string | null;
} }
export interface FamilyGroup { export interface FamilyGroup {
@@ -699,6 +708,8 @@ export interface ChatMessage {
senderId: string; senderId: string;
senderName: string; senderName: string;
senderHasAvatar: boolean; senderHasAvatar: boolean;
senderIsVerified?: boolean;
senderVerificationIcon?: string | null;
type: string; type: string;
content?: string; content?: string;
replyToId?: string; replyToId?: string;
@@ -735,6 +746,8 @@ export interface ChatRoomMember {
userId: string; userId: string;
displayName: string; displayName: string;
hasAvatar: boolean; hasAvatar: boolean;
isVerified?: boolean;
verificationIcon?: string | null;
notificationsMuted: boolean; notificationsMuted: boolean;
familyRole?: string; familyRole?: string;
isChatCreator?: boolean; isChatCreator?: boolean;

View File

@@ -0,0 +1,30 @@
import { ChatRoom, createChatRoom, fetchChatRooms } from '@/lib/api';
export async function findOrCreateMemberChat(
groupId: string,
memberUserId: string,
memberName: string,
currentUserId: string,
token: string
): Promise<ChatRoom> {
const response = await fetchChatRooms(groupId, token);
const rooms = response.rooms ?? [];
const existing = rooms.find(
(room) =>
room.type === 'GROUP' &&
room.members.length === 2 &&
room.members.some((member) => member.userId === memberUserId) &&
room.members.some((member) => member.userId === currentUserId)
);
if (existing) return existing;
return createChatRoom(groupId, memberName, [memberUserId], token);
}
export function roomDisplayLabel(room: ChatRoom, currentUserId: string) {
if (room.type === 'GENERAL') return room.name;
if (room.members.length === 2) {
const other = room.members.find((member) => member.userId !== currentUserId);
if (other) return other.displayName;
}
return room.name;
}

View File

@@ -0,0 +1,4 @@
export function defaultFamilyGroupName(displayName: string) {
const trimmed = displayName.trim();
return trimmed ? `Семья пользователя ${trimmed}` : 'Семья пользователя';
}

View File

@@ -0,0 +1,47 @@
import {
Award,
BadgeCheck,
Crown,
Gem,
Heart,
Moon,
ShieldCheck,
Sparkles,
Star,
Sun,
type LucideIcon
} from 'lucide-react';
export const DEFAULT_VERIFICATION_ICON = 'badge-check';
export const VERIFICATION_ICON_OPTIONS = [
{ slug: 'badge-check', name: 'Галочка', Icon: BadgeCheck },
{ slug: 'star', name: 'Звезда', Icon: Star },
{ slug: 'sparkles', name: 'Искры', Icon: Sparkles },
{ slug: 'moon', name: 'Луна', Icon: Moon },
{ slug: 'sun', name: 'Солнце', Icon: Sun },
{ slug: 'crown', name: 'Корона', Icon: Crown },
{ slug: 'gem', name: 'Драгоценность', Icon: Gem },
{ slug: 'heart', name: 'Сердце', Icon: Heart },
{ slug: 'award', name: 'Награда', Icon: Award },
{ slug: 'shield-check', name: 'Щит', Icon: ShieldCheck }
] as const;
export type VerificationIconSlug = (typeof VERIFICATION_ICON_OPTIONS)[number]['slug'];
const iconBySlug = Object.fromEntries(VERIFICATION_ICON_OPTIONS.map((option) => [option.slug, option.Icon])) as Record<
VerificationIconSlug,
LucideIcon
>;
export function resolveVerificationIcon(slug?: string | null): VerificationIconSlug {
if (slug && slug in iconBySlug) {
return slug as VerificationIconSlug;
}
return DEFAULT_VERIFICATION_ICON;
}
export function VerificationIconGlyph({ slug, className }: { slug?: string | null; className?: string }) {
const Icon = iconBySlug[resolveVerificationIcon(slug)];
return <Icon className={className} aria-hidden />;
}

View File

@@ -49,6 +49,9 @@ model User {
birthDate DateTime? birthDate DateTime?
gender String? gender String?
isSuperAdmin Boolean @default(false) isSuperAdmin Boolean @default(false)
isVerified Boolean @default(false)
verificationIcon String?
verifiedAt DateTime?
status UserStatus @default(ACTIVE) status UserStatus @default(ACTIVE)
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt

View File

@@ -14,6 +14,7 @@ export interface UserAccessContext {
canViewUsers: boolean; canViewUsers: boolean;
canManageSettings: boolean; canManageSettings: boolean;
canViewUserDocuments: boolean; canViewUserDocuments: boolean;
canVerifyUsers: boolean;
} }
function hasAnyPermission(permissions: string[], ...slugs: string[]) { function hasAnyPermission(permissions: string[], ...slugs: string[]) {
@@ -40,7 +41,8 @@ export class AccessService {
'users.manage.all', 'users.manage.all',
'settings.manage', 'settings.manage',
'rbac.manage', 'rbac.manage',
'documents.view_others' 'documents.view_others',
'users.verify'
], ],
canAccessAdmin: true, canAccessAdmin: true,
canManageRoles: true, canManageRoles: true,
@@ -51,7 +53,8 @@ export class AccessService {
canManageAllUsers: true, canManageAllUsers: true,
canViewUsers: true, canViewUsers: true,
canManageSettings: true, canManageSettings: true,
canViewUserDocuments: true canViewUserDocuments: true,
canVerifyUsers: true
}; };
} }
@@ -98,7 +101,8 @@ export class AccessService {
canManageAllUsers, canManageAllUsers,
canViewUsers, canViewUsers,
canManageSettings: permissions.includes('settings.manage'), canManageSettings: permissions.includes('settings.manage'),
canViewUserDocuments: permissions.includes('documents.view_others') canViewUserDocuments: permissions.includes('documents.view_others'),
canVerifyUsers: permissions.includes('users.verify')
}; };
} }
@@ -124,6 +128,18 @@ export class AccessService {
} }
} }
async assertCanVerifyUsers(actorUserId: string) {
const actor = await this.prisma.user.findUnique({ where: { id: actorUserId } });
if (!actor) {
throw new NotFoundException('Пользователь не найден');
}
if (actor.isSuperAdmin) return;
const access = await this.getUserAccess(actorUserId, false);
if (!access.canVerifyUsers) {
throw new ForbiddenException('Недостаточно прав для верификации пользователей');
}
}
async assertSuperAdmin(actorUserId: string) { async assertSuperAdmin(actorUserId: string) {
const actor = await this.prisma.user.findUnique({ where: { id: actorUserId } }); const actor = await this.prisma.user.findUnique({ where: { id: actorUserId } });
if (!actor?.isSuperAdmin) { if (!actor?.isSuperAdmin) {

View File

@@ -13,6 +13,7 @@ const PERMISSIONS = [
{ slug: 'users.view.all', name: 'Просмотр всех пользователей', description: 'Просмотр полного списка пользователей системы' }, { slug: 'users.view.all', name: 'Просмотр всех пользователей', description: 'Просмотр полного списка пользователей системы' },
{ slug: 'users.manage', name: 'Управление пользователями', description: 'Редактирование, блокировка и сброс паролей' }, { slug: 'users.manage', name: 'Управление пользователями', description: 'Редактирование, блокировка и сброс паролей' },
{ slug: 'users.manage.all', name: 'Полное управление пользователями', description: 'Расширенное управление всеми пользователями' }, { slug: 'users.manage.all', name: 'Полное управление пользователями', description: 'Расширенное управление всеми пользователями' },
{ slug: 'users.verify', name: 'Верификация пользователей', description: 'Выдача и снятие верификации, выбор значка' },
{ slug: 'users.read', name: 'Просмотр пользователей (устар.)', description: 'Устаревшее право, заменено на users.view' }, { slug: 'users.read', name: 'Просмотр пользователей (устар.)', description: 'Устаревшее право, заменено на users.view' },
{ slug: 'settings.manage', name: 'Управление настройками', description: 'Изменение глобальных SystemSetting' }, { slug: 'settings.manage', name: 'Управление настройками', description: 'Изменение глобальных SystemSetting' },
{ slug: 'rbac.manage', name: 'Управление ролями и правами', description: 'Назначение ролей, прав пользователям и редактирование ролей' }, { slug: 'rbac.manage', name: 'Управление ролями и правами', description: 'Назначение ролей, прав пользователям и редактирование ролей' },
@@ -32,7 +33,7 @@ const ROLES = [
slug: 'admin', slug: 'admin',
name: 'Администратор', name: 'Администратор',
description: 'Полный доступ к админ-панели', description: 'Полный доступ к админ-панели',
permissions: ['admin.access', 'oauth.manage.all', 'oauth.view.all', 'users.manage.all', 'users.view.all', 'settings.manage', 'rbac.manage'], permissions: ['admin.access', 'oauth.manage.all', 'oauth.view.all', 'users.manage.all', 'users.view.all', 'users.verify', 'settings.manage', 'rbac.manage'],
isSystem: false, isSystem: false,
isDefault: false isDefault: false
}, },

View File

@@ -3,6 +3,7 @@ import * as bcrypt from 'bcryptjs';
import { UserStatus } from '../generated/prisma/client'; import { UserStatus } from '../generated/prisma/client';
import { PrismaService } from '../infra/prisma.service'; import { PrismaService } from '../infra/prisma.service';
import { AccessService } from './access.service'; import { AccessService } from './access.service';
import { DEFAULT_VERIFICATION_ICON, isAllowedVerificationIcon, VERIFICATION_ICONS } from './verification.constants';
@Injectable() @Injectable()
export class AdminService { export class AdminService {
@@ -92,6 +93,43 @@ export class AdminService {
return this.toAdminUser(user); return this.toAdminUser(user);
} }
async setUserVerification(actorUserId: string, userId: string, data: { isVerified: boolean; verificationIcon?: string }) {
await this.access.assertCanVerifyUsers(actorUserId);
await this.ensureUserExists(userId);
if (data.isVerified) {
const icon = data.verificationIcon ?? DEFAULT_VERIFICATION_ICON;
if (!isAllowedVerificationIcon(icon)) {
throw new BadRequestException('Выберите значок верификации из списка');
}
const user = await this.prisma.user.update({
where: { id: userId },
data: {
isVerified: true,
verificationIcon: icon,
verifiedAt: new Date()
},
include: { userRoles: { include: { role: true } }, userPermissions: { include: { permission: true } } }
});
return this.toAdminUser(user);
}
const user = await this.prisma.user.update({
where: { id: userId },
data: {
isVerified: false,
verificationIcon: null,
verifiedAt: null
},
include: { userRoles: { include: { role: true } }, userPermissions: { include: { permission: true } } }
});
return this.toAdminUser(user);
}
listVerificationIcons() {
return { icons: VERIFICATION_ICONS.map((icon) => ({ slug: icon.slug, name: icon.name })) };
}
async deleteUser(userId: string) { async deleteUser(userId: string) {
await this.ensureUserExists(userId); await this.ensureUserExists(userId);
const user = await this.prisma.user.update({ const user = await this.prisma.user.update({
@@ -111,6 +149,8 @@ export class AdminService {
displayName: string; displayName: string;
username: string | null; username: string | null;
isSuperAdmin: boolean; isSuperAdmin: boolean;
isVerified: boolean;
verificationIcon: string | null;
status: UserStatus; status: UserStatus;
createdAt: Date; createdAt: Date;
userRoles?: { role: { slug: string } }[]; userRoles?: { role: { slug: string } }[];
@@ -125,6 +165,8 @@ export class AdminService {
displayName: user.displayName, displayName: user.displayName,
username: user.username ?? undefined, username: user.username ?? undefined,
isSuperAdmin: user.isSuperAdmin, isSuperAdmin: user.isSuperAdmin,
isVerified: user.isVerified,
verificationIcon: user.isVerified ? (user.verificationIcon ?? DEFAULT_VERIFICATION_ICON) : undefined,
status: user.status, status: user.status,
createdAt: user.createdAt.toISOString(), createdAt: user.createdAt.toISOString(),
roles: user.userRoles?.map((link) => link.role.slug) ?? [], roles: user.userRoles?.map((link) => link.role.slug) ?? [],

View File

@@ -157,6 +157,19 @@ export class AuthGrpcController {
return this.admin.setSuperAdmin(command.actorUserId, command.userId, command.isSuperAdmin); return this.admin.setSuperAdmin(command.actorUserId, command.userId, command.isSuperAdmin);
} }
@GrpcMethod('AdminService', 'SetUserVerification')
setUserVerification(command: { actorUserId: string; userId: string; isVerified: boolean; verificationIcon?: string }) {
return this.admin.setUserVerification(command.actorUserId, command.userId, {
isVerified: command.isVerified,
verificationIcon: command.verificationIcon
});
}
@GrpcMethod('AdminService', 'ListVerificationIcons')
listVerificationIcons() {
return this.admin.listVerificationIcons();
}
@GrpcMethod('RbacService', 'ListRoles') @GrpcMethod('RbacService', 'ListRoles')
async listRoles() { async listRoles() {
const roles = await this.rbac.listRoles(); const roles = await this.rbac.listRoles();

View File

@@ -16,6 +16,7 @@ import { NotificationsService } from './notifications.service';
import { canonicalPhoneE164, phoneLookupVariants } from '../infra/phone.util'; import { canonicalPhoneE164, phoneLookupVariants } from '../infra/phone.util';
import { TotpService } from './totp.service'; import { TotpService } from './totp.service';
import { RbacService } from './rbac.service'; import { RbacService } from './rbac.service';
import { DEFAULT_VERIFICATION_ICON, resolveVerificationIcon } from './verification.constants';
const FIRST_ADMIN_LOCK = 'locks:first-super-admin'; const FIRST_ADMIN_LOCK = 'locks:first-super-admin';
const TOTP_LOGIN_CHALLENGE_TTL_SECONDS = 5 * 60; const TOTP_LOGIN_CHALLENGE_TTL_SECONDS = 5 * 60;
@@ -765,7 +766,7 @@ export class AuthService {
return this.toPublicUser(user); return this.toPublicUser(user);
} }
async toPublicUser(user: Pick<User, 'id' | 'email' | 'phone' | 'backupEmail' | 'backupPhone' | 'displayName' | 'username' | 'avatarUrl' | 'avatarStorageKey' | 'isSuperAdmin' | 'status' | 'passwordHash'>): Promise<PublicUser> { async toPublicUser(user: Pick<User, 'id' | 'email' | 'phone' | 'backupEmail' | 'backupPhone' | 'displayName' | 'username' | 'avatarUrl' | 'avatarStorageKey' | 'isSuperAdmin' | 'isVerified' | 'verificationIcon' | 'status' | 'passwordHash'>): Promise<PublicUser> {
const access = await this.access.getUserAccess(user.id, user.isSuperAdmin); const access = await this.access.getUserAccess(user.id, user.isSuperAdmin);
return { return {
id: user.id, id: user.id,
@@ -778,6 +779,8 @@ export class AuthService {
avatarUrl: user.avatarUrl, avatarUrl: user.avatarUrl,
hasAvatar: Boolean(user.avatarStorageKey || user.avatarUrl), hasAvatar: Boolean(user.avatarStorageKey || user.avatarUrl),
isSuperAdmin: user.isSuperAdmin, isSuperAdmin: user.isSuperAdmin,
isVerified: user.isVerified,
verificationIcon: user.isVerified ? resolveVerificationIcon(user.verificationIcon) : undefined,
status: user.status, status: user.status,
hasPassword: Boolean(user.passwordHash), hasPassword: Boolean(user.passwordHash),
roles: access.roles, roles: access.roles,
@@ -791,7 +794,8 @@ export class AuthService {
canManageAllUsers: access.canManageAllUsers, canManageAllUsers: access.canManageAllUsers,
canManageSettings: access.canManageSettings, canManageSettings: access.canManageSettings,
canViewUsers: access.canViewUsers, canViewUsers: access.canViewUsers,
canViewUserDocuments: access.canViewUserDocuments canViewUserDocuments: access.canViewUserDocuments,
canVerifyUsers: access.canVerifyUsers
}; };
} }

View File

@@ -1,5 +1,6 @@
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common'; import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../infra/prisma.service'; import { PrismaService } from '../infra/prisma.service';
import { resolveVerificationIcon } from './verification.constants';
import { FamilyService } from './family.service'; import { FamilyService } from './family.service';
import { NotificationsService } from './notifications.service'; import { NotificationsService } from './notifications.service';
@@ -467,7 +468,7 @@ export class ChatService {
id: string; id: string;
userId: string; userId: string;
notificationsMuted: boolean; notificationsMuted: boolean;
user: { displayName: string; avatarStorageKey: string | null }; user: { displayName: string; avatarStorageKey: string | null; isVerified: boolean; verificationIcon: string | null };
}>; }>;
}, },
familyRoleByUserId: Map<string, string>, familyRoleByUserId: Map<string, string>,
@@ -486,6 +487,8 @@ export class ChatService {
userId: member.userId, userId: member.userId,
displayName: member.user.displayName, displayName: member.user.displayName,
hasAvatar: Boolean(member.user.avatarStorageKey), hasAvatar: Boolean(member.user.avatarStorageKey),
isVerified: member.user.isVerified,
verificationIcon: member.user.isVerified ? resolveVerificationIcon(member.user.verificationIcon) : undefined,
notificationsMuted: member.notificationsMuted, notificationsMuted: member.notificationsMuted,
familyRole: familyRoleByUserId.get(member.userId) ?? 'member', familyRole: familyRoleByUserId.get(member.userId) ?? 'member',
isChatCreator: room.createdById === member.userId isChatCreator: room.createdById === member.userId
@@ -594,7 +597,7 @@ export class ChatService {
createdAt: Date; createdAt: Date;
editedAt?: Date | null; editedAt?: Date | null;
deletedAt?: Date | null; deletedAt?: Date | null;
sender: { displayName: string; avatarStorageKey: string | null }; sender: { displayName: string; avatarStorageKey: string | null; isVerified: boolean; verificationIcon: string | null };
poll?: { poll?: {
id: string; id: string;
question: string; question: string;
@@ -621,6 +624,8 @@ export class ChatService {
senderId: message.senderId, senderId: message.senderId,
senderName: message.sender.displayName, senderName: message.sender.displayName,
senderHasAvatar: Boolean(message.sender.avatarStorageKey), senderHasAvatar: Boolean(message.sender.avatarStorageKey),
senderIsVerified: message.sender.isVerified,
senderVerificationIcon: message.sender.isVerified ? resolveVerificationIcon(message.sender.verificationIcon) : undefined,
type: message.type, type: message.type,
content: isDeleted ? undefined : message.content ?? undefined, content: isDeleted ? undefined : message.content ?? undefined,
replyToId: message.replyToId ?? undefined, replyToId: message.replyToId ?? undefined,

View File

@@ -52,6 +52,9 @@ export interface PublicUser {
canViewUsers?: boolean; canViewUsers?: boolean;
canViewUserDocuments?: boolean; canViewUserDocuments?: boolean;
hasPassword?: boolean; hasPassword?: boolean;
isVerified?: boolean;
verificationIcon?: string;
canVerifyUsers?: boolean;
} }
export interface VerifyPinCommand { export interface VerifyPinCommand {

View File

@@ -1,6 +1,7 @@
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common'; import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../infra/prisma.service'; import { PrismaService } from '../infra/prisma.service';
import { resolveVerificationIcon } from './verification.constants';
import { SettingsService } from './settings.service'; import { SettingsService } from './settings.service';
@@ -496,7 +497,9 @@ export class FamilyService {
email: true, email: true,
phone: true, phone: true,
username: true, username: true,
avatarStorageKey: true avatarStorageKey: true,
isVerified: true,
verificationIcon: true
} }
}); });
@@ -507,7 +510,9 @@ export class FamilyService {
email: user.email, email: user.email,
phone: user.phone, phone: user.phone,
username: user.username, username: user.username,
hasAvatar: Boolean(user.avatarStorageKey) hasAvatar: Boolean(user.avatarStorageKey),
isVerified: user.isVerified,
verificationIcon: user.isVerified ? resolveVerificationIcon(user.verificationIcon) : undefined
})) }))
}; };
} }
@@ -800,7 +805,7 @@ export class FamilyService {
createdAt: Date; createdAt: Date;
user?: { displayName: string; avatarStorageKey: string | null }; user?: { displayName: string; avatarStorageKey: string | null; isVerified: boolean; verificationIcon: string | null };
}>; }>;
@@ -840,7 +845,7 @@ export class FamilyService {
createdAt: Date; createdAt: Date;
user?: { displayName: string; avatarStorageKey: string | null }; user?: { displayName: string; avatarStorageKey: string | null; isVerified: boolean; verificationIcon: string | null };
}) { }) {
@@ -858,6 +863,10 @@ export class FamilyService {
hasAvatar: Boolean(member.user?.avatarStorageKey), hasAvatar: Boolean(member.user?.avatarStorageKey),
isVerified: member.user?.isVerified ?? false,
verificationIcon: member.user?.isVerified ? resolveVerificationIcon(member.user?.verificationIcon) : undefined,
createdAt: member.createdAt.toISOString() createdAt: member.createdAt.toISOString()
}; };

View File

@@ -0,0 +1,25 @@
export const DEFAULT_VERIFICATION_ICON = 'badge-check';
export const VERIFICATION_ICONS = [
{ slug: 'badge-check', name: 'Галочка' },
{ slug: 'star', name: 'Звезда' },
{ slug: 'sparkles', name: 'Искры' },
{ slug: 'moon', name: 'Луна' },
{ slug: 'sun', name: 'Солнце' },
{ slug: 'crown', name: 'Корона' },
{ slug: 'gem', name: 'Драгоценность' },
{ slug: 'heart', name: 'Сердце' },
{ slug: 'award', name: 'Награда' },
{ slug: 'shield-check', name: 'Щит' }
] as const;
export type VerificationIconSlug = (typeof VERIFICATION_ICONS)[number]['slug'];
export function isAllowedVerificationIcon(slug: string | null | undefined): slug is VerificationIconSlug {
if (!slug) return false;
return VERIFICATION_ICONS.some((icon) => icon.slug === slug);
}
export function resolveVerificationIcon(slug: string | null | undefined): VerificationIconSlug {
return isAllowedVerificationIcon(slug) ? slug : DEFAULT_VERIFICATION_ICON;
}

View File

@@ -8,8 +8,12 @@ service AdminService {
rpc ResetPassword (ResetPasswordRequest) returns (AdminUser); rpc ResetPassword (ResetPasswordRequest) returns (AdminUser);
rpc SuspendUser (UserIdRequest) returns (AdminUser); rpc SuspendUser (UserIdRequest) returns (AdminUser);
rpc SetSuperAdmin (SetSuperAdminRequest) returns (AdminUser); rpc SetSuperAdmin (SetSuperAdminRequest) returns (AdminUser);
rpc SetUserVerification (SetUserVerificationRequest) returns (AdminUser);
rpc ListVerificationIcons (Empty) returns (ListVerificationIconsResponse);
} }
message Empty {}
message ListUsersRequest { message ListUsersRequest {
optional string search = 1; optional string search = 1;
} }
@@ -39,6 +43,22 @@ message SetSuperAdminRequest {
bool isSuperAdmin = 3; bool isSuperAdmin = 3;
} }
message SetUserVerificationRequest {
string actorUserId = 1;
string userId = 2;
bool isVerified = 3;
optional string verificationIcon = 4;
}
message VerificationIconOption {
string slug = 1;
string name = 2;
}
message ListVerificationIconsResponse {
repeated VerificationIconOption icons = 1;
}
message AdminUser { message AdminUser {
string id = 1; string id = 1;
optional string email = 2; optional string email = 2;
@@ -52,6 +72,8 @@ message AdminUser {
string createdAt = 10; string createdAt = 10;
repeated string roles = 11; repeated string roles = 11;
repeated string directPermissions = 12; repeated string directPermissions = 12;
bool isVerified = 13;
optional string verificationIcon = 14;
} }
message ListUsersResponse { message ListUsersResponse {

View File

@@ -189,6 +189,9 @@ message PublicUser {
bool canViewOAuth = 22; bool canViewOAuth = 22;
bool canManageAllOAuth = 23; bool canManageAllOAuth = 23;
bool canManageAllUsers = 24; bool canManageAllUsers = 24;
bool isVerified = 25;
optional string verificationIcon = 26;
bool canVerifyUsers = 27;
} }
message AuthTokens { message AuthTokens {

View File

@@ -147,6 +147,8 @@ message ChatMessageResponse {
string senderId = 3; string senderId = 3;
string senderName = 4; string senderName = 4;
bool senderHasAvatar = 5; bool senderHasAvatar = 5;
bool senderIsVerified = 17;
optional string senderVerificationIcon = 18;
string type = 6; string type = 6;
optional string content = 7; optional string content = 7;
optional string replyToId = 8; optional string replyToId = 8;

View File

@@ -252,6 +252,8 @@ message FamilyMemberResponse {
string displayName = 5; string displayName = 5;
bool hasAvatar = 6; bool hasAvatar = 6;
string createdAt = 7; string createdAt = 7;
bool isVerified = 8;
optional string verificationIcon = 9;
} }
message FamilyGroupResponse { message FamilyGroupResponse {