feat: init stripe utils

This commit is contained in:
swve 2024-10-19 01:10:26 +02:00
parent 412651e817
commit 416c3a4afc
8 changed files with 315 additions and 41 deletions

View file

@ -1,13 +1,16 @@
import React, { useState } from 'react';
'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, createPaymentConfig, updatePaymentConfig } from '@services/payments/payments';
import { getPaymentConfigs, createPaymentConfig, updatePaymentConfig, deletePaymentConfig } from '@services/payments/payments';
import FormLayout, { ButtonBlack, Input, Textarea, FormField, FormLabelAndMessage, Flex } from '@components/StyledElements/Form/Form';
import { Check, Edit } from 'lucide-react';
import { Check, Edit, Trash2 } from 'lucide-react';
import toast from 'react-hot-toast';
import useSWR, { mutate } from 'swr';
import Modal from '@components/StyledElements/Modal/Modal';
import ConfirmationModal from '@components/StyledElements/ConfirmationModal/ConfirmationModal';
import { Button } from '@components/ui/button';
const PaymentsConfigurationPage: React.FC = () => {
const org = useOrg() as any;
@ -37,6 +40,17 @@ const PaymentsConfigurationPage: React.FC = () => {
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');
}
};
if (isLoading) {
return <div>Loading...</div>;
}
@ -52,23 +66,44 @@ const PaymentsConfigurationPage: React.FC = () => {
<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>
<div className="flex flex-col py-4 px-6 rounded-lg light-shadow">
<div className="flex flex-col rounded-lg light-shadow">
{stripeConfig ? (
<div className="flex items-center justify-between bg-white ">
<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">
<Check className="text-green-500" size={24} />
<span className="text-lg font-semibold">Stripe is enabled</span>
<SiStripe className="text-white" size={32} />
<span className="text-xl font-semibold text-white">Stripe is enabled</span>
</div>
<div className="flex space-x-2">
<Button
onClick={editConfig}
className="flex items-center space-x-2 px-4 py-2 bg-white text-purple-700 text-sm rounded-full hover:bg-gray-100 transition duration-300"
>
<Edit size={16} />
<span>Edit Configuration</span>
</Button>
<ConfirmationModal
confirmationButtonText="Delete Configuration"
confirmationMessage="Are you sure you want to delete the Stripe configuration? This action cannot be undone."
dialogTitle="Delete Stripe Configuration"
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">
<Trash2 size={16} />
<span>Delete Configuration</span>
</Button>
}
functionToExecute={deleteConfig}
status="warning"
/>
</div>
<ButtonBlack onClick={editConfig} className="flex items-center space-x-2 bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition duration-300">
<Edit size={16} />
<span>Edit Configuration</span>
</ButtonBlack>
</div>
) : (
<ButtonBlack onClick={enableStripe} className="flex items-center space-x-2 bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition duration-300">
<SiStripe size={16} />
<span>Enable Stripe</span>
</ButtonBlack>
<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"
>
<SiStripe size={24} />
<span className="text-lg font-semibold">Enable Stripe</span>
</Button>
)}
</div>
</div>
@ -94,14 +129,36 @@ interface EditStripeConfigModalProps {
}
const EditStripeConfigModal: React.FC<EditStripeConfigModalProps> = ({ orgId, configId, accessToken, isOpen, onClose }) => {
const [stripeKey, setStripeKey] = useState('');
const [stripePublishableKey, setStripePublishableKey] = useState('');
const [stripeSecretKey, setStripeSecretKey] = useState('');
const [stripeWebhookSecret, setStripeWebhookSecret] = useState('');
// Add this useEffect hook to fetch and set the existing configuration
useEffect(() => {
const fetchConfig = async () => {
try {
const config = await getPaymentConfigs(orgId, accessToken);
const stripeConfig = config.find((c: any) => c.id === configId);
if (stripeConfig && stripeConfig.provider_config) {
setStripePublishableKey(stripeConfig.provider_config.stripe_publishable_key || '');
setStripeSecretKey(stripeConfig.provider_config.stripe_secret_key || '');
setStripeWebhookSecret(stripeConfig.provider_config.stripe_webhook_secret || '');
}
} 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_key: stripeKey,
stripe_publishable_key: stripePublishableKey,
stripe_secret_key: stripeSecretKey,
stripe_webhook_secret: stripeWebhookSecret,
};
@ -123,16 +180,31 @@ const EditStripeConfigModal: React.FC<EditStripeConfigModalProps> = ({ orgId, co
dialogContent={
<FormLayout onSubmit={handleSubmit}>
<FormField name="stripe-key">
<FormLabelAndMessage label="Stripe Key" />
<Input type="password" value={stripeKey} onChange={(e) => setStripeKey(e.target.value)} />
<FormLabelAndMessage label="Stripe Publishable Key" />
<Input
type="text"
value={stripePublishableKey}
onChange={(e) => setStripePublishableKey(e.target.value)}
placeholder="pk_test_..."
/>
</FormField>
<FormField name="stripe-secret-key">
<FormLabelAndMessage label="Stripe Secret Key" />
<Input type="password" value={stripeSecretKey} onChange={(e) => setStripeSecretKey(e.target.value)} />
<Input
type="password"
value={stripeSecretKey}
onChange={(e) => setStripeSecretKey(e.target.value)}
placeholder="sk_test_..."
/>
</FormField>
<FormField name="stripe-webhook-secret">
<FormLabelAndMessage label="Stripe Webhook Secret" />
<Input type="password" value={stripeWebhookSecret} onChange={(e) => setStripeWebhookSecret(e.target.value)} />
<Input
type="password"
value={stripeWebhookSecret}
onChange={(e) => setStripeWebhookSecret(e.target.value)}
placeholder="whsec_..."
/>
</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">

View file

@ -4,9 +4,9 @@ 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 { getProducts, updateProduct, archiveProduct } from '@services/payments/products';
import CreateProductForm from '@components/Dashboard/Payments/SubComponents/CreateProductForm';
import { Plus, Trash2, Pencil, Info, RefreshCcw, SquareCheck, ChevronDown, ChevronUp } from 'lucide-react';
import { Plus, Trash2, Pencil, Info, RefreshCcw, SquareCheck, ChevronDown, ChevronUp, Archive } from 'lucide-react';
import Modal from '@components/StyledElements/Modal/Modal';
import ConfirmationModal from '@components/StyledElements/ConfirmationModal/ConfirmationModal';
import toast from 'react-hot-toast';
@ -18,6 +18,7 @@ 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';
const validationSchema = Yup.object().shape({
name: Yup.string().required('Name is required'),
@ -33,19 +34,32 @@ function PaymentsProductPage() {
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 { data: products, error } = useSWR(
() => org && session ? [`/payments/${org.id}/products`, session.data?.tokens?.access_token] : null,
([url, token]) => getProducts(org.id, token)
);
const handleDeleteProduct = async (productId: string) => {
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) => {
try {
await deleteProduct(org.id, productId, session.data?.tokens?.access_token);
await archiveProduct(org.id, productId, session.data?.tokens?.access_token);
mutate([`/payments/${org.id}/products`, session.data?.tokens?.access_token]);
toast.success('Product deleted successfully');
toast.success('Product archived successfully');
} catch (error) {
toast.error('Failed to delete product');
toast.error('Failed to archive product');
}
}
@ -86,30 +100,31 @@ function PaymentsProductPage() {
) : (
<div className="flex flex-col h-full">
<div className="flex justify-between items-start mb-2">
<div className="flex space-x-2 items-center">
<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}</span>
<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"
className={`text-blue-500 hover:text-blue-700 ${isStripeEnabled ? '' : 'opacity-50 cursor-not-allowed'}`}
disabled={!isStripeEnabled}
>
<Pencil size={16} />
</button>
<ConfirmationModal
confirmationButtonText="Delete Product"
confirmationMessage="Are you sure you want to delete this product?"
dialogTitle={`Delete ${product.name}?`}
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">
<Trash2 size={16} />
<Archive size={16} />
</button>
}
functionToExecute={() => handleDeleteProduct(product.id)}
functionToExecute={() => handleArchiveProduct(product.id)}
status="warning"
/>
</div>
@ -164,10 +179,14 @@ function PaymentsProductPage() {
<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"
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>