fix and update
This commit is contained in:
@@ -3,7 +3,7 @@ import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiTags } from '@nestjs
|
||||
import { map } from 'rxjs';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
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';
|
||||
|
||||
@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')
|
||||
@ApiOperation({ summary: 'Обновить профиль пользователя', description: 'Обновляет основные и резервные контакты пользователя.' })
|
||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||
@@ -66,4 +75,20 @@ export class AdminController {
|
||||
setSuperAdmin(@Param('userId') userId: string, @Body() dto: SetSuperAdminDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||
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
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,3 +58,14 @@ export class SetSuperAdminDto {
|
||||
@IsBoolean({ message: '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;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ export interface AdminRequestUser {
|
||||
canManageAllUsers: boolean;
|
||||
canViewUsers: boolean;
|
||||
canManageSettings: boolean;
|
||||
canVerifyUsers: boolean;
|
||||
roles: string[];
|
||||
permissions: string[];
|
||||
}
|
||||
@@ -58,6 +59,7 @@ export class AdminGuard implements CanActivate {
|
||||
canManageAllUsers: Boolean(profile.canManageAllUsers),
|
||||
canManageSettings: Boolean(profile.canManageSettings),
|
||||
canViewUsers: Boolean(profile.canViewUsers),
|
||||
canVerifyUsers: Boolean(profile.canVerifyUsers),
|
||||
roles: profile.roles ?? [],
|
||||
permissions: profile.permissions ?? []
|
||||
};
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
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 { AdminShell } from '@/components/id/admin-shell';
|
||||
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 { AdminPermission, AdminRole, AdminUser, apiFetch } from '@/lib/api';
|
||||
import { getAdminLandingPath } from '@/lib/admin-access';
|
||||
import { DEFAULT_VERIFICATION_ICON, VERIFICATION_ICON_OPTIONS } from '@/lib/verification-icons';
|
||||
|
||||
const statusLabels: Record<string, string> = {
|
||||
ACTIVE: 'Активен',
|
||||
@@ -42,8 +44,9 @@ export default function AdminUsersPage() {
|
||||
const [selectedUser, setSelectedUser] = useState<AdminUser | null>(null);
|
||||
const [password, setPassword] = useState('');
|
||||
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 [verificationIcon, setVerificationIcon] = useState(DEFAULT_VERIFICATION_ICON);
|
||||
|
||||
const loadUsers = useCallback(async () => {
|
||||
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) {
|
||||
const userRoles = user.roles ?? [];
|
||||
const extraRoles = userRoles.filter((role) => role !== DEFAULT_USER_ROLE);
|
||||
@@ -271,7 +321,10 @@ export default function AdminUsersPage() {
|
||||
{users.map((user) => (
|
||||
<TableRow key={user.id}>
|
||||
<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>
|
||||
</TableCell>
|
||||
<TableCell>{user.phone ?? '—'}</TableCell>
|
||||
@@ -315,6 +368,17 @@ export default function AdminUsersPage() {
|
||||
<FileText className="h-4 w-4" />
|
||||
</Button>
|
||||
) : 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 ? (
|
||||
<>
|
||||
<Button
|
||||
@@ -432,6 +496,49 @@ export default function AdminUsersPage() {
|
||||
</DialogContent>
|
||||
</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 ? (
|
||||
<UserDocumentsDialog
|
||||
open={Boolean(documentsUser)}
|
||||
|
||||
@@ -235,7 +235,17 @@ export default function DataPage() {
|
||||
<IdShell active="/data">
|
||||
<div className="mb-8 flex items-center gap-4 rounded-[24px] border border-[#20212b] p-4">
|
||||
{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" />
|
||||
)}
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
'use client';
|
||||
|
||||
import { use } from 'react';
|
||||
import { IdShell } from '@/components/id/shell';
|
||||
import { use, useEffect } from 'react';
|
||||
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 }> }) {
|
||||
const { groupId } = use(params);
|
||||
const { setSelectedGroupId } = useFamilyOverlay();
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedGroupId(groupId);
|
||||
}, [groupId, setSelectedGroupId]);
|
||||
|
||||
return (
|
||||
<IdShell active="/family" wide>
|
||||
<FamilyGroupView groupId={groupId} />
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { useRequireAuth } from '@/hooks/use-require-auth';
|
||||
import { apiFetch, FamilyGroup, fetchFamilyGroups, getApiErrorMessage } from '@/lib/api';
|
||||
import { defaultFamilyGroupName } from '@/lib/family-defaults';
|
||||
|
||||
export default function FamilyPage() {
|
||||
const router = useRouter();
|
||||
@@ -17,9 +18,15 @@ export default function FamilyPage() {
|
||||
const { isReady, isPinLocked } = useRequireAuth();
|
||||
const { showToast } = useToast();
|
||||
const [groups, setGroups] = useState<FamilyGroup[]>([]);
|
||||
const [name, setName] = useState('Моя семья');
|
||||
const [name, setName] = useState('');
|
||||
const [creating, setCreating] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (user?.displayName) {
|
||||
setName(defaultFamilyGroupName(user.displayName));
|
||||
}
|
||||
}, [user?.displayName]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user || !token || isPinLocked) return;
|
||||
fetchFamilyGroups(user.id, token)
|
||||
@@ -63,7 +70,7 @@ export default function FamilyPage() {
|
||||
|
||||
<div className="mt-8 flex gap-3">
|
||||
<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" />Создать</>)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { AddressQuickSection } from '@/components/addresses/address-quick-sectio
|
||||
import { DocumentFormDialog } from '@/components/documents/document-form-dialog';
|
||||
import { ActionTile, SectionTitle } from '@/components/id/action-tile';
|
||||
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 { IdShell } from '@/components/id/shell';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -17,7 +17,7 @@ import { apiFetch, UserDocument } from '@/lib/api';
|
||||
|
||||
export default function HomePage() {
|
||||
const router = useRouter();
|
||||
const { user, token, refreshProfile, isPinLocked } = useAuth();
|
||||
const { user, token, isPinLocked } = useAuth();
|
||||
const { isReady } = useRequireAuth();
|
||||
const contactLine = [user?.phone, user?.username ?? user?.email].filter(Boolean).join(' · ');
|
||||
const [documents, setDocuments] = useState<UserDocument[]>([]);
|
||||
@@ -55,12 +55,15 @@ export default function HomePage() {
|
||||
<IdShell active="/" wide>
|
||||
<div className="flex flex-col items-center">
|
||||
{user ? (
|
||||
<AvatarUpload
|
||||
<AvatarDisplay
|
||||
userId={user.id}
|
||||
displayName={user.displayName}
|
||||
hasAvatar={user.hasAvatar}
|
||||
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]" />
|
||||
|
||||
55
apps/frontend/components/family/avatar-with-presence.tsx
Normal file
55
apps/frontend/components/family/avatar-with-presence.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
76
apps/frontend/components/family/family-group-selector.tsx
Normal file
76
apps/frontend/components/family/family-group-selector.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -23,7 +23,10 @@ import {
|
||||
Volume2,
|
||||
VolumeX
|
||||
} 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 { UserAvatar } from '@/components/id/user-avatar';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { useRealtime } from '@/components/notifications/realtime-provider';
|
||||
@@ -48,7 +51,6 @@ import {
|
||||
deleteFamilyGroup,
|
||||
editChatMessage,
|
||||
FamilyGroup,
|
||||
FamilyInviteCandidate,
|
||||
FamilyPresenceMember,
|
||||
fetchChatMessages,
|
||||
fetchChatRooms,
|
||||
@@ -58,9 +60,7 @@ import {
|
||||
markChatRoomRead,
|
||||
removeChatRoomMember,
|
||||
removeFamilyMember,
|
||||
searchFamilyInviteUsers,
|
||||
sendChatMessage,
|
||||
sendFamilyInvite,
|
||||
setChatRoomMuted,
|
||||
updateFamilyGroup,
|
||||
uploadMediaObject,
|
||||
@@ -132,18 +132,6 @@ function messagePreview(message?: ChatMessage) {
|
||||
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 }) {
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
@@ -206,10 +194,6 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
const [membersOpen, setMembersOpen] = useState(false);
|
||||
const [familyMembersOpen, setFamilyMembersOpen] = 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 [newRoomName, setNewRoomName] = useState('');
|
||||
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() {
|
||||
if (!token || !newRoomName.trim()) return;
|
||||
try {
|
||||
@@ -941,7 +892,19 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
const isEditing = editingMessageId === message.id;
|
||||
const canEdit = mine && !message.isDeleted && (message.type === 'TEXT' || message.type === 'EMOJI');
|
||||
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
|
||||
className={cn(
|
||||
'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 = '';
|
||||
}} />
|
||||
|
||||
<Dialog open={inviteOpen} onOpenChange={(open) => {
|
||||
setInviteOpen(open);
|
||||
if (!open) {
|
||||
setInviteQuery('');
|
||||
setInviteResults([]);
|
||||
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>
|
||||
<FamilyInviteDialog
|
||||
groupId={groupId}
|
||||
open={inviteOpen}
|
||||
onOpenChange={setInviteOpen}
|
||||
onInvited={() => void loadGroup()}
|
||||
/>
|
||||
|
||||
<Dialog open={familyMembersOpen} onOpenChange={setFamilyMembersOpen}>
|
||||
<DialogContent className="rounded-[28px] sm:max-w-[480px]">
|
||||
@@ -1262,21 +1163,27 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
|
||||
return (
|
||||
<div key={member.id} className="flex items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3">
|
||||
<div className="relative shrink-0">
|
||||
<Avatar className="h-10 w-10">
|
||||
<AvatarFallback>{member.displayName.slice(0, 1)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<OnlineDot online={presence?.online} />
|
||||
</div>
|
||||
<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-10 w-10"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate font-medium">
|
||||
{member.displayName}
|
||||
{isSelf ? <span className="ml-1 text-xs font-normal text-[#667085]">(Вы)</span> : null}
|
||||
</p>
|
||||
<p className="text-xs text-[#667085]">{familyMemberRoleLabel(member.role)}</p>
|
||||
<p className={cn('text-xs', presence?.online ? 'font-medium text-emerald-600' : 'text-[#a8adbc]')}>
|
||||
{presence ? formatPresenceStatus(presence) : 'Статус неизвестен'}
|
||||
</p>
|
||||
{!isSelf ? (
|
||||
<p className={cn('text-xs', presence?.online ? 'font-medium text-emerald-600' : 'text-[#a8adbc]')}>
|
||||
{presence ? formatPresenceStatus(presence) : 'Статус неизвестен'}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
{canRemove ? (
|
||||
<Button
|
||||
@@ -1357,12 +1264,16 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
|
||||
return (
|
||||
<div key={member.id} className="flex items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3">
|
||||
<div className="relative shrink-0">
|
||||
<Avatar className="h-10 w-10">
|
||||
<AvatarFallback>{member.displayName.slice(0, 1)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<OnlineDot online={presence?.online} />
|
||||
</div>
|
||||
<AvatarWithPresence
|
||||
userId={member.userId}
|
||||
displayName={member.displayName}
|
||||
hasAvatar={member.hasAvatar}
|
||||
token={token}
|
||||
isVerified={member.isVerified}
|
||||
verificationIcon={member.verificationIcon}
|
||||
online={presence?.online}
|
||||
className="h-10 w-10"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate font-medium">{member.displayName}</p>
|
||||
<p className="text-xs text-[#667085]">{memberRoleLabel(member)}</p>
|
||||
@@ -1404,22 +1315,32 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
<DialogHeader><DialogTitle>Добавить в чат</DialogTitle></DialogHeader>
|
||||
<div className="space-y-2">
|
||||
{familyMembersNotInRoom.length ? (
|
||||
familyMembersNotInRoom.map((member) => (
|
||||
familyMembersNotInRoom.map((member) => {
|
||||
const presence = presenceByUserId.get(member.userId);
|
||||
return (
|
||||
<button
|
||||
key={member.id}
|
||||
type="button"
|
||||
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)}
|
||||
>
|
||||
<Avatar className="h-9 w-9">
|
||||
<AvatarFallback>{member.displayName.slice(0, 1)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<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>
|
||||
<p className="font-medium">{member.displayName}</p>
|
||||
<p className="text-xs text-[#667085]">{member.role === 'owner' ? 'Создатель семьи' : 'Участник семьи'}</p>
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<p className="py-6 text-center text-sm text-[#667085]">Все участники семьи уже в этом чате</p>
|
||||
)}
|
||||
|
||||
141
apps/frontend/components/family/family-invite-dialog.tsx
Normal file
141
apps/frontend/components/family/family-invite-dialog.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
111
apps/frontend/components/family/family-overlay-provider.tsx
Normal file
111
apps/frontend/components/family/family-overlay-provider.tsx
Normal 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;
|
||||
}
|
||||
130
apps/frontend/components/family/family-sidebar-panel.tsx
Normal file
130
apps/frontend/components/family/family-sidebar-panel.tsx
Normal 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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
394
apps/frontend/components/family/mini-family-chat.tsx
Normal file
394
apps/frontend/components/family/mini-family-chat.tsx
Normal 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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -3,10 +3,11 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { Camera, Loader2 } from 'lucide-react';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { useAvatarUrl } from '@/hooks/use-avatar-url';
|
||||
import { apiFetch, getApiErrorMessage, uploadMediaObject } from '@/lib/api';
|
||||
import { VerificationBadge } from '@/components/id/verification-badge';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface PresignedUploadResponse {
|
||||
uploadUrl: string;
|
||||
@@ -20,13 +21,21 @@ export function AvatarUpload({
|
||||
displayName,
|
||||
hasAvatar,
|
||||
token,
|
||||
onUpdated
|
||||
onUpdated,
|
||||
isVerified,
|
||||
verificationIcon,
|
||||
className = 'h-24 w-24',
|
||||
badgeSize = 'md'
|
||||
}: {
|
||||
userId: string;
|
||||
displayName?: string;
|
||||
hasAvatar?: boolean;
|
||||
token: string | null;
|
||||
onUpdated: () => Promise<void>;
|
||||
isVerified?: boolean;
|
||||
verificationIcon?: string | null;
|
||||
className?: string;
|
||||
badgeSize?: 'xs' | 'sm' | 'md' | 'lg';
|
||||
}) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const { showToast } = useToast();
|
||||
@@ -73,24 +82,45 @@ export function AvatarUpload({
|
||||
}
|
||||
}
|
||||
|
||||
function openFilePicker() {
|
||||
if (isUploading || !token) return;
|
||||
inputRef.current?.click();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative inline-flex">
|
||||
<Avatar className="h-24 w-24 border-4 border-white shadow-xl">
|
||||
{avatarUrl ? <AvatarImage src={avatarUrl} alt={displayName ?? 'Аватар'} /> : null}
|
||||
<AvatarFallback className="bg-[linear-gradient(135deg,#6f58ff,#ffd2a8)] text-2xl">{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<input ref={inputRef} type="file" accept="image/jpeg,image/png,image/webp,image/gif" className="hidden" onChange={handleFileChange} />
|
||||
<Button
|
||||
<div className="relative inline-flex shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="absolute -bottom-2 left-1/2 -translate-x-1/2 rounded-full px-3 shadow"
|
||||
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}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
aria-label="Изменить фото профиля"
|
||||
onClick={openFilePicker}
|
||||
>
|
||||
{isUploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Camera className="h-4 w-4" />}
|
||||
{isUploading ? 'Загрузка...' : 'Фото'}
|
||||
</Button>
|
||||
<Avatar className={cn('border-4 border-white shadow-xl', className)}>
|
||||
{avatarUrl ? <AvatarImage src={avatarUrl} alt={displayName ?? 'Аватар'} /> : null}
|
||||
<AvatarFallback className="bg-[linear-gradient(135deg,#6f58ff,#ffd2a8)] text-2xl">{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<span
|
||||
className={cn(
|
||||
'absolute inset-0 flex items-center justify-center rounded-full transition',
|
||||
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'
|
||||
)}
|
||||
>
|
||||
{isUploading ? (
|
||||
<Loader2 className="h-5 w-5 animate-spin text-white" />
|
||||
) : (
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -100,21 +130,36 @@ export function AvatarDisplay({
|
||||
displayName,
|
||||
hasAvatar,
|
||||
token,
|
||||
className
|
||||
className,
|
||||
isVerified,
|
||||
verificationIcon,
|
||||
badgeSize = 'sm'
|
||||
}: {
|
||||
userId: string;
|
||||
displayName?: string;
|
||||
hasAvatar?: boolean;
|
||||
token: string | null;
|
||||
className?: string;
|
||||
isVerified?: boolean;
|
||||
verificationIcon?: string | null;
|
||||
badgeSize?: 'xs' | 'sm' | 'md' | 'lg';
|
||||
}) {
|
||||
const { avatarUrl } = useAvatarUrl(userId, hasAvatar, token);
|
||||
const initials = (displayName ?? '').slice(0, 2).toUpperCase() || 'ID';
|
||||
|
||||
return (
|
||||
<Avatar className={className}>
|
||||
{avatarUrl ? <AvatarImage src={avatarUrl} alt={displayName ?? 'Аватар'} /> : null}
|
||||
<AvatarFallback className="bg-[linear-gradient(135deg,#6f58ff,#ffd2a8)]">{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="relative inline-flex shrink-0">
|
||||
<Avatar className={className}>
|
||||
{avatarUrl ? <AvatarImage src={avatarUrl} alt={displayName ?? 'Аватар'} /> : null}
|
||||
<AvatarFallback className="bg-[linear-gradient(135deg,#6f58ff,#ffd2a8)]">{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
{isVerified ? (
|
||||
<VerificationBadge
|
||||
verificationIcon={verificationIcon}
|
||||
size={badgeSize}
|
||||
className="absolute -top-0.5 -right-0.5 z-20"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,18 +3,23 @@
|
||||
import { Sidebar } from './sidebar';
|
||||
import { UserMenu } from './user-menu';
|
||||
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 }) {
|
||||
return (
|
||||
<div className="min-h-screen bg-white">
|
||||
<Sidebar active={active} />
|
||||
<div className="fixed right-4 top-4 z-40 flex items-center gap-2 lg:right-8 lg:top-6">
|
||||
<NotificationBell />
|
||||
<UserMenu />
|
||||
<FamilyOverlayProvider>
|
||||
<div className="min-h-screen bg-white">
|
||||
<Sidebar active={active} />
|
||||
<div className="fixed right-4 top-4 z-40 flex items-center gap-2 lg:right-8 lg:top-6">
|
||||
<NotificationBell />
|
||||
<UserMenu />
|
||||
</div>
|
||||
<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>
|
||||
</main>
|
||||
<MiniFamilyChat />
|
||||
</div>
|
||||
<main className="px-5 py-8 lg:pl-[170px] lg:pr-8">
|
||||
<div className={wide ? 'mx-auto max-w-[920px]' : 'mx-auto max-w-[560px]'}>{children}</div>
|
||||
</main>
|
||||
</div>
|
||||
</FamilyOverlayProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import Link from 'next/link';
|
||||
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 { cn } from '@/lib/utils';
|
||||
import { getAdminLandingPath } from '@/lib/admin-access';
|
||||
@@ -22,8 +23,8 @@ export function Sidebar({ active }: { active: string }) {
|
||||
: baseItems;
|
||||
|
||||
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">
|
||||
<div>
|
||||
<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 className="flex min-h-0 flex-1 flex-col">
|
||||
<Link href="/" className="mb-7 block">
|
||||
<BrandLogo size="lg" variant="dark" />
|
||||
</Link>
|
||||
@@ -42,6 +43,9 @@ export function Sidebar({ active }: { active: string }) {
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
<div className="min-h-0 flex-1 overflow-hidden">
|
||||
<FamilySidebarPanel />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 text-[11px] text-[#667085]">
|
||||
{user ? <p className="truncate font-medium text-[#1f2430]">{user.displayName}</p> : null}
|
||||
|
||||
54
apps/frontend/components/id/user-avatar.tsx
Normal file
54
apps/frontend/components/id/user-avatar.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -13,10 +13,9 @@ import {
|
||||
UserRound
|
||||
} from 'lucide-react';
|
||||
import { AdminBadge } from '@/components/id/admin-badge';
|
||||
import { UserAvatar } from '@/components/id/user-avatar';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { useAvatarUrl } from '@/hooks/use-avatar-url';
|
||||
import { getAdminLandingPath } from '@/lib/admin-access';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
@@ -38,17 +37,10 @@ const menuItems = [
|
||||
export function UserMenu({ className }: { className?: string }) {
|
||||
const router = useRouter();
|
||||
const { user, token, logout } = useAuth();
|
||||
const { avatarUrl } = useAvatarUrl(user?.id, user?.hasAvatar, token);
|
||||
|
||||
if (!user) return null;
|
||||
|
||||
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 (
|
||||
<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)}
|
||||
aria-label="Меню пользователя"
|
||||
>
|
||||
<Avatar className="h-9 w-9">
|
||||
{avatarUrl ? <AvatarImage src={avatarUrl} alt={user.displayName} /> : null}
|
||||
<AvatarFallback className="text-xs font-semibold">{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<UserAvatar
|
||||
userId={user.id}
|
||||
displayName={user.displayName}
|
||||
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>
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<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">
|
||||
<Avatar className="mx-auto h-20 w-20">
|
||||
{avatarUrl ? <AvatarImage src={avatarUrl} alt={user.displayName} /> : null}
|
||||
<AvatarFallback className="text-lg font-semibold">{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<UserAvatar
|
||||
userId={user.id}
|
||||
displayName={user.displayName}
|
||||
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">
|
||||
<p className="text-lg font-semibold">{user.displayName}</p>
|
||||
<AdminBadge user={user} />
|
||||
|
||||
42
apps/frontend/components/id/verification-badge.tsx
Normal file
42
apps/frontend/components/id/verification-badge.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
102
apps/frontend/hooks/use-primary-family.ts
Normal file
102
apps/frontend/hooks/use-primary-family.ts
Normal 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);
|
||||
}
|
||||
@@ -79,6 +79,9 @@ export interface PublicUser {
|
||||
canViewUsers?: boolean;
|
||||
canViewUserDocuments?: boolean;
|
||||
hasPassword?: boolean;
|
||||
isVerified?: boolean;
|
||||
verificationIcon?: string | null;
|
||||
canVerifyUsers?: boolean;
|
||||
}
|
||||
|
||||
export interface AdminUser {
|
||||
@@ -92,6 +95,8 @@ export interface AdminUser {
|
||||
createdAt: string;
|
||||
roles: string[];
|
||||
directPermissions?: string[];
|
||||
isVerified?: boolean;
|
||||
verificationIcon?: string | null;
|
||||
}
|
||||
|
||||
export interface AdminRole {
|
||||
@@ -230,6 +235,8 @@ export interface FamilyInviteCandidate {
|
||||
phone?: string | null;
|
||||
username?: string | null;
|
||||
hasAvatar?: boolean;
|
||||
isVerified?: boolean;
|
||||
verificationIcon?: string | null;
|
||||
}
|
||||
|
||||
export async function searchFamilyInviteUsers(groupId: string, query: string, token?: string | null) {
|
||||
@@ -653,6 +660,8 @@ export interface FamilyMember {
|
||||
role: string;
|
||||
displayName: string;
|
||||
hasAvatar: boolean;
|
||||
isVerified?: boolean;
|
||||
verificationIcon?: string | null;
|
||||
}
|
||||
|
||||
export interface FamilyGroup {
|
||||
@@ -699,6 +708,8 @@ export interface ChatMessage {
|
||||
senderId: string;
|
||||
senderName: string;
|
||||
senderHasAvatar: boolean;
|
||||
senderIsVerified?: boolean;
|
||||
senderVerificationIcon?: string | null;
|
||||
type: string;
|
||||
content?: string;
|
||||
replyToId?: string;
|
||||
@@ -735,6 +746,8 @@ export interface ChatRoomMember {
|
||||
userId: string;
|
||||
displayName: string;
|
||||
hasAvatar: boolean;
|
||||
isVerified?: boolean;
|
||||
verificationIcon?: string | null;
|
||||
notificationsMuted: boolean;
|
||||
familyRole?: string;
|
||||
isChatCreator?: boolean;
|
||||
|
||||
30
apps/frontend/lib/family-chat.ts
Normal file
30
apps/frontend/lib/family-chat.ts
Normal 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;
|
||||
}
|
||||
4
apps/frontend/lib/family-defaults.ts
Normal file
4
apps/frontend/lib/family-defaults.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export function defaultFamilyGroupName(displayName: string) {
|
||||
const trimmed = displayName.trim();
|
||||
return trimmed ? `Семья пользователя ${trimmed}` : 'Семья пользователя';
|
||||
}
|
||||
47
apps/frontend/lib/verification-icons.tsx
Normal file
47
apps/frontend/lib/verification-icons.tsx
Normal 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 />;
|
||||
}
|
||||
@@ -49,6 +49,9 @@ model User {
|
||||
birthDate DateTime?
|
||||
gender String?
|
||||
isSuperAdmin Boolean @default(false)
|
||||
isVerified Boolean @default(false)
|
||||
verificationIcon String?
|
||||
verifiedAt DateTime?
|
||||
status UserStatus @default(ACTIVE)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -14,6 +14,7 @@ export interface UserAccessContext {
|
||||
canViewUsers: boolean;
|
||||
canManageSettings: boolean;
|
||||
canViewUserDocuments: boolean;
|
||||
canVerifyUsers: boolean;
|
||||
}
|
||||
|
||||
function hasAnyPermission(permissions: string[], ...slugs: string[]) {
|
||||
@@ -40,7 +41,8 @@ export class AccessService {
|
||||
'users.manage.all',
|
||||
'settings.manage',
|
||||
'rbac.manage',
|
||||
'documents.view_others'
|
||||
'documents.view_others',
|
||||
'users.verify'
|
||||
],
|
||||
canAccessAdmin: true,
|
||||
canManageRoles: true,
|
||||
@@ -51,7 +53,8 @@ export class AccessService {
|
||||
canManageAllUsers: true,
|
||||
canViewUsers: true,
|
||||
canManageSettings: true,
|
||||
canViewUserDocuments: true
|
||||
canViewUserDocuments: true,
|
||||
canVerifyUsers: true
|
||||
};
|
||||
}
|
||||
|
||||
@@ -98,7 +101,8 @@ export class AccessService {
|
||||
canManageAllUsers,
|
||||
canViewUsers,
|
||||
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) {
|
||||
const actor = await this.prisma.user.findUnique({ where: { id: actorUserId } });
|
||||
if (!actor?.isSuperAdmin) {
|
||||
|
||||
@@ -13,6 +13,7 @@ const PERMISSIONS = [
|
||||
{ slug: 'users.view.all', name: 'Просмотр всех пользователей', description: 'Просмотр полного списка пользователей системы' },
|
||||
{ slug: 'users.manage', name: 'Управление пользователями', description: 'Редактирование, блокировка и сброс паролей' },
|
||||
{ slug: 'users.manage.all', name: 'Полное управление пользователями', description: 'Расширенное управление всеми пользователями' },
|
||||
{ slug: 'users.verify', name: 'Верификация пользователей', description: 'Выдача и снятие верификации, выбор значка' },
|
||||
{ slug: 'users.read', name: 'Просмотр пользователей (устар.)', description: 'Устаревшее право, заменено на users.view' },
|
||||
{ slug: 'settings.manage', name: 'Управление настройками', description: 'Изменение глобальных SystemSetting' },
|
||||
{ slug: 'rbac.manage', name: 'Управление ролями и правами', description: 'Назначение ролей, прав пользователям и редактирование ролей' },
|
||||
@@ -32,7 +33,7 @@ const ROLES = [
|
||||
slug: 'admin',
|
||||
name: 'Администратор',
|
||||
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,
|
||||
isDefault: false
|
||||
},
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as bcrypt from 'bcryptjs';
|
||||
import { UserStatus } from '../generated/prisma/client';
|
||||
import { PrismaService } from '../infra/prisma.service';
|
||||
import { AccessService } from './access.service';
|
||||
import { DEFAULT_VERIFICATION_ICON, isAllowedVerificationIcon, VERIFICATION_ICONS } from './verification.constants';
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
@@ -92,6 +93,43 @@ export class AdminService {
|
||||
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) {
|
||||
await this.ensureUserExists(userId);
|
||||
const user = await this.prisma.user.update({
|
||||
@@ -111,6 +149,8 @@ export class AdminService {
|
||||
displayName: string;
|
||||
username: string | null;
|
||||
isSuperAdmin: boolean;
|
||||
isVerified: boolean;
|
||||
verificationIcon: string | null;
|
||||
status: UserStatus;
|
||||
createdAt: Date;
|
||||
userRoles?: { role: { slug: string } }[];
|
||||
@@ -125,6 +165,8 @@ export class AdminService {
|
||||
displayName: user.displayName,
|
||||
username: user.username ?? undefined,
|
||||
isSuperAdmin: user.isSuperAdmin,
|
||||
isVerified: user.isVerified,
|
||||
verificationIcon: user.isVerified ? (user.verificationIcon ?? DEFAULT_VERIFICATION_ICON) : undefined,
|
||||
status: user.status,
|
||||
createdAt: user.createdAt.toISOString(),
|
||||
roles: user.userRoles?.map((link) => link.role.slug) ?? [],
|
||||
|
||||
@@ -157,6 +157,19 @@ export class AuthGrpcController {
|
||||
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')
|
||||
async listRoles() {
|
||||
const roles = await this.rbac.listRoles();
|
||||
|
||||
@@ -16,6 +16,7 @@ import { NotificationsService } from './notifications.service';
|
||||
import { canonicalPhoneE164, phoneLookupVariants } from '../infra/phone.util';
|
||||
import { TotpService } from './totp.service';
|
||||
import { RbacService } from './rbac.service';
|
||||
import { DEFAULT_VERIFICATION_ICON, resolveVerificationIcon } from './verification.constants';
|
||||
|
||||
const FIRST_ADMIN_LOCK = 'locks:first-super-admin';
|
||||
const TOTP_LOGIN_CHALLENGE_TTL_SECONDS = 5 * 60;
|
||||
@@ -765,7 +766,7 @@ export class AuthService {
|
||||
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);
|
||||
return {
|
||||
id: user.id,
|
||||
@@ -778,6 +779,8 @@ export class AuthService {
|
||||
avatarUrl: user.avatarUrl,
|
||||
hasAvatar: Boolean(user.avatarStorageKey || user.avatarUrl),
|
||||
isSuperAdmin: user.isSuperAdmin,
|
||||
isVerified: user.isVerified,
|
||||
verificationIcon: user.isVerified ? resolveVerificationIcon(user.verificationIcon) : undefined,
|
||||
status: user.status,
|
||||
hasPassword: Boolean(user.passwordHash),
|
||||
roles: access.roles,
|
||||
@@ -791,7 +794,8 @@ export class AuthService {
|
||||
canManageAllUsers: access.canManageAllUsers,
|
||||
canManageSettings: access.canManageSettings,
|
||||
canViewUsers: access.canViewUsers,
|
||||
canViewUserDocuments: access.canViewUserDocuments
|
||||
canViewUserDocuments: access.canViewUserDocuments,
|
||||
canVerifyUsers: access.canVerifyUsers
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../infra/prisma.service';
|
||||
import { resolveVerificationIcon } from './verification.constants';
|
||||
import { FamilyService } from './family.service';
|
||||
import { NotificationsService } from './notifications.service';
|
||||
|
||||
@@ -467,7 +468,7 @@ export class ChatService {
|
||||
id: string;
|
||||
userId: string;
|
||||
notificationsMuted: boolean;
|
||||
user: { displayName: string; avatarStorageKey: string | null };
|
||||
user: { displayName: string; avatarStorageKey: string | null; isVerified: boolean; verificationIcon: string | null };
|
||||
}>;
|
||||
},
|
||||
familyRoleByUserId: Map<string, string>,
|
||||
@@ -486,6 +487,8 @@ export class ChatService {
|
||||
userId: member.userId,
|
||||
displayName: member.user.displayName,
|
||||
hasAvatar: Boolean(member.user.avatarStorageKey),
|
||||
isVerified: member.user.isVerified,
|
||||
verificationIcon: member.user.isVerified ? resolveVerificationIcon(member.user.verificationIcon) : undefined,
|
||||
notificationsMuted: member.notificationsMuted,
|
||||
familyRole: familyRoleByUserId.get(member.userId) ?? 'member',
|
||||
isChatCreator: room.createdById === member.userId
|
||||
@@ -594,7 +597,7 @@ export class ChatService {
|
||||
createdAt: Date;
|
||||
editedAt?: Date | null;
|
||||
deletedAt?: Date | null;
|
||||
sender: { displayName: string; avatarStorageKey: string | null };
|
||||
sender: { displayName: string; avatarStorageKey: string | null; isVerified: boolean; verificationIcon: string | null };
|
||||
poll?: {
|
||||
id: string;
|
||||
question: string;
|
||||
@@ -621,6 +624,8 @@ export class ChatService {
|
||||
senderId: message.senderId,
|
||||
senderName: message.sender.displayName,
|
||||
senderHasAvatar: Boolean(message.sender.avatarStorageKey),
|
||||
senderIsVerified: message.sender.isVerified,
|
||||
senderVerificationIcon: message.sender.isVerified ? resolveVerificationIcon(message.sender.verificationIcon) : undefined,
|
||||
type: message.type,
|
||||
content: isDeleted ? undefined : message.content ?? undefined,
|
||||
replyToId: message.replyToId ?? undefined,
|
||||
|
||||
@@ -52,6 +52,9 @@ export interface PublicUser {
|
||||
canViewUsers?: boolean;
|
||||
canViewUserDocuments?: boolean;
|
||||
hasPassword?: boolean;
|
||||
isVerified?: boolean;
|
||||
verificationIcon?: string;
|
||||
canVerifyUsers?: boolean;
|
||||
}
|
||||
|
||||
export interface VerifyPinCommand {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
|
||||
import { PrismaService } from '../infra/prisma.service';
|
||||
import { resolveVerificationIcon } from './verification.constants';
|
||||
|
||||
import { SettingsService } from './settings.service';
|
||||
|
||||
@@ -496,7 +497,9 @@ export class FamilyService {
|
||||
email: true,
|
||||
phone: true,
|
||||
username: true,
|
||||
avatarStorageKey: true
|
||||
avatarStorageKey: true,
|
||||
isVerified: true,
|
||||
verificationIcon: true
|
||||
}
|
||||
});
|
||||
|
||||
@@ -507,7 +510,9 @@ export class FamilyService {
|
||||
email: user.email,
|
||||
phone: user.phone,
|
||||
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;
|
||||
|
||||
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;
|
||||
|
||||
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),
|
||||
|
||||
isVerified: member.user?.isVerified ?? false,
|
||||
|
||||
verificationIcon: member.user?.isVerified ? resolveVerificationIcon(member.user?.verificationIcon) : undefined,
|
||||
|
||||
createdAt: member.createdAt.toISOString()
|
||||
|
||||
};
|
||||
|
||||
25
apps/sso-core/src/domain/verification.constants.ts
Normal file
25
apps/sso-core/src/domain/verification.constants.ts
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user