feat: update pool management functionality with new fields and state handling

This commit is contained in:
seaznCode 2025-12-04 18:26:51 +01:00
parent 6831b92169
commit 6a96b27d2e
7 changed files with 185 additions and 65 deletions

View File

@ -4,7 +4,7 @@ import React from 'react'
interface Props { interface Props {
isOpen: boolean isOpen: boolean
onClose: () => void onClose: () => void
onCreate: (data: { name: string; description: string }) => void | Promise<void> onCreate: (data: { pool_name: string; description: string; price: number; pool_type: 'coffee' | 'other' }) => void | Promise<void>
creating: boolean creating: boolean
error?: string error?: string
success?: string success?: string
@ -20,13 +20,19 @@ export default function CreateNewPoolModal({
success, success,
clearMessages clearMessages
}: Props) { }: Props) {
const [name, setName] = React.useState('') const [poolName, setPoolName] = React.useState('')
const [description, setDescription] = React.useState('') const [description, setDescription] = React.useState('')
const [price, setPrice] = React.useState('0.00')
const [poolType, setPoolType] = React.useState<'coffee' | 'other'>('other')
const isDisabled = creating || !!success
React.useEffect(() => { React.useEffect(() => {
if (!isOpen) { if (!isOpen) {
setName('') setPoolName('')
setDescription('') setDescription('')
setPrice('0.00')
setPoolType('other')
} }
}, [isOpen]) }, [isOpen])
@ -67,7 +73,7 @@ export default function CreateNewPoolModal({
onSubmit={e => { onSubmit={e => {
e.preventDefault() e.preventDefault()
clearMessages() clearMessages()
onCreate({ name, description }) onCreate({ pool_name: poolName, description, price: parseFloat(price) || 0, pool_type: poolType })
}} }}
className="space-y-4" className="space-y-4"
> >
@ -76,9 +82,10 @@ export default function CreateNewPoolModal({
<input <input
className="w-full rounded-lg border border-gray-300 px-4 py-3 text-sm bg-gray-50 text-gray-900 focus:ring-2 focus:ring-blue-900 focus:border-transparent" className="w-full rounded-lg border border-gray-300 px-4 py-3 text-sm bg-gray-50 text-gray-900 focus:ring-2 focus:ring-blue-900 focus:border-transparent"
placeholder="e.g., VIP Members" placeholder="e.g., VIP Members"
value={name} value={poolName}
onChange={e => setName(e.target.value)} onChange={e => setPoolName(e.target.value)}
disabled={creating} disabled={isDisabled}
required
/> />
</div> </div>
<div> <div>
@ -89,13 +96,39 @@ export default function CreateNewPoolModal({
placeholder="Short description of the pool" placeholder="Short description of the pool"
value={description} value={description}
onChange={e => setDescription(e.target.value)} onChange={e => setDescription(e.target.value)}
disabled={creating} disabled={isDisabled}
/> />
</div> </div>
<div>
<label className="block text-sm font-medium text-blue-900 mb-1">Price (per capsule)</label>
<input
type="number"
step="0.01"
min="0"
className="w-full rounded-lg border border-gray-300 px-4 py-3 text-sm bg-gray-50 text-gray-900 focus:ring-2 focus:ring-blue-900 focus:border-transparent"
placeholder="0.00"
value={price}
onChange={e => setPrice(e.target.value)}
disabled={isDisabled}
required
/>
</div>
<div>
<label className="block text-sm font-medium text-blue-900 mb-1">Pool Type</label>
<select
className="w-full rounded-lg border border-gray-300 px-4 py-3 text-sm bg-gray-50 text-gray-900 focus:ring-2 focus:ring-blue-900 focus:border-transparent"
value={poolType}
onChange={e => setPoolType(e.target.value as 'coffee' | 'other')}
disabled={isDisabled}
>
<option value="other">Other</option>
<option value="coffee">Coffee</option>
</select>
</div>
<div className="flex gap-2"> <div className="flex gap-2">
<button <button
type="submit" type="submit"
disabled={creating} disabled={isDisabled}
className="px-5 py-3 text-sm font-semibold text-blue-50 rounded-lg bg-blue-900 hover:bg-blue-800 shadow inline-flex items-center gap-2 disabled:opacity-60" className="px-5 py-3 text-sm font-semibold text-blue-50 rounded-lg bg-blue-900 hover:bg-blue-800 shadow inline-flex items-center gap-2 disabled:opacity-60"
> >
{creating && <span className="h-4 w-4 rounded-full border-2 border-white/30 border-t-white animate-spin" />} {creating && <span className="h-4 w-4 rounded-full border-2 border-white/30 border-t-white animate-spin" />}
@ -104,8 +137,8 @@ export default function CreateNewPoolModal({
<button <button
type="button" type="button"
className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-200 rounded-lg hover:bg-gray-300 transition" className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-200 rounded-lg hover:bg-gray-300 transition"
onClick={() => { setName(''); setDescription(''); clearMessages(); }} onClick={() => { setPoolName(''); setDescription(''); setPrice('0.00'); setPoolType('other'); clearMessages(); }}
disabled={creating} disabled={isDisabled}
> >
Reset Reset
</button> </button>
@ -113,7 +146,7 @@ export default function CreateNewPoolModal({
type="button" type="button"
className="ml-auto px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-800 transition" className="ml-auto px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-800 transition"
onClick={() => { clearMessages(); onClose(); }} onClick={() => { clearMessages(); onClose(); }}
disabled={creating} disabled={isDisabled}
> >
Close Close
</button> </button>

View File

@ -1,9 +1,11 @@
import { authFetch } from '../../../utils/authFetch'; import { authFetch } from '../../../utils/authFetch';
export type AddPoolPayload = { export type AddPoolPayload = {
name: string; pool_name: string;
description?: string; description?: string;
state?: 'active' | 'inactive'; price: number;
pool_type: 'coffee' | 'other';
is_active?: boolean;
}; };
export async function addPool(payload: AddPoolPayload) { export async function addPool(payload: AddPoolPayload) {
@ -31,7 +33,7 @@ export async function addPool(payload: AddPoolPayload) {
(res.status === 409 (res.status === 409
? 'Pool name already exists.' ? 'Pool name already exists.'
: res.status === 400 : res.status === 400
? 'Invalid request. Check name/state.' ? 'Invalid request. Check pool data.'
: res.status === 401 : res.status === 401
? 'Unauthorized.' ? 'Unauthorized.'
: res.status === 403 : res.status === 403

View File

@ -1,18 +1,18 @@
import { authFetch } from '../../../utils/authFetch'; import { authFetch } from '../../../utils/authFetch';
export async function setPoolState( async function setPoolActiveStatus(
id: string | number, id: string | number,
state: 'active' | 'inactive' | 'archived' is_active: boolean
) { ) {
const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:3001'; const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:3001';
const url = `${BASE_URL}/api/admin/pools/${id}/state`; const url = `${BASE_URL}/api/admin/pools/${id}/active`;
const res = await authFetch(url, { const res = await authFetch(url, {
method: 'PATCH', method: 'PATCH',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Accept: 'application/json', Accept: 'application/json',
}, },
body: JSON.stringify({ state }), body: JSON.stringify({ is_active }),
}); });
let body: any = null; let body: any = null;
@ -40,6 +40,10 @@ export async function setPoolState(
return { ok, status: res.status, body, message }; return { ok, status: res.status, body, message };
} }
export async function archivePoolById(id: string | number) { export async function setPoolInactive(id: string | number) {
return setPoolState(id, 'archived'); return setPoolActiveStatus(id, false);
}
export async function setPoolActive(id: string | number) {
return setPoolActiveStatus(id, true);
} }

View File

@ -4,11 +4,13 @@ import { log } from '../../../utils/logger';
export type AdminPool = { export type AdminPool = {
id: string; id: string;
name: string; pool_name: string;
description?: string; description?: string;
price?: number;
pool_type?: 'coffee' | 'other';
is_active?: boolean;
membersCount: number; membersCount: number;
createdAt: string; createdAt: string;
archived?: boolean;
}; };
export function useAdminPools() { export function useAdminPools() {
@ -58,11 +60,13 @@ export function useAdminPools() {
const mapped: AdminPool[] = apiItems.map(item => ({ const mapped: AdminPool[] = apiItems.map(item => ({
id: String(item.id), id: String(item.id),
name: String(item.name ?? 'Unnamed Pool'), pool_name: String(item.pool_name ?? 'Unnamed Pool'),
description: String(item.description ?? ''), description: String(item.description ?? ''),
price: Number(item.price ?? 0),
pool_type: item.pool_type === 'coffee' ? 'coffee' : 'other',
is_active: Boolean(item.is_active),
membersCount: 0, membersCount: 0,
createdAt: String(item.created_at ?? new Date().toISOString()), createdAt: String(item.created_at ?? new Date().toISOString()),
archived: String(item.state ?? '').toLowerCase() === 'archived',
})); }));
log("✅ Pools: Mapped sample:", mapped.slice(0, 3)); log("✅ Pools: Mapped sample:", mapped.slice(0, 3));
@ -94,11 +98,13 @@ export function useAdminPools() {
const apiItems: any[] = Array.isArray(body?.data) ? body.data : []; const apiItems: any[] = Array.isArray(body?.data) ? body.data : [];
setPools(apiItems.map(item => ({ setPools(apiItems.map(item => ({
id: String(item.id), id: String(item.id),
name: String(item.name ?? 'Unnamed Pool'), pool_name: String(item.pool_name ?? 'Unnamed Pool'),
description: String(item.description ?? ''), description: String(item.description ?? ''),
price: Number(item.price ?? 0),
pool_type: item.pool_type === 'coffee' ? 'coffee' : 'other',
is_active: Boolean(item.is_active),
membersCount: 0, membersCount: 0,
createdAt: String(item.created_at ?? new Date().toISOString()), createdAt: String(item.created_at ?? new Date().toISOString()),
archived: String(item.state ?? '').toLowerCase() === 'archived',
}))); })));
log("✅ Pools: Refresh succeeded, items:", apiItems.length); log("✅ Pools: Refresh succeeded, items:", apiItems.length);
return true; return true;

View File

@ -0,0 +1,49 @@
import { authFetch } from '../../../utils/authFetch';
async function setPoolActiveStatus(
id: string | number,
is_active: boolean
) {
const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:3001';
const url = `${BASE_URL}/api/admin/pools/${id}/active`;
const res = await authFetch(url, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({ is_active }),
});
let body: any = null;
try {
body = await res.json();
} catch {
body = null;
}
const ok = res.ok;
const message =
body?.message ||
(res.status === 404
? 'Pool not found.'
: res.status === 400
? 'Invalid request.'
: res.status === 403
? 'Forbidden.'
: res.status === 500
? 'Server error.'
: !ok
? `Request failed (${res.status}).`
: '');
return { ok, status: res.status, body, message };
}
export async function setPoolInactive(id: string | number) {
return setPoolActiveStatus(id, false);
}
export async function setPoolActive(id: string | number) {
return setPoolActiveStatus(id, true);
}

View File

@ -45,9 +45,11 @@ export default function PoolManagePage() {
// Read pool data from query params with fallbacks (hooks must be before any return) // Read pool data from query params with fallbacks (hooks must be before any return)
const poolId = searchParams.get('id') ?? 'pool-unknown' const poolId = searchParams.get('id') ?? 'pool-unknown'
const poolName = searchParams.get('name') ?? 'Unnamed Pool' const poolName = searchParams.get('pool_name') ?? 'Unnamed Pool'
const poolDescription = searchParams.get('description') ?? '' const poolDescription = searchParams.get('description') ?? ''
const poolState = searchParams.get('state') ?? 'active' const poolPrice = parseFloat(searchParams.get('price') ?? '0')
const poolType = searchParams.get('pool_type') as 'coffee' | 'other' || 'other'
const poolIsActive = searchParams.get('is_active') === 'true'
const poolCreatedAt = searchParams.get('createdAt') ?? new Date().toISOString() const poolCreatedAt = searchParams.get('createdAt') ?? new Date().toISOString()
// Members (no dummy data) // Members (no dummy data)
@ -117,9 +119,9 @@ export default function PoolManagePage() {
{poolDescription ? poolDescription : 'Manage users and track pool funds'} {poolDescription ? poolDescription : 'Manage users and track pool funds'}
</p> </p>
<div className="mt-1 flex items-center gap-2 text-xs text-gray-600"> <div className="mt-1 flex items-center gap-2 text-xs text-gray-600">
<span className={`inline-flex items-center rounded-full px-2 py-0.5 font-medium ${poolState === 'archived' ? 'bg-gray-100 text-gray-700' : 'bg-green-100 text-green-800'}`}> <span className={`inline-flex items-center rounded-full px-2 py-0.5 font-medium ${!poolIsActive ? 'bg-gray-100 text-gray-700' : 'bg-green-100 text-green-800'}`}>
<span className={`mr-1.5 h-1.5 w-1.5 rounded-full ${poolState === 'archived' ? 'bg-gray-400' : 'bg-green-500'}`} /> <span className={`mr-1.5 h-1.5 w-1.5 rounded-full ${!poolIsActive ? 'bg-gray-400' : 'bg-green-500'}`} />
{poolState === 'archived' ? 'Archived' : 'Active'} {!poolIsActive ? 'Inactive' : 'Active'}
</span> </span>
<span></span> <span></span>
<span>Created {new Date(poolCreatedAt).toLocaleDateString('de-DE', { year: 'numeric', month: 'short', day: '2-digit' })}</span> <span>Created {new Date(poolCreatedAt).toLocaleDateString('de-DE', { year: 'numeric', month: 'short', day: '2-digit' })}</span>

View File

@ -8,17 +8,19 @@ import { useAdminPools } from './hooks/getlist'
import useAuthStore from '../../store/authStore' import useAuthStore from '../../store/authStore'
import { addPool } from './hooks/addPool' import { addPool } from './hooks/addPool'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { archivePoolById, setPoolState } from './hooks/archivePool' import { setPoolInactive, setPoolActive } from './hooks/poolStatus'
import PageTransitionEffect from '../../components/animation/pageTransitionEffect' import PageTransitionEffect from '../../components/animation/pageTransitionEffect'
import CreateNewPoolModal from './components/createNewPoolModal' import CreateNewPoolModal from './components/createNewPoolModal'
type Pool = { type Pool = {
id: string id: string
name: string pool_name: string
description?: string description?: string
price?: number
pool_type?: 'coffee' | 'other'
is_active?: boolean
membersCount: number membersCount: number
createdAt: string createdAt: string
archived?: boolean
} }
export default function PoolManagementPage() { export default function PoolManagementPage() {
@ -38,6 +40,7 @@ export default function PoolManagementPage() {
// Replace local fetch with hook // Replace local fetch with hook
const { pools: initialPools, loading, error, refresh } = useAdminPools() const { pools: initialPools, loading, error, refresh } = useAdminPools()
const [pools, setPools] = React.useState<Pool[]>([]) const [pools, setPools] = React.useState<Pool[]>([])
const [showInactive, setShowInactive] = React.useState(false)
React.useEffect(() => { React.useEffect(() => {
if (!loading && !error) { if (!loading && !error) {
@ -45,24 +48,28 @@ export default function PoolManagementPage() {
} }
}, [initialPools, loading, error]) }, [initialPools, loading, error])
// REPLACED: handleCreatePool to accept data from modal const filteredPools = pools.filter(p => showInactive ? !p.is_active : p.is_active)
async function handleCreatePool(data: { name: string; description: string }) {
// REPLACED: handleCreatePool to accept data from modal with new schema fields
async function handleCreatePool(data: { pool_name: string; description: string; price: number; pool_type: 'coffee' | 'other' }) {
setCreateError('') setCreateError('')
setCreateSuccess('') setCreateSuccess('')
const name = data.name.trim() const pool_name = data.pool_name.trim()
const description = data.description.trim() const description = data.description.trim()
if (!name) { if (!pool_name) {
setCreateError('Please provide a pool name.') setCreateError('Please provide a pool name.')
return return
} }
setCreating(true) setCreating(true)
try { try {
const res = await addPool({ name, description: description || undefined, state: 'active' }) const res = await addPool({ pool_name, description: description || undefined, price: data.price, pool_type: data.pool_type, is_active: true })
if (res.ok && res.body?.data) { if (res.ok && res.body?.data) {
setCreateSuccess('Pool created successfully.') setCreateSuccess('Pool created successfully.')
await refresh?.() await refresh?.()
// keep modal open so user sees success; optional close: setTimeout(() => {
// setCreateModalOpen(false) setCreateModalOpen(false)
setCreateSuccess('')
}, 1500)
} else { } else {
setCreateError(res.message || 'Failed to create pool.') setCreateError(res.message || 'Failed to create pool.')
} }
@ -75,17 +82,17 @@ export default function PoolManagementPage() {
async function handleArchive(poolId: string) { async function handleArchive(poolId: string) {
setArchiveError('') setArchiveError('')
const res = await archivePoolById(poolId) const res = await setPoolInactive(poolId)
if (res.ok) { if (res.ok) {
await refresh?.() await refresh?.()
} else { } else {
setArchiveError(res.message || 'Failed to archive pool.') setArchiveError(res.message || 'Failed to deactivate pool.')
} }
} }
async function handleSetActive(poolId: string) { async function handleSetActive(poolId: string) {
setArchiveError('') setArchiveError('')
const res = await setPoolState(poolId, 'active') const res = await setPoolActive(poolId)
if (res.ok) { if (res.ok) {
await refresh?.() await refresh?.()
} else { } else {
@ -142,6 +149,21 @@ export default function PoolManagementPage() {
Create New Pool Create New Pool
</button> </button>
</div> </div>
<div className="flex items-center gap-2">
<span className="text-sm text-gray-600">Show:</span>
<button
onClick={() => setShowInactive(false)}
className={`px-4 py-2 text-sm font-medium rounded-lg transition ${!showInactive ? 'bg-blue-900 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}
>
Active Pools
</button>
<button
onClick={() => setShowInactive(true)}
className={`px-4 py-2 text-sm font-medium rounded-lg transition ${showInactive ? 'bg-blue-900 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}
>
Inactive Pools
</button>
</div>
</header> </header>
{/* Pools List card */} {/* Pools List card */}
@ -178,18 +200,18 @@ export default function PoolManagementPage() {
</div> </div>
) : ( ) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6"> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
{pools.map(pool => ( {filteredPools.map(pool => (
<article key={pool.id} className="rounded-2xl bg-white border border-gray-100 shadow p-5 flex flex-col relative z-0"> <article key={pool.id} className="rounded-2xl bg-white border border-gray-100 shadow p-5 flex flex-col relative z-0">
<div className="flex items-start justify-between"> <div className="flex items-start justify-between">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className="h-9 w-9 rounded-lg bg-blue-50 border border-blue-200 flex items-center justify-center"> <div className="h-9 w-9 rounded-lg bg-blue-50 border border-blue-200 flex items-center justify-center">
<UsersIcon className="h-5 w-5 text-blue-900" /> <UsersIcon className="h-5 w-5 text-blue-900" />
</div> </div>
<h3 className="text-lg font-semibold text-blue-900">{pool.name}</h3> <h3 className="text-lg font-semibold text-blue-900">{pool.pool_name}</h3>
</div> </div>
<span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${pool.archived ? 'bg-gray-100 text-gray-700' : 'bg-green-100 text-green-800'}`}> <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${!pool.is_active ? 'bg-gray-100 text-gray-700' : 'bg-green-100 text-green-800'}`}>
<span className={`mr-1.5 h-1.5 w-1.5 rounded-full ${pool.archived ? 'bg-gray-400' : 'bg-green-500'}`} /> <span className={`mr-1.5 h-1.5 w-1.5 rounded-full ${!pool.is_active ? 'bg-gray-400' : 'bg-green-500'}`} />
{pool.archived ? 'Archived' : 'Active'} {!pool.is_active ? 'Inactive' : 'Active'}
</span> </span>
</div> </div>
<p className="mt-2 text-sm text-gray-700">{pool.description || '-'}</p> <p className="mt-2 text-sm text-gray-700">{pool.description || '-'}</p>
@ -211,9 +233,11 @@ export default function PoolManagementPage() {
onClick={() => { onClick={() => {
const params = new URLSearchParams({ const params = new URLSearchParams({
id: String(pool.id), id: String(pool.id),
name: pool.name ?? '', pool_name: pool.pool_name ?? '',
description: pool.description ?? '', description: pool.description ?? '',
state: pool.archived ? 'archived' : 'active', price: String(pool.price ?? 0),
pool_type: pool.pool_type ?? 'other',
is_active: pool.is_active ? 'true' : 'false',
createdAt: pool.createdAt ?? '', createdAt: pool.createdAt ?? '',
}) })
router.push(`/admin/pool-management/manage?${params.toString()}`) router.push(`/admin/pool-management/manage?${params.toString()}`)
@ -221,7 +245,7 @@ export default function PoolManagementPage() {
> >
Manage Manage
</button> </button>
{pool.archived ? ( {!pool.is_active ? (
<button <button
className="px-4 py-2 text-xs font-medium rounded-lg bg-green-100 text-green-800 hover:bg-green-200 transition" className="px-4 py-2 text-xs font-medium rounded-lg bg-green-100 text-green-800 hover:bg-green-200 transition"
onClick={() => handleSetActive(pool.id)} onClick={() => handleSetActive(pool.id)}
@ -241,9 +265,9 @@ export default function PoolManagementPage() {
</div> </div>
</article> </article>
))} ))}
{pools.length === 0 && !loading && !error && ( {filteredPools.length === 0 && !loading && !error && (
<div className="col-span-full text-center text-gray-500 italic py-6"> <div className="col-span-full text-center text-gray-500 italic py-6">
No pools found. {showInactive ? 'No inactive pools found.' : 'No active pools found.'}
</div> </div>
)} )}
</div> </div>