feat: update pool management functionality with new fields and state handling
This commit is contained in:
parent
6831b92169
commit
6a96b27d2e
@ -4,7 +4,7 @@ import React from 'react'
|
||||
interface Props {
|
||||
isOpen: boolean
|
||||
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
|
||||
error?: string
|
||||
success?: string
|
||||
@ -20,13 +20,19 @@ export default function CreateNewPoolModal({
|
||||
success,
|
||||
clearMessages
|
||||
}: Props) {
|
||||
const [name, setName] = React.useState('')
|
||||
const [poolName, setPoolName] = 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(() => {
|
||||
if (!isOpen) {
|
||||
setName('')
|
||||
setPoolName('')
|
||||
setDescription('')
|
||||
setPrice('0.00')
|
||||
setPoolType('other')
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
@ -67,7 +73,7 @@ export default function CreateNewPoolModal({
|
||||
onSubmit={e => {
|
||||
e.preventDefault()
|
||||
clearMessages()
|
||||
onCreate({ name, description })
|
||||
onCreate({ pool_name: poolName, description, price: parseFloat(price) || 0, pool_type: poolType })
|
||||
}}
|
||||
className="space-y-4"
|
||||
>
|
||||
@ -76,26 +82,53 @@ export default function CreateNewPoolModal({
|
||||
<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"
|
||||
placeholder="e.g., VIP Members"
|
||||
value={name}
|
||||
onChange={e => setName(e.target.value)}
|
||||
disabled={creating}
|
||||
value={poolName}
|
||||
onChange={e => setPoolName(e.target.value)}
|
||||
disabled={isDisabled}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-blue-900 mb-1">Description</label>
|
||||
<textarea
|
||||
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"
|
||||
rows={3}
|
||||
placeholder="Short description of the pool"
|
||||
value={description}
|
||||
onChange={e => setDescription(e.target.value)}
|
||||
disabled={creating}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-blue-900 mb-1">Description</label>
|
||||
<textarea
|
||||
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"
|
||||
rows={3}
|
||||
placeholder="Short description of the pool"
|
||||
value={description}
|
||||
onChange={e => setDescription(e.target.value)}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
</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">
|
||||
<button
|
||||
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"
|
||||
>
|
||||
{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
|
||||
type="button"
|
||||
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(); }}
|
||||
disabled={creating}
|
||||
onClick={() => { setPoolName(''); setDescription(''); setPrice('0.00'); setPoolType('other'); clearMessages(); }}
|
||||
disabled={isDisabled}
|
||||
>
|
||||
Reset
|
||||
</button>
|
||||
@ -113,7 +146,7 @@ export default function CreateNewPoolModal({
|
||||
type="button"
|
||||
className="ml-auto px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-800 transition"
|
||||
onClick={() => { clearMessages(); onClose(); }}
|
||||
disabled={creating}
|
||||
disabled={isDisabled}
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
import { authFetch } from '../../../utils/authFetch';
|
||||
|
||||
export type AddPoolPayload = {
|
||||
name: string;
|
||||
pool_name: string;
|
||||
description?: string;
|
||||
state?: 'active' | 'inactive';
|
||||
price: number;
|
||||
pool_type: 'coffee' | 'other';
|
||||
is_active?: boolean;
|
||||
};
|
||||
|
||||
export async function addPool(payload: AddPoolPayload) {
|
||||
@ -31,7 +33,7 @@ export async function addPool(payload: AddPoolPayload) {
|
||||
(res.status === 409
|
||||
? 'Pool name already exists.'
|
||||
: res.status === 400
|
||||
? 'Invalid request. Check name/state.'
|
||||
? 'Invalid request. Check pool data.'
|
||||
: res.status === 401
|
||||
? 'Unauthorized.'
|
||||
: res.status === 403
|
||||
|
||||
@ -1,18 +1,18 @@
|
||||
import { authFetch } from '../../../utils/authFetch';
|
||||
|
||||
export async function setPoolState(
|
||||
async function setPoolActiveStatus(
|
||||
id: string | number,
|
||||
state: 'active' | 'inactive' | 'archived'
|
||||
is_active: boolean
|
||||
) {
|
||||
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, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ state }),
|
||||
body: JSON.stringify({ is_active }),
|
||||
});
|
||||
|
||||
let body: any = null;
|
||||
@ -40,6 +40,10 @@ export async function setPoolState(
|
||||
return { ok, status: res.status, body, message };
|
||||
}
|
||||
|
||||
export async function archivePoolById(id: string | number) {
|
||||
return setPoolState(id, 'archived');
|
||||
export async function setPoolInactive(id: string | number) {
|
||||
return setPoolActiveStatus(id, false);
|
||||
}
|
||||
|
||||
export async function setPoolActive(id: string | number) {
|
||||
return setPoolActiveStatus(id, true);
|
||||
}
|
||||
|
||||
@ -4,11 +4,13 @@ import { log } from '../../../utils/logger';
|
||||
|
||||
export type AdminPool = {
|
||||
id: string;
|
||||
name: string;
|
||||
pool_name: string;
|
||||
description?: string;
|
||||
price?: number;
|
||||
pool_type?: 'coffee' | 'other';
|
||||
is_active?: boolean;
|
||||
membersCount: number;
|
||||
createdAt: string;
|
||||
archived?: boolean;
|
||||
};
|
||||
|
||||
export function useAdminPools() {
|
||||
@ -58,11 +60,13 @@ export function useAdminPools() {
|
||||
|
||||
const mapped: AdminPool[] = apiItems.map(item => ({
|
||||
id: String(item.id),
|
||||
name: String(item.name ?? 'Unnamed Pool'),
|
||||
pool_name: String(item.pool_name ?? 'Unnamed Pool'),
|
||||
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,
|
||||
createdAt: String(item.created_at ?? new Date().toISOString()),
|
||||
archived: String(item.state ?? '').toLowerCase() === 'archived',
|
||||
}));
|
||||
log("✅ Pools: Mapped sample:", mapped.slice(0, 3));
|
||||
|
||||
@ -94,11 +98,13 @@ export function useAdminPools() {
|
||||
const apiItems: any[] = Array.isArray(body?.data) ? body.data : [];
|
||||
setPools(apiItems.map(item => ({
|
||||
id: String(item.id),
|
||||
name: String(item.name ?? 'Unnamed Pool'),
|
||||
pool_name: String(item.pool_name ?? 'Unnamed Pool'),
|
||||
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,
|
||||
createdAt: String(item.created_at ?? new Date().toISOString()),
|
||||
archived: String(item.state ?? '').toLowerCase() === 'archived',
|
||||
})));
|
||||
log("✅ Pools: Refresh succeeded, items:", apiItems.length);
|
||||
return true;
|
||||
|
||||
49
src/app/admin/pool-management/hooks/poolStatus.ts
Normal file
49
src/app/admin/pool-management/hooks/poolStatus.ts
Normal 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);
|
||||
}
|
||||
@ -45,9 +45,11 @@ export default function PoolManagePage() {
|
||||
|
||||
// Read pool data from query params with fallbacks (hooks must be before any return)
|
||||
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 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()
|
||||
|
||||
// Members (no dummy data)
|
||||
@ -117,9 +119,9 @@ export default function PoolManagePage() {
|
||||
{poolDescription ? poolDescription : 'Manage users and track pool funds'}
|
||||
</p>
|
||||
<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={`mr-1.5 h-1.5 w-1.5 rounded-full ${poolState === 'archived' ? 'bg-gray-400' : 'bg-green-500'}`} />
|
||||
{poolState === 'archived' ? 'Archived' : 'Active'}
|
||||
<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 ${!poolIsActive ? 'bg-gray-400' : 'bg-green-500'}`} />
|
||||
{!poolIsActive ? 'Inactive' : 'Active'}
|
||||
</span>
|
||||
<span>•</span>
|
||||
<span>Created {new Date(poolCreatedAt).toLocaleDateString('de-DE', { year: 'numeric', month: 'short', day: '2-digit' })}</span>
|
||||
|
||||
@ -8,17 +8,19 @@ import { useAdminPools } from './hooks/getlist'
|
||||
import useAuthStore from '../../store/authStore'
|
||||
import { addPool } from './hooks/addPool'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { archivePoolById, setPoolState } from './hooks/archivePool'
|
||||
import { setPoolInactive, setPoolActive } from './hooks/poolStatus'
|
||||
import PageTransitionEffect from '../../components/animation/pageTransitionEffect'
|
||||
import CreateNewPoolModal from './components/createNewPoolModal'
|
||||
|
||||
type Pool = {
|
||||
id: string
|
||||
name: string
|
||||
pool_name: string
|
||||
description?: string
|
||||
price?: number
|
||||
pool_type?: 'coffee' | 'other'
|
||||
is_active?: boolean
|
||||
membersCount: number
|
||||
createdAt: string
|
||||
archived?: boolean
|
||||
}
|
||||
|
||||
export default function PoolManagementPage() {
|
||||
@ -38,6 +40,7 @@ export default function PoolManagementPage() {
|
||||
// Replace local fetch with hook
|
||||
const { pools: initialPools, loading, error, refresh } = useAdminPools()
|
||||
const [pools, setPools] = React.useState<Pool[]>([])
|
||||
const [showInactive, setShowInactive] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!loading && !error) {
|
||||
@ -45,24 +48,28 @@ export default function PoolManagementPage() {
|
||||
}
|
||||
}, [initialPools, loading, error])
|
||||
|
||||
// REPLACED: handleCreatePool to accept data from modal
|
||||
async function handleCreatePool(data: { name: string; description: string }) {
|
||||
const filteredPools = pools.filter(p => showInactive ? !p.is_active : p.is_active)
|
||||
|
||||
// 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('')
|
||||
setCreateSuccess('')
|
||||
const name = data.name.trim()
|
||||
const pool_name = data.pool_name.trim()
|
||||
const description = data.description.trim()
|
||||
if (!name) {
|
||||
if (!pool_name) {
|
||||
setCreateError('Please provide a pool name.')
|
||||
return
|
||||
}
|
||||
setCreating(true)
|
||||
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) {
|
||||
setCreateSuccess('Pool created successfully.')
|
||||
await refresh?.()
|
||||
// keep modal open so user sees success; optional close:
|
||||
// setCreateModalOpen(false)
|
||||
setTimeout(() => {
|
||||
setCreateModalOpen(false)
|
||||
setCreateSuccess('')
|
||||
}, 1500)
|
||||
} else {
|
||||
setCreateError(res.message || 'Failed to create pool.')
|
||||
}
|
||||
@ -75,17 +82,17 @@ export default function PoolManagementPage() {
|
||||
|
||||
async function handleArchive(poolId: string) {
|
||||
setArchiveError('')
|
||||
const res = await archivePoolById(poolId)
|
||||
const res = await setPoolInactive(poolId)
|
||||
if (res.ok) {
|
||||
await refresh?.()
|
||||
} else {
|
||||
setArchiveError(res.message || 'Failed to archive pool.')
|
||||
setArchiveError(res.message || 'Failed to deactivate pool.')
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSetActive(poolId: string) {
|
||||
setArchiveError('')
|
||||
const res = await setPoolState(poolId, 'active')
|
||||
const res = await setPoolActive(poolId)
|
||||
if (res.ok) {
|
||||
await refresh?.()
|
||||
} else {
|
||||
@ -142,6 +149,21 @@ export default function PoolManagementPage() {
|
||||
Create New Pool
|
||||
</button>
|
||||
</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>
|
||||
|
||||
{/* Pools List card */}
|
||||
@ -178,18 +200,18 @@ export default function PoolManagementPage() {
|
||||
</div>
|
||||
) : (
|
||||
<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">
|
||||
<div className="flex items-start justify-between">
|
||||
<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">
|
||||
<UsersIcon className="h-5 w-5 text-blue-900" />
|
||||
</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>
|
||||
<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={`mr-1.5 h-1.5 w-1.5 rounded-full ${pool.archived ? 'bg-gray-400' : 'bg-green-500'}`} />
|
||||
{pool.archived ? 'Archived' : 'Active'}
|
||||
<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.is_active ? 'bg-gray-400' : 'bg-green-500'}`} />
|
||||
{!pool.is_active ? 'Inactive' : 'Active'}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-2 text-sm text-gray-700">{pool.description || '-'}</p>
|
||||
@ -211,9 +233,11 @@ export default function PoolManagementPage() {
|
||||
onClick={() => {
|
||||
const params = new URLSearchParams({
|
||||
id: String(pool.id),
|
||||
name: pool.name ?? '',
|
||||
pool_name: pool.pool_name ?? '',
|
||||
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 ?? '',
|
||||
})
|
||||
router.push(`/admin/pool-management/manage?${params.toString()}`)
|
||||
@ -221,7 +245,7 @@ export default function PoolManagementPage() {
|
||||
>
|
||||
Manage
|
||||
</button>
|
||||
{pool.archived ? (
|
||||
{!pool.is_active ? (
|
||||
<button
|
||||
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)}
|
||||
@ -241,9 +265,9 @@ export default function PoolManagementPage() {
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
{pools.length === 0 && !loading && !error && (
|
||||
{filteredPools.length === 0 && !loading && !error && (
|
||||
<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>
|
||||
|
||||
Loading…
Reference in New Issue
Block a user