mirror of
https://github.com/rzmk/learnhouse.git
synced 2025-12-19 04:19:25 +00:00
feat: Improve the contributors admin UX/UI
This commit is contained in:
parent
77aec2cf92
commit
c0c32f9564
8 changed files with 899 additions and 50 deletions
|
|
@ -1,10 +1,12 @@
|
|||
import { useCourse, useCourseDispatch } from '@components/Contexts/CourseContext'
|
||||
import { useLHSession } from '@components/Contexts/LHSessionContext'
|
||||
import { useOrg } from '@components/Contexts/OrgContext'
|
||||
import ConfirmationModal from '@components/Objects/StyledElements/ConfirmationModal/ConfirmationModal'
|
||||
import { getAPIUrl } from '@services/config/config'
|
||||
import { editContributor, getCourseContributors } from '@services/courses/courses'
|
||||
import { bulkAddContributors, bulkRemoveContributors, editContributor, getCourseContributors } from '@services/courses/courses'
|
||||
import { searchOrgContent } from '@services/search/search'
|
||||
import { swrFetcher } from '@services/utils/ts/requests'
|
||||
import { Check, ChevronDown, UserPen, Users } from 'lucide-react'
|
||||
import { Check, ChevronDown, Search, UserPen, Users } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import toast from 'react-hot-toast'
|
||||
import useSWR, { mutate } from 'swr'
|
||||
|
|
@ -24,6 +26,9 @@ import {
|
|||
} from "@/components/ui/table"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import UserAvatar from '@components/Objects/UserAvatar'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { useDebounce } from '@/hooks/useDebounce'
|
||||
import { getUserAvatarMediaDirectory } from '@services/media/media'
|
||||
|
||||
type EditCourseContributorsProps = {
|
||||
orgslug: string
|
||||
|
|
@ -33,26 +38,58 @@ type EditCourseContributorsProps = {
|
|||
type ContributorRole = 'CREATOR' | 'CONTRIBUTOR' | 'MAINTAINER' | 'REPORTER'
|
||||
type ContributorStatus = 'ACTIVE' | 'INACTIVE' | 'PENDING'
|
||||
|
||||
interface SearchUser {
|
||||
username: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
avatar_image: string;
|
||||
avatar_url?: string;
|
||||
id: number;
|
||||
user_uuid: string;
|
||||
}
|
||||
|
||||
interface Contributor {
|
||||
id: string;
|
||||
user_id: string;
|
||||
authorship: ContributorRole;
|
||||
authorship_status: ContributorStatus;
|
||||
creation_date: string;
|
||||
user: {
|
||||
username: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
avatar_image: string;
|
||||
user_uuid: string;
|
||||
}
|
||||
}
|
||||
|
||||
interface BulkAddResponse {
|
||||
successful: string[];
|
||||
failed: {
|
||||
username: string;
|
||||
reason: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
// Helper function for date formatting
|
||||
const formatDate = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
};
|
||||
|
||||
function EditCourseContributors(props: EditCourseContributorsProps) {
|
||||
const session = useLHSession() as any;
|
||||
const access_token = session?.data?.tokens?.access_token;
|
||||
const course = useCourse() as any;
|
||||
const { isLoading, courseStructure } = course as any;
|
||||
const dispatchCourse = useCourseDispatch() as any;
|
||||
const org = useOrg() as any;
|
||||
|
||||
const { data: contributors } = useSWR<Contributor[]>(
|
||||
courseStructure ? `${getAPIUrl()}courses/${courseStructure.course_uuid}/contributors` : null,
|
||||
|
|
@ -60,6 +97,13 @@ function EditCourseContributors(props: EditCourseContributorsProps) {
|
|||
);
|
||||
|
||||
const [isOpenToContributors, setIsOpenToContributors] = useState<boolean | undefined>(undefined);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [searchResults, setSearchResults] = useState<SearchUser[]>([]);
|
||||
const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
|
||||
const [isSearching, setIsSearching] = useState(false);
|
||||
const debouncedSearch = useDebounce(searchQuery, 300);
|
||||
const [selectedContributors, setSelectedContributors] = useState<string[]>([]);
|
||||
const [masterCheckboxChecked, setMasterCheckboxChecked] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && courseStructure?.open_to_contributors !== undefined) {
|
||||
|
|
@ -80,6 +124,95 @@ function EditCourseContributors(props: EditCourseContributorsProps) {
|
|||
}
|
||||
}, [isLoading, isOpenToContributors, courseStructure, dispatchCourse]);
|
||||
|
||||
useEffect(() => {
|
||||
const searchUsers = async () => {
|
||||
if (debouncedSearch.trim().length === 0) {
|
||||
setSearchResults([]);
|
||||
setIsSearching(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSearching(true);
|
||||
try {
|
||||
const response = await searchOrgContent(
|
||||
org?.slug,
|
||||
debouncedSearch,
|
||||
1,
|
||||
5,
|
||||
null,
|
||||
access_token
|
||||
);
|
||||
|
||||
if (response.success && response.data?.users) {
|
||||
const users = response.data.users.map((user: SearchUser) => ({
|
||||
...user,
|
||||
avatar_url: user.avatar_image ? getUserAvatarMediaDirectory(user.user_uuid, user.avatar_image) : ''
|
||||
}));
|
||||
setSearchResults(users);
|
||||
} else {
|
||||
setSearchResults([]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error searching users:', error);
|
||||
setSearchResults([]);
|
||||
}
|
||||
setIsSearching(false);
|
||||
};
|
||||
|
||||
if (org?.slug && access_token) {
|
||||
searchUsers();
|
||||
}
|
||||
}, [debouncedSearch, org?.slug, access_token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (contributors) {
|
||||
const nonCreatorContributors = contributors.filter(c => c.authorship !== 'CREATOR');
|
||||
setMasterCheckboxChecked(
|
||||
nonCreatorContributors.length > 0 &&
|
||||
selectedContributors.length === nonCreatorContributors.length
|
||||
);
|
||||
}
|
||||
}, [contributors, selectedContributors]);
|
||||
|
||||
const handleUserSelect = (username: string) => {
|
||||
setSelectedUsers(prev => {
|
||||
if (prev.includes(username)) {
|
||||
return prev.filter(u => u !== username);
|
||||
}
|
||||
return [...prev, username];
|
||||
});
|
||||
};
|
||||
|
||||
const handleAddContributors = async () => {
|
||||
if (selectedUsers.length === 0) return;
|
||||
|
||||
try {
|
||||
const response = await bulkAddContributors(courseStructure.course_uuid, selectedUsers, access_token);
|
||||
if (response.status === 200) {
|
||||
const result = response.data as BulkAddResponse;
|
||||
|
||||
// Show success message for successful adds
|
||||
if (result.successful.length > 0) {
|
||||
toast.success(`Successfully added ${result.successful.length} contributor(s)`);
|
||||
}
|
||||
|
||||
// Show error messages for failed adds
|
||||
result.failed.forEach(failure => {
|
||||
toast.error(`Failed to add ${failure.username}: ${failure.reason}`);
|
||||
});
|
||||
|
||||
// Refresh contributors list
|
||||
mutate(`${getAPIUrl()}courses/${courseStructure.course_uuid}/contributors`);
|
||||
// Clear selection and search
|
||||
setSelectedUsers([]);
|
||||
setSearchQuery('');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error adding contributors:', error);
|
||||
toast.error('Failed to add contributors');
|
||||
}
|
||||
};
|
||||
|
||||
const updateContributor = async (contributorId: string, data: { authorship?: ContributorRole; authorship_status?: ContributorStatus }) => {
|
||||
try {
|
||||
// Find the current contributor to get their current values
|
||||
|
|
@ -188,6 +321,45 @@ function EditCourseContributors(props: EditCourseContributorsProps) {
|
|||
return creator ? [creator, ...otherContributors] : otherContributors;
|
||||
};
|
||||
|
||||
const handleContributorSelect = (userId: string) => {
|
||||
setSelectedContributors(prev => {
|
||||
if (prev.includes(userId)) {
|
||||
return prev.filter(id => id !== userId);
|
||||
}
|
||||
return [...prev, userId];
|
||||
});
|
||||
};
|
||||
|
||||
const handleBulkRemove = async () => {
|
||||
if (selectedContributors.length === 0) return;
|
||||
|
||||
try {
|
||||
// Get the usernames from the selected contributors
|
||||
const selectedUsernames = contributors
|
||||
?.filter(c => selectedContributors.includes(c.user_id))
|
||||
.map(c => c.user.username) || [];
|
||||
|
||||
console.log('Sending usernames:', selectedUsernames); // Debug log
|
||||
|
||||
const response = await bulkRemoveContributors(
|
||||
courseStructure.course_uuid,
|
||||
selectedUsernames, // Send as raw array, not stringified
|
||||
access_token
|
||||
);
|
||||
|
||||
if (response.status === 200) {
|
||||
toast.success(`Successfully removed ${selectedContributors.length} contributor(s)`);
|
||||
// Refresh contributors list
|
||||
mutate(`${getAPIUrl()}courses/${courseStructure.course_uuid}/contributors`);
|
||||
// Clear selection
|
||||
setSelectedContributors([]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error removing contributors:', error);
|
||||
toast.error('Failed to remove contributors');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{courseStructure && (
|
||||
|
|
@ -197,7 +369,7 @@ function EditCourseContributors(props: EditCourseContributorsProps) {
|
|||
<div className="flex flex-col bg-gray-50 -space-y-1 px-3 sm:px-5 py-3 rounded-md mb-3">
|
||||
<h1 className="font-bold text-lg sm:text-xl text-gray-800">Course Contributors</h1>
|
||||
<h2 className="text-gray-500 text-xs sm:text-sm">
|
||||
Choose if you want your course to be open for contributors and manage existing contributors
|
||||
Manage contributors and add new ones to your course
|
||||
</h2>
|
||||
</div>
|
||||
<div className="flex flex-col sm:flex-row sm:space-x-2 space-y-2 sm:space-y-0 mx-auto mb-3">
|
||||
|
|
@ -252,51 +424,234 @@ function EditCourseContributors(props: EditCourseContributorsProps) {
|
|||
status="info"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col bg-gray-50 -space-y-1 px-3 sm:px-5 py-3 rounded-md mb-3">
|
||||
<h1 className="font-bold text-lg sm:text-xl text-gray-800">Current Contributors</h1>
|
||||
<h2 className="text-gray-500 text-xs sm:text-sm">
|
||||
Manage the current contributors of this course
|
||||
</h2>
|
||||
</div>
|
||||
<div className="max-h-[600px] overflow-y-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[50px]"></TableHead>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Role</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{sortContributors(contributors)?.map((contributor) => (
|
||||
<TableRow key={contributor.id}>
|
||||
<TableCell>
|
||||
<UserAvatar
|
||||
width={30}
|
||||
border='border-2'
|
||||
avatar_url={contributor.user.avatar_image}
|
||||
rounded="rounded"
|
||||
predefined_avatar={contributor.user.avatar_image === '' ? 'empty' : undefined}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">
|
||||
{contributor.user.first_name} {contributor.user.last_name}
|
||||
</TableCell>
|
||||
<TableCell className="text-gray-500">
|
||||
{contributor.user.email}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<RoleDropdown contributor={contributor} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<StatusDropdown contributor={contributor} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div className="space-y-4">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search users by name or username to add as contributors..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
{searchQuery && (
|
||||
<div className="bg-white rounded-xl nice-shadow divide-y">
|
||||
{isSearching ? (
|
||||
<div className="p-4 text-center text-sm text-gray-500">
|
||||
Searching...
|
||||
</div>
|
||||
) : searchResults && searchResults.length > 0 ? (
|
||||
<>
|
||||
{selectedUsers.length > 0 && (
|
||||
<div className="p-3 bg-gray-100">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-gray-700">
|
||||
{selectedUsers.length} user{selectedUsers.length > 1 ? 's' : ''} selected
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={() => setSelectedUsers([])}
|
||||
variant="outline"
|
||||
className="text-sm"
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleAddContributors}
|
||||
className="bg-gray-900 text-white hover:bg-gray-800 text-sm"
|
||||
>
|
||||
Add Selected
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{searchResults.map((user) => {
|
||||
const isSelected = selectedUsers.includes(user.username);
|
||||
const isExistingContributor = contributors?.some(
|
||||
c => c.user.username === user.username
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={user.username}
|
||||
className={`flex items-center justify-between p-4 ${
|
||||
isSelected ? 'bg-gray-100' : ''
|
||||
} ${!isExistingContributor ? 'cursor-pointer hover:bg-gray-50' : ''} transition-colors`}
|
||||
onClick={(e) => {
|
||||
// Don't handle click if it's on a checkbox
|
||||
if (e.target instanceof HTMLElement && e.target.closest('input[type="checkbox"]')) {
|
||||
return;
|
||||
}
|
||||
if (!isExistingContributor) {
|
||||
handleUserSelect(user.username);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<div onClick={(e) => e.stopPropagation()}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isSelected || false}
|
||||
onChange={() => !isExistingContributor && handleUserSelect(user.username)}
|
||||
disabled={isExistingContributor}
|
||||
className="h-4 w-4 rounded border-gray-300 text-gray-600 focus:ring-gray-500 disabled:opacity-50"
|
||||
/>
|
||||
</div>
|
||||
<UserAvatar
|
||||
width={40}
|
||||
avatar_url={user.avatar_url}
|
||||
predefined_avatar={user.avatar_image ? undefined : 'empty'}
|
||||
userId={user.id.toString()}
|
||||
showProfilePopup
|
||||
rounded="rounded-full"
|
||||
backgroundColor="bg-gray-100"
|
||||
/>
|
||||
<div>
|
||||
<div className="font-medium text-gray-900">
|
||||
{user.first_name} {user.last_name}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500">
|
||||
@{user.username}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{isExistingContributor && (
|
||||
<span className="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded">
|
||||
Already a contributor
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
) : (
|
||||
<div className="p-4 text-center text-sm text-gray-500">
|
||||
No users found
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="bg-white rounded-xl nice-shadow">
|
||||
{selectedContributors.length > 0 && (
|
||||
<div className="p-3 bg-gray-100 rounded-t-xl border-b">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-gray-700">
|
||||
{selectedContributors.length} contributor{selectedContributors.length > 1 ? 's' : ''} selected
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={() => setSelectedContributors([])}
|
||||
variant="outline"
|
||||
className="text-sm"
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleBulkRemove}
|
||||
className="bg-red-600 text-white hover:bg-red-700 text-sm"
|
||||
>
|
||||
Remove Selected
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="max-h-[600px] overflow-y-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[30px]">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={masterCheckboxChecked}
|
||||
onChange={(e) => {
|
||||
setMasterCheckboxChecked(e.target.checked);
|
||||
if (contributors) {
|
||||
if (e.target.checked) {
|
||||
// Select all non-creator contributors
|
||||
const nonCreatorContributors = contributors
|
||||
.filter(c => c.authorship !== 'CREATOR')
|
||||
.map(c => c.user_id);
|
||||
setSelectedContributors(nonCreatorContributors);
|
||||
} else {
|
||||
setSelectedContributors([]);
|
||||
}
|
||||
}
|
||||
}}
|
||||
className="h-4 w-4 rounded border-gray-300 text-gray-600 focus:ring-gray-500"
|
||||
/>
|
||||
</TableHead>
|
||||
<TableHead className="w-[50px]"></TableHead>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Username</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Role</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Added On</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{sortContributors(contributors)?.map((contributor) => (
|
||||
<TableRow
|
||||
key={`${contributor.user_id}-${contributor.id}`}
|
||||
className={`${selectedContributors.includes(contributor.user_id) ? 'bg-gray-50' : ''} ${contributor.authorship !== 'CREATOR' ? 'cursor-pointer hover:bg-gray-50' : ''}`}
|
||||
onClick={(e) => {
|
||||
// Don't handle click if it's on a dropdown or checkbox
|
||||
if (
|
||||
e.target instanceof HTMLElement &&
|
||||
(e.target.closest('button') ||
|
||||
e.target.closest('input[type="checkbox"]'))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (contributor.authorship !== 'CREATOR') {
|
||||
handleContributorSelect(contributor.user_id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<TableCell onClick={(e) => e.stopPropagation()}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedContributors.includes(contributor.user_id)}
|
||||
onChange={() => handleContributorSelect(contributor.user_id)}
|
||||
disabled={contributor.authorship === 'CREATOR'}
|
||||
className="h-4 w-4 rounded border-gray-300 text-gray-600 focus:ring-gray-500 disabled:opacity-50"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<UserAvatar
|
||||
width={30}
|
||||
border='border-2'
|
||||
avatar_url={contributor.user.avatar_image ? getUserAvatarMediaDirectory(contributor.user.user_uuid, contributor.user.avatar_image) : ''}
|
||||
rounded="rounded"
|
||||
predefined_avatar={contributor.user.avatar_image === '' ? 'empty' : undefined}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">
|
||||
{contributor.user.first_name} {contributor.user.last_name}
|
||||
</TableCell>
|
||||
<TableCell className="text-gray-500">
|
||||
@{contributor.user.username}
|
||||
</TableCell>
|
||||
<TableCell className="text-gray-500">
|
||||
{contributor.user.email}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<RoleDropdown contributor={contributor} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<StatusDropdown contributor={contributor} />
|
||||
</TableCell>
|
||||
<TableCell className="text-gray-500 text-sm">
|
||||
{formatDate(contributor.creation_date)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue