chore: refactor frontend components folder

This commit is contained in:
swve 2024-11-25 23:26:33 +01:00
parent 46f016f661
commit 5a746a946d
106 changed files with 159 additions and 164 deletions

View file

@ -0,0 +1,201 @@
import { useCourse, useCourseDispatch } from '@components/Contexts/CourseContext'
import LinkToUserGroup from '@components/Objects/Modals/Dash/EditCourseAccess/LinkToUserGroup'
import ConfirmationModal from '@components/Objects/StyledElements/ConfirmationModal/ConfirmationModal'
import Modal from '@components/Objects/StyledElements/Modal/Modal'
import { getAPIUrl } from '@services/config/config'
import { unLinkResourcesToUserGroup } from '@services/usergroups/usergroups'
import { swrFetcher } from '@services/utils/ts/requests'
import { Globe, SquareUserRound, Users, X } from 'lucide-react'
import { useLHSession } from '@components/Contexts/LHSessionContext'
import React, { useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import useSWR, { mutate } from 'swr'
type EditCourseAccessProps = {
orgslug: string
course_uuid?: string
}
function EditCourseAccess(props: EditCourseAccessProps) {
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 { data: usergroups } = useSWR(courseStructure ? `${getAPIUrl()}usergroups/resource/${courseStructure.course_uuid}` : null, (url) => swrFetcher(url, access_token));
const [isClientPublic, setIsClientPublic] = useState<boolean | undefined>(undefined);
useEffect(() => {
if (!isLoading && courseStructure?.public !== undefined) {
setIsClientPublic(courseStructure.public);
}
}, [isLoading, courseStructure]);
useEffect(() => {
if (!isLoading && courseStructure?.public !== undefined && isClientPublic !== undefined) {
if (isClientPublic !== courseStructure.public) {
dispatchCourse({ type: 'setIsNotSaved' });
const updatedCourse = {
...courseStructure,
public: isClientPublic,
};
dispatchCourse({ type: 'setCourseStructure', payload: updatedCourse });
}
}
}, [isLoading, isClientPublic, courseStructure, dispatchCourse]);
return (
<div>
{courseStructure && (
<div>
<div className="h-6"></div>
<div className="mx-4 sm:mx-10 bg-white rounded-xl shadow-sm px-4 py-4">
<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">Access to the course</h1>
<h2 className="text-gray-500 text-xs sm:text-sm">
Choose if you want your course to be publicly available on the internet or only accessible to signed in users
</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">
<ConfirmationModal
confirmationButtonText="Change to Public"
confirmationMessage="Are you sure you want this course to be publicly available on the internet?"
dialogTitle="Change to Public?"
dialogTrigger={
<div className="w-full h-[200px] bg-slate-100 rounded-lg cursor-pointer hover:bg-slate-200 transition-all">
{isClientPublic && (
<div className="bg-green-200 text-green-600 font-bold w-fit my-3 mx-3 absolute text-sm px-3 py-1 rounded-lg">
Active
</div>
)}
<div className="flex flex-col space-y-1 justify-center items-center h-full p-2 sm:p-4">
<Globe className="text-slate-400" size={32} />
<div className="text-xl sm:text-2xl text-slate-700 font-bold">
Public
</div>
<div className="text-gray-400 text-sm sm:text-md tracking-tight w-full sm:w-[500px] leading-5 text-center">
The Course is publicly available on the internet, it is indexed by search engines and can be accessed by anyone
</div>
</div>
</div>
}
functionToExecute={() => setIsClientPublic(true)}
status="info"
/>
<ConfirmationModal
confirmationButtonText="Change to Users Only"
confirmationMessage="Are you sure you want this course to be only accessible to signed in users?"
dialogTitle="Change to Users Only?"
dialogTrigger={
<div className="w-full h-[200px] bg-slate-100 rounded-lg cursor-pointer hover:bg-slate-200 transition-all">
{!isClientPublic && (
<div className="bg-green-200 text-green-600 font-bold w-fit my-3 mx-3 absolute text-sm px-3 py-1 rounded-lg">
Active
</div>
)}
<div className="flex flex-col space-y-1 justify-center items-center h-full p-2 sm:p-4">
<Users className="text-slate-400" size={32} />
<div className="text-xl sm:text-2xl text-slate-700 font-bold">
Users Only
</div>
<div className="text-gray-400 text-sm sm:text-md tracking-tight w-full sm:w-[500px] leading-5 text-center">
The Course is only accessible to signed in users, additionally you can choose which UserGroups can access this course
</div>
</div>
</div>
}
functionToExecute={() => setIsClientPublic(false)}
status="info"
/>
</div>
{!isClientPublic && <UserGroupsSection usergroups={usergroups} />}
</div>
</div>
)}
</div>
);
}
function UserGroupsSection({ usergroups }: { usergroups: any[] }) {
const course = useCourse() as any;
const [userGroupModal, setUserGroupModal] = useState(false);
const session = useLHSession() as any;
const access_token = session?.data?.tokens?.access_token;
const removeUserGroupLink = async (usergroup_id: number) => {
try {
const res = await unLinkResourcesToUserGroup(usergroup_id, course.courseStructure.course_uuid, access_token);
if (res.status === 200) {
toast.success('Successfully unlinked from usergroup');
mutate(`${getAPIUrl()}usergroups/resource/${course.courseStructure.course_uuid}`);
} else {
toast.error(`Error ${res.status}: ${res.data.detail}`);
}
} catch (error) {
toast.error('An error occurred while unlinking the user group.');
}
};
return (
<>
<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">UserGroups</h1>
<h2 className="text-gray-500 text-xs sm:text-sm">
You can choose to give access to this course to specific groups of users only by linking it to a UserGroup
</h2>
</div>
<div className="overflow-x-auto">
<table className="table-auto w-full text-left whitespace-nowrap rounded-md overflow-hidden">
<thead className="bg-gray-100 text-gray-500 rounded-xl uppercase">
<tr className="font-bolder text-sm">
<th className="py-3 px-4">Name</th>
<th className="py-3 px-4">Actions</th>
</tr>
</thead>
<tbody className="mt-5 bg-white rounded-md">
{usergroups?.map((usergroup: any) => (
<tr key={usergroup.invite_code_uuid} className="border-b border-gray-100 text-sm">
<td className="py-3 px-4">{usergroup.name}</td>
<td className="py-3 px-4">
<ConfirmationModal
confirmationButtonText="Delete Link"
confirmationMessage="Users from this UserGroup will no longer have access to this course"
dialogTitle="Unlink UserGroup?"
dialogTrigger={
<button className="mr-2 flex space-x-2 hover:cursor-pointer p-1 px-3 bg-rose-700 rounded-md font-bold items-center text-sm text-rose-100">
<X className="w-4 h-4" />
<span>Delete link</span>
</button>
}
functionToExecute={() => removeUserGroupLink(usergroup.id)}
status="warning"
/>
</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="flex flex-row-reverse mt-3 mr-2">
<Modal
isDialogOpen={userGroupModal}
onOpenChange={() => setUserGroupModal(!userGroupModal)}
minHeight="no-min"
minWidth="md"
dialogContent={<LinkToUserGroup setUserGroupModal={setUserGroupModal} />}
dialogTitle="Link Course to a UserGroup"
dialogDescription="Choose a UserGroup to link this course to. Users from this UserGroup will have access to this course."
dialogTrigger={
<button className="flex space-x-2 hover:cursor-pointer p-1 px-3 bg-green-700 rounded-md font-bold items-center text-xs sm:text-sm text-green-100">
<SquareUserRound className="w-3 h-3 sm:w-4 sm:h-4" />
<span>Link to a UserGroup</span>
</button>
}
/>
</div>
</>
);
}
export default EditCourseAccess;

View file

@ -0,0 +1,176 @@
import FormLayout, {
FormField,
FormLabelAndMessage,
Input,
Textarea,
} from '@components/Objects/StyledElements/Form/Form';
import { useFormik } from 'formik';
import { AlertTriangle } from 'lucide-react';
import * as Form from '@radix-ui/react-form';
import React, { useEffect, useState } from 'react';
import ThumbnailUpdate from './ThumbnailUpdate';
import { useCourse, useCourseDispatch } from '@components/Contexts/CourseContext';
type EditCourseStructureProps = {
orgslug: string
course_uuid?: string
}
const validate = (values: any) => {
const errors = {} as any;
if (!values.name) {
errors.name = 'Required';
} else if (values.name.length > 100) {
errors.name = 'Must be 100 characters or less';
}
if (!values.description) {
errors.description = 'Required';
} else if (values.description.length > 1000) {
errors.description = 'Must be 1000 characters or less';
}
if (!values.learnings) {
errors.learnings = 'Required';
}
return errors;
};
function EditCourseGeneral(props: EditCourseStructureProps) {
const [error, setError] = useState('');
const course = useCourse();
const dispatchCourse = useCourseDispatch() as any;
const { isLoading, courseStructure } = course as any;
const formik = useFormik({
initialValues: {
name: courseStructure?.name || '',
description: courseStructure?.description || '',
about: courseStructure?.about || '',
learnings: courseStructure?.learnings || '',
tags: courseStructure?.tags || '',
public: courseStructure?.public || '',
},
validate,
onSubmit: async values => {
try {
// Add your submission logic here
dispatchCourse({ type: 'setIsSaved' });
} catch (e) {
setError('Failed to save course structure.');
}
},
enableReinitialize: true,
}) as any;
useEffect(() => {
if (!isLoading) {
const formikValues = formik.values as any;
const initialValues = formik.initialValues as any;
const valuesChanged = Object.keys(formikValues).some(
key => formikValues[key] !== initialValues[key]
);
if (valuesChanged) {
dispatchCourse({ type: 'setIsNotSaved' });
const updatedCourse = {
...courseStructure,
...formikValues,
};
dispatchCourse({ type: 'setCourseStructure', payload: updatedCourse });
}
}
}, [formik.values, isLoading]);
return (
<div>
<div className="h-6"></div>
<div className="ml-10 mr-10 mx-auto bg-white rounded-xl shadow-sm px-6 py-5">
{courseStructure && (
<div className="editcourse-form">
{error && (
<div className="flex justify-center bg-red-200 rounded-md text-red-950 space-x-2 items-center p-4 transition-all shadow-sm">
<AlertTriangle size={18} />
<div className="font-bold text-sm">{error}</div>
</div>
)}
<FormLayout onSubmit={formik.handleSubmit}>
<FormField name="name">
<FormLabelAndMessage label="Name" message={formik.errors.name} />
<Form.Control asChild>
<Input
style={{ backgroundColor: 'white' }}
onChange={formik.handleChange}
value={formik.values.name}
type="text"
required
/>
</Form.Control>
</FormField>
<FormField name="description">
<FormLabelAndMessage label="Description" message={formik.errors.description} />
<Form.Control asChild>
<Input
style={{ backgroundColor: 'white' }}
onChange={formik.handleChange}
value={formik.values.description}
type="text"
required
/>
</Form.Control>
</FormField>
<FormField name="about">
<FormLabelAndMessage label="About" message={formik.errors.about} />
<Form.Control asChild>
<Textarea
style={{ backgroundColor: 'white' }}
onChange={formik.handleChange}
value={formik.values.about}
required
/>
</Form.Control>
</FormField>
<FormField name="learnings">
<FormLabelAndMessage label="Learnings" message={formik.errors.learnings} />
<Form.Control asChild>
<Textarea
style={{ backgroundColor: 'white' }}
onChange={formik.handleChange}
value={formik.values.learnings}
required
/>
</Form.Control>
</FormField>
<FormField name="tags">
<FormLabelAndMessage label="Tags" message={formik.errors.tags} />
<Form.Control asChild>
<Textarea
style={{ backgroundColor: 'white' }}
onChange={formik.handleChange}
value={formik.values.tags}
required
/>
</Form.Control>
</FormField>
<FormField name="thumbnail">
<FormLabelAndMessage label="Thumbnail" />
<Form.Control asChild>
<ThumbnailUpdate />
</Form.Control>
</FormField>
</FormLayout>
</div>
)}
</div>
</div>
);
}
export default EditCourseGeneral;

View file

@ -0,0 +1,123 @@
import { useCourse } from '@components/Contexts/CourseContext'
import { useOrg } from '@components/Contexts/OrgContext'
import { getAPIUrl } from '@services/config/config'
import { updateCourseThumbnail } from '@services/courses/courses'
import { getCourseThumbnailMediaDirectory } from '@services/media/media'
import { ArrowBigUpDash, UploadCloud, Image as ImageIcon } from 'lucide-react'
import { useLHSession } from '@components/Contexts/LHSessionContext'
import React, { useState } from 'react'
import { mutate } from 'swr'
import UnsplashImagePicker from './UnsplashImagePicker'
function ThumbnailUpdate() {
const course = useCourse() as any
const session = useLHSession() as any;
const org = useOrg() as any
const [localThumbnail, setLocalThumbnail] = React.useState(null) as any
const [isLoading, setIsLoading] = React.useState(false) as any
const [error, setError] = React.useState('') as any
const [showUnsplashPicker, setShowUnsplashPicker] = useState(false)
const handleFileChange = async (event: any) => {
const file = event.target.files[0]
setLocalThumbnail(file)
await updateThumbnail(file)
}
const handleUnsplashSelect = async (imageUrl: string) => {
setIsLoading(true)
const response = await fetch(imageUrl)
const blob = await response.blob()
const file = new File([blob], 'unsplash_image.jpg', { type: 'image/jpeg' })
setLocalThumbnail(file)
await updateThumbnail(file)
}
const updateThumbnail = async (file: File) => {
setIsLoading(true)
const res = await updateCourseThumbnail(
course.courseStructure.course_uuid,
file,
session.data?.tokens?.access_token
)
mutate(`${getAPIUrl()}courses/${course.courseStructure.course_uuid}/meta`)
// wait for 1 second to show loading animation
await new Promise((r) => setTimeout(r, 1500))
if (res.success === false) {
setError(res.HTTPmessage)
} else {
setIsLoading(false)
setError('')
}
}
return (
<div className="w-auto bg-gray-50 rounded-xl outline outline-1 outline-gray-200 h-[200px] shadow">
<div className="flex flex-col justify-center items-center h-full">
<div className="flex flex-col justify-center items-center">
<div className="flex flex-col justify-center items-center">
{error && (
<div className="flex justify-center bg-red-200 rounded-md text-red-950 space-x-2 items-center p-2 transition-all shadow-sm">
<div className="text-sm font-semibold">{error}</div>
</div>
)}
{localThumbnail ? (
<img
src={URL.createObjectURL(localThumbnail)}
className={`${isLoading ? 'animate-pulse' : ''} shadow w-[200px] h-[100px] rounded-md`}
/>
) : (
<img
src={`${course.courseStructure.thumbnail_image ? getCourseThumbnailMediaDirectory(
org?.org_uuid,
course.courseStructure.course_uuid,
course.courseStructure.thumbnail_image
) : '/empty_thumbnail.png'}`}
className="shadow w-[200px] h-[100px] rounded-md bg-gray-200"
/>
)}
</div>
{isLoading ? (
<div className="flex justify-center items-center">
<div className="font-bold animate-pulse antialiased items-center bg-green-200 text-gray text-sm rounded-md px-4 py-2 mt-4 flex">
<ArrowBigUpDash size={16} className="mr-2" />
<span>Uploading</span>
</div>
</div>
) : (
<div className="flex justify-center items-center space-x-2">
<input
type="file"
id="fileInput"
style={{ display: 'none' }}
onChange={handleFileChange}
/>
<button
className="font-bold antialiased items-center text-gray text-sm rounded-md px-4 mt-6 flex"
onClick={() => document.getElementById('fileInput')?.click()}
>
<UploadCloud size={16} className="mr-2" />
<span>Upload Image</span>
</button>
<button
className="font-bold antialiased items-center text-gray text-sm rounded-md px-4 mt-6 flex"
onClick={() => setShowUnsplashPicker(true)}
>
<ImageIcon size={16} className="mr-2" />
<span>Choose from Gallery</span>
</button>
</div>
)}
</div>
</div>
{showUnsplashPicker && (
<UnsplashImagePicker
onSelect={handleUnsplashSelect}
onClose={() => setShowUnsplashPicker(false)}
/>
)}
</div>
)
}
export default ThumbnailUpdate

View file

@ -0,0 +1,175 @@
import React, { useState, useEffect, useCallback } from 'react';
import { createApi } from 'unsplash-js';
import { Search, X, Cpu, Briefcase, GraduationCap, Heart, Palette, Plane, Utensils,
Dumbbell, Music, Shirt, Book, Building, Bike, Camera, Microscope, Coins, Coffee, Gamepad,
Flower} from 'lucide-react';
import Modal from '@components/Objects/StyledElements/Modal/Modal';
const unsplash = createApi({
accessKey: process.env.NEXT_PUBLIC_UNSPLASH_ACCESS_KEY as string,
});
const IMAGES_PER_PAGE = 20;
const predefinedLabels = [
{ name: 'Nature', icon: Flower },
{ name: 'Technology', icon: Cpu },
{ name: 'Business', icon: Briefcase },
{ name: 'Education', icon: GraduationCap },
{ name: 'Health', icon: Heart },
{ name: 'Art', icon: Palette },
{ name: 'Science', icon: Microscope },
{ name: 'Travel', icon: Plane },
{ name: 'Food', icon: Utensils },
{ name: 'Sports', icon: Dumbbell },
{ name: 'Music', icon: Music },
{ name: 'Fashion', icon: Shirt },
{ name: 'History', icon: Book },
{ name: 'Architecture', icon: Building },
{ name: 'Fitness', icon: Bike },
{ name: 'Photography', icon: Camera },
{ name: 'Biology', icon: Microscope },
{ name: 'Finance', icon: Coins },
{ name: 'Lifestyle', icon: Coffee },
{ name: 'Gaming', icon: Gamepad },
];
interface UnsplashImagePickerProps {
onSelect: (imageUrl: string) => void;
onClose: () => void;
isOpen?: boolean;
}
const UnsplashImagePicker: React.FC<UnsplashImagePickerProps> = ({ onSelect, onClose, isOpen = true }) => {
const [query, setQuery] = useState('');
const [images, setImages] = useState<any[]>([]);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const fetchImages = useCallback(async (searchQuery: string, pageNum: number) => {
setLoading(true);
try {
const result = await unsplash.search.getPhotos({
query: searchQuery,
page: pageNum,
perPage: IMAGES_PER_PAGE,
});
if (result && result.response) {
setImages(prevImages => pageNum === 1 ? result.response.results : [...prevImages, ...result.response.results]);
}
} catch (error) {
console.error('Error fetching images:', error);
} finally {
setLoading(false);
}
}, []);
const debouncedFetchImages = useCallback(
debounce((searchQuery: string) => {
setPage(1);
fetchImages(searchQuery, 1);
}, 300),
[fetchImages]
);
useEffect(() => {
if (query) {
debouncedFetchImages(query);
}
}, [query, debouncedFetchImages]);
const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
setQuery(e.target.value);
};
const handleLabelClick = (label: string) => {
setQuery(label);
};
const handleLoadMore = () => {
const nextPage = page + 1;
setPage(nextPage);
fetchImages(query, nextPage);
};
const handleImageSelect = (imageUrl: string) => {
onSelect(imageUrl);
onClose();
};
const modalContent = (
<div className="flex flex-col h-full">
<div className="p-4 space-y-4">
<div className="relative">
<input
type="text"
value={query}
onChange={handleSearch}
placeholder="Search for images..."
className="w-full p-2 pl-10 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
</div>
<div className="flex flex-wrap gap-2">
{predefinedLabels.map(label => (
<button
key={label.name}
onClick={() => handleLabelClick(label.name)}
className="px-3 py-1 bg-neutral-100 rounded-lg hover:bg-neutral-200 nice-shadow transition-colors flex items-center gap-1 space-x-1"
>
<label.icon size={16} />
<span>{label.name}</span>
</button>
))}
</div>
</div>
<div className="flex-1 overflow-y-auto p-4 pt-0">
<div className="grid grid-cols-3 gap-4">
{images.map(image => (
<div key={image.id} className="relative w-full pb-[56.25%]">
<img
src={image.urls.small}
alt={image.alt_description}
className="absolute inset-0 w-full h-full object-cover rounded-lg cursor-pointer hover:opacity-80 transition-opacity"
onClick={() => handleImageSelect(image.urls.regular)}
/>
</div>
))}
</div>
{loading && <p className="text-center mt-4">Loading...</p>}
{!loading && images.length > 0 && (
<button
onClick={handleLoadMore}
className="mt-4 w-full px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
>
Load More
</button>
)}
</div>
</div>
);
return (
<Modal
dialogTitle="Choose an image from Unsplash"
dialogContent={modalContent}
onOpenChange={onClose}
isDialogOpen={isOpen}
minWidth="lg"
minHeight="lg"
customHeight="h-[80vh]"
/>
);
};
// Custom debounce function
const debounce = (func: Function, delay: number) => {
let timeoutId: NodeJS.Timeout;
return (...args: any[]) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func(...args), delay);
};
};
export default UnsplashImagePicker;

View file

@ -0,0 +1,131 @@
import { useCourse } from '@components/Contexts/CourseContext'
import NewActivityModal from '@components/Objects/Modals/Activities/Create/NewActivity'
import Modal from '@components/Objects/StyledElements/Modal/Modal'
import { getAPIUrl } from '@services/config/config'
import {
createActivity,
createExternalVideoActivity,
createFileActivity,
} from '@services/courses/activities'
import { getOrganizationContextInfoWithoutCredentials } from '@services/organizations/orgs'
import { revalidateTags } from '@services/utils/ts/requests'
import { Layers } from 'lucide-react'
import { useLHSession } from '@components/Contexts/LHSessionContext'
import { useRouter } from 'next/navigation'
import React, { useEffect } from 'react'
import { mutate } from 'swr'
import toast from 'react-hot-toast'
type NewActivityButtonProps = {
chapterId: string
orgslug: string
}
function NewActivityButton(props: NewActivityButtonProps) {
const [newActivityModal, setNewActivityModal] = React.useState(false)
const router = useRouter()
const course = useCourse() as any
const session = useLHSession() as any;
const access_token = session?.data?.tokens?.access_token;
const openNewActivityModal = async (chapterId: any) => {
setNewActivityModal(true)
}
const closeNewActivityModal = async () => {
setNewActivityModal(false)
}
// Submit new activity
const submitActivity = async (activity: any) => {
let org = await getOrganizationContextInfoWithoutCredentials(
props.orgslug,
{ revalidate: 1800 }
)
const toast_loading = toast.loading('Creating activity...')
await createActivity(activity, props.chapterId, org.org_id, access_token)
mutate(`${getAPIUrl()}courses/${course.courseStructure.course_uuid}/meta`)
toast.dismiss(toast_loading)
toast.success('Activity created successfully')
setNewActivityModal(false)
await revalidateTags(['courses'], props.orgslug)
router.refresh()
}
// Submit File Upload
const submitFileActivity = async (
file: any,
type: any,
activity: any,
chapterId: string
) => {
toast.loading('Uploading file and creating activity...')
await createFileActivity(file, type, activity, chapterId, access_token)
mutate(`${getAPIUrl()}courses/${course.courseStructure.course_uuid}/meta`)
setNewActivityModal(false)
toast.dismiss()
toast.success('File uploaded successfully')
toast.success('Activity created successfully')
await revalidateTags(['courses'], props.orgslug)
router.refresh()
}
// Submit YouTube Video Upload
const submitExternalVideo = async (
external_video_data: any,
activity: any,
chapterId: string
) => {
const toast_loading = toast.loading('Creating activity and uploading file...')
await createExternalVideoActivity(
external_video_data,
activity,
props.chapterId, access_token
)
mutate(`${getAPIUrl()}courses/${course.courseStructure.course_uuid}/meta`)
setNewActivityModal(false)
toast.dismiss(toast_loading)
toast.success('Activity created successfully')
await revalidateTags(['courses'], props.orgslug)
router.refresh()
}
useEffect(() => { }, [course])
return (
<div className="flex justify-center">
<Modal
isDialogOpen={newActivityModal}
onOpenChange={setNewActivityModal}
minHeight="no-min"
minWidth='md'
addDefCloseButton={false}
dialogContent={
<NewActivityModal
closeModal={closeNewActivityModal}
submitFileActivity={submitFileActivity}
submitExternalVideo={submitExternalVideo}
submitActivity={submitActivity}
chapterId={props.chapterId}
course={course}
></NewActivityModal>
}
dialogTitle="Create Activity"
dialogDescription="Choose between types of activities to add to the course"
/>
<div
onClick={() => {
openNewActivityModal(props.chapterId)
}}
className="flex w-44 h-10 space-x-2 items-center py-2 my-3 rounded-xl justify-center text-white bg-black hover:cursor-pointer"
>
<Layers className="" size={17} />
<div className="text-sm mx-auto my-auto items-center font-bold">
Add Activity
</div>
</div>
</div>
)
}
export default NewActivityButton

View file

@ -0,0 +1,329 @@
import ConfirmationModal from '@components/Objects/StyledElements/ConfirmationModal/ConfirmationModal'
import { getAPIUrl, getUriWithOrg } from '@services/config/config'
import { deleteActivity, updateActivity } from '@services/courses/activities'
import { revalidateTags } from '@services/utils/ts/requests'
import {
Backpack,
Eye,
File,
FilePenLine,
FileSymlink,
Globe,
Lock,
MoreVertical,
Pencil,
Save,
Sparkles,
Video,
X,
} from 'lucide-react'
import { useLHSession } from '@components/Contexts/LHSessionContext'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import React, { useEffect, useState } from 'react'
import { Draggable } from 'react-beautiful-dnd'
import { mutate } from 'swr'
import { deleteAssignmentUsingActivityUUID, getAssignmentFromActivityUUID } from '@services/courses/assignments'
import { useOrg } from '@components/Contexts/OrgContext'
import { useCourse } from '@components/Contexts/CourseContext'
import toast from 'react-hot-toast'
import { useMediaQuery } from 'usehooks-ts'
import ToolTip from '@components/Objects/StyledElements/Tooltip/Tooltip'
type ActivitiyElementProps = {
orgslug: string
activity: any
activityIndex: any
course_uuid: string
}
interface ModifiedActivityInterface {
activityId: string
activityName: string
}
function ActivityElement(props: ActivitiyElementProps) {
const router = useRouter()
const session = useLHSession() as any;
const access_token = session?.data?.tokens?.access_token;
const [modifiedActivity, setModifiedActivity] = React.useState<
ModifiedActivityInterface | undefined
>(undefined)
const [selectedActivity, setSelectedActivity] = React.useState<
string | undefined
>(undefined)
const activityUUID = props.activity.activity_uuid
const isMobile = useMediaQuery('(max-width: 767px)')
async function deleteActivityUI() {
const toast_loading = toast.loading('Deleting activity...')
// Assignments
if (props.activity.activity_type === 'TYPE_ASSIGNMENT') {
await deleteAssignmentUsingActivityUUID(props.activity.activity_uuid, access_token)
}
await deleteActivity(props.activity.activity_uuid, access_token)
mutate(`${getAPIUrl()}courses/${props.course_uuid}/meta`)
await revalidateTags(['courses'], props.orgslug)
toast.dismiss(toast_loading)
toast.success('Activity deleted successfully')
router.refresh()
}
async function changePublicStatus() {
const toast_loading = toast.loading('Updating assignment...')
await updateActivity(
{
...props.activity,
published: !props.activity.published,
},
props.activity.activity_uuid,
access_token
)
mutate(`${getAPIUrl()}courses/${props.course_uuid}/meta`)
toast.dismiss(toast_loading)
toast.success('The activity has been updated successfully')
await revalidateTags(['courses'], props.orgslug)
router.refresh()
}
async function updateActivityName(activityId: string) {
if (
modifiedActivity?.activityId === activityId &&
selectedActivity !== undefined
) {
let modifiedActivityCopy = {
...props.activity,
name: modifiedActivity.activityName,
}
await updateActivity(modifiedActivityCopy, activityUUID, access_token)
mutate(`${getAPIUrl()}courses/${props.course_uuid}/meta`)
await revalidateTags(['courses'], props.orgslug)
router.refresh()
}
setSelectedActivity(undefined)
}
return (
<Draggable
key={props.activity.activity_uuid}
draggableId={props.activity.activity_uuid}
index={props.activityIndex}
>
{(provided, snapshot) => (
<div
className="flex flex-col sm:flex-row py-2 px-3 my-2 w-full rounded-md bg-gray-50 text-gray-500 hover:bg-gray-100 hover:scale-102 space-y-2 sm:space-y-0 sm:space-x-2 items-center ring-1 ring-inset ring-gray-400/10 nice-shadow"
key={props.activity.id}
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
>
{/* Activity Type Icon */}
<ActivityTypeIndicator activityType={props.activity.activity_type} isMobile={isMobile} />
{/* Centered Activity Name */}
<div className="grow items-center space-x-2 flex mx-auto justify-center">
{selectedActivity === props.activity.id ? (
<div className="chapter-modification-zone text-[7px] text-gray-600 shadow-inner bg-gray-200/60 py-1 px-4 rounded-lg space-x-3">
<input
type="text"
className="bg-transparent outline-none text-xs text-gray-500"
placeholder="Activity name"
value={
modifiedActivity
? modifiedActivity?.activityName
: props.activity.name
}
onChange={(e) =>
setModifiedActivity({
activityId: props.activity.id,
activityName: e.target.value,
})
}
/>
<button
onClick={() => updateActivityName(props.activity.id)}
className="bg-transparent text-neutral-700 hover:cursor-pointer hover:text-neutral-900"
>
<Save size={12} />
</button>
</div>
) : (
<p className="first-letter:uppercase text-center sm:text-left"> {props.activity.name} </p>
)}
<Pencil
onClick={() => setSelectedActivity(props.activity.id)}
className="text-neutral-400 hover:cursor-pointer size-3 min-w-3"
/>
</div>
{/* Edit, View, Publish, and Delete Buttons */}
<div className="flex flex-wrap justify-center sm:justify-end gap-2 w-full sm:w-auto">
<ActivityElementOptions activity={props.activity} isMobile={isMobile} />
{/* Publishing */}
<button
className={`p-1 px-2 sm:px-3 border shadow-md rounded-md font-bold text-xs flex items-center space-x-1 transition-colors duration-200 ${
!props.activity.published
? 'bg-gradient-to-bl text-green-800 from-green-400/50 to-lime-200/80 border-green-600/10 hover:from-green-500/50 hover:to-lime-300/80'
: 'bg-gradient-to-bl text-gray-800 from-gray-400/50 to-gray-200/80 border-gray-600/10 hover:from-gray-500/50 hover:to-gray-300/80'
}`}
onClick={() => changePublicStatus()}
>
{!props.activity.published ? (
<Globe strokeWidth={2} size={12} className="text-green-600" />
) : (
<Lock strokeWidth={2} size={12} className="text-gray-600" />
)}
<span>{!props.activity.published ? 'Publish' : 'Unpublish'}</span>
</button>
<div className="w-px h-3 bg-gray-300 mx-1 self-center rounded-full hidden sm:block" />
<ToolTip content="Preview Activity" sideOffset={8}>
<Link
href={
getUriWithOrg(props.orgslug, '') +
`/course/${props.course_uuid.replace(
'course_',
''
)}/activity/${props.activity.activity_uuid.replace(
'activity_',
''
)}`
}
prefetch
className="p-1 px-2 sm:px-3 bg-gradient-to-bl text-cyan-800 from-sky-400/50 to-cyan-200/80 border border-cyan-600/10 shadow-md rounded-md font-bold text-xs flex items-center space-x-1 transition-colors duration-200 hover:from-sky-500/50 hover:to-cyan-300/80"
rel="noopener noreferrer"
>
<Eye strokeWidth={2} size={14} className="text-sky-600" />
</Link>
</ToolTip>
{/* Delete Button */}
<ConfirmationModal
confirmationMessage="Are you sure you want to delete this activity ?"
confirmationButtonText="Delete Activity"
dialogTitle={'Delete ' + props.activity.name + ' ?'}
dialogTrigger={
<button
className="p-1 px-2 sm:px-3 bg-red-600 rounded-md flex items-center space-x-1 shadow-md transition-colors duration-200 hover:bg-red-700"
rel="noopener noreferrer"
>
<X size={15} className="text-rose-200 font-bold" />
</button>
}
functionToExecute={() => deleteActivityUI()}
status="warning"
/>
</div>
</div>
)}
</Draggable>
)
}
const ACTIVITIES = {
'TYPE_VIDEO': {
displayName: 'Video',
Icon: Video
},
'TYPE_DOCUMENT': {
displayName: 'Document',
Icon: File
},
'TYPE_ASSIGNMENT': {
displayName: 'Assignment',
Icon: Backpack
},
'TYPE_DYNAMIC': {
displayName: 'Dynamic',
Icon: Sparkles
}
}
const ActivityTypeIndicator = ({activityType, isMobile} : { activityType: keyof typeof ACTIVITIES, isMobile: boolean}) => {
const {displayName, Icon} = ACTIVITIES[activityType]
return (
<div className={`px-3 text-gray-300 space-x-1 w-28 flex ${isMobile ? 'flex-col' : ''}`}>
<div className="flex space-x-2 items-center">
<Icon className="size-4" />{' '}
<div className="text-xs bg-gray-200 text-gray-400 font-bold px-2 py-1 rounded-full mx-auto justify-center align-middle">
{displayName}
</div>{' '}
</div>
</div>
)
}
const ActivityElementOptions = ({ activity, isMobile }: { activity: any; isMobile: boolean }) => {
const [assignmentUUID, setAssignmentUUID] = useState('');
const org = useOrg() as any;
const course = useCourse() as any;
const session = useLHSession() as any;
const access_token = session?.data?.tokens?.access_token;
async function getAssignmentUUIDFromActivityUUID(activityUUID: string): Promise<string | undefined> {
const activity = await getAssignmentFromActivityUUID(activityUUID, access_token);
if (activity) {
return activity.data.assignment_uuid;
}
}
const fetchAssignmentUUID = async () => {
if (activity.activity_type === 'TYPE_ASSIGNMENT') {
const assignment_uuid = await getAssignmentUUIDFromActivityUUID(activity.activity_uuid);
if(assignment_uuid)
setAssignmentUUID(assignment_uuid.replace('assignment_', ''));
}
};
useEffect(() => {
fetchAssignmentUUID();
}, [activity, course]);
return (
<>
{activity.activity_type === 'TYPE_DYNAMIC' && (
<>
<Link
href={
getUriWithOrg(org.slug, '') +
`/course/${course?.courseStructure.course_uuid.replace(
'course_',
''
)}/activity/${activity.activity_uuid.replace(
'activity_',
''
)}/edit`
}
prefetch
className={`hover:cursor-pointer p-1 ${isMobile ? 'px-2' : 'px-3'} bg-sky-700 rounded-md items-center`}
target='_blank'
>
<div className="text-sky-100 font-bold text-xs flex items-center space-x-1">
<FilePenLine size={12} /> <span>Edit Page</span>
</div>
</Link>
</>
)}
{activity.activity_type === 'TYPE_ASSIGNMENT' && (
<>
<Link
href={
getUriWithOrg(org.slug, '') +
`/dash/assignments/${assignmentUUID}`
}
prefetch
className={`hover:cursor-pointer p-1 ${isMobile ? 'px-2' : 'px-3'} bg-teal-700 rounded-md items-center`}
>
<div className="text-sky-100 font-bold text-xs flex items-center space-x-1">
<FilePenLine size={12} /> {!isMobile && <span>Edit Assignment</span>}
</div>
</Link>
</>
)}
</>
);
};
export default ActivityElement

View file

@ -0,0 +1,187 @@
import ConfirmationModal from '@components/Objects/StyledElements/ConfirmationModal/ConfirmationModal'
import {
Hexagon,
MoreHorizontal,
MoreVertical,
Pencil,
Save,
X,
Trash2,
} from 'lucide-react'
import React from 'react'
import { Draggable, Droppable } from 'react-beautiful-dnd'
import ActivityElement from './ActivityElement'
import NewActivityButton from '../Buttons/NewActivityButton'
import { deleteChapter, updateChapter } from '@services/courses/chapters'
import { revalidateTags } from '@services/utils/ts/requests'
import { useRouter } from 'next/navigation'
import { getAPIUrl } from '@services/config/config'
import { mutate } from 'swr'
import { useLHSession } from '@components/Contexts/LHSessionContext'
type ChapterElementProps = {
chapter: any
chapterIndex: number
orgslug: string
course_uuid: string
}
interface ModifiedChapterInterface {
chapterId: string
chapterName: string
}
function ChapterElement(props: ChapterElementProps) {
const activities = props.chapter.activities || []
const session = useLHSession() as any;
const access_token = session?.data?.tokens?.access_token;
const [modifiedChapter, setModifiedChapter] = React.useState<
ModifiedChapterInterface | undefined
>(undefined)
const [selectedChapter, setSelectedChapter] = React.useState<
string | undefined
>(undefined)
const router = useRouter()
const deleteChapterUI = async () => {
await deleteChapter(props.chapter.id, access_token)
mutate(`${getAPIUrl()}courses/${props.course_uuid}/meta`)
await revalidateTags(['courses'], props.orgslug)
router.refresh()
}
async function updateChapterName(chapterId: string) {
if (modifiedChapter?.chapterId === chapterId) {
let modifiedChapterCopy = {
name: modifiedChapter.chapterName,
}
await updateChapter(chapterId, modifiedChapterCopy, access_token)
mutate(`${getAPIUrl()}courses/${props.course_uuid}/meta`)
await revalidateTags(['courses'], props.orgslug)
router.refresh()
}
setSelectedChapter(undefined)
}
return (
<Draggable
key={props.chapter.chapter_uuid}
draggableId={props.chapter.chapter_uuid}
index={props.chapterIndex}
>
{(provided, snapshot) => (
<div
className="mx-2 sm:mx-4 md:mx-6 lg:mx-10 bg-white rounded-xl nice-shadow px-3 sm:px-4 md:px-6 pt-4 sm:pt-6"
key={props.chapter.chapter_uuid}
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
>
<div className="flex flex-wrap items-center justify-between pb-3">
<div className="flex grow items-center space-x-2 mb-2 sm:mb-0">
<div className="bg-neutral-100 rounded-md p-2">
<Hexagon
strokeWidth={3}
size={16}
className="text-neutral-600"
/>
</div>
<div className="flex items-center space-x-2">
{selectedChapter === props.chapter.id ? (
<div className="chapter-modification-zone bg-neutral-100 py-1 px-2 sm:px-4 rounded-lg flex items-center space-x-2">
<input
type="text"
className="bg-transparent outline-none text-sm text-neutral-700 w-full max-w-[150px] sm:max-w-none"
placeholder="Chapter name"
value={
modifiedChapter
? modifiedChapter?.chapterName
: props.chapter.name
}
onChange={(e) =>
setModifiedChapter({
chapterId: props.chapter.id,
chapterName: e.target.value,
})
}
/>
<button
onClick={() => updateChapterName(props.chapter.id)}
className="bg-transparent text-neutral-700 hover:cursor-pointer hover:text-neutral-900"
>
<Save size={15} />
</button>
</div>
) : (
<p className="text-neutral-700 first-letter:uppercase text-sm sm:text-base">
{props.chapter.name}
</p>
)}
<Pencil
size={15}
onClick={() => setSelectedChapter(props.chapter.id)}
className="text-neutral-600 hover:cursor-pointer"
/>
</div>
</div>
<div className="flex items-center space-x-2">
<MoreVertical size={15} className="text-gray-300" />
<ConfirmationModal
confirmationButtonText="Delete Chapter"
confirmationMessage="Are you sure you want to delete this chapter?"
dialogTitle={'Delete ' + props.chapter.name + ' ?'}
dialogTrigger={
<button
className="hover:cursor-pointer p-1 px-2 sm:px-3 bg-red-600 rounded-md shadow flex items-center text-rose-100 text-sm"
rel="noopener noreferrer"
>
<Trash2 size={15} className="text-rose-200" />
</button>
}
functionToExecute={() => deleteChapterUI()}
status="warning"
/>
</div>
</div>
<Droppable
key={props.chapter.chapter_uuid}
droppableId={props.chapter.chapter_uuid}
type="activity"
>
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
<div className="flex flex-col">
{activities.map((activity: any, index: any) => {
return (
<div key={activity.activity_uuid} className="flex items-center ">
<ActivityElement
orgslug={props.orgslug}
course_uuid={props.course_uuid}
activityIndex={index}
activity={activity}
/>
</div>
)
})}
{provided.placeholder}
</div>
</div>
)}
</Droppable>
<NewActivityButton
orgslug={props.orgslug}
chapterId={props.chapter.id}
/>
<div className="h-6">
<div className="flex items-center">
<MoreHorizontal size={19} className="text-gray-300 mx-auto" />
</div>
</div>
</div>
)}
</Draggable>
)
}
export default ChapterElement

View file

@ -0,0 +1,187 @@
'use client'
import { getAPIUrl } from '@services/config/config'
import { revalidateTags } from '@services/utils/ts/requests'
import React, { useEffect, useState } from 'react'
import { DragDropContext, Droppable } from 'react-beautiful-dnd'
import { mutate } from 'swr'
import ChapterElement from './DraggableElements/ChapterElement'
import PageLoading from '@components/Objects/Loaders/PageLoading'
import { createChapter } from '@services/courses/chapters'
import { useRouter } from 'next/navigation'
import {
useCourse,
useCourseDispatch,
} from '@components/Contexts/CourseContext'
import { Hexagon } from 'lucide-react'
import Modal from '@components/Objects/StyledElements/Modal/Modal'
import NewChapterModal from '@components/Objects/Modals/Chapters/NewChapter'
import { useLHSession } from '@components/Contexts/LHSessionContext'
type EditCourseStructureProps = {
orgslug: string
course_uuid?: string
}
export type OrderPayload =
| {
chapter_order_by_ids: [
{
chapter_id: string
activities_order_by_ids: [
{
activity_id: string
},
]
},
]
}
| undefined
const EditCourseStructure = (props: EditCourseStructureProps) => {
const router = useRouter()
const session = useLHSession() as any;
const access_token = session?.data?.tokens?.access_token;
// Check window availability
const [winReady, setwinReady] = useState(false)
const dispatchCourse = useCourseDispatch() as any
const [order, setOrder] = useState<OrderPayload>()
const course = useCourse() as any
const course_structure = course ? course.courseStructure : {}
const course_uuid = course ? course.courseStructure.course_uuid : ''
// New Chapter creation
const [newChapterModal, setNewChapterModal] = useState(false)
const closeNewChapterModal = async () => {
setNewChapterModal(false)
}
// Submit new chapter
const submitChapter = async (chapter: any) => {
await createChapter(chapter,access_token)
mutate(`${getAPIUrl()}courses/${course.courseStructure.course_uuid}/meta`)
await revalidateTags(['courses'], props.orgslug)
router.refresh()
setNewChapterModal(false)
}
const updateStructure = (result: any) => {
const { destination, source, draggableId, type } = result
if (!destination) return
if (
destination.droppableId === source.droppableId &&
destination.index === source.index
)
return
if (type === 'chapter') {
const newChapterOrder = Array.from(course_structure.chapters)
newChapterOrder.splice(source.index, 1)
newChapterOrder.splice(
destination.index,
0,
course_structure.chapters[source.index]
)
dispatchCourse({
type: 'setCourseStructure',
payload: { ...course_structure, chapters: newChapterOrder },
})
dispatchCourse({ type: 'setIsNotSaved' })
}
if (type === 'activity') {
const newChapterOrder = Array.from(course_structure.chapters)
const sourceChapter = newChapterOrder.find(
(chapter: any) => chapter.chapter_uuid === source.droppableId
) as any
const destinationChapter = newChapterOrder.find(
(chapter: any) => chapter.chapter_uuid === destination.droppableId
)
? newChapterOrder.find(
(chapter: any) => chapter.chapter_uuid === destination.droppableId
)
: sourceChapter
const activity = sourceChapter.activities.find(
(activity: any) => activity.activity_uuid === draggableId
)
sourceChapter.activities.splice(source.index, 1)
destinationChapter.activities.splice(destination.index, 0, activity)
dispatchCourse({
type: 'setCourseStructure',
payload: { ...course_structure, chapters: newChapterOrder },
})
dispatchCourse({ type: 'setIsNotSaved' })
}
}
useEffect(() => {
setwinReady(true)
}, [props.course_uuid, course_structure, course])
if (!course) return <PageLoading></PageLoading>
return (
<div className="flex flex-col">
<div className="h-6"></div>
{winReady ? (
<DragDropContext onDragEnd={updateStructure}>
<Droppable type="chapter" droppableId="chapters">
{(provided) => (
<div
className="space-y-4"
{...provided.droppableProps}
ref={provided.innerRef}
>
{course_structure.chapters &&
course_structure.chapters.map((chapter: any, index: any) => {
return (
<ChapterElement
key={chapter.chapter_uuid}
chapterIndex={index}
orgslug={props.orgslug}
course_uuid={course_uuid}
chapter={chapter}
/>
)
})}
{provided.placeholder}
</div>
)}
</Droppable>
{/* New Chapter Modal */}
<Modal
isDialogOpen={newChapterModal}
onOpenChange={setNewChapterModal}
minHeight="sm"
dialogContent={
<NewChapterModal
course={course ? course.courseStructure : null}
closeModal={closeNewChapterModal}
submitChapter={submitChapter}
></NewChapterModal>
}
dialogTitle="Create chapter"
dialogDescription="Add a new chapter to the course"
dialogTrigger={
<div className="w-44 my-16 py-5 max-w-screen-2xl mx-auto bg-cyan-800 text-white rounded-xl shadow-sm px-6 items-center flex flex-row h-10">
<div className="mx-auto flex space-x-2 items-center hover:cursor-pointer">
<Hexagon
strokeWidth={3}
size={16}
className="text-white text-sm "
/>
<div className="font-bold text-sm">Add Chapter</div>
</div>
</div>
}
/>
</DragDropContext>
) : (
<></>
)}
</div>
)
}
export default EditCourseStructure

View file

@ -0,0 +1,243 @@
'use client'
import React, { useEffect, useState } from 'react'
import { Field, Form, Formik } from 'formik'
import {
updateOrganization,
uploadOrganizationLogo,
uploadOrganizationThumbnail,
} from '@services/settings/org'
import { UploadCloud, Info } from 'lucide-react'
import { revalidateTags } from '@services/utils/ts/requests'
import { useRouter } from 'next/navigation'
import { useOrg } from '@components/Contexts/OrgContext'
import { useLHSession } from '@components/Contexts/LHSessionContext'
import { getOrgLogoMediaDirectory, getOrgThumbnailMediaDirectory } from '@services/media/media'
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@components/Ui/tabs"
import { Toaster, toast } from 'react-hot-toast';
import { constructAcceptValue } from '@/lib/constants';
const SUPPORTED_FILES = constructAcceptValue(['png', 'jpg'])
interface OrganizationValues {
name: string
description: string
slug: string
logo: string
email: string
thumbnail: string
}
function OrgEditGeneral() {
const router = useRouter()
const session = useLHSession() as any
const access_token = session?.data?.tokens?.access_token
const org = useOrg() as any
const [selectedTab, setSelectedTab] = useState<'logo' | 'thumbnail'>('logo');
const [localLogo, setLocalLogo] = useState<string | null>(null);
const [localThumbnail, setLocalThumbnail] = useState<string | null>(null);
const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files.length > 0) {
const file = event.target.files[0]
setLocalLogo(URL.createObjectURL(file))
const loadingToast = toast.loading('Uploading logo...');
try {
await uploadOrganizationLogo(org.id, file, access_token)
await new Promise((r) => setTimeout(r, 1500))
toast.success('Logo Updated', { id: loadingToast });
router.refresh()
} catch (err) {
toast.error('Failed to upload logo', { id: loadingToast });
}
}
}
const handleThumbnailChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files.length > 0) {
const file = event.target.files[0];
setLocalThumbnail(URL.createObjectURL(file));
const loadingToast = toast.loading('Uploading thumbnail...');
try {
await uploadOrganizationThumbnail(org.id, file, access_token);
await new Promise((r) => setTimeout(r, 1500));
toast.success('Thumbnail Updated', { id: loadingToast });
router.refresh()
} catch (err) {
toast.error('Failed to upload thumbnail', { id: loadingToast });
}
}
};
const handleImageButtonClick = (inputId: string) => (event: React.MouseEvent) => {
event.preventDefault(); // Prevent form submission
document.getElementById(inputId)?.click();
};
let orgValues: OrganizationValues = {
name: org?.name,
description: org?.description,
slug: org?.slug,
logo: org?.logo,
email: org?.email,
thumbnail: org?.thumbnail,
}
const updateOrg = async (values: OrganizationValues) => {
const loadingToast = toast.loading('Updating organization...');
try {
await updateOrganization(org.id, values, access_token)
await revalidateTags(['organizations'], org.slug)
toast.success('Organization Updated', { id: loadingToast });
} catch (err) {
toast.error('Failed to update organization', { id: loadingToast });
}
}
useEffect(() => {}, [org])
return (
<div className="sm:ml-10 sm:mr-10 ml-0 mr-0 mx-auto bg-white rounded-xl shadow-sm px-6 py-5 sm:mb-0 mb-16">
<Toaster />
<Formik
enableReinitialize
initialValues={orgValues}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
setSubmitting(false)
updateOrg(values)
}, 400)
}}
>
{({ isSubmitting }) => (
<Form>
<div className="flex flex-col lg:flex-row lg:space-x-8">
<div className="w-full lg:w-1/2 mb-8 lg:mb-0">
<label className="block mb-2 font-bold" htmlFor="name">
Name
</label>
<Field
className="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
type="text"
name="name"
/>
<label className="block mb-2 font-bold" htmlFor="description">
Description
</label>
<Field
className="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
type="text"
name="description"
/>
<label className="block mb-2 font-bold" htmlFor="slug">
Slug
</label>
<Field
className="w-full px-4 py-2 mb-4 border rounded-lg bg-gray-200 cursor-not-allowed"
disabled
type="text"
name="slug"
/>
<label className="block mb-2 font-bold" htmlFor="email">
Email
</label>
<Field
className="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
type="email"
name="email"
/>
<button
type="submit"
disabled={isSubmitting}
className="w-full sm:w-auto px-6 py-3 text-white bg-black rounded-lg shadow-md hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-black"
>
Submit
</button>
</div>
<div className="w-full lg:w-1/2">
<Tabs defaultValue="logo" className="w-full">
<TabsList className="grid w-full grid-cols-2 mb-6 sm:mb-10">
<TabsTrigger value="logo">Logo</TabsTrigger>
<TabsTrigger value="thumbnail">Thumbnail</TabsTrigger>
</TabsList>
<TabsContent value="logo">
<div className="flex flex-col space-y-3">
<div className="w-auto bg-gray-50 rounded-xl outline outline-1 outline-gray-200 h-[200px] shadow mx-4 sm:mx-10">
<div className="flex flex-col justify-center items-center mt-6 sm:mt-10">
<div
className="w-[150px] sm:w-[200px] h-[75px] sm:h-[100px] bg-contain bg-no-repeat bg-center rounded-lg nice-shadow bg-white"
style={{ backgroundImage: `url(${localLogo || getOrgLogoMediaDirectory(org?.org_uuid, org?.logo_image)})` }}
/>
</div>
<div className="flex justify-center items-center">
<input
type="file"
id="fileInput"
accept={SUPPORTED_FILES}
style={{ display: 'none' }}
onChange={handleFileChange}
/>
<button
type="button"
className="font-bold antialiased items-center text-gray text-sm rounded-md px-4 py-2 mt-4 flex"
onClick={handleImageButtonClick('fileInput')}
>
<UploadCloud size={16} className="mr-2" />
<span>Change Logo</span>
</button>
</div>
</div>
<div className="flex text-xs space-x-2 items-center text-gray-500 justify-center">
<Info size={13} />
<p>Accepts PNG, JPG</p>
</div>
</div>
</TabsContent>
<TabsContent value="thumbnail">
<div className="flex flex-col space-y-3">
<div className="w-auto bg-gray-50 rounded-xl outline outline-1 outline-gray-200 h-[200px] shadow mx-4 sm:mx-10">
<div className="flex flex-col justify-center items-center mt-6 sm:mt-10">
<div
className="w-[150px] sm:w-[200px] h-[75px] sm:h-[100px] bg-contain bg-no-repeat bg-center rounded-lg nice-shadow bg-white"
style={{ backgroundImage: `url(${localThumbnail || getOrgThumbnailMediaDirectory(org?.org_uuid, org?.thumbnail_image)})` }}
/>
</div>
<div className="flex justify-center items-center">
<input
type="file"
accept={SUPPORTED_FILES}
id="thumbnailInput"
style={{ display: 'none' }}
onChange={handleThumbnailChange}
/>
<button
type="button"
className="font-bold antialiased items-center text-gray text-sm rounded-md px-4 py-2 mt-4 flex"
onClick={handleImageButtonClick('thumbnailInput')}
>
<UploadCloud size={16} className="mr-2" />
<span>Change Thumbnail</span>
</button>
</div>
</div>
<div className="flex text-xs space-x-2 items-center text-gray-500 justify-center">
<Info size={13} />
<p>Accepts PNG, JPG</p>
</div>
</div>
</TabsContent>
</Tabs>
</div>
</div>
</Form>
)}
</Formik>
</div>
)
}
export default OrgEditGeneral

View file

@ -0,0 +1,290 @@
'use client';
import React, { useState, useEffect } from 'react';
import { useOrg } from '@components/Contexts/OrgContext';
import { SiStripe } from '@icons-pack/react-simple-icons'
import { useLHSession } from '@components/Contexts/LHSessionContext';
import { getPaymentConfigs, initializePaymentConfig, updatePaymentConfig, deletePaymentConfig, updateStripeAccountID, getStripeOnboardingLink } from '@services/payments/payments';
import FormLayout, { ButtonBlack, Input, Textarea, FormField, FormLabelAndMessage, Flex } from '@components/Objects/StyledElements/Form/Form';
import { AlertTriangle, BarChart2, Check, Coins, CreditCard, Edit, ExternalLink, Info, Loader2, RefreshCcw, Trash2, UnplugIcon } from 'lucide-react';
import toast from 'react-hot-toast';
import useSWR, { mutate } from 'swr';
import Modal from '@components/Objects/StyledElements/Modal/Modal';
import ConfirmationModal from '@components/Objects/StyledElements/ConfirmationModal/ConfirmationModal';
import { Button } from '@components/Ui/button';
import { Alert, AlertDescription, AlertTitle } from '@components/Ui/alert';
import { useRouter } from 'next/navigation';
import { getUriWithoutOrg } from '@services/config/config';
const PaymentsConfigurationPage: React.FC = () => {
const org = useOrg() as any;
const session = useLHSession() as any;
const router = useRouter();
const access_token = session?.data?.tokens?.access_token;
const { data: paymentConfigs, error, isLoading } = useSWR(
() => (org && access_token ? [`/payments/${org.id}/config`, access_token] : null),
([url, token]) => getPaymentConfigs(org.id, token)
);
const stripeConfig = paymentConfigs?.find((config: any) => config.provider === 'stripe');
const [isModalOpen, setIsModalOpen] = useState(false);
const [isOnboarding, setIsOnboarding] = useState(false);
const [isOnboardingLoading, setIsOnboardingLoading] = useState(false);
const enableStripe = async () => {
try {
setIsOnboarding(true);
const newConfig = { provider: 'stripe', enabled: true };
const config = await initializePaymentConfig(org.id, newConfig, 'stripe', access_token);
toast.success('Stripe enabled successfully');
mutate([`/payments/${org.id}/config`, access_token]);
} catch (error) {
console.error('Error enabling Stripe:', error);
toast.error('Failed to enable Stripe');
} finally {
setIsOnboarding(false);
}
};
const editConfig = async () => {
setIsModalOpen(true);
};
const deleteConfig = async () => {
try {
await deletePaymentConfig(org.id, stripeConfig.id, access_token);
toast.success('Stripe configuration deleted successfully');
mutate([`/payments/${org.id}/config`, access_token]);
} catch (error) {
console.error('Error deleting Stripe configuration:', error);
toast.error('Failed to delete Stripe configuration');
}
};
const handleStripeOnboarding = async () => {
try {
setIsOnboardingLoading(true);
const { connect_url } = await getStripeOnboardingLink(org.id, access_token, getUriWithoutOrg('/payments/stripe/connect/oauth'));
window.open(connect_url, '_blank');
} catch (error) {
console.error('Error getting onboarding link:', error);
toast.error('Failed to start Stripe onboarding');
} finally {
setIsOnboardingLoading(false);
}
};
if (isLoading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error loading payment configuration</div>;
}
return (
<div>
<div className="ml-10 mr-10 mx-auto bg-white rounded-xl shadow-sm px-4 py-4">
<div className="flex flex-col bg-gray-50 -space-y-1 px-5 py-3 rounded-md mb-3">
<h1 className="font-bold text-xl text-gray-800">Payments Configuration</h1>
<h2 className="text-gray-500 text-md">Manage your organization payments configuration</h2>
</div>
<Alert className="mb-3 p-6 border-2 border-blue-100 bg-blue-50/50">
<AlertTitle className="text-lg font-semibold mb-2 flex items-center space-x-2"> <Info className="h-5 w-5 " /> <span>About the Stripe Integration</span></AlertTitle>
<AlertDescription className="space-y-5">
<div className="pl-2">
<ul className="list-disc list-inside space-y-1 text-gray-600 pl-2">
<li className="flex items-center space-x-2">
<CreditCard className="h-4 w-4" />
<span>Accept payments for courses and subscriptions</span>
</li>
<li className="flex items-center space-x-2">
<RefreshCcw className="h-4 w-4" />
<span>Manage recurring billing and subscriptions</span>
</li>
<li className="flex items-center space-x-2">
<Coins className="h-4 w-4" />
<span>Handle multiple currencies and payment methods</span>
</li>
<li className="flex items-center space-x-2">
<BarChart2 className="h-4 w-4" />
<span>Access detailed payment analytics</span>
</li>
</ul>
</div>
<a
href="https://stripe.com/docs"
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:text-blue-800 inline-flex items-center font-medium transition-colors duration-200 pl-2"
>
Learn more about Stripe
<ExternalLink className="ml-1.5 h-4 w-4" />
</a>
</AlertDescription>
</Alert>
<div className="flex flex-col rounded-lg light-shadow">
{stripeConfig ? (
<div className="flex items-center justify-between bg-gradient-to-r from-indigo-500 to-purple-600 p-6 rounded-lg shadow-md">
<div className="flex items-center space-x-3">
<SiStripe className="text-white" size={32} />
<div className="flex flex-col">
<div className="flex items-center space-x-2">
<span className="text-xl font-semibold text-white">Stripe</span>
{stripeConfig.provider_specific_id && stripeConfig.active ? (
<div className="flex items-center space-x-1 bg-green-500/20 px-2 py-0.5 rounded-full">
<div className="h-2 w-2 bg-green-500 rounded-full" />
<span className="text-xs text-green-100">Connected</span>
</div>
) : (
<div className="flex items-center space-x-1 bg-red-500/20 px-2 py-0.5 rounded-full">
<div className="h-2 w-2 bg-red-500 rounded-full" />
<span className="text-xs text-red-100">Not Connected</span>
</div>
)}
</div>
<span className="text-white/80 text-sm">
{stripeConfig.provider_specific_id ?
`Linked Account: ${stripeConfig.provider_specific_id}` :
'Account ID not configured'}
</span>
</div>
</div>
<div className="flex space-x-2">
{(!stripeConfig.provider_specific_id || !stripeConfig.active) && (
<Button
onClick={handleStripeOnboarding}
className="flex items-center space-x-2 px-4 py-2 bg-green-500 text-white text-sm rounded-full hover:bg-green-600 transition duration-300 disabled:opacity-50 disabled:cursor-not-allowed border-2 border-green-400 shadow-md"
disabled={isOnboardingLoading}
>
{isOnboardingLoading ? (
<Loader2 className="animate-spin h-4 w-4" />
) : (
<UnplugIcon className="h-3 w-3" />
)}
<span className="font-semibold">Connect with Stripe</span>
</Button>
)}
<ConfirmationModal
confirmationButtonText="Remove Connection"
confirmationMessage="Are you sure you want to remove the Stripe connection? This action cannot be undone."
dialogTitle="Remove Stripe Connection"
dialogTrigger={
<Button
className="flex items-center space-x-2 bg-red-500 text-white text-sm rounded-full hover:bg-red-600 transition duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
>
<Trash2 size={16} />
<span>Remove Connection</span>
</Button>
}
functionToExecute={deleteConfig}
status="warning"
/>
</div>
</div>
) : (
<Button
onClick={enableStripe}
className="flex items-center justify-center space-x-2 bg-gradient-to-r p-3 from-indigo-500 to-purple-600 text-white px-6 rounded-lg hover:from-indigo-600 hover:to-purple-700 transition duration-300 shadow-md disabled:opacity-50 disabled:cursor-not-allowed"
disabled={isOnboarding}
>
{isOnboarding ? (
<>
<Loader2 className="animate-spin" size={24} />
<span className="text-lg font-semibold">Connecting to Stripe...</span>
</>
) : (
<>
<SiStripe size={24} />
<span className="text-lg font-semibold">Enable Stripe</span>
</>
)}
</Button>
)}
</div>
</div>
{stripeConfig && (
<EditStripeConfigModal
orgId={org.id}
configId={stripeConfig.id}
accessToken={access_token}
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
/>
)}
</div>
);
};
interface EditStripeConfigModalProps {
orgId: number;
configId: string;
accessToken: string;
isOpen: boolean;
onClose: () => void;
}
const EditStripeConfigModal: React.FC<EditStripeConfigModalProps> = ({ orgId, configId, accessToken, isOpen, onClose }) => {
const [stripeAccountId, setStripeAccountId] = useState('');
useEffect(() => {
const fetchConfig = async () => {
try {
const config = await getPaymentConfigs(orgId, accessToken);
const stripeConfig = config.find((c: any) => c.id === configId);
if (stripeConfig && stripeConfig.provider_specific_id) {
setStripeAccountId(stripeConfig.provider_specific_id || '');
}
} catch (error) {
console.error('Error fetching Stripe configuration:', error);
toast.error('Failed to load existing configuration');
}
};
if (isOpen) {
fetchConfig();
}
}, [isOpen, orgId, configId, accessToken]);
const handleSubmit = async () => {
try {
const stripe_config = {
stripe_account_id: stripeAccountId,
};
await updateStripeAccountID(orgId, stripe_config, accessToken);
toast.success('Configuration updated successfully');
mutate([`/payments/${orgId}/config`, accessToken]);
onClose();
} catch (error) {
console.error('Error updating config:', error);
toast.error('Failed to update configuration');
}
};
return (
<Modal isDialogOpen={isOpen} dialogTitle="Edit Stripe Configuration" dialogDescription='Edit your stripe configuration' onOpenChange={onClose}
dialogContent={
<FormLayout onSubmit={handleSubmit}>
<FormField name="stripe-account-id">
<FormLabelAndMessage label="Stripe Account ID" />
<Input
type="text"
value={stripeAccountId}
onChange={(e) => setStripeAccountId(e.target.value)}
placeholder="acct_..."
/>
</FormField>
<Flex css={{ marginTop: 25, justifyContent: 'flex-end' }}>
<ButtonBlack type="submit" className="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition duration-300">
Save
</ButtonBlack>
</Flex>
</FormLayout>
}
/>
);
};
export default PaymentsConfigurationPage;

View file

@ -0,0 +1,155 @@
import React from 'react'
import { useOrg } from '@components/Contexts/OrgContext'
import { useLHSession } from '@components/Contexts/LHSessionContext'
import useSWR from 'swr'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@components/Ui/table"
import { getOrgCustomers } from '@services/payments/payments'
import { Badge } from '@components/Ui/badge'
import PageLoading from '@components/Objects/Loaders/PageLoading'
import { RefreshCcw, SquareCheck } from 'lucide-react'
import { getUserAvatarMediaDirectory } from '@services/media/media'
import UserAvatar from '@components/Objects/UserAvatar'
import { usePaymentsEnabled } from '@hooks/usePaymentsEnabled'
import UnconfiguredPaymentsDisclaimer from '@components/Pages/Payments/UnconfiguredPaymentsDisclaimer'
interface PaymentUserData {
payment_user_id: number;
user: {
username: string;
first_name: string;
last_name: string;
email: string;
avatar_image: string;
user_uuid: string;
};
product: {
name: string;
description: string;
product_type: string;
amount: number;
currency: string;
};
status: string;
creation_date: string;
}
function PaymentsUsersTable({ data }: { data: PaymentUserData[] }) {
if (!data || data.length === 0) {
return (
<div className="text-center py-8 text-gray-500">
No customers found
</div>
);
}
return (
<Table>
<TableHeader>
<TableRow>
<TableHead>User</TableHead>
<TableHead>Product</TableHead>
<TableHead>Type</TableHead>
<TableHead>Amount</TableHead>
<TableHead>Status</TableHead>
<TableHead>Purchase Date</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.map((item) => (
<TableRow key={item.payment_user_id}>
<TableCell className="font-medium">
<div className="flex items-center space-x-3">
<UserAvatar
border="border-2"
rounded="rounded-md"
avatar_url={getUserAvatarMediaDirectory(item.user.user_uuid, item.user.avatar_image)}
/>
<div className="flex flex-col">
<span className="font-medium">
{item.user.first_name || item.user.username}
</span>
<span className="text-sm text-gray-500">{item.user.email}</span>
</div>
</div>
</TableCell>
<TableCell>{item.product.name}</TableCell>
<TableCell>
<div className="flex items-center space-x-2">
{item.product.product_type === 'subscription' ? (
<Badge variant="outline" className="flex items-center gap-1">
<RefreshCcw size={12} />
<span>Subscription</span>
</Badge>
) : (
<Badge variant="outline" className="flex items-center gap-1">
<SquareCheck size={12} />
<span>One-time</span>
</Badge>
)}
</div>
</TableCell>
<TableCell>
{new Intl.NumberFormat('en-US', {
style: 'currency',
currency: item.product.currency
}).format(item.product.amount)}
</TableCell>
<TableCell>
<Badge
variant={item.status === 'active' ? 'default' :
item.status === 'completed' ? 'default' : 'secondary'}
>
{item.status}
</Badge>
</TableCell>
<TableCell>
{new Date(item.creation_date).toLocaleDateString()}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
);
}
function PaymentsCustomersPage() {
const org = useOrg() as any
const session = useLHSession() as any
const access_token = session?.data?.tokens?.access_token
const { isEnabled, isLoading } = usePaymentsEnabled()
const { data: customers, error, isLoading: customersLoading } = useSWR(
org ? [`/payments/${org.id}/customers`, access_token] : null,
([url, token]) => getOrgCustomers(org.id, token)
)
if (!isEnabled && !isLoading) {
return (
<UnconfiguredPaymentsDisclaimer />
)
}
if (isLoading || customersLoading) return <PageLoading />
if (error) return <div>Error loading customers</div>
if (!customers) return <div>No customer data available</div>
return (
<div className="ml-10 mr-10 mx-auto bg-white rounded-xl shadow-sm px-4 py-4">
<div className="flex flex-col bg-gray-50 -space-y-1 px-5 py-3 rounded-md mb-3">
<h1 className="font-bold text-xl text-gray-800">Customers</h1>
<h2 className="text-gray-500 text-md">View and manage your customer information</h2>
</div>
<PaymentsUsersTable data={customers} />
</div>
)
}
export default PaymentsCustomersPage

View file

@ -0,0 +1,312 @@
'use client';
import React, { useState, useEffect } from 'react'
import currencyCodes from 'currency-codes';
import { useOrg } from '@components/Contexts/OrgContext';
import { useLHSession } from '@components/Contexts/LHSessionContext';
import useSWR, { mutate } from 'swr';
import { getProducts, updateProduct, archiveProduct } from '@services/payments/products';
import { Plus, Pencil, Info, RefreshCcw, SquareCheck, ChevronDown, ChevronUp, Archive } from 'lucide-react';
import Modal from '@components/Objects/StyledElements/Modal/Modal';
import ConfirmationModal from '@components/Objects/StyledElements/ConfirmationModal/ConfirmationModal';
import toast from 'react-hot-toast';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@components/Ui/select"
import { Button } from "@components/Ui/button"
import { Input } from "@components/Ui/input"
import { Textarea } from "@components/Ui/textarea"
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import { Label } from '@components/Ui/label';
import { Badge } from '@components/Ui/badge';
import { getPaymentConfigs } from '@services/payments/payments';
import ProductLinkedCourses from './SubComponents/ProductLinkedCourses';
import { usePaymentsEnabled } from '@hooks/usePaymentsEnabled';
import UnconfiguredPaymentsDisclaimer from '@components/Pages/Payments/UnconfiguredPaymentsDisclaimer';
import CreateProductForm from './SubComponents/CreateProductForm';
const validationSchema = Yup.object().shape({
name: Yup.string().required('Name is required'),
description: Yup.string().required('Description is required'),
amount: Yup.number().min(0, 'Amount must be positive').required('Amount is required'),
benefits: Yup.string(),
currency: Yup.string().required('Currency is required'),
});
function PaymentsProductPage() {
const org = useOrg() as any;
const session = useLHSession() as any;
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const [editingProductId, setEditingProductId] = useState<string | null>(null);
const [expandedProducts, setExpandedProducts] = useState<{ [key: string]: boolean }>({});
const [isStripeEnabled, setIsStripeEnabled] = useState(false);
const { isEnabled, isLoading } = usePaymentsEnabled();
const { data: products, error } = useSWR(
() => org && session ? [`/payments/${org.id}/products`, session.data?.tokens?.access_token] : null,
([url, token]) => getProducts(org.id, token)
);
const { data: paymentConfigs, error: paymentConfigError } = useSWR(
() => org && session ? [`/payments/${org.id}/config`, session.data?.tokens?.access_token] : null,
([url, token]) => getPaymentConfigs(org.id, token)
);
useEffect(() => {
if (paymentConfigs) {
const stripeConfig = paymentConfigs.find((config: any) => config.provider === 'stripe');
setIsStripeEnabled(!!stripeConfig);
}
}, [paymentConfigs]);
const handleArchiveProduct = async (productId: string) => {
const res = await archiveProduct(org.id, productId, session.data?.tokens?.access_token);
mutate([`/payments/${org.id}/products`, session.data?.tokens?.access_token]);
if (res.status === 200) {
toast.success('Product archived successfully');
} else {
toast.error(res.data.detail);
}
}
const toggleProductExpansion = (productId: string) => {
setExpandedProducts(prev => ({
...prev,
[productId]: !prev[productId]
}));
};
if (!isEnabled && !isLoading) {
return (
<UnconfiguredPaymentsDisclaimer />
);
}
if (error) return <div>Failed to load products</div>;
if (!products) return <div>Loading...</div>;
return (
<div className="h-full w-full bg-[#f8f8f8]">
<div className="pl-10 pr-10 mx-auto">
<Modal
isDialogOpen={isCreateModalOpen}
onOpenChange={setIsCreateModalOpen}
dialogTitle="Create New Product"
dialogDescription="Add a new product to your organization"
dialogContent={
<CreateProductForm onSuccess={() => setIsCreateModalOpen(false)} />
}
/>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{products.data.map((product: any) => (
<div key={product.id} className="bg-white p-4 rounded-lg nice-shadow flex flex-col h-full">
{editingProductId === product.id ? (
<EditProductForm
product={product}
onSuccess={() => setEditingProductId(null)}
onCancel={() => setEditingProductId(null)}
/>
) : (
<div className="flex flex-col h-full">
<div className="flex justify-between items-start mb-2">
<div className="flex flex-col space-y-1 items-start">
<Badge className='w-fit flex items-center space-x-2' variant="outline">
{product.product_type === 'subscription' ? <RefreshCcw size={12} /> : <SquareCheck size={12} />}
<span className='text-sm'>{product.product_type === 'subscription' ? 'Subscription' : 'One-time payment'}</span>
</Badge>
<h3 className="font-bold text-lg">{product.name}</h3>
</div>
<div className="flex space-x-2">
<button
onClick={() => setEditingProductId(product.id)}
className={`text-blue-500 hover:text-blue-700 ${isStripeEnabled ? '' : 'opacity-50 cursor-not-allowed'}`}
disabled={!isStripeEnabled}
>
<Pencil size={16} />
</button>
<ConfirmationModal
confirmationButtonText="Archive Product"
confirmationMessage="Are you sure you want to archive this product?"
dialogTitle={`Archive ${product.name}?`}
dialogTrigger={
<button className="text-red-500 hover:text-red-700">
<Archive size={16} />
</button>
}
functionToExecute={() => handleArchiveProduct(product.id)}
status="warning"
/>
</div>
</div>
<div className="flex-grow overflow-hidden">
<div className={`transition-all duration-300 ease-in-out ${expandedProducts[product.id] ? 'max-h-[1000px]' : 'max-h-24'} overflow-hidden`}>
<p className="text-gray-600">
{product.description}
</p>
{product.benefits && (
<div className="mt-2">
<h4 className="font-semibold text-sm">Benefits:</h4>
<p className="text-sm text-gray-600">
{product.benefits}
</p>
</div>
)}
</div>
</div>
<div className="mt-2">
<button
onClick={() => toggleProductExpansion(product.id)}
className="text-slate-500 hover:text-slate-700 text-sm flex items-center"
>
{expandedProducts[product.id] ? (
<>
<ChevronUp size={16} />
<span>Show less</span>
</>
) : (
<>
<ChevronDown size={16} />
<span>Show more</span>
</>
)}
</button>
</div>
<ProductLinkedCourses productId={product.id} />
<div className="mt-2 flex items-center justify-between bg-gray-100 rounded-md p-2">
<span className="text-sm text-gray-600">Price:</span>
<span className="font-semibold text-lg">
{new Intl.NumberFormat('en-US', { style: 'currency', currency: product.currency }).format(product.amount)}
</span>
</div>
</div>
)}
</div>
))}
</div>
{products.data.length === 0 && (
<div className="flex mx-auto space-x-2 font-semibold mt-3 text-gray-600 items-center">
<Info size={20} />
<p>No products available. Create a new product to get started.</p>
</div>
)}
<div className="flex justify-center items-center py-10">
<button
onClick={() => setIsCreateModalOpen(true)}
className={`mb-4 flex items-center space-x-2 px-3 py-1.5 rounded-lg bg-gradient-to-bl text-white font-medium from-gray-700 to-gray-900 border border-gray-600 shadow-gray-900/20 nice-shadow transition duration-300 ${isStripeEnabled ? 'hover:from-gray-600 hover:to-gray-800' : 'opacity-50 cursor-not-allowed'
}`}
disabled={!isStripeEnabled}
>
<Plus size={18} />
<span className="text-sm font-bold">Create New Product</span>
</button>
</div>
</div>
</div>
)
}
const EditProductForm = ({ product, onSuccess, onCancel }: { product: any, onSuccess: () => void, onCancel: () => void }) => {
const org = useOrg() as any;
const session = useLHSession() as any;
const [currencies, setCurrencies] = useState<{ code: string; name: string }[]>([]);
useEffect(() => {
const allCurrencies = currencyCodes.data.map(currency => ({
code: currency.code,
name: `${currency.code} - ${currency.currency}`
}));
setCurrencies(allCurrencies);
}, []);
const initialValues = {
name: product.name,
description: product.description,
amount: product.amount,
benefits: product.benefits || '',
currency: product.currency || '',
product_type: product.product_type,
};
const handleSubmit = async (values: typeof initialValues, { setSubmitting }: { setSubmitting: (isSubmitting: boolean) => void }) => {
try {
await updateProduct(org.id, product.id, values, session.data?.tokens?.access_token);
mutate([`/payments/${org.id}/products`, session.data?.tokens?.access_token]);
onSuccess();
toast.success('Product updated successfully');
} catch (error) {
toast.error('Failed to update product');
} finally {
setSubmitting(false);
}
};
return (
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={handleSubmit}
>
{({ isSubmitting, values, setFieldValue }) => (
<Form className="space-y-4">
<div className='px-1.5 py-2 flex-col space-y-3'>
<div>
<Label htmlFor="name">Product Name</Label>
<Field name="name" as={Input} placeholder="Product Name" />
<ErrorMessage name="name" component="div" className="text-red-500 text-sm mt-1" />
</div>
<div>
<Label htmlFor="description">Description</Label>
<Field name="description" as={Textarea} placeholder="Product Description" />
<ErrorMessage name="description" component="div" className="text-red-500 text-sm mt-1" />
</div>
<div className="flex space-x-2">
<div className="flex-grow">
<Label htmlFor="amount">Price</Label>
<Field name="amount" as={Input} type="number" placeholder="Price" />
<ErrorMessage name="amount" component="div" className="text-red-500 text-sm mt-1" />
</div>
<div className="w-1/3">
<Label htmlFor="currency">Currency</Label>
<Select
value={values.currency}
onValueChange={(value) => setFieldValue('currency', value)}
>
<SelectTrigger>
<SelectValue placeholder="Currency" />
</SelectTrigger>
<SelectContent>
{currencies.map((currency) => (
<SelectItem key={currency.code} value={currency.code}>
{currency.name}
</SelectItem>
))}
</SelectContent>
</Select>
<ErrorMessage name="currency" component="div" className="text-red-500 text-sm mt-1" />
</div>
</div>
<div>
<Label htmlFor="benefits">Benefits</Label>
<Field name="benefits" as={Textarea} placeholder="Product Benefits" />
<ErrorMessage name="benefits" component="div" className="text-red-500 text-sm mt-1" />
</div>
</div>
<div className="flex justify-end space-x-2">
<Button type="button" variant="outline" onClick={onCancel}>Cancel</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Saving...' : 'Save'}
</Button>
</div>
</Form>
)}
</Formik>
);
};
export default PaymentsProductPage

View file

@ -0,0 +1,184 @@
import React, { useEffect, useState } from 'react';
import { useOrg } from '@components/Contexts/OrgContext';
import { useLHSession } from '@components/Contexts/LHSessionContext';
import { createProduct } from '@services/payments/products';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import toast from 'react-hot-toast';
import { mutate } from 'swr';
import { Button } from "@components/Ui/button";
import { Input } from "@components/Ui/input";
import { Textarea } from "@components/Ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@components/Ui/select";
import { Label } from "@components/Ui/label";
import currencyCodes from 'currency-codes';
const validationSchema = Yup.object().shape({
name: Yup.string().required('Name is required'),
description: Yup.string().required('Description is required'),
amount: Yup.number()
.min(1, 'Amount must be greater than zero')
.required('Amount is required'),
benefits: Yup.string(),
currency: Yup.string().required('Currency is required'),
product_type: Yup.string().oneOf(['one_time', 'subscription']).required('Product type is required'),
price_type: Yup.string().oneOf(['fixed_price', 'customer_choice']).required('Price type is required'),
});
interface ProductFormValues {
name: string;
description: string;
product_type: 'one_time' | 'subscription';
price_type: 'fixed_price' | 'customer_choice';
benefits: string;
amount: number;
currency: string;
}
const CreateProductForm: React.FC<{ onSuccess: () => void }> = ({ onSuccess }) => {
const org = useOrg() as any;
const session = useLHSession() as any;
const [currencies, setCurrencies] = useState<{ code: string; name: string }[]>([]);
useEffect(() => {
const allCurrencies = currencyCodes.data.map(currency => ({
code: currency.code,
name: `${currency.code} - ${currency.currency}`
}));
setCurrencies(allCurrencies);
}, []);
const initialValues: ProductFormValues = {
name: '',
description: '',
product_type: 'one_time',
price_type: 'fixed_price',
benefits: '',
amount: 1,
currency: 'USD',
};
const handleSubmit = async (values: ProductFormValues, { setSubmitting, resetForm }: any) => {
try {
const res = await createProduct(org.id, values, session.data?.tokens?.access_token);
if (res.success) {
toast.success('Product created successfully');
mutate([`/payments/${org.id}/products`, session.data?.tokens?.access_token]);
resetForm();
onSuccess();
} else {
toast.error('Failed to create product');
}
} catch (error) {
console.error('Error creating product:', error);
toast.error('An error occurred while creating the product');
} finally {
setSubmitting(false);
}
};
return (
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={handleSubmit}
>
{({ isSubmitting, values, setFieldValue }) => (
<Form className="space-y-4">
<div className='px-1.5 py-2 flex-col space-y-3'>
<div>
<Label htmlFor="name">Product Name</Label>
<Field name="name" as={Input} placeholder="Product Name" />
<ErrorMessage name="name" component="div" className="text-red-500 text-sm mt-1" />
</div>
<div>
<Label htmlFor="description">Description</Label>
<Field name="description" as={Textarea} placeholder="Product Description" />
<ErrorMessage name="description" component="div" className="text-red-500 text-sm mt-1" />
</div>
<div>
<Label htmlFor="product_type">Product Type</Label>
<Select
value={values.product_type}
onValueChange={(value) => setFieldValue('product_type', value)}
>
<SelectTrigger>
<SelectValue placeholder="Product Type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="one_time">One Time</SelectItem>
<SelectItem value="subscription">Subscription</SelectItem>
</SelectContent>
</Select>
<ErrorMessage name="product_type" component="div" className="text-red-500 text-sm mt-1" />
</div>
<div>
<Label htmlFor="price_type">Price Type</Label>
<Select
value={values.price_type}
onValueChange={(value) => setFieldValue('price_type', value)}
>
<SelectTrigger>
<SelectValue placeholder="Price Type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="fixed_price">Fixed Price</SelectItem>
{values.product_type !== 'subscription' && (
<SelectItem value="customer_choice">Customer Choice</SelectItem>
)}
</SelectContent>
</Select>
<ErrorMessage name="price_type" component="div" className="text-red-500 text-sm mt-1" />
</div>
<div className="flex space-x-2">
<div className="flex-grow">
<Label htmlFor="amount">
{values.price_type === 'fixed_price' ? 'Price' : 'Minimum Amount'}
</Label>
<Field name="amount" as={Input} type="number" placeholder={values.price_type === 'fixed_price' ? 'Price' : 'Minimum Amount'} />
<ErrorMessage name="amount" component="div" className="text-red-500 text-sm mt-1" />
</div>
<div className="w-1/3">
<Label htmlFor="currency">Currency</Label>
<Select
value={values.currency}
onValueChange={(value) => setFieldValue('currency', value)}
>
<SelectTrigger>
<SelectValue placeholder="Currency" />
</SelectTrigger>
<SelectContent>
{currencies.map((currency) => (
<SelectItem key={currency.code} value={currency.code}>
{currency.name}
</SelectItem>
))}
</SelectContent>
</Select>
<ErrorMessage name="currency" component="div" className="text-red-500 text-sm mt-1" />
</div>
</div>
<div>
<Label htmlFor="benefits">Benefits</Label>
<Field name="benefits" as={Textarea} placeholder="Product Benefits" />
<ErrorMessage name="benefits" component="div" className="text-red-500 text-sm mt-1" />
</div>
</div>
<div className="flex justify-end">
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Creating...' : 'Create Product'}
</Button>
</div>
</Form>
)}
</Formik>
);
};
export default CreateProductForm;

View file

@ -0,0 +1,143 @@
import React, { useState } from 'react';
import { useOrg } from '@components/Contexts/OrgContext';
import { useLHSession } from '@components/Contexts/LHSessionContext';
import { linkCourseToProduct } from '@services/payments/products';
import { Button } from "@components/Ui/button";
import { Input } from "@components/Ui/input";
import { Search } from 'lucide-react';
import toast from 'react-hot-toast';
import { mutate } from 'swr';
import useSWR from 'swr';
import { getOrgCourses } from '@services/courses/courses';
import { getCoursesLinkedToProduct } from '@services/payments/products';
import Link from 'next/link';
import { getCourseThumbnailMediaDirectory } from '@services/media/media';
import { getUriWithOrg } from '@services/config/config';
interface LinkCourseModalProps {
productId: string;
onSuccess: () => void;
}
interface CoursePreviewProps {
course: {
id: string;
name: string;
description: string;
thumbnail_image: string;
course_uuid: string;
};
orgslug: string;
onLink: (courseId: string) => void;
isLinked: boolean;
}
const CoursePreview = ({ course, orgslug, onLink, isLinked }: CoursePreviewProps) => {
const org = useOrg() as any;
const thumbnailImage = course.thumbnail_image
? getCourseThumbnailMediaDirectory(org?.org_uuid, course.course_uuid, course.thumbnail_image)
: '../empty_thumbnail.png';
return (
<div className="flex gap-4 p-4 bg-white rounded-lg border border-gray-100 hover:border-gray-200 transition-colors">
{/* Thumbnail */}
<div
className="flex-shrink-0 w-[120px] h-[68px] rounded-md bg-cover bg-center ring-1 ring-inset ring-black/10"
style={{ backgroundImage: `url(${thumbnailImage})` }}
/>
{/* Content */}
<div className="flex-grow space-y-1">
<h3 className="font-medium text-gray-900 line-clamp-1">
{course.name}
</h3>
<p className="text-sm text-gray-500 line-clamp-2">
{course.description}
</p>
</div>
{/* Action Button */}
<div className="flex-shrink-0 flex items-center">
{isLinked ? (
<Button
variant="outline"
size="sm"
disabled
className="text-gray-500"
>
Already Linked
</Button>
) : (
<Button
onClick={() => onLink(course.id)}
size="sm"
>
Link Course
</Button>
)}
</div>
</div>
);
};
export default function LinkCourseModal({ productId, onSuccess }: LinkCourseModalProps) {
const [searchTerm, setSearchTerm] = useState('');
const org = useOrg() as any;
const session = useLHSession() as any;
const { data: courses } = useSWR(
() => org && session ? [org.slug, searchTerm, session.data?.tokens?.access_token] : null,
([orgSlug, search, token]) => getOrgCourses(orgSlug, null, token)
);
const { data: linkedCourses } = useSWR(
() => org && session ? [`/payments/${org.id}/products/${productId}/courses`, session.data?.tokens?.access_token] : null,
([_, token]) => getCoursesLinkedToProduct(org.id, productId, token)
);
const handleLinkCourse = async (courseId: string) => {
try {
const response = await linkCourseToProduct(org.id, productId, courseId, session.data?.tokens?.access_token);
if (response.success) {
mutate([`/payments/${org.id}/products`, session.data?.tokens?.access_token]);
toast.success('Course linked successfully');
onSuccess();
} else {
toast.error(response.data?.detail || 'Failed to link course');
}
} catch (error) {
toast.error('Failed to link course');
}
};
const isLinked = (courseId: string) => {
return linkedCourses?.data?.some((course: any) => course.id === courseId);
};
return (
<div className="space-y-4">
{/* Course List */}
<div className="max-h-[400px] overflow-y-auto space-y-2 px-3">
{courses?.map((course: any) => (
<CoursePreview
key={course.course_uuid}
course={course}
orgslug={org.slug}
onLink={handleLinkCourse}
isLinked={isLinked(course.id)}
/>
))}
{/* Empty State */}
{(!courses || courses.length === 0) && (
<div className="text-center py-6 text-gray-500">
No courses found
</div>
)}
</div>
</div>
);
}

View file

@ -0,0 +1,106 @@
import React, { useEffect, useState } from 'react';
import { getCoursesLinkedToProduct, unlinkCourseFromProduct } from '@services/payments/products';
import { useLHSession } from '@components/Contexts/LHSessionContext';
import { useOrg } from '@components/Contexts/OrgContext';
import { Trash2, Plus, BookOpen } from 'lucide-react';
import { Button } from "@components/Ui/button";
import toast from 'react-hot-toast';
import { mutate } from 'swr';
import Modal from '@components/Objects/StyledElements/Modal/Modal';
import LinkCourseModal from './LinkCourseModal';
interface ProductLinkedCoursesProps {
productId: string;
}
export default function ProductLinkedCourses({ productId }: ProductLinkedCoursesProps) {
const [linkedCourses, setLinkedCourses] = useState<any[]>([]);
const [isLinkModalOpen, setIsLinkModalOpen] = useState(false);
const session = useLHSession() as any;
const org = useOrg() as any;
const fetchLinkedCourses = async () => {
try {
const response = await getCoursesLinkedToProduct(org.id, productId, session.data?.tokens?.access_token);
setLinkedCourses(response.data || []);
} catch (error) {
toast.error('Failed to fetch linked courses');
}
};
const handleUnlinkCourse = async (courseId: string) => {
try {
const response = await unlinkCourseFromProduct(org.id, productId, courseId, session.data?.tokens?.access_token);
if (response.success) {
await fetchLinkedCourses();
mutate([`/payments/${org.id}/products`, session.data?.tokens?.access_token]);
toast.success('Course unlinked successfully');
} else {
toast.error(response.data?.detail || 'Failed to unlink course');
}
} catch (error) {
toast.error('Failed to unlink course');
}
};
useEffect(() => {
if (org && session && productId) {
fetchLinkedCourses();
}
}, [org, session, productId]);
return (
<div className="mt-4">
<div className="flex justify-between items-center mb-2">
<h3 className="text-sm font-semibold text-gray-700">Linked Courses</h3>
<Modal
isDialogOpen={isLinkModalOpen}
onOpenChange={setIsLinkModalOpen}
dialogTitle="Link Course to Product"
dialogDescription="Select a course to link to this product"
dialogContent={
<LinkCourseModal
productId={productId}
onSuccess={() => {
setIsLinkModalOpen(false);
fetchLinkedCourses();
}}
/>
}
dialogTrigger={
<Button variant="outline" size="sm" className="flex items-center gap-2">
<Plus size={16} />
<span>Link Course</span>
</Button>
}
/>
</div>
<div className="space-y-2">
{linkedCourses.length === 0 ? (
<div className="text-sm text-gray-500 flex items-center gap-2">
<BookOpen size={16} />
<span>No courses linked yet</span>
</div>
) : (
linkedCourses.map((course) => (
<div
key={course.id}
className="flex items-center justify-between p-2 bg-gray-50 rounded-md"
>
<span className="text-sm font-medium">{course.name}</span>
<Button
variant="ghost"
size="sm"
onClick={() => handleUnlinkCourse(course.id)}
className="text-red-500 hover:text-red-700"
>
<Trash2 size={16} />
</Button>
</div>
))
)}
</div>
</div>
);
}

View file

@ -0,0 +1,160 @@
'use client';
import { updateProfile } from '@services/settings/profile'
import React, { useEffect } from 'react'
import { Formik, Form, Field } from 'formik'
import { useLHSession } from '@components/Contexts/LHSessionContext'
import {
ArrowBigUpDash,
Check,
FileWarning,
Info,
UploadCloud,
} from 'lucide-react'
import UserAvatar from '@components/Objects/UserAvatar'
import { updateUserAvatar } from '@services/users/users'
import { constructAcceptValue } from '@/lib/constants';
const SUPPORTED_FILES = constructAcceptValue(['image'])
function UserEditGeneral() {
const session = useLHSession() as any;
const access_token = session?.data?.tokens?.access_token;
const [localAvatar, setLocalAvatar] = React.useState(null) as any
const [isLoading, setIsLoading] = React.useState(false) as any
const [error, setError] = React.useState() as any
const [success, setSuccess] = React.useState('') as any
const handleFileChange = async (event: any) => {
const file = event.target.files[0]
setLocalAvatar(file)
setIsLoading(true)
const res = await updateUserAvatar(session.data.user_uuid, file, access_token)
// wait for 1 second to show loading animation
await new Promise((r) => setTimeout(r, 1500))
if (res.success === false) {
setError(res.HTTPmessage)
} else {
setIsLoading(false)
setError('')
setSuccess('Avatar Updated')
}
}
useEffect(() => { }, [session, session.data])
return (
<div className="ml-10 mr-10 mx-auto bg-white rounded-xl shadow-sm px-6 py-5 sm:mb-0 mb-16">
{session.data.user && (
<Formik
enableReinitialize
initialValues={{
username: session.data.user.username,
first_name: session.data.user.first_name,
last_name: session.data.user.last_name,
email: session.data.user.email,
bio: session.data.user.bio,
}}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
setSubmitting(false)
updateProfile(values, session.data.user.id, access_token)
}, 400)
}}
>
{({ isSubmitting }) => (
<div className="flex flex-col lg:flex-row gap-8">
<Form className="flex-1 min-w-0">
<div className="space-y-4">
{[
{ label: 'Email', name: 'email', type: 'email' },
{ label: 'Username', name: 'username', type: 'text' },
{ label: 'First Name', name: 'first_name', type: 'text' },
{ label: 'Last Name', name: 'last_name', type: 'text' },
{ label: 'Bio', name: 'bio', type: 'text' },
].map((field) => (
<div key={field.name}>
<label className="block mb-2 font-bold" htmlFor={field.name}>
{field.label}
</label>
<Field
className="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
type={field.type}
name={field.name}
/>
</div>
))}
</div>
<button
type="submit"
disabled={isSubmitting}
className="mt-6 px-6 py-3 text-white bg-black rounded-lg shadow-md hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
Submit
</button>
</Form>
<div className="flex-1 min-w-0">
<div className="flex flex-col items-center space-y-4">
<label className="font-bold">Avatar</label>
{error && (
<div className="flex items-center bg-red-200 rounded-md text-red-950 px-4 py-2 text-sm">
<FileWarning size={16} className="mr-2" />
<span className="font-semibold first-letter:uppercase">{error}</span>
</div>
)}
{success && (
<div className="flex items-center bg-green-200 rounded-md text-green-950 px-4 py-2 text-sm">
<Check size={16} className="mr-2" />
<span className="font-semibold first-letter:uppercase">{success}</span>
</div>
)}
<div className="w-full max-w-xs bg-gray-50 rounded-xl outline outline-1 outline-gray-200 shadow p-6">
<div className="flex flex-col items-center space-y-4">
{localAvatar ? (
<UserAvatar
border="border-8"
width={100}
avatar_url={URL.createObjectURL(localAvatar)}
/>
) : (
<UserAvatar border="border-8" width={100} />
)}
{isLoading ? (
<div className="font-bold animate-pulse antialiased bg-green-200 text-gray text-sm rounded-md px-4 py-2 flex items-center">
<ArrowBigUpDash size={16} className="mr-2" />
<span>Uploading</span>
</div>
) : (
<>
<input
type="file"
id="fileInput"
accept={SUPPORTED_FILES}
className="hidden"
onChange={handleFileChange}
/>
<button
className="font-bold antialiased text-gray text-sm rounded-md px-4 py-2 flex items-center"
onClick={() => document.getElementById('fileInput')?.click()}
>
<UploadCloud size={16} className="mr-2" />
<span>Change Avatar</span>
</button>
</>
)}
</div>
</div>
<div className="flex items-center text-xs text-gray-500">
<Info size={13} className="mr-2" />
<p>Recommended size 100x100</p>
</div>
</div>
</div>
</div>
)}
</Formik>
)}
</div>
)
}
export default UserEditGeneral

View file

@ -0,0 +1,63 @@
import { useLHSession } from '@components/Contexts/LHSessionContext'
import { updatePassword } from '@services/settings/password'
import { Formik, Form, Field } from 'formik'
import React, { useEffect } from 'react'
function UserEditPassword() {
const session = useLHSession() as any
const access_token = session?.data?.tokens?.access_token;
const updatePasswordUI = async (values: any) => {
let user_id = session.data.user.id
await updatePassword(user_id, values, access_token)
}
useEffect(() => { }, [session])
return (
<div className="ml-10 mr-10 mx-auto bg-white rounded-xl shadow-sm px-6 py-5">
<Formik
initialValues={{ old_password: '', new_password: '' }}
enableReinitialize
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
setSubmitting(false)
updatePasswordUI(values)
}, 400)
}}
>
{({ isSubmitting }) => (
<Form className="max-w-md">
<label className="block mb-2 font-bold" htmlFor="old_password">
Old Password
</label>
<Field
className="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
type="password"
name="old_password"
/>
<label className="block mb-2 font-bold" htmlFor="new_password">
New Password
</label>
<Field
className="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
type="password"
name="new_password"
/>
<button
type="submit"
disabled={isSubmitting}
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"
>
Submit
</button>
</Form>
)}
</Formik>
</div>
)
}
export default UserEditPassword

View file

@ -0,0 +1,268 @@
import { useOrg } from '@components/Contexts/OrgContext'
import PageLoading from '@components/Objects/Loaders/PageLoading'
import ConfirmationModal from '@components/Objects/StyledElements/ConfirmationModal/ConfirmationModal'
import { getAPIUrl, getUriWithOrg } from '@services/config/config'
import { swrFetcher } from '@services/utils/ts/requests'
import { Globe, Ticket, UserSquare, Users, X } from 'lucide-react'
import Link from 'next/link'
import React, { useEffect } from 'react'
import useSWR, { mutate } from 'swr'
import dayjs from 'dayjs'
import {
changeSignupMechanism,
deleteInviteCode,
} from '@services/organizations/invites'
import toast from 'react-hot-toast'
import { useRouter } from 'next/navigation'
import Modal from '@components/Objects/StyledElements/Modal/Modal'
import OrgInviteCodeGenerate from '@components/Objects/Modals/Dash/OrgAccess/OrgInviteCodeGenerate'
import { useLHSession } from '@components/Contexts/LHSessionContext'
function OrgAccess() {
const org = useOrg() as any
const session = useLHSession() as any
const access_token = session?.data?.tokens?.access_token;
const { data: invites } = useSWR(
org ? `${getAPIUrl()}orgs/${org?.id}/invites` : null,
(url) => swrFetcher(url, access_token)
)
const [isLoading, setIsLoading] = React.useState(false)
const [joinMethod, setJoinMethod] = React.useState('closed')
const [invitesModal, setInvitesModal] = React.useState(false)
const router = useRouter()
async function getOrgJoinMethod() {
if (org) {
if (org.config.config.features.members.signup_mode == 'open') {
setJoinMethod('open')
} else {
setJoinMethod('inviteOnly')
}
}
}
async function deleteInvite(invite: any) {
let res = await deleteInviteCode(org.id, invite.invite_code_uuid, access_token)
if (res.status == 200) {
mutate(`${getAPIUrl()}orgs/${org.id}/invites`)
} else {
toast.error('Error ' + res.status + ': ' + res.data.detail)
}
}
async function changeJoinMethod(method: 'open' | 'inviteOnly') {
let res = await changeSignupMechanism(org.id, method, access_token)
if (res.status == 200) {
router.refresh()
mutate(`${getAPIUrl()}orgs/slug/${org?.slug}`)
} else {
toast.error('Error ' + res.status + ': ' + res.data.detail)
}
}
useEffect(() => {
if (invites && org) {
getOrgJoinMethod()
setIsLoading(false)
}
}, [org, invites])
return (
<>
{!isLoading ? (
<>
<div className="h-6"></div>
<div className="ml-10 mr-10 mx-auto bg-white rounded-xl shadow-sm px-4 py-4 anit ">
<div className="flex flex-col bg-gray-50 -space-y-1 px-5 py-3 rounded-md mb-3 ">
<h1 className="font-bold text-xl text-gray-800">Join method</h1>
<h2 className="text-gray-500 text-md">
{' '}
Choose how users can join your organization{' '}
</h2>
</div>
<div className="flex space-x-2 mx-auto">
<ConfirmationModal
confirmationButtonText="Change to open "
confirmationMessage="Are you sure you want to change the signup mechanism to open ? This will allow users to join your organization freely."
dialogTitle={'Change to open ?'}
dialogTrigger={
<div className="w-full h-[160px] bg-slate-100 rounded-lg cursor-pointer hover:bg-slate-200 ease-linear transition-all">
{joinMethod == 'open' ? (
<div className="bg-green-200 text-green-600 font-bold w-fit my-3 mx-3 absolute text-sm px-3 py-1 rounded-lg">
Active
</div>
) : null}
<div className="flex flex-col space-y-1 justify-center items-center h-full">
<Globe className="text-slate-400" size={40}></Globe>
<div className="text-2xl text-slate-700 font-bold">
Open
</div>
<div className="text-gray-400 text-center">
Users can join freely from the signup page
</div>
</div>
</div>
}
functionToExecute={() => {
changeJoinMethod('open')
}}
status="info"
></ConfirmationModal>
<ConfirmationModal
confirmationButtonText="Change to closed "
confirmationMessage="Are you sure you want to change the signup mechanism to closed ? This will allow users to join your organization only by invitation."
dialogTitle={'Change to closed ?'}
dialogTrigger={
<div className="w-full h-[160px] bg-slate-100 rounded-lg cursor-pointer hover:bg-slate-200 ease-linear transition-all">
{joinMethod == 'inviteOnly' ? (
<div className="bg-green-200 text-green-600 font-bold w-fit my-3 mx-3 absolute text-sm px-3 py-1 rounded-lg">
Active
</div>
) : null}
<div className="flex flex-col space-y-1 justify-center items-center h-full">
<Ticket className="text-slate-400" size={40}></Ticket>
<div className="text-2xl text-slate-700 font-bold">
Closed
</div>
<div className="text-gray-400 text-center">
Users can join only by invitation
</div>
</div>
</div>
}
functionToExecute={() => {
changeJoinMethod('inviteOnly')
}}
status="info"
></ConfirmationModal>
</div>
<div
className={
joinMethod == 'open'
? 'opacity-20 pointer-events-none'
: 'pointer-events-auto'
}
>
<div className="flex flex-col bg-gray-50 -space-y-1 px-5 py-3 rounded-md mt-3 mb-3 ">
<h1 className="font-bold text-xl text-gray-800">
Invite codes
</h1>
<h2 className="text-gray-500 text-md">
Invite codes can be copied and used to join your organization{' '}
</h2>
</div>
<table className="table-auto w-full text-left whitespace-nowrap rounded-md overflow-hidden">
<thead className="bg-gray-100 text-gray-500 rounded-xl uppercase">
<tr className="font-bolder text-sm">
<th className="py-3 px-4">Code</th>
<th className="py-3 px-4">Signup link</th>
<th className="py-3 px-4">Type</th>
<th className="py-3 px-4">Expiration date</th>
<th className="py-3 px-4">Actions</th>
</tr>
</thead>
<>
<tbody className="mt-5 bg-white rounded-md">
{invites?.map((invite: any) => (
<tr
key={invite.invite_code_uuid}
className="border-b border-gray-100 text-sm"
>
<td className="py-3 px-4">{invite.invite_code}</td>
<td className="py-3 px-4 ">
<Link
className="outline bg-gray-50 text-gray-600 px-2 py-1 rounded-md outline-gray-300 outline-dashed outline-1"
target="_blank"
href={getUriWithOrg(
org?.slug,
`/signup?inviteCode=${invite.invite_code}`
)}
>
{getUriWithOrg(
org?.slug,
`/signup?inviteCode=${invite.invite_code}`
)}
</Link>
</td>
<td className="py-3 px-4">
{invite.usergroup_id ? (
<div className="flex space-x-2 items-center">
<UserSquare className="w-4 h-4" />
<span>Linked to a UserGroup</span>
</div>
) : (
<div className="flex space-x-2 items-center">
<Users className="w-4 h-4" />
<span>Normal</span>
</div>
)}
</td>
<td className="py-3 px-4">
{dayjs(invite.expiration_date)
.add(1, 'year')
.format('DD/MM/YYYY')}{' '}
</td>
<td className="py-3 px-4">
<ConfirmationModal
confirmationButtonText="Delete Code"
confirmationMessage="Are you sure you want remove this invite code ?"
dialogTitle={'Delete code ?'}
dialogTrigger={
<button className="mr-2 flex space-x-2 hover:cursor-pointer p-1 px-3 bg-rose-700 rounded-md font-bold items-center text-sm text-rose-100">
<X className="w-4 h-4" />
<span> Delete code</span>
</button>
}
functionToExecute={() => {
deleteInvite(invite)
}}
status="warning"
></ConfirmationModal>
</td>
</tr>
))}
</tbody>
</>
</table>
<div className='flex flex-row-reverse mt-3 mr-2'>
<Modal
isDialogOpen={
invitesModal
}
onOpenChange={() =>
setInvitesModal(!invitesModal)
}
minHeight="no-min"
minWidth='lg'
dialogContent={
<OrgInviteCodeGenerate
setInvitesModal={setInvitesModal}
/>
}
dialogTitle="Generate Invite Code"
dialogDescription={
'Generate a new invite code for your organization'
}
dialogTrigger={
<button
className=" flex space-x-2 hover:cursor-pointer p-1 px-3 bg-green-700 rounded-md font-bold items-center text-sm text-green-100"
>
<Ticket className="w-4 h-4" />
<span> Generate invite code</span>
</button>
}
/>
</div>
</div>
</div>
</>
) : (
<PageLoading />
)}
</>
)
}
export default OrgAccess

View file

@ -0,0 +1,179 @@
'use client'
import { useLHSession } from '@components/Contexts/LHSessionContext'
import { useOrg } from '@components/Contexts/OrgContext'
import AddUserGroup from '@components/Objects/Modals/Dash/OrgUserGroups/AddUserGroup'
import EditUserGroup from '@components/Objects/Modals/Dash/OrgUserGroups/EditUserGroup'
import ManageUsers from '@components/Objects/Modals/Dash/OrgUserGroups/ManageUsers'
import ConfirmationModal from '@components/Objects/StyledElements/ConfirmationModal/ConfirmationModal'
import Modal from '@components/Objects/StyledElements/Modal/Modal'
import { getAPIUrl } from '@services/config/config'
import { deleteUserGroup } from '@services/usergroups/usergroups'
import { swrFetcher } from '@services/utils/ts/requests'
import { Pencil, SquareUserRound, Users, X } from 'lucide-react'
import React from 'react'
import toast from 'react-hot-toast'
import useSWR, { mutate } from 'swr'
function OrgUserGroups() {
const org = useOrg() as any
const session = useLHSession() as any
const access_token = session?.data?.tokens?.access_token;
const [userGroupManagementModal, setUserGroupManagementModal] = React.useState(false)
const [createUserGroupModal, setCreateUserGroupModal] = React.useState(false)
const [editUserGroupModal, setEditUserGroupModal] = React.useState(false)
const [selectedUserGroup, setSelectedUserGroup] = React.useState(null) as any
const { data: usergroups } = useSWR(
org ? `${getAPIUrl()}usergroups/org/${org.id}` : null,
(url) => swrFetcher(url, access_token)
)
const deleteUserGroupUI = async (usergroup_id: any) => {
const res = await deleteUserGroup(usergroup_id, access_token)
if (res.status == 200) {
mutate(`${getAPIUrl()}usergroups/org/${org.id}`)
}
else {
toast.error('Error ' + res.status + ': ' + res.data.detail)
}
}
const handleUserGroupManagementModal = (usergroup_id: any) => {
setSelectedUserGroup(usergroup_id)
setUserGroupManagementModal(!userGroupManagementModal)
}
return (
<>
<div className="h-6"></div>
<div className="ml-10 mr-10 mx-auto bg-white rounded-xl shadow-sm px-4 py-4">
<div className="flex flex-col bg-gray-50 -space-y-1 px-5 py-3 rounded-md mb-3 ">
<h1 className="font-bold text-xl text-gray-800">Manage UserGroups & Users</h1>
<h2 className="text-gray-500 text-sm">
{' '}
UserGroups are a way to group users together to manage their access to the resources (Courses) in your organization.{' '}
</h2>
</div>
<div className="overflow-x-auto">
<table className="table-auto w-full text-left whitespace-nowrap rounded-md overflow-hidden">
<thead className="bg-gray-100 text-gray-500 rounded-xl uppercase">
<tr className="font-bolder text-sm">
<th className="py-3 px-4">UserGroup</th>
<th className="py-3 px-4">Description</th>
<th className="py-3 px-4">Manage Users</th>
<th className="py-3 px-4">Actions</th>
</tr>
</thead>
<>
<tbody className="mt-5 bg-white rounded-md">
{usergroups?.map((usergroup: any) => (
<tr key={usergroup.id} className="border-b border-gray-100 text-sm">
<td className="py-3 px-4">{usergroup.name}</td>
<td className="py-3 px-4 ">{usergroup.description}</td>
<td className="py-3 px-4 ">
<Modal
isDialogOpen={
userGroupManagementModal &&
selectedUserGroup === usergroup.id
}
onOpenChange={() =>
handleUserGroupManagementModal(usergroup.id)
}
minHeight="lg"
minWidth='lg'
dialogContent={
<ManageUsers
usergroup_id={usergroup.id}
/>
}
dialogTitle="Manage UserGroup Users"
dialogDescription={
'Manage the users in this UserGroup'
}
dialogTrigger={
<button className="flex space-x-2 hover:cursor-pointer p-1 px-3 bg-yellow-700 rounded-md font-bold items-center text-sm text-yellow-100">
<Users className="w-4 h-4" />
<span> Manage Users</span>
</button>
}
/>
</td>
<td className="py-3 px-4 flex space-x-2">
<Modal
isDialogOpen={editUserGroupModal}
dialogTrigger={
<button className="flex space-x-2 hover:cursor-pointer p-1 px-3 bg-sky-700 rounded-md font-bold items-center text-sm text-sky-100">
<Pencil className="size-4" />
<span>Edit</span>
</button>
}
minHeight='sm'
minWidth='sm'
onOpenChange={() => {
setEditUserGroupModal(!editUserGroupModal)
}}
dialogContent={
<EditUserGroup usergroup={usergroup} />
}
/>
<ConfirmationModal
confirmationButtonText="Delete UserGroup"
confirmationMessage="Access to all resources will be removed for all users in this UserGroup. Are you sure you want to delete this UserGroup ?"
dialogTitle={'Delete UserGroup ?'}
dialogTrigger={
<button className="flex space-x-2 hover:cursor-pointer p-1 px-3 bg-rose-700 rounded-md font-bold items-center text-sm text-rose-100">
<X className="w-4 h-4" />
<span>Delete</span>
</button>
}
functionToExecute={() => {
deleteUserGroupUI(usergroup.id)
}}
status="warning"
></ConfirmationModal>
</td>
</tr>
))}
</tbody>
</>
</table>
</div>
<div className='flex justify-end mt-3 mr-2'>
<Modal
isDialogOpen={
createUserGroupModal
}
onOpenChange={() =>
setCreateUserGroupModal(!createUserGroupModal)
}
minHeight="no-min"
dialogContent={
<AddUserGroup
setCreateUserGroupModal={setCreateUserGroupModal}
/>
}
dialogTitle="Create a UserGroup"
dialogDescription={
'Create a new UserGroup to manage users'
}
dialogTrigger={
<button
className=" flex space-x-2 hover:cursor-pointer p-1 px-3 bg-green-700 rounded-md font-bold items-center text-sm text-green-100"
>
<SquareUserRound className="w-4 h-4" />
<span>Create a UserGroup</span>
</button>
}
/>
</div>
</div>
</>
)
}
export default OrgUserGroups

View file

@ -0,0 +1,146 @@
import { useLHSession } from '@components/Contexts/LHSessionContext'
import { useOrg } from '@components/Contexts/OrgContext'
import PageLoading from '@components/Objects/Loaders/PageLoading'
import RolesUpdate from '@components/Objects/Modals/Dash/OrgUsers/RolesUpdate'
import ConfirmationModal from '@components/Objects/StyledElements/ConfirmationModal/ConfirmationModal'
import Modal from '@components/Objects/StyledElements/Modal/Modal'
import Toast from '@components/Objects/StyledElements/Toast/Toast'
import { getAPIUrl } from '@services/config/config'
import { removeUserFromOrg } from '@services/organizations/orgs'
import { swrFetcher } from '@services/utils/ts/requests'
import { KeyRound, LogOut } from 'lucide-react'
import React, { useEffect } from 'react'
import toast from 'react-hot-toast'
import useSWR, { mutate } from 'swr'
function OrgUsers() {
const org = useOrg() as any
const session = useLHSession() as any
const access_token = session?.data?.tokens?.access_token;
const { data: orgUsers } = useSWR(
org ? `${getAPIUrl()}orgs/${org?.id}/users` : null,
(url) => swrFetcher(url, access_token)
)
const [rolesModal, setRolesModal] = React.useState(false)
const [selectedUser, setSelectedUser] = React.useState(null) as any
const [isLoading, setIsLoading] = React.useState(true)
const handleRolesModal = (user_uuid: any) => {
setSelectedUser(user_uuid)
setRolesModal(!rolesModal)
}
const handleRemoveUser = async (user_id: any) => {
const res = await removeUserFromOrg(org.id, user_id,access_token)
if (res.status === 200) {
await mutate(`${getAPIUrl()}orgs/${org.id}/users`)
} else {
toast.error('Error ' + res.status + ': ' + res.data.detail)
}
}
useEffect(() => {
if (orgUsers) {
setIsLoading(false)
}
}, [org, orgUsers])
return (
<div>
{isLoading ? (
<div>
<PageLoading />
</div>
) : (
<>
<Toast></Toast>
<div className="h-6"></div>
<div className="ml-10 mr-10 mx-auto bg-white rounded-xl shadow-sm px-4 py-4 ">
<div className="flex flex-col bg-gray-50 -space-y-1 px-5 py-3 rounded-md mb-3 ">
<h1 className="font-bold text-xl text-gray-800">Active users</h1>
<h2 className="text-gray-500 text-md">
{' '}
Manage your organization users, assign roles and permissions{' '}
</h2>
</div>
<table className="table-auto w-full text-left whitespace-nowrap rounded-md overflow-hidden">
<thead className="bg-gray-100 text-gray-500 rounded-xl uppercase">
<tr className="font-bolder text-sm">
<th className="py-3 px-4">User</th>
<th className="py-3 px-4">Role</th>
<th className="py-3 px-4">Actions</th>
</tr>
</thead>
<>
<tbody className="mt-5 bg-white rounded-md">
{orgUsers?.map((user: any) => (
<tr
key={user.user.id}
className="border-b border-gray-200 border-dashed"
>
<td className="py-3 px-4 flex space-x-2 items-center">
<span>
{user.user.first_name + ' ' + user.user.last_name}
</span>
<span className="text-xs bg-neutral-100 p-1 px-2 rounded-full text-neutral-400 font-semibold">
@{user.user.username}
</span>
</td>
<td className="py-3 px-4">{user.role.name}</td>
<td className="py-3 px-4 flex space-x-2 items-end">
<Modal
isDialogOpen={
rolesModal && selectedUser === user.user.user_uuid
}
onOpenChange={() =>
handleRolesModal(user.user.user_uuid)
}
minHeight="no-min"
dialogContent={
<RolesUpdate
alreadyAssignedRole={user.role.role_uuid}
setRolesModal={setRolesModal}
user={user}
/>
}
dialogTitle="Update Role"
dialogDescription={
'Update @' + user.user.username + "'s role"
}
dialogTrigger={
<button className="flex space-x-2 hover:cursor-pointer p-1 px-3 bg-yellow-700 rounded-md font-bold items-center text-sm text-yellow-100">
<KeyRound className="w-4 h-4" />
<span> Edit Role</span>
</button>
}
/>
<ConfirmationModal
confirmationButtonText="Remove User"
confirmationMessage="Are you sure you want remove this user from the organization?"
dialogTitle={'Delete ' + user.user.username + ' ?'}
dialogTrigger={
<button className="mr-2 flex space-x-2 hover:cursor-pointer p-1 px-3 bg-rose-700 rounded-md font-bold items-center text-sm text-rose-100">
<LogOut className="w-4 h-4" />
<span> Remove from organization</span>
</button>
}
functionToExecute={() => {
handleRemoveUser(user.user.id)
}}
status="warning"
></ConfirmationModal>
</td>
</tr>
))}
</tbody>
</>
</table>
</div>
</>
)}
</div>
)
}
export default OrgUsers

View file

@ -0,0 +1,142 @@
import { useLHSession } from '@components/Contexts/LHSessionContext'
import { useOrg } from '@components/Contexts/OrgContext'
import PageLoading from '@components/Objects/Loaders/PageLoading'
import Toast from '@components/Objects/StyledElements/Toast/Toast'
import ToolTip from '@components/Objects/StyledElements/Tooltip/Tooltip'
import { getAPIUrl } from '@services/config/config'
import { inviteBatchUsers } from '@services/organizations/invites'
import { swrFetcher } from '@services/utils/ts/requests'
import { Info, UserPlus } from 'lucide-react'
import React, { useEffect } from 'react'
import toast from 'react-hot-toast'
import useSWR, { mutate } from 'swr'
function OrgUsersAdd() {
const org = useOrg() as any
const session = useLHSession() as any
const access_token = session?.data?.tokens?.access_token;
const [isLoading, setIsLoading] = React.useState(false)
const [invitedUsers, setInvitedUsers] = React.useState('');
const [selectedInviteCode, setSelectedInviteCode] = React.useState('');
async function sendInvites() {
setIsLoading(true)
let res = await inviteBatchUsers(org.id, invitedUsers, selectedInviteCode,access_token)
if (res.status == 200) {
mutate(`${getAPIUrl()}orgs/${org?.id}/invites/users`)
setIsLoading(false)
} else {
toast.error('Error ' + res.status + ': ' + res.data.detail)
setIsLoading(false)
}
}
const { data: invites } = useSWR(
org ? `${getAPIUrl()}orgs/${org?.id}/invites` : null,
(url) => swrFetcher(url, access_token)
)
const { data: invited_users } = useSWR(
org ? `${getAPIUrl()}orgs/${org?.id}/invites/users` : null,
(url) => swrFetcher(url, access_token)
)
useEffect(() => {
if (invites) {
setSelectedInviteCode(invites?.[0]?.invite_code_uuid)
}
}
, [invites, invited_users])
return (
<>
<Toast></Toast>
{!isLoading ? (
<>
<div className="h-6"></div>
<div className="ml-10 mr-10 mx-auto bg-white rounded-xl shadow-sm px-4 py-4 anit ">
<div className="flex flex-col bg-gray-50 -space-y-1 px-5 py-3 rounded-md mb-3 ">
<h1 className="font-bold text-xl text-gray-800">Invite users to your Organization</h1>
<h2 className="text-gray-500 text-md">
{' '}
Send invite via email, separated by comma{' '}
</h2>
</div>
<div className="flex space-x-2 mx-auto">
<textarea
onChange={(e) => setInvitedUsers(e.target.value)}
className='w-full h-[200px] rounded-md border px-3 py-2 bg-gray-100/40 placeholder:italic placeholder:text-slate-300' placeholder='Example : spike.spiegel@bepop.space, michael.scott@dundermifflin.com' name="" id="" ></textarea>
</div>
<div className="flex space-x-2 mx-auto my-5 ml-2 items-center space-x-4 justify-between">
<div className='flex space-x-2 items-center'>
<p className='flex items-center'>Invite Code </p>
<select
onChange={(e) => setSelectedInviteCode(e.target.value)}
defaultValue={selectedInviteCode}
className='text-gray-400 border rounded-md px-3 py-1' name="" id="">
{invites?.map((invite: any) => (
<option key={invite.invite_code_uuid} value={invite.invite_code_uuid}>{invite.invite_code}</option>
))}
</select>
<ToolTip content={'Use one of the invite codes that you generated from the signup access page'} sideOffset={8} side="right"><Info className='text-gray-400' size={14} /></ToolTip>
</div>
<div className='flex flex-row-reverse '>
<button
onClick={sendInvites}
className="flex space-x-2 hover:cursor-pointer p-1 px-3 bg-green-700 rounded-md font-bold items-center text-sm text-green-100"
>
<UserPlus className="w-4 h-4" />
<span>Send invites via email</span>
</button>
</div>
</div>
<div className="flex flex-col bg-gray-50 -space-y-1 px-5 py-3 rounded-md mt-3 mb-3 ">
<h1 className="font-bold text-xl text-gray-800">
Invited Users
</h1>
<h2 className="text-gray-500 text-md">
{' '}
Users who have been invited to join your organization{' '}
</h2>
</div>
<div className="overflow-x-auto">
<table className="table-auto w-full text-left whitespace-nowrap rounded-md overflow-hidden">
<thead className="bg-gray-100 text-gray-500 rounded-xl uppercase">
<tr className="font-bolder text-sm">
<th className="py-3 px-4">Email</th>
<th className="py-3 px-4">Signup Status</th>
<th className="py-3 px-4">Email sent</th>
</tr>
</thead>
<>
<tbody className="mt-5 bg-white rounded-md">
{invited_users?.map((invited_user: any) => (
<tr
key={invited_user.email}
className="border-b border-gray-100 text-sm"
>
<td className="py-3 px-4">{invited_user.email}</td>
<td className="py-3 px-4">{invited_user.pending ? <div className='bg-orange-400 text-orange-100 w-fit px-2 py1 rounded-md'>Pending</div> : <div className='bg-green-400 text-green-100 w-fit px-2 py1 rounded-md'>Signed</div>}</td>
<td className="py-3 px-4">{invited_user.email_sent ? <div className='bg-green-600 text-green-100 w-fit px-2 py1 rounded-md'>Sent</div> : <div className='bg-red-400 text-red-100 w-fit px-2 py1 rounded-md'>No</div>}</td>
</tr>
))}
</tbody>
</>
</table>
</div>
</div>
</>
) : (
<PageLoading />
)
}
</>
)
}
export default OrgUsersAdd