mirror of
https://github.com/rzmk/learnhouse.git
synced 2025-12-19 04:19:25 +00:00
chore: refactor frontend components folder
This commit is contained in:
parent
46f016f661
commit
5a746a946d
106 changed files with 159 additions and 164 deletions
|
|
@ -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;
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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;
|
||||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue