feat: improve products & subscriptions page

This commit is contained in:
swve 2024-10-17 22:35:04 +02:00
parent c762d2333e
commit 412651e817
8 changed files with 380 additions and 195 deletions

View file

@ -1,22 +1,38 @@
'use client';
import React, { useState } from 'react'
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, deleteProduct, updateProduct } from '@services/payments/products';
import CreateProductForm from '@components/Dashboard/Payments/SubComponents/CreateProductForm';
import { Plus, Trash2, Pencil, DollarSign, Info } from 'lucide-react';
import { Plus, Trash2, Pencil, Info, RefreshCcw, SquareCheck, ChevronDown, ChevronUp } from 'lucide-react';
import Modal from '@components/StyledElements/Modal/Modal';
import ConfirmationModal from '@components/StyledElements/ConfirmationModal/ConfirmationModal';
import toast from 'react-hot-toast';
import Link from 'next/link';
import { getUriWithOrg } from '@services/config/config';
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';
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 { data: products, error } = useSWR(
() => org && session ? [`/payments/${org.id}/products`, session.data?.tokens?.access_token] : null,
@ -33,22 +49,20 @@ function PaymentsProductPage() {
}
}
const toggleProductExpansion = (productId: string) => {
setExpandedProducts(prev => ({
...prev,
[productId]: !prev[productId]
}));
};
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">
<div className="flex justify-between items-center">
<h1 className="text-2xl font-bold">Products</h1>
<button
onClick={() => setIsCreateModalOpen(true)}
className="mb-4 flex items-center space-x-2 px-2 py-1.5 rounded-md bg-gradient-to-bl text-gray-800 font-medium from-gray-400/50 to-gray-200/80 border border-gray-600/10 shadow-gray-900/10 shadow-lg hover:from-gray-300/50 hover:to-gray-100/80 transition duration-300"
>
<Plus size={18} />
<span className="text-sm font-bold">Create New Product</span>
</button>
</div>
<Modal
isDialogOpen={isCreateModalOpen}
@ -62,7 +76,7 @@ function PaymentsProductPage() {
<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">
<div key={product.id} className="bg-white p-4 rounded-lg nice-shadow flex flex-col h-full">
{editingProductId === product.id ? (
<EditProductForm
product={product}
@ -70,9 +84,15 @@ function PaymentsProductPage() {
onCancel={() => setEditingProductId(null)}
/>
) : (
<div className="flex flex-col space-y-2">
<div className="flex justify-between items-start">
<h3 className="font-bold text-lg">{product.name}</h3>
<div className="flex flex-col h-full">
<div className="flex justify-between items-start mb-2">
<div className="flex space-x-2 items-center">
<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}</span>
</Badge>
<h3 className="font-bold text-lg">{product.name}</h3>
</div>
<div className="flex space-x-2">
<button
onClick={() => setEditingProductId(product.id)}
@ -94,86 +114,169 @@ function PaymentsProductPage() {
/>
</div>
</div>
<p className="text-gray-600">{product.description}</p>
<p className="mt-2 font-semibold">${product.amount.toFixed(2)}</p>
<p className="text-sm text-gray-500">{product.product_type}</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 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>
<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 hover:from-gray-600 hover:to-gray-800 transition duration-300"
>
<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 [name, setName] = useState(product.name);
const [description, setDescription] = useState(product.description);
const [amount, setAmount] = useState(product.amount);
const [benefits, setBenefits] = useState(product.benefits || '');
const org = useOrg() as any;
const session = useLHSession() as any;
const [currencies, setCurrencies] = useState<{ code: string; name: string }[]>([]);
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
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, { name, description, amount, benefits }, session.data?.tokens?.access_token);
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 (
<form onSubmit={handleSubmit} className="space-y-4">
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full p-2 border rounded"
placeholder="Product Name"
/>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
className="w-full p-2 border rounded"
placeholder="Product Description"
/>
<input
type="number"
value={amount}
onChange={(e) => setAmount(parseFloat(e.target.value))}
className="w-full p-2 border rounded"
placeholder="Price"
step="0.01"
/>
<textarea
value={benefits}
onChange={(e) => setBenefits(e.target.value)}
className="w-full p-2 border rounded"
placeholder="Product Benefits"
/>
<div className="flex justify-end space-x-2">
<button type="button" onClick={onCancel} className="px-4 py-2 text-gray-600 border rounded">Cancel</button>
<button type="submit" className="px-4 py-2 text-white bg-blue-500 rounded">Save</button>
</div>
</form>
<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>
);
};

View file

@ -1,138 +1,157 @@
import React, { useState } from 'react';
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 FormLayout, { ButtonBlack, Input, Textarea, FormField, FormLabelAndMessage, Flex } from '@components/StyledElements/Form/Form';
import * as Form from '@radix-ui/react-form';
import { useFormik } from 'formik';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import toast from 'react-hot-toast';
import { mutate } from 'swr';
import { getAPIUrl } from '@services/config/config';
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(0, 'Amount must be positive').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'),
});
interface ProductFormValues {
name: string;
description: string;
product_type: string;
product_type: 'one_time' | 'subscription';
benefits: string;
amount: number;
currency: string;
}
const CreateProductForm: React.FC<{ onSuccess: () => void }> = ({ onSuccess }) => {
const org = useOrg() as any;
const session = useLHSession() as any;
const [isSubmitting, setIsSubmitting] = useState(false);
const [currencies, setCurrencies] = useState<{ code: string; name: string }[]>([]);
const validate = (values: any) => {
const errors: any = {};
useEffect(() => {
const allCurrencies = currencyCodes.data.map(currency => ({
code: currency.code,
name: `${currency.code} - ${currency.currency}`
}));
setCurrencies(allCurrencies);
}, []);
if (!values.name) {
errors.name = 'Required';
}
if (!values.description) {
errors.description = 'Required';
}
if (!values.amount) {
errors.amount = 'Required';
} else {
const numAmount = Number(values.amount);
if (isNaN(numAmount) || numAmount <= 0) {
errors.amount = 'Amount must be greater than 0';
}
}
return errors;
const initialValues: ProductFormValues = {
name: '',
description: '',
product_type: 'one_time',
benefits: '',
amount: 0,
currency: 'USD',
};
const formik = useFormik<ProductFormValues>({
initialValues: {
name: '',
description: '',
product_type: 'one_time',
benefits: '',
amount: 0,
},
validate,
onSubmit: async (values) => {
setIsSubmitting(true);
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]);
formik.resetForm();
onSuccess(); // Call the onSuccess function to close the modal
} 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 {
setIsSubmitting(false);
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 (
<div className="p-5">
<FormLayout onSubmit={formik.handleSubmit}>
<FormField name="name">
<FormLabelAndMessage label="Product Name" message={formik.errors.name} />
<Form.Control asChild>
<Input
onChange={formik.handleChange}
value={formik.values.name}
type="text"
required
/>
</Form.Control>
</FormField>
<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>
<FormField name="description">
<FormLabelAndMessage label="Description" message={formik.errors.description} />
<Form.Control asChild>
<Textarea
onChange={formik.handleChange}
value={formik.values.description}
required
/>
</Form.Control>
</FormField>
<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>
<FormField name="benefits">
<FormLabelAndMessage label="Benefits" />
<Form.Control asChild>
<Textarea
onChange={formik.handleChange}
value={formik.values.benefits}
/>
</Form.Control>
</FormField>
<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>
<FormField name="amount">
<FormLabelAndMessage label="Amount" message={formik.errors.amount} />
<Form.Control asChild>
<Input
onChange={formik.handleChange}
value={formik.values.amount}
type="number"
min="0"
step="0.01"
required
/>
</Form.Control>
</FormField>
<Flex css={{ marginTop: 25, justifyContent: 'flex-end' }}>
<Form.Submit asChild>
<ButtonBlack type="submit" disabled={isSubmitting}>
<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="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'}
</ButtonBlack>
</Form.Submit>
</Flex>
</FormLayout>
</div>
</Button>
</div>
</Form>
)}
</Formik>
);
};