fix: collections bugs and issues

This commit is contained in:
swve 2025-01-24 22:59:04 +01:00
parent 79a31dd8ec
commit be7b9499f2
4 changed files with 210 additions and 111 deletions

View file

@ -47,15 +47,23 @@ async def get_collection(
# get courses in collection # get courses in collection
statement_all = ( statement_all = (
select(Course) select(Course)
.join(CollectionCourse, Course.id == CollectionCourse.course_id) .join(CollectionCourse)
.where(CollectionCourse.org_id == collection.org_id) .where(
.distinct(Course.id) CollectionCourse.collection_id == collection.id,
CollectionCourse.org_id == collection.org_id
)
.distinct()
) )
statement_public = ( statement_public = (
select(Course) select(Course)
.join(CollectionCourse, Course.id == CollectionCourse.course_id) .join(CollectionCourse)
.where(CollectionCourse.org_id == collection.org_id, Course.public == True) .where(
CollectionCourse.collection_id == collection.id,
CollectionCourse.org_id == collection.org_id,
Course.public == True
)
.distinct()
) )
if current_user.user_uuid == "user_anonymous": if current_user.user_uuid == "user_anonymous":
@ -63,7 +71,7 @@ async def get_collection(
else: else:
statement = statement_all statement = statement_all
courses = db_session.exec(statement).all() courses = list(db_session.exec(statement).all())
collection = CollectionRead(**collection.model_dump(), courses=courses) collection = CollectionRead(**collection.model_dump(), courses=courses)
@ -110,10 +118,11 @@ async def create_collection(
# Get courses once again # Get courses once again
statement = ( statement = (
select(Course) select(Course)
.join(CollectionCourse, Course.id == CollectionCourse.course_id) .join(CollectionCourse)
.distinct(Course.id) .where(CollectionCourse.collection_id == collection.id)
.distinct()
) )
courses = db_session.exec(statement).all() courses = list(db_session.exec(statement).all())
collection = CollectionRead(**collection.model_dump(), courses=courses) collection = CollectionRead(**collection.model_dump(), courses=courses)
@ -183,12 +192,11 @@ async def update_collection(
# Get courses once again # Get courses once again
statement = ( statement = (
select(Course) select(Course)
.join(CollectionCourse, Course.id == CollectionCourse.course_id) .join(CollectionCourse)
.where(Course.org_id == collection.org_id) .where(CollectionCourse.collection_id == collection.id)
.distinct(Course.id) .distinct()
) )
courses = list(db_session.exec(statement).all())
courses = db_session.exec(statement).all()
collection = CollectionRead(**collection.model_dump(), courses=courses) collection = CollectionRead(**collection.model_dump(), courses=courses)
@ -255,14 +263,22 @@ async def get_collections(
for collection in collections: for collection in collections:
statement_all = ( statement_all = (
select(Course) select(Course)
.join(CollectionCourse, Course.id == CollectionCourse.course_id) .join(CollectionCourse)
.where(CollectionCourse.org_id == collection.org_id) .where(
.distinct(Course.id) CollectionCourse.collection_id == collection.id,
CollectionCourse.org_id == collection.org_id
)
.distinct()
) )
statement_public = ( statement_public = (
select(Course) select(Course)
.join(CollectionCourse, Course.id == CollectionCourse.course_id) .join(CollectionCourse)
.where(CollectionCourse.org_id == org_id, Course.public == True) .where(
CollectionCourse.collection_id == collection.id,
CollectionCourse.org_id == org_id,
Course.public == True
)
.distinct()
) )
if current_user.id == 0: if current_user.id == 0:
statement = statement_public statement = statement_public

View file

@ -7,17 +7,22 @@ import { getAPIUrl, getUriWithOrg } from '@services/config/config'
import { revalidateTags, swrFetcher } from '@services/utils/ts/requests' import { revalidateTags, swrFetcher } from '@services/utils/ts/requests'
import { useOrg } from '@components/Contexts/OrgContext' import { useOrg } from '@components/Contexts/OrgContext'
import { useLHSession } from '@components/Contexts/LHSessionContext' import { useLHSession } from '@components/Contexts/LHSessionContext'
import { Loader2, Image as ImageIcon } from 'lucide-react'
import { toast } from 'react-hot-toast'
import Image from 'next/image'
import { getCourseThumbnailMediaDirectory } from '@services/media/media'
function NewCollection(params: any) { function NewCollection(params: any) {
const org = useOrg() as any const org = useOrg() as any
const session = useLHSession() as any; const session = useLHSession() as any
const access_token = session?.data?.tokens?.access_token; const access_token = session?.data?.tokens?.access_token
const orgslug = params.params.orgslug const orgslug = params.params.orgslug
const [name, setName] = React.useState('') const [name, setName] = React.useState('')
const [description, setDescription] = React.useState('') const [description, setDescription] = React.useState('')
const [selectedCourses, setSelectedCourses] = React.useState([]) as any const [selectedCourses, setSelectedCourses] = React.useState([]) as any
const [isSubmitting, setIsSubmitting] = useState(false)
const router = useRouter() const router = useRouter()
const { data: courses, error: error } = useSWR( const { data: courses, error: error, isLoading } = useSWR(
`${getAPIUrl()}courses/org_slug/${orgslug}/page/1/limit/10`, `${getAPIUrl()}courses/org_slug/${orgslug}/page/1/limit/10`,
(url) => swrFetcher(url, access_token) (url) => swrFetcher(url, access_token)
) )
@ -32,111 +37,189 @@ function NewCollection(params: any) {
} }
const handleDescriptionChange = ( const handleDescriptionChange = (
event: React.ChangeEvent<HTMLInputElement> event: React.ChangeEvent<HTMLTextAreaElement>
) => { ) => {
setDescription(event.target.value) setDescription(event.target.value)
} }
const handleSubmit = async (e: any) => { const handleSubmit = async (e: any) => {
e.preventDefault() e.preventDefault()
const collection = { if (!name.trim()) {
name: name, toast.error('Please enter a collection name')
description: description, return
courses: selectedCourses,
public: isPublic,
org_id: org.id,
} }
await createCollection(collection, session.data?.tokens?.access_token)
await revalidateTags(['collections'], org.slug)
// reload the page
router.refresh()
// wait for 2s before reloading the page if (!description.trim()) {
setTimeout(() => { toast.error('Please enter a description')
return
}
if (selectedCourses.length === 0) {
toast.error('Please select at least one course')
return
}
setIsSubmitting(true)
try {
const collection = {
name: name.trim(),
description: description.trim(),
courses: selectedCourses,
public: isPublic,
org_id: org.id,
}
await createCollection(collection, session.data?.tokens?.access_token)
await revalidateTags(['collections'], org.slug)
toast.success('Collection created successfully!')
router.push(getUriWithOrg(orgslug, '/collections')) router.push(getUriWithOrg(orgslug, '/collections'))
}, 1000) } catch (error) {
toast.error('Failed to create collection. Please try again.')
} finally {
setIsSubmitting(false)
}
}
if (error) {
return (
<div className="flex items-center justify-center h-[60vh]">
<div className="text-red-500">Failed to load courses. Please try again later.</div>
</div>
)
} }
return ( return (
<> <div className="max-w-2xl mx-auto py-12 px-4">
<div className="w-64 m-auto py-20"> <div className="space-y-8">
<div className="font-bold text-lg mb-4">Add new</div> <div>
<h1 className="text-2xl font-bold text-gray-900">Create New Collection</h1>
<p className="mt-2 text-sm text-gray-600">
Group your courses together in a collection to make them easier to find and manage.
</p>
</div>
<input <form onSubmit={handleSubmit} className="space-y-6">
type="text" <div className="space-y-4">
placeholder="Name" <label className="block">
value={name} <span className="text-sm font-medium text-gray-700">Collection Name</span>
onChange={handleNameChange} <input
className="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" type="text"
/> placeholder="Enter collection name"
value={name}
onChange={handleNameChange}
className="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
maxLength={100}
/>
</label>
<select <label className="block">
onChange={handleVisibilityChange} <span className="text-sm font-medium text-gray-700">Visibility</span>
className="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" <select
defaultValue={isPublic} onChange={handleVisibilityChange}
> className="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
<option value="false">Private Collection</option> defaultValue={isPublic}
<option value="true">Public Collection </option>
</select>
{!courses ? (
<p className="text-gray-500">Loading...</p>
) : (
<div className="space-y-4 p-3">
<p>Courses</p>
{courses.map((course: any) => (
<div
key={course.course_uuid}
className="flex items-center space-x-2"
> >
<input <option value="true">Public Collection - Visible to everyone</option>
type="checkbox" <option value="false">Private Collection - Only visible to organization members</option>
id={course.id} </select>
name={course.name} </label>
value={course.id}
onChange={(e) => {
if (e.target.checked) {
setSelectedCourses([...selectedCourses, course.id])
} else {
setSelectedCourses(
selectedCourses.filter(
(course_uuid: any) =>
course_uuid !== course.course_uuid
)
)
}
}}
className="text-blue-500 rounded focus:ring-2 focus:ring-blue-500"
/>
<label <label className="block">
htmlFor={course.course_uuid} <span className="text-sm font-medium text-gray-700">Description</span>
className="text-sm text-gray-700" <textarea
> placeholder="Enter collection description"
{course.name} value={description}
</label> onChange={handleDescriptionChange}
</div> rows={4}
))} className="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
maxLength={500}
/>
</label>
<div className="space-y-2">
<span className="text-sm font-medium text-gray-700">Select Courses</span>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="w-6 h-6 animate-spin text-gray-500" />
</div>
) : courses?.length === 0 ? (
<p className="text-sm text-gray-500 py-4">No courses available. Create some courses first.</p>
) : (
<div className="mt-2 border border-gray-200 rounded-lg bg-gray-50">
<div className="max-h-[400px] overflow-y-auto p-4 space-y-3 scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-transparent hover:scrollbar-thumb-gray-400">
{courses?.map((course: any) => (
<label
key={course.id}
className="relative flex items-center p-4 bg-white rounded-md hover:bg-gray-50 transition cursor-pointer gap-4"
>
<input
type="checkbox"
id={course.id}
name={course.name}
value={course.id}
onChange={(e) => {
if (e.target.checked) {
setSelectedCourses([...selectedCourses, course.id])
} else {
setSelectedCourses(
selectedCourses.filter((id: any) => id !== course.id)
)
}
}}
className="h-4 w-4 text-blue-500 rounded border-gray-300 focus:ring-blue-500"
/>
<div className="relative w-24 h-16 rounded-md overflow-hidden bg-gray-100 flex-shrink-0">
{course.thumbnail_image ? (
<img
src={getCourseThumbnailMediaDirectory(org.org_uuid, course.course_uuid, course.thumbnail_image)}
alt={course.name}
className="object-cover"
/>
) : (
<div className="w-full h-full flex items-center justify-center">
<ImageIcon className="w-6 h-6 text-gray-400" />
</div>
)}
</div>
<div className="flex-1 min-w-0">
<h3 className="text-sm font-medium text-gray-900 truncate">{course.name}</h3>
{course.description && (
<p className="mt-1 text-xs text-gray-500 line-clamp-2">{course.description}</p>
)}
</div>
</label>
))}
</div>
<div className="px-4 py-3 bg-gray-50 border-t border-gray-200">
<p className="text-xs text-gray-500">
Selected courses: {selectedCourses.length}
</p>
</div>
</div>
)}
</div>
</div> </div>
)}
<input <div className="flex items-center justify-end space-x-4">
type="text" <button
placeholder="Description" type="button"
value={description} onClick={() => router.back()}
onChange={handleDescriptionChange} className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition"
className="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" >
/> Cancel
</button>
<button <button
onClick={handleSubmit} type="submit"
className="px-6 py-3 text-white bg-black rounded-lg shadow-md hover:bg-black focus:outline-none focus:ring-2 focus:ring-blue-500" disabled={isSubmitting}
> className="px-6 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2"
Submit >
</button> {isSubmitting && <Loader2 className="w-4 h-4 animate-spin" />}
<span>{isSubmitting ? 'Creating...' : 'Create Collection'}</span>
</button>
</div>
</form>
</div> </div>
</> </div>
) )
} }

View file

@ -136,7 +136,7 @@ const CollectionsPage = async (params: any) => {
text="Create a collection to add content" text="Create a collection to add content"
/> />
</p> </p>
<div className="mt-4"> <div className="mt-4 flex justify-center">
<AuthenticatedClientElement <AuthenticatedClientElement
checkMethod="roles" checkMethod="roles"
ressourceType="collections" ressourceType="collections"

View file

@ -11,10 +11,10 @@ function getMediaUrl() {
export function getCourseThumbnailMediaDirectory( export function getCourseThumbnailMediaDirectory(
orgUUID: string, orgUUID: string,
courseId: string, courseUUID: string,
fileId: string fileId: string
) { ) {
let uri = `${getMediaUrl()}content/orgs/${orgUUID}/courses/${courseId}/thumbnails/${fileId}` let uri = `${getMediaUrl()}content/orgs/${orgUUID}/courses/${courseUUID}/thumbnails/${fileId}`
return uri return uri
} }