feat: Complete production deployment pipeline with admin dashboard
Some checks failed
ParentFlow CI/CD Pipeline / Backend Tests (push) Has been cancelled
ParentFlow CI/CD Pipeline / Frontend Tests (push) Has been cancelled
ParentFlow CI/CD Pipeline / Security Scanning (push) Has been cancelled
ParentFlow CI/CD Pipeline / Build Docker Images (map[context:maternal-app/maternal-app-backend dockerfile:Dockerfile.production name:backend]) (push) Has been cancelled
ParentFlow CI/CD Pipeline / Build Docker Images (map[context:maternal-web dockerfile:Dockerfile.production name:frontend]) (push) Has been cancelled
ParentFlow CI/CD Pipeline / Deploy to Development (push) Has been cancelled
ParentFlow CI/CD Pipeline / Deploy to Production (push) Has been cancelled
CI/CD Pipeline / Lint and Test (push) Has been cancelled
CI/CD Pipeline / E2E Tests (push) Has been cancelled
CI/CD Pipeline / Build Application (push) Has been cancelled

- Add unified deployment script with Node.js 22 installation
- Create comprehensive database migration script (28 migrations + admin tables)
- Add production start/stop scripts for all services
- Integrate admin dashboard (parentflow-admin) into PM2 ecosystem
- Configure all services: Backend (3020), Frontend (3030), Admin (3335)
- Update ecosystem.config.js with admin dashboard configuration
- Add invite codes module for user registration management
This commit is contained in:
2025-10-06 22:43:28 +00:00
parent 560fd22023
commit 4e19b992df
37 changed files with 6767 additions and 675 deletions

41
parentflow-admin/.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View File

@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

View File

@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

3564
parentflow-admin/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,34 @@
{
"name": "parentflow-admin",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev -p 3335 -H 0.0.0.0",
"build": "next build",
"start": "next start -p 3335"
},
"dependencies": {
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.3.4",
"@mui/material": "^7.3.4",
"@mui/material-nextjs": "^7.3.3",
"@mui/x-charts": "^8.13.1",
"@mui/x-data-grid": "^8.13.1",
"@tanstack/react-query": "^5.90.2",
"axios": "^1.12.2",
"date-fns": "^4.1.0",
"next": "15.5.4",
"react": "19.1.0",
"react-dom": "19.1.0",
"recharts": "^3.2.1"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"tailwindcss": "^4",
"typescript": "^5"
}
}

View File

@@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;

View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -0,0 +1,26 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}

View File

@@ -0,0 +1,393 @@
'use client';
import { useState, useEffect } from 'react';
import {
Box,
Paper,
Button,
Typography,
IconButton,
Chip,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
TextField,
FormControlLabel,
Switch,
Alert,
Tooltip,
Grid,
} from '@mui/material';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import {
Add,
Edit,
Delete,
ContentCopy,
Refresh,
} from '@mui/icons-material';
import { format } from 'date-fns';
import AdminLayout from '@/components/AdminLayout';
import apiClient from '@/lib/api-client';
interface InviteCode {
id: string;
code: string;
uses: number;
maxUses: number | null;
expiresAt: string | null;
createdAt: string;
createdBy: string;
isActive: boolean;
metadata?: any;
}
export default function InviteCodesPage() {
const [inviteCodes, setInviteCodes] = useState<InviteCode[]>([]);
const [loading, setLoading] = useState(true);
const [openDialog, setOpenDialog] = useState(false);
const [editingCode, setEditingCode] = useState<InviteCode | null>(null);
const [copied, setCopied] = useState<string | null>(null);
// Form state
const [formData, setFormData] = useState({
code: '',
maxUses: '',
hasExpiry: false,
expiresAt: '',
description: '',
});
const fetchInviteCodes = async () => {
setLoading(true);
try {
const data = await apiClient.getInviteCodes();
setInviteCodes(data.codes || []);
} catch (error) {
console.error('Failed to fetch invite codes:', error);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchInviteCodes();
}, []);
const generateRandomCode = () => {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
let code = '';
for (let i = 0; i < 8; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
if (i === 3) code += '-';
}
setFormData({ ...formData, code });
};
const handleCopyCode = (code: string) => {
navigator.clipboard.writeText(code);
setCopied(code);
setTimeout(() => setCopied(null), 2000);
};
const handleSubmit = async () => {
try {
const payload = {
code: formData.code,
maxUses: formData.maxUses ? parseInt(formData.maxUses) : undefined,
expiresAt: formData.hasExpiry ? formData.expiresAt : undefined,
metadata: formData.description ? { description: formData.description } : undefined,
};
if (editingCode) {
await apiClient.updateInviteCode(editingCode.id, payload);
} else {
await apiClient.createInviteCode(payload);
}
fetchInviteCodes();
handleCloseDialog();
} catch (error) {
console.error('Failed to save invite code:', error);
}
};
const handleDelete = async (id: string) => {
if (confirm('Are you sure you want to delete this invite code?')) {
try {
await apiClient.deleteInviteCode(id);
fetchInviteCodes();
} catch (error) {
console.error('Failed to delete invite code:', error);
}
}
};
const handleCloseDialog = () => {
setOpenDialog(false);
setEditingCode(null);
setFormData({
code: '',
maxUses: '',
hasExpiry: false,
expiresAt: '',
description: '',
});
};
const columns: GridColDef[] = [
{
field: 'code',
headerName: 'Code',
width: 150,
renderCell: (params) => (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="body2" sx={{ fontFamily: 'monospace', fontWeight: 500 }}>
{params.value}
</Typography>
<Tooltip title={copied === params.value ? 'Copied!' : 'Copy code'}>
<IconButton size="small" onClick={() => handleCopyCode(params.value)}>
<ContentCopy fontSize="small" />
</IconButton>
</Tooltip>
</Box>
),
},
{
field: 'status',
headerName: 'Status',
width: 120,
renderCell: (params) => {
const isExpired = params.row.expiresAt && new Date(params.row.expiresAt) < new Date();
const isMaxedOut = params.row.maxUses && params.row.uses >= params.row.maxUses;
if (!params.row.isActive) {
return <Chip label="Inactive" size="small" color="default" />;
} else if (isExpired) {
return <Chip label="Expired" size="small" color="error" />;
} else if (isMaxedOut) {
return <Chip label="Used Up" size="small" color="warning" />;
}
return <Chip label="Active" size="small" color="success" />;
},
},
{
field: 'uses',
headerName: 'Uses',
width: 100,
renderCell: (params) => (
<Typography variant="body2">
{params.value} / {params.row.maxUses || '∞'}
</Typography>
),
},
{
field: 'expiresAt',
headerName: 'Expires',
width: 150,
renderCell: (params) => (
<Typography variant="body2">
{params.value ? format(new Date(params.value), 'MMM dd, yyyy') : 'Never'}
</Typography>
),
},
{
field: 'createdAt',
headerName: 'Created',
width: 150,
renderCell: (params) => (
<Typography variant="body2">
{format(new Date(params.value), 'MMM dd, yyyy')}
</Typography>
),
},
{
field: 'actions',
headerName: 'Actions',
width: 100,
sortable: false,
renderCell: (params) => (
<Box>
<IconButton size="small" onClick={() => {
setEditingCode(params.row);
setFormData({
code: params.row.code,
maxUses: params.row.maxUses?.toString() || '',
hasExpiry: !!params.row.expiresAt,
expiresAt: params.row.expiresAt || '',
description: params.row.metadata?.description || '',
});
setOpenDialog(true);
}}>
<Edit fontSize="small" />
</IconButton>
<IconButton size="small" onClick={() => handleDelete(params.row.id)} color="error">
<Delete fontSize="small" />
</IconButton>
</Box>
),
},
];
return (
<AdminLayout>
<Box>
<Box sx={{ mb: 3, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<Typography variant="h5" fontWeight={600}>
Invite Codes Management
</Typography>
<Box sx={{ display: 'flex', gap: 1 }}>
<Button
startIcon={<Refresh />}
onClick={fetchInviteCodes}
variant="outlined"
>
Refresh
</Button>
<Button
startIcon={<Add />}
variant="contained"
onClick={() => setOpenDialog(true)}
>
Create Invite Code
</Button>
</Box>
</Box>
<Grid container spacing={3} sx={{ mb: 3 }}>
<Grid item xs={12} sm={6} md={3}>
<Paper sx={{ p: 2 }}>
<Typography variant="body2" color="text.secondary" gutterBottom>
Total Codes
</Typography>
<Typography variant="h4">{inviteCodes.length}</Typography>
</Paper>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<Paper sx={{ p: 2 }}>
<Typography variant="body2" color="text.secondary" gutterBottom>
Active Codes
</Typography>
<Typography variant="h4">
{inviteCodes.filter(c => c.isActive).length}
</Typography>
</Paper>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<Paper sx={{ p: 2 }}>
<Typography variant="body2" color="text.secondary" gutterBottom>
Total Uses
</Typography>
<Typography variant="h4">
{inviteCodes.reduce((sum, c) => sum + c.uses, 0)}
</Typography>
</Paper>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<Paper sx={{ p: 2 }}>
<Typography variant="body2" color="text.secondary" gutterBottom>
Available
</Typography>
<Typography variant="h4">
{inviteCodes.filter(c => {
const isExpired = c.expiresAt && new Date(c.expiresAt) < new Date();
const isMaxedOut = c.maxUses && c.uses >= c.maxUses;
return c.isActive && !isExpired && !isMaxedOut;
}).length}
</Typography>
</Paper>
</Grid>
</Grid>
<Paper sx={{ p: 2 }}>
<DataGrid
rows={inviteCodes}
columns={columns}
loading={loading}
pageSizeOptions={[10, 25, 50]}
initialState={{
pagination: { paginationModel: { pageSize: 10 } },
}}
disableRowSelectionOnClick
autoHeight
/>
</Paper>
<Dialog open={openDialog} onClose={handleCloseDialog} maxWidth="sm" fullWidth>
<DialogTitle>
{editingCode ? 'Edit Invite Code' : 'Create New Invite Code'}
</DialogTitle>
<DialogContent>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}>
<Box sx={{ display: 'flex', gap: 1 }}>
<TextField
label="Invite Code"
value={formData.code}
onChange={(e) => setFormData({ ...formData, code: e.target.value })}
fullWidth
required
placeholder="ABCD-1234"
/>
<Button onClick={generateRandomCode} variant="outlined">
Generate
</Button>
</Box>
<TextField
label="Max Uses (leave empty for unlimited)"
type="number"
value={formData.maxUses}
onChange={(e) => setFormData({ ...formData, maxUses: e.target.value })}
fullWidth
InputProps={{ inputProps: { min: 1 } }}
/>
<FormControlLabel
control={
<Switch
checked={formData.hasExpiry}
onChange={(e) => setFormData({ ...formData, hasExpiry: e.target.checked })}
/>
}
label="Set expiration date"
/>
{formData.hasExpiry && (
<TextField
label="Expires At"
type="datetime-local"
value={formData.expiresAt}
onChange={(e) => setFormData({ ...formData, expiresAt: e.target.value })}
fullWidth
InputLabelProps={{ shrink: true }}
/>
)}
<TextField
label="Description (optional)"
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
fullWidth
multiline
rows={2}
placeholder="e.g., Beta testers group"
/>
<Alert severity="info">
Share this code with users to allow them to register.
The code can be used during the signup process.
</Alert>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={handleCloseDialog}>Cancel</Button>
<Button onClick={handleSubmit} variant="contained" disabled={!formData.code}>
{editingCode ? 'Update' : 'Create'}
</Button>
</DialogActions>
</Dialog>
</Box>
</AdminLayout>
);
}

View File

@@ -0,0 +1,30 @@
import type { Metadata } from 'next';
import { AppRouterCacheProvider } from '@mui/material-nextjs/v15-appRouter';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import theme from '@/lib/theme';
import './globals.css';
export const metadata: Metadata = {
title: 'ParentFlow Admin Dashboard',
description: 'Admin dashboard for managing ParentFlow application',
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body>
<AppRouterCacheProvider>
<ThemeProvider theme={theme}>
<CssBaseline />
{children}
</ThemeProvider>
</AppRouterCacheProvider>
</body>
</html>
);
}

View File

@@ -0,0 +1,105 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import {
Container,
Paper,
TextField,
Button,
Typography,
Box,
Alert,
CircularProgress,
} from '@mui/material';
import { LockOutlined } from '@mui/icons-material';
import apiClient from '@/lib/api-client';
export default function LoginPage() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
try {
await apiClient.login(email, password);
router.push('/');
} catch (err: any) {
setError(err.response?.data?.message || 'Login failed. Please check your credentials.');
} finally {
setLoading(false);
}
};
return (
<Container component="main" maxWidth="sm" sx={{ minHeight: '100vh', display: 'flex', alignItems: 'center' }}>
<Paper elevation={3} sx={{ p: 4, width: '100%', borderRadius: 2 }}>
<Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<Box sx={{ mb: 2, p: 1.5, borderRadius: '50%', bgcolor: 'primary.main' }}>
<LockOutlined sx={{ color: 'white', fontSize: 30 }} />
</Box>
<Typography component="h1" variant="h4" sx={{ mb: 1, fontWeight: 600 }}>
Admin Login
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
ParentFlow Admin Dashboard
</Typography>
{error && (
<Alert severity="error" sx={{ width: '100%', mb: 2 }}>
{error}
</Alert>
)}
<Box component="form" onSubmit={handleSubmit} sx={{ width: '100%' }}>
<TextField
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={loading}
/>
<TextField
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={loading}
/>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2, py: 1.5 }}
disabled={loading}
>
{loading ? <CircularProgress size={24} /> : 'Sign In'}
</Button>
</Box>
</Box>
</Paper>
</Container>
);
}

View File

@@ -0,0 +1,393 @@
'use client';
import { useState, useEffect } from 'react';
import {
Box,
Grid,
Paper,
Typography,
Card,
CardContent,
LinearProgress,
List,
ListItem,
ListItemText,
ListItemAvatar,
Avatar,
Chip,
IconButton,
} from '@mui/material';
import {
People,
FamilyRestroom,
ChildCare,
TrendingUp,
Warning,
CheckCircle,
Refresh,
AccessTime,
} from '@mui/icons-material';
import { LineChart, Line, AreaChart, Area, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { format, subDays, startOfDay } from 'date-fns';
import AdminLayout from '@/components/AdminLayout';
import apiClient from '@/lib/api-client';
interface DashboardStats {
totalUsers: number;
totalFamilies: number;
totalChildren: number;
activeUsers: number;
newUsersToday: number;
activitiesLogged: number;
aiQueriesTotal: number;
systemStatus: 'healthy' | 'warning' | 'error';
}
const COLORS = ['#FF8B7D', '#FFB5A0', '#FFD4CC', '#81C784', '#FFB74D'];
export default function DashboardPage() {
const [stats, setStats] = useState<DashboardStats>({
totalUsers: 0,
totalFamilies: 0,
totalChildren: 0,
activeUsers: 0,
newUsersToday: 0,
activitiesLogged: 0,
aiQueriesTotal: 0,
systemStatus: 'healthy',
});
const [loading, setLoading] = useState(true);
const [userGrowthData, setUserGrowthData] = useState<any[]>([]);
const [activityData, setActivityData] = useState<any[]>([]);
const [recentUsers, setRecentUsers] = useState<any[]>([]);
const fetchDashboardData = async () => {
setLoading(true);
try {
// Simulate API calls - replace with actual calls
const analyticsData = await apiClient.getAnalytics();
const growthData = await apiClient.getUserGrowth();
const activityStats = await apiClient.getActivityStats();
// Mock data for now - replace with actual API response
setStats({
totalUsers: 1250,
totalFamilies: 420,
totalChildren: 680,
activeUsers: 890,
newUsersToday: 23,
activitiesLogged: 15420,
aiQueriesTotal: 3250,
systemStatus: 'healthy',
});
// Mock user growth data
const mockGrowthData = Array.from({ length: 30 }, (_, i) => {
const date = subDays(new Date(), 29 - i);
return {
date: format(date, 'MMM dd'),
users: Math.floor(Math.random() * 50) + 20,
activities: Math.floor(Math.random() * 200) + 100,
};
});
setUserGrowthData(mockGrowthData);
// Mock activity distribution
setActivityData([
{ name: 'Feeding', value: 4500, color: '#FF8B7D' },
{ name: 'Sleep', value: 3200, color: '#FFB5A0' },
{ name: 'Diapers', value: 2800, color: '#FFD4CC' },
{ name: 'Milestones', value: 1200, color: '#81C784' },
{ name: 'Other', value: 3720, color: '#FFB74D' },
]);
// Mock recent users
setRecentUsers([
{ id: 1, name: 'Sarah Johnson', email: 'sarah@example.com', joinedAt: new Date() },
{ id: 2, name: 'Mike Chen', email: 'mike@example.com', joinedAt: new Date() },
{ id: 3, name: 'Emma Davis', email: 'emma@example.com', joinedAt: new Date() },
]);
} catch (error) {
console.error('Failed to fetch dashboard data:', error);
// Use mock data even on error for development
setStats({
totalUsers: 1250,
totalFamilies: 420,
totalChildren: 680,
activeUsers: 890,
newUsersToday: 23,
activitiesLogged: 15420,
aiQueriesTotal: 3250,
systemStatus: 'healthy',
});
const mockGrowthData = Array.from({ length: 30 }, (_, i) => {
const date = subDays(new Date(), 29 - i);
return {
date: format(date, 'MMM dd'),
users: Math.floor(Math.random() * 50) + 20,
activities: Math.floor(Math.random() * 200) + 100,
};
});
setUserGrowthData(mockGrowthData);
setActivityData([
{ name: 'Feeding', value: 4500, color: '#FF8B7D' },
{ name: 'Sleep', value: 3200, color: '#FFB5A0' },
{ name: 'Diapers', value: 2800, color: '#FFD4CC' },
{ name: 'Milestones', value: 1200, color: '#81C784' },
{ name: 'Other', value: 3720, color: '#FFB74D' },
]);
setRecentUsers([
{ id: 1, name: 'Sarah Johnson', email: 'sarah@example.com', joinedAt: new Date() },
{ id: 2, name: 'Mike Chen', email: 'mike@example.com', joinedAt: new Date() },
{ id: 3, name: 'Emma Davis', email: 'emma@example.com', joinedAt: new Date() },
]);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchDashboardData();
}, []);
const StatCard = ({ icon, title, value, change, color }: any) => (
<Card sx={{ height: '100%' }}>
<CardContent>
<Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
<Avatar sx={{ bgcolor: `${color}.light`, color: `${color}.main`, mr: 2 }}>
{icon}
</Avatar>
<Box sx={{ flexGrow: 1 }}>
<Typography color="text.secondary" variant="body2">
{title}
</Typography>
<Typography variant="h4" fontWeight={600}>
{value.toLocaleString()}
</Typography>
{change && (
<Typography
variant="caption"
sx={{ color: change > 0 ? 'success.main' : 'error.main' }}
>
{change > 0 ? '+' : ''}{change}% from yesterday
</Typography>
)}
</Box>
</Box>
</CardContent>
</Card>
);
if (loading) {
return (
<AdminLayout>
<LinearProgress />
</AdminLayout>
);
}
return (
<AdminLayout>
<Box>
<Box sx={{ mb: 3, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<Box>
<Typography variant="h5" fontWeight={600}>
Dashboard Overview
</Typography>
<Typography variant="body2" color="text.secondary">
Welcome back! Here's what's happening with ParentFlow today.
</Typography>
</Box>
<IconButton onClick={fetchDashboardData}>
<Refresh />
</IconButton>
</Box>
{/* Stats Cards */}
<Grid container spacing={3} sx={{ mb: 3 }}>
<Grid item xs={12} sm={6} md={3}>
<StatCard
icon={<People />}
title="Total Users"
value={stats.totalUsers}
change={5.2}
color="primary"
/>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<StatCard
icon={<FamilyRestroom />}
title="Families"
value={stats.totalFamilies}
change={3.1}
color="secondary"
/>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<StatCard
icon={<ChildCare />}
title="Children"
value={stats.totalChildren}
change={4.5}
color="info"
/>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<StatCard
icon={<TrendingUp />}
title="Activities Today"
value={stats.activitiesLogged}
change={12.3}
color="success"
/>
</Grid>
</Grid>
{/* Charts Row */}
<Grid container spacing={3} sx={{ mb: 3 }}>
<Grid item xs={12} md={8}>
<Paper sx={{ p: 3 }}>
<Typography variant="h6" gutterBottom>
User Growth (Last 30 Days)
</Typography>
<ResponsiveContainer width="100%" height={300}>
<AreaChart data={userGrowthData}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="date" />
<YAxis />
<Tooltip />
<Area
type="monotone"
dataKey="users"
stroke="#FF8B7D"
fill="#FFB5A0"
fillOpacity={0.6}
/>
</AreaChart>
</ResponsiveContainer>
</Paper>
</Grid>
<Grid item xs={12} md={4}>
<Paper sx={{ p: 3 }}>
<Typography variant="h6" gutterBottom>
Activity Distribution
</Typography>
<ResponsiveContainer width="100%" height={300}>
<PieChart>
<Pie
data={activityData}
cx="50%"
cy="50%"
labelLine={false}
label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
outerRadius={80}
fill="#8884d8"
dataKey="value"
>
{activityData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Tooltip />
</PieChart>
</ResponsiveContainer>
</Paper>
</Grid>
</Grid>
{/* Recent Activity and System Status */}
<Grid container spacing={3}>
<Grid item xs={12} md={6}>
<Paper sx={{ p: 3 }}>
<Typography variant="h6" gutterBottom>
Recent Users
</Typography>
<List>
{recentUsers.map((user) => (
<ListItem key={user.id}>
<ListItemAvatar>
<Avatar sx={{ bgcolor: 'primary.main' }}>
{user.name.charAt(0)}
</Avatar>
</ListItemAvatar>
<ListItemText
primary={user.name}
secondary={user.email}
/>
<Chip
icon={<AccessTime />}
label="New"
size="small"
color="success"
variant="outlined"
/>
</ListItem>
))}
</List>
</Paper>
</Grid>
<Grid item xs={12} md={6}>
<Paper sx={{ p: 3 }}>
<Typography variant="h6" gutterBottom>
System Status
</Typography>
<List>
<ListItem>
<ListItemAvatar>
<Avatar sx={{ bgcolor: 'success.light' }}>
<CheckCircle color="success" />
</Avatar>
</ListItemAvatar>
<ListItemText
primary="API Server"
secondary="Responding normally"
/>
<Chip label="Healthy" color="success" size="small" />
</ListItem>
<ListItem>
<ListItemAvatar>
<Avatar sx={{ bgcolor: 'success.light' }}>
<CheckCircle color="success" />
</Avatar>
</ListItemAvatar>
<ListItemText
primary="Database"
secondary="10.0.0.207 - Connected"
/>
<Chip label="Healthy" color="success" size="small" />
</ListItem>
<ListItem>
<ListItemAvatar>
<Avatar sx={{ bgcolor: 'success.light' }}>
<CheckCircle color="success" />
</Avatar>
</ListItemAvatar>
<ListItemText
primary="Redis Cache"
secondary="Active connections: 12"
/>
<Chip label="Healthy" color="success" size="small" />
</ListItem>
<ListItem>
<ListItemAvatar>
<Avatar sx={{ bgcolor: 'warning.light' }}>
<Warning color="warning" />
</Avatar>
</ListItemAvatar>
<ListItemText
primary="AI Service"
secondary="High usage - 85% of quota"
/>
<Chip label="Warning" color="warning" size="small" />
</ListItem>
</List>
</Paper>
</Grid>
</Grid>
</Box>
</AdminLayout>
);
}

View File

@@ -0,0 +1,196 @@
'use client';
import { useState, ReactNode } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import {
Box,
Drawer,
AppBar,
Toolbar,
List,
Typography,
IconButton,
ListItem,
ListItemButton,
ListItemIcon,
ListItemText,
Avatar,
Menu,
MenuItem,
Divider,
Chip,
} from '@mui/material';
import {
Menu as MenuIcon,
Dashboard,
People,
ConfirmationNumber,
Analytics,
Settings,
Logout,
FamilyRestroom,
HealthAndSafety,
} from '@mui/icons-material';
import apiClient from '@/lib/api-client';
const drawerWidth = 240;
interface AdminLayoutProps {
children: ReactNode;
}
export default function AdminLayout({ children }: AdminLayoutProps) {
const router = useRouter();
const pathname = usePathname();
const [mobileOpen, setMobileOpen] = useState(false);
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
const handleDrawerToggle = () => {
setMobileOpen(!mobileOpen);
};
const handleLogout = async () => {
await apiClient.logout();
router.push('/login');
};
const menuItems = [
{ text: 'Dashboard', icon: <Dashboard />, path: '/' },
{ text: 'Users', icon: <People />, path: '/users' },
{ text: 'Families', icon: <FamilyRestroom />, path: '/families' },
{ text: 'Invite Codes', icon: <ConfirmationNumber />, path: '/invite-codes' },
{ text: 'Analytics', icon: <Analytics />, path: '/analytics' },
{ text: 'System Health', icon: <HealthAndSafety />, path: '/health' },
{ text: 'Settings', icon: <Settings />, path: '/settings' },
];
const drawer = (
<Box>
<Toolbar sx={{ justifyContent: 'center', py: 2 }}>
<Typography variant="h6" noWrap sx={{ fontWeight: 600, color: 'primary.main' }}>
ParentFlow Admin
</Typography>
</Toolbar>
<Divider />
<List>
{menuItems.map((item) => (
<ListItem key={item.text} disablePadding>
<ListItemButton
onClick={() => router.push(item.path)}
selected={pathname === item.path}
sx={{
'&.Mui-selected': {
backgroundColor: 'primary.light',
'&:hover': {
backgroundColor: 'primary.light',
},
},
}}
>
<ListItemIcon sx={{ color: pathname === item.path ? 'primary.main' : 'inherit' }}>
{item.icon}
</ListItemIcon>
<ListItemText primary={item.text} />
</ListItemButton>
</ListItem>
))}
</List>
</Box>
);
return (
<Box sx={{ display: 'flex' }}>
<AppBar
position="fixed"
sx={{
width: { sm: `calc(100% - ${drawerWidth}px)` },
ml: { sm: `${drawerWidth}px` },
backgroundColor: 'white',
color: 'text.primary',
}}
elevation={1}
>
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
edge="start"
onClick={handleDrawerToggle}
sx={{ mr: 2, display: { sm: 'none' } }}
>
<MenuIcon />
</IconButton>
<Box sx={{ flexGrow: 1 }}>
<Typography variant="h6" noWrap component="div">
{menuItems.find(item => item.path === pathname)?.text || 'Dashboard'}
</Typography>
</Box>
<Chip label="Admin" color="primary" size="small" sx={{ mr: 2 }} />
<IconButton onClick={(e) => setAnchorEl(e.currentTarget)}>
<Avatar sx={{ bgcolor: 'primary.main', width: 32, height: 32 }}>A</Avatar>
</IconButton>
<Menu
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={() => setAnchorEl(null)}
>
<MenuItem onClick={handleLogout}>
<ListItemIcon>
<Logout fontSize="small" />
</ListItemIcon>
Logout
</MenuItem>
</Menu>
</Toolbar>
</AppBar>
<Box
component="nav"
sx={{ width: { sm: drawerWidth }, flexShrink: { sm: 0 } }}
>
<Drawer
variant="temporary"
open={mobileOpen}
onClose={handleDrawerToggle}
ModalProps={{
keepMounted: true, // Better open performance on mobile
}}
sx={{
display: { xs: 'block', sm: 'none' },
'& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
}}
>
{drawer}
</Drawer>
<Drawer
variant="permanent"
sx={{
display: { xs: 'none', sm: 'block' },
'& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
}}
open
>
{drawer}
</Drawer>
</Box>
<Box
component="main"
sx={{
flexGrow: 1,
p: 3,
width: { sm: `calc(100% - ${drawerWidth}px)` },
mt: 8,
backgroundColor: 'background.default',
minHeight: '100vh',
}}
>
{children}
</Box>
</Box>
);
}

View File

@@ -0,0 +1,183 @@
import axios from 'axios';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3020/api/v1';
class ApiClient {
private token: string | null = null;
private refreshToken: string | null = null;
constructor() {
// Initialize tokens from localStorage if available
if (typeof window !== 'undefined') {
this.token = localStorage.getItem('admin_access_token');
this.refreshToken = localStorage.getItem('admin_refresh_token');
}
}
setTokens(accessToken: string, refreshToken: string) {
this.token = accessToken;
this.refreshToken = refreshToken;
if (typeof window !== 'undefined') {
localStorage.setItem('admin_access_token', accessToken);
localStorage.setItem('admin_refresh_token', refreshToken);
}
}
clearTokens() {
this.token = null;
this.refreshToken = null;
if (typeof window !== 'undefined') {
localStorage.removeItem('admin_access_token');
localStorage.removeItem('admin_refresh_token');
}
}
private async request(method: string, endpoint: string, data?: any, options?: any) {
const config = {
method,
url: `${API_BASE_URL}${endpoint}`,
headers: {
'Content-Type': 'application/json',
...(this.token ? { Authorization: `Bearer ${this.token}` } : {}),
...options?.headers,
},
...options,
};
if (data) {
config.data = data;
}
try {
const response = await axios(config);
return response.data;
} catch (error: any) {
// Handle token refresh
if (error.response?.status === 401 && this.refreshToken) {
try {
const refreshResponse = await axios.post(`${API_BASE_URL}/auth/refresh`, {
refreshToken: this.refreshToken,
});
this.setTokens(refreshResponse.data.accessToken, refreshResponse.data.refreshToken);
// Retry original request
config.headers.Authorization = `Bearer ${this.token}`;
const response = await axios(config);
return response.data;
} catch (refreshError) {
this.clearTokens();
window.location.href = '/login';
throw refreshError;
}
}
throw error;
}
}
// Auth endpoints
async login(email: string, password: string) {
const response = await this.request('POST', '/admin/auth/login', { email, password });
this.setTokens(response.accessToken, response.refreshToken);
return response;
}
async logout() {
try {
await this.request('POST', '/admin/auth/logout');
} finally {
this.clearTokens();
}
}
async getCurrentAdmin() {
return this.request('GET', '/admin/auth/me');
}
// User management endpoints
async getUsers(params?: { page?: number; limit?: number; search?: string }) {
const queryString = params ? '?' + new URLSearchParams(params as any).toString() : '';
return this.request('GET', `/admin/users${queryString}`);
}
async getUserById(id: string) {
return this.request('GET', `/admin/users/${id}`);
}
async updateUser(id: string, data: any) {
return this.request('PATCH', `/admin/users/${id}`, data);
}
async deleteUser(id: string) {
return this.request('DELETE', `/admin/users/${id}`);
}
// Invite code endpoints
async getInviteCodes(params?: { page?: number; limit?: number; status?: string }) {
const queryString = params ? '?' + new URLSearchParams(params as any).toString() : '';
return this.request('GET', `/admin/invite-codes${queryString}`);
}
async createInviteCode(data: {
code: string;
maxUses?: number;
expiresAt?: string;
metadata?: any;
}) {
return this.request('POST', '/admin/invite-codes', data);
}
async updateInviteCode(id: string, data: any) {
return this.request('PATCH', `/admin/invite-codes/${id}`, data);
}
async deleteInviteCode(id: string) {
return this.request('DELETE', `/admin/invite-codes/${id}`);
}
// Analytics endpoints
async getAnalytics(params?: { startDate?: string; endDate?: string }) {
const queryString = params ? '?' + new URLSearchParams(params as any).toString() : '';
return this.request('GET', `/admin/analytics${queryString}`);
}
async getUserGrowth() {
return this.request('GET', '/admin/analytics/user-growth');
}
async getActivityStats() {
return this.request('GET', '/admin/analytics/activity-stats');
}
async getSystemHealth() {
return this.request('GET', '/admin/analytics/system-health');
}
// Family management
async getFamilies(params?: { page?: number; limit?: number; search?: string }) {
const queryString = params ? '?' + new URLSearchParams(params as any).toString() : '';
return this.request('GET', `/admin/families${queryString}`);
}
async getFamilyById(id: string) {
return this.request('GET', `/admin/families/${id}`);
}
// Activity logs
async getActivityLogs(params?: { page?: number; limit?: number; userId?: string }) {
const queryString = params ? '?' + new URLSearchParams(params as any).toString() : '';
return this.request('GET', `/admin/logs${queryString}`);
}
// System settings
async getSettings() {
return this.request('GET', '/admin/settings');
}
async updateSettings(data: any) {
return this.request('PATCH', '/admin/settings', data);
}
}
export const apiClient = new ApiClient();
export default apiClient;

View File

@@ -0,0 +1,106 @@
import { createTheme } from '@mui/material/styles';
const theme = createTheme({
palette: {
mode: 'light',
primary: {
main: '#FF8B7D',
light: '#FFB5A0',
dark: '#FF6B59',
contrastText: '#FFFFFF',
},
secondary: {
main: '#FFD4CC',
light: '#FFE8E4',
dark: '#FFB5A0',
contrastText: '#2C2C2C',
},
success: {
main: '#81C784',
light: '#A5D6A7',
dark: '#66BB6A',
},
warning: {
main: '#FFB74D',
light: '#FFCC80',
dark: '#FFA726',
},
error: {
main: '#FF8A80',
light: '#FFAB91',
dark: '#FF7961',
},
background: {
default: '#FFF8F5',
paper: '#FFFFFF',
},
text: {
primary: '#2C2C2C',
secondary: '#5E5E5E',
},
},
typography: {
fontFamily: '"Inter", "Roboto", "Helvetica", "Arial", sans-serif',
h1: {
fontSize: '2.5rem',
fontWeight: 600,
lineHeight: 1.2,
},
h2: {
fontSize: '2rem',
fontWeight: 600,
lineHeight: 1.3,
},
h3: {
fontSize: '1.75rem',
fontWeight: 500,
lineHeight: 1.4,
},
h4: {
fontSize: '1.5rem',
fontWeight: 500,
lineHeight: 1.4,
},
h5: {
fontSize: '1.25rem',
fontWeight: 500,
lineHeight: 1.5,
},
h6: {
fontSize: '1rem',
fontWeight: 500,
lineHeight: 1.6,
},
},
shape: {
borderRadius: 12,
},
components: {
MuiButton: {
styleOverrides: {
root: {
textTransform: 'none',
borderRadius: 8,
fontWeight: 500,
},
},
},
MuiCard: {
styleOverrides: {
root: {
borderRadius: 12,
boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
},
},
},
MuiPaper: {
styleOverrides: {
root: {
borderRadius: 12,
},
},
},
},
});
export default theme;

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}