'use client' import { useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' import Modal from '@/app/components/base/modal' import Button from '@/app/components/base/button' import Checkbox from '@/app/components/base/checkbox' import Loading from '@/app/components/base/loading' import { fetchDownloadPermission, updateDownloadPermission } from '@/service/datasets' import { useToastContext } from '@/app/components/base/toast' type User = { id: string name: string email: string has_permission: boolean } type PermissionModalProps = { datasetId: string documentId: string documentName: string onClose: () => void } const PermissionModal = ({ datasetId, documentId, documentName, onClose, }: PermissionModalProps) => { const { t } = useTranslation() const { notify } = useToastContext() const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [isRestricted, setIsRestricted] = useState(false) const [users, setUsers] = useState([]) // Load permission configuration useEffect(() => { loadPermission() }, []) const loadPermission = async () => { try { const data = await fetchDownloadPermission(datasetId, documentId) setIsRestricted(data.is_restricted) setUsers(data.users) } catch (error) { notify({ type: 'error', message: t('common.actionMsg.loadFailed') }) } finally { setLoading(false) } } const handleSave = async () => { setSaving(true) try { // If not restricted, pass empty array; otherwise pass selected user IDs const userIds = isRestricted ? users.filter(u => u.has_permission).map(u => u.id) : [] await updateDownloadPermission(datasetId, documentId, { is_restricted: isRestricted, user_ids: userIds, }) notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') }) onClose() } catch (error) { notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') }) } finally { setSaving(false) } } const toggleUser = (userId: string) => { setUsers(users.map(u => u.id === userId ? { ...u, has_permission: !u.has_permission } : u, )) } const selectAll = () => { setUsers(users.map(u => ({ ...u, has_permission: true }))) } const deselectAll = () => { setUsers(users.map(u => ({ ...u, has_permission: false }))) } const selectedCount = users.filter(u => u.has_permission).length return (
{t('dataset.downloadPermission.title')}
{documentName}
} className="w-[600px]" > {loading ? (
) : ( <>
{/* Enable restriction toggle */}
{t('dataset.downloadPermission.enableRestriction')}
{t('dataset.downloadPermission.enableRestrictionDesc')}
setIsRestricted(!isRestricted)} />
{/* User list */} {isRestricted && (
{t('dataset.downloadPermission.selectUsers')}
|
{users.length === 0 ? (
{t('dataset.downloadPermission.noUsers')}
) : (
{users.map(user => ( ))}
)}
{users.length > 0 && (
{t('dataset.downloadPermission.selectedCount', { count: selectedCount, total: users.length, })}
)}
)}
{/* Footer buttons */}
)}
) } export default PermissionModal