Develop QR code generator app for campaign

This commit is contained in:
Hafid Nur
2026-02-14 16:38:15 +07:00
parent c79580b4ea
commit 5bb5a05a25
36 changed files with 3384 additions and 941 deletions
+4 -4
View File
@@ -2,12 +2,12 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Qrcampaign</title>
<title>QR Code Generator - IMPHNEN</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<link rel="stylesheet" href="/src/styles.css" />
<meta name="description" content="QR Code Generator - IMPHNEN" />
<meta name="keywords" content="qr, campaign, imphnen" />
<link rel="icon" type="image/svg+xml" href="/images/imphnen-logo.svg" />
</head>
<body>
<div id="root"></div>
+9
View File
@@ -0,0 +1,9 @@
import { join } from 'path';
export default {
plugins: {
'@tailwindcss/postcss': {
base: join(import.meta.dirname, '../../'),
},
},
};
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 351 KiB

+23
View File
@@ -0,0 +1,23 @@
import { Link } from 'react-router-dom';
export default function NotFoundPage() {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="text-center">
<h1 className="text-9xl font-bold text-gray-200 mb-4">404</h1>
<h2 className="text-3xl font-semibold text-gray-900 mb-4">
Page Not Found
</h2>
<p className="text-gray-600 mb-8">
The page you are looking for doesn't exist or has been moved.
</p>
<Link
to="/"
className="inline-block px-6 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors"
>
Go Back Home
</Link>
</div>
</div>
);
}
@@ -0,0 +1,262 @@
import { useState, useEffect } from 'react';
import { ColumnDef } from '@tanstack/react-table';
import { DataTable } from '@imphnen-frontend-service/ui/organisms';
import {
campaignService,
Campaign,
CreateCampaignRequest,
} from '../../features/admin/api/campaign.service';
import {
DeleteOutlined,
CheckCircleOutlined,
PlusOutlined,
} from '@ant-design/icons';
export default function CampaignsPage() {
const [campaigns, setCampaigns] = useState<Campaign[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [showCreateModal, setShowCreateModal] = useState(false);
const [createLoading, setCreateLoading] = useState(false);
const [formData, setFormData] = useState<CreateCampaignRequest>({
name: '',
url: '',
});
const fetchCampaigns = async () => {
try {
setLoading(true);
setError(null);
const data = await campaignService.getCampaigns();
setCampaigns(data);
} catch (err) {
setError('Failed to load campaigns');
console.error('Error fetching campaigns:', err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchCampaigns();
}, []);
const handleCreateCampaign = async (e: React.FormEvent) => {
e.preventDefault();
try {
setCreateLoading(true);
await campaignService.createCampaign(formData);
setShowCreateModal(false);
setFormData({ name: '', url: '' });
await fetchCampaigns();
} catch (err) {
console.error('Error creating campaign:', err);
alert('Failed to create campaign');
} finally {
setCreateLoading(false);
}
};
const handleActivateCampaign = async (campaignId: string) => {
try {
await campaignService.activateCampaign(campaignId);
await fetchCampaigns();
} catch (err) {
console.error('Error activating campaign:', err);
alert('Failed to activate campaign');
}
};
const handleDeleteCampaign = async (
campaignId: string,
campaignName: string
) => {
if (!confirm(`Are you sure you want to delete "${campaignName}"?`)) {
return;
}
try {
await campaignService.deleteCampaign(campaignId);
await fetchCampaigns();
} catch (err) {
console.error('Error deleting campaign:', err);
alert('Failed to delete campaign');
}
};
const columns: ColumnDef<Campaign>[] = [
{
accessorKey: 'name',
header: 'Name',
cell: ({ row }) => (
<div className="font-medium text-gray-900">{row.original.name}</div>
),
},
{
accessorKey: 'url',
header: 'URL',
cell: ({ row }) => (
<a
href={row.original.url}
target="_blank"
rel="noopener noreferrer"
className="text-primary-600 hover:underline"
>
{row.original.url}
</a>
),
},
{
accessorKey: 'is_active',
header: 'Status',
cell: ({ row }) => (
<span
className={`px-2 py-1 rounded-2xl text-xs font-medium ${
row.original.is_active
? 'bg-success-100 text-success-800'
: 'bg-gray-100 text-gray-800'
}`}
>
{row.original.is_active ? 'Active' : 'Inactive'}
</span>
),
},
{
accessorKey: 'created_at',
header: 'Created At',
cell: ({ row }) => (
<span className="text-gray-600">
{new Date(row.original.created_at).toLocaleDateString()}
</span>
),
},
{
id: 'actions',
header: 'Actions',
cell: ({ row }) => (
<div className="flex gap-2">
{!row.original.is_active && (
<button
onClick={() => handleActivateCampaign(row.original.id)}
className="p-2 text-success-600 hover:bg-success-50 rounded-md transition-colors cursor-pointer"
title="Activate Campaign"
>
<CheckCircleOutlined />
</button>
)}
<button
onClick={() =>
handleDeleteCampaign(row.original.id, row.original.name)
}
className="p-2 text-danger-600 hover:bg-danger-50 rounded-md transition-colors cursor-pointer"
title="Delete Campaign"
>
<DeleteOutlined />
</button>
</div>
),
},
];
if (loading) {
return (
<div className="p-6">
<div className="text-center py-12">
<div className="text-gray-600">Loading campaigns...</div>
</div>
</div>
);
}
if (error) {
return (
<div className="p-6">
<div className="bg-red-50 border border-red-200 rounded-lg p-4 text-red-800">
{error}
</div>
</div>
);
}
return (
<div className="p-6">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-2xl font-bold text-gray-900">
Campaign Management
</h1>
<p className="text-gray-600 mt-1">Manage your QR campaigns</p>
</div>
<button
onClick={() => setShowCreateModal(true)}
className="flex items-center gap-2 bg-primary-500 text-white px-4 py-2 rounded-lg hover:bg-primary-600 transition-colors cursor-pointer"
>
<PlusOutlined />
Create Campaign
</button>
</div>
<DataTable data={campaigns} columns={columns} pageSize={10} />
{/* Create Campaign Modal */}
{showCreateModal && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-white rounded-lg p-6 w-full max-w-md">
<h2 className="text-xl font-bold mb-4">Create New Campaign</h2>
<form onSubmit={handleCreateCampaign}>
<div className="mb-4">
<label className="block text-sm font-medium text-gray-700 mb-2">
Campaign Name
</label>
<input
type="text"
value={formData.name}
onChange={(e) =>
setFormData({ ...formData, name: e.target.value })
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="IMPHNEN Promo Campaign"
required
/>
</div>
<div className="mb-6">
<label className="block text-sm font-medium text-gray-700 mb-2">
Campaign URL
</label>
<input
type="url"
value={formData.url}
onChange={(e) =>
setFormData({ ...formData, url: e.target.value })
}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="https://imphnen.dev/promo"
required
/>
</div>
<div className="flex gap-3 justify-end">
<button
type="button"
onClick={() => {
setShowCreateModal(false);
setFormData({ name: '', url: '' });
}}
className="px-4 py-2 text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors cursor-pointer"
disabled={createLoading}
>
Cancel
</button>
<button
type="submit"
className="px-4 py-2 bg-primary-500 text-white rounded-md hover:bg-primary-600 transition-colors disabled:opacity-50 cursor-pointer"
disabled={createLoading}
>
{createLoading ? 'Creating...' : 'Create'}
</button>
</div>
</form>
</div>
</div>
)}
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { Outlet } from 'react-router-dom';
import { RequireAdmin } from '../features/admin/components/RequireAdmin';
export default function AdminLayout() {
return (
<RequireAdmin>
<Outlet />
</RequireAdmin>
);
}
+3
View File
@@ -0,0 +1,3 @@
export default function AdminPage() {
return <div className="p-4">Select a menu item from the sidebar.</div>;
}
@@ -0,0 +1,199 @@
import { useState, useEffect } from 'react';
import { ColumnDef } from '@tanstack/react-table';
import { DataTable } from '@imphnen-frontend-service/ui/organisms';
import { userService, User } from '../../features/admin/api/user.service';
import { DeleteOutlined, EditOutlined } from '@ant-design/icons';
export default function UsersPage() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [editingUserId, setEditingUserId] = useState<string | null>(null);
const [selectedRole, setSelectedRole] = useState<string>('');
const fetchUsers = async () => {
try {
setLoading(true);
setError(null);
const data = await userService.getUsers();
setUsers(data);
} catch (err) {
setError('Failed to load users');
console.error('Error fetching users:', err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchUsers();
}, []);
const handleUpdateRole = async (userId: string, currentRole: string) => {
if (editingUserId === userId) {
// Save the role
try {
await userService.updateUserRole(userId, selectedRole);
setEditingUserId(null);
setSelectedRole('');
await fetchUsers();
} catch (err) {
console.error('Error updating user role:', err);
alert('Failed to update user role');
}
} else {
// Start editing
setEditingUserId(userId);
setSelectedRole(currentRole);
}
};
const handleDeleteUser = async (userId: string, userName: string) => {
if (!confirm(`Are you sure you want to delete user "${userName}"?`)) {
return;
}
try {
await userService.deleteUser(userId);
await fetchUsers();
} catch (err) {
console.error('Error deleting user:', err);
alert('Failed to delete user');
}
};
const columns: ColumnDef<User>[] = [
{
accessorKey: 'name',
header: 'Name',
cell: ({ row }) => (
<div className="font-medium text-gray-900">{row.original.name}</div>
),
},
{
accessorKey: 'email',
header: 'Email',
cell: ({ row }) => (
<div className="text-gray-600">{row.original.email}</div>
),
},
{
accessorKey: 'role',
header: 'Role',
cell: ({ row }) => {
const isEditing = editingUserId === row.original.id;
return (
<div className="flex items-center gap-2">
{isEditing ? (
<select
value={selectedRole}
onChange={(e) => setSelectedRole(e.target.value)}
className="px-2 py-1 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="user">User</option>
<option value="admin">Admin</option>
</select>
) : (
<span
className={`px-2 py-1 rounded-2xl text-xs font-medium ${
row.original.role === 'admin'
? 'bg-danger-100 text-danger-800'
: 'bg-primary-100 text-primary-800'
}`}
>
{row.original.role.charAt(0).toUpperCase() +
row.original.role.slice(1)}
</span>
)}
</div>
);
},
},
{
accessorKey: 'created_at',
header: 'Created At',
cell: ({ row }) => (
<span className="text-gray-600">
{new Date(row.original.created_at).toLocaleDateString()}
</span>
),
},
{
id: 'actions',
header: 'Actions',
cell: ({ row }) => {
const isEditing = editingUserId === row.original.id;
return (
<div className="flex gap-2">
<button
onClick={() =>
handleUpdateRole(row.original.id, row.original.role)
}
className={`p-2 rounded-md transition-colors cursor-pointer ${
isEditing
? 'text-success-600 hover:bg-success-50'
: 'text-primary-600 hover:bg-primary-50'
}`}
title={isEditing ? 'Save Role' : 'Change Role'}
>
<EditOutlined />
</button>
{isEditing && (
<button
onClick={() => {
setEditingUserId(null);
setSelectedRole('');
}}
className="p-2 text-gray-600 hover:bg-gray-50 rounded-md transition-colors cursor-pointer"
title="Cancel"
>
</button>
)}
{!isEditing && (
<button
onClick={() =>
handleDeleteUser(row.original.id, row.original.name)
}
className="p-2 text-danger-600 hover:bg-danger-50 rounded-md transition-colors cursor-pointer"
title="Delete User"
>
<DeleteOutlined />
</button>
)}
</div>
);
},
},
];
if (loading) {
return (
<div className="p-6">
<div className="text-center py-12">
<div className="text-gray-600">Loading users...</div>
</div>
</div>
);
}
if (error) {
return (
<div className="p-6">
<div className="bg-red-50 border border-red-200 rounded-lg p-4 text-red-800">
{error}
</div>
</div>
);
}
return (
<div className="p-6">
<div className="mb-6">
<h1 className="text-2xl font-bold text-gray-900">User Management</h1>
<p className="text-gray-600 mt-1">Manage users and their roles</p>
</div>
<DataTable data={users} columns={columns} pageSize={10} />
</div>
);
}
-1
View File
@@ -1 +0,0 @@
/* Your styles goes here. */
-26
View File
@@ -1,26 +0,0 @@
import { render } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import App from './app';
describe('App', () => {
it('should render successfully', () => {
const { baseElement } = render(
<BrowserRouter>
<App />
</BrowserRouter>
);
expect(baseElement).toBeTruthy();
});
it('should have a greeting as the title', () => {
const { getAllByText } = render(
<BrowserRouter>
<App />
</BrowserRouter>
);
expect(
getAllByText(new RegExp('Welcome qrcampaign', 'gi')).length > 0
).toBeTruthy();
});
});
@@ -0,0 +1,183 @@
import { FC, ReactElement, useEffect, useState, useRef } from 'react';
import { useNavigate } from 'react-router';
import { useGitHubCallback } from '@imphnen-frontend-service/service';
import { toast } from 'sonner';
const CallbackPage: FC = (): ReactElement => {
const navigate = useNavigate();
const { mutateAsync: exchangeGitHubCode } = useGitHubCallback();
const [isProcessing, setIsProcessing] = useState(true);
const [error, setError] = useState<string | null>(null);
const hasRunRef = useRef(false);
useEffect(() => {
const handleCallback = async () => {
if (hasRunRef.current) {
return;
}
hasRunRef.current = true;
try {
// Check URL hash for Supabase email confirmation callback
const hashParams = new URLSearchParams(
globalThis.location.hash.substring(1)
);
const urlParams = new URLSearchParams(globalThis.location.search);
const type = hashParams.get('type') || urlParams.get('type');
const accessToken =
hashParams.get('access_token') || urlParams.get('access_token');
// Debug: log what we received
console.log('[Callback] Params:', {
type,
accessToken: !!accessToken,
hash: globalThis.location.hash,
search: globalThis.location.search,
});
// Handle Supabase email callbacks (has access_token in hash or query)
// This includes: signup confirmation, email confirmation, password recovery
if (accessToken) {
setIsProcessing(false);
// Password recovery - type is 'recovery' or we have access_token from reset email
if (type === 'recovery' || type === 'magiclink') {
toast.success('Email verified! Please set your new password.');
navigate('/auth/reset-password?access_token=' + accessToken);
return;
}
// Signup/Email confirmation
if (type === 'signup' || type === 'email_confirmation') {
toast.success(
'Email verified successfully! Please log in to continue.'
);
navigate('/auth/login');
return;
}
// If we have access_token but unknown type, assume it's password recovery
// (Supabase sometimes sends without explicit type)
toast.success('Email verified! Please set your new password.');
navigate('/auth/reset-password?access_token=' + accessToken);
return;
}
// Get the code from URL query params (GitHub OAuth)
const code = urlParams.get('code');
if (!code) {
throw new Error('No authorization code received');
}
// Exchange the code for tokens using backend API (GitHub OAuth)
const result = await exchangeGitHubCode({ code });
toast.success('Login successful!');
setIsProcessing(false);
// Check if user has completed onboarding (has location)
if (result.user.location) {
globalThis.location.replace('/dashboard');
} else {
globalThis.location.replace('/onboarding/user');
}
} catch (err) {
console.error('[Callback] Error:', err);
setError((err as Error).message);
setIsProcessing(false);
toast.error('An error occurred during login');
setTimeout(() => {
navigate('/auth/login');
}, 3000);
}
};
handleCallback();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
if (error) {
// Check if error is related to private email
const isPrivateEmailError =
error.toLowerCase().includes('failed to create user') ||
error.toLowerCase().includes('email') ||
error.toLowerCase().includes('user record');
return (
<div className="flex justify-center items-center min-h-screen bg-gray-50 px-4">
<div className="bg-white w-full max-w-2xl p-8 rounded-2xl shadow-lg border border-red-200">
<div className="text-center mb-6">
<div className="text-red-500 text-5xl mb-4"></div>
<h2 className="text-2xl font-bold text-gray-900 mb-2">
GitHub Login Failed
</h2>
<p className="text-red-600 mb-4 whitespace-pre-line">{error}</p>
</div>
{isPrivateEmailError && (
<div className="bg-amber-50 border border-amber-200 rounded-lg p-4 mb-6">
<h3 className="font-semibold text-amber-800 mb-2">
Is your GitHub email set to private?
</h3>
<p className="text-amber-700 text-sm mb-3">
GitHub login requires a public email address. Please follow
these steps:
</p>
<ol className="text-amber-700 text-sm list-decimal list-inside space-y-1 mb-3">
<li>
Go to{' '}
<a
href="https://github.com/settings/emails"
target="_blank"
rel="noopener noreferrer"
className="underline hover:text-amber-900"
>
GitHub Email Settings
</a>
</li>
<li>Uncheck "Keep my email addresses private"</li>
<li>
Or go to{' '}
<a
href="https://github.com/settings/profile"
target="_blank"
rel="noopener noreferrer"
className="underline hover:text-amber-900"
>
Profile Settings
</a>{' '}
and set a public email
</li>
<li>Try signing in with GitHub again</li>
</ol>
<p className="text-amber-600 text-xs">
Alternatively, you can sign up using email and password instead.
</p>
</div>
)}
<p className="text-gray-600 text-sm mt-6 text-center">
Redirecting to login page in 3 seconds...
</p>
</div>
</div>
);
}
return (
<div className="flex justify-center items-center min-h-screen bg-gray-50">
<div className="text-center">
<div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mb-4"></div>
<h2 className="text-xl font-semibold text-gray-900 mb-2">
Completing login...
</h2>
<p className="text-gray-600">Please wait</p>
</div>
</div>
);
};
export default CallbackPage;
@@ -0,0 +1,125 @@
import { useState } from 'react';
import { useForgotPassword } from '@imphnen-frontend-service/service';
import { Link, useNavigate } from 'react-router';
import { toast } from 'sonner';
import { Icon } from '@iconify/react';
export default function ForgotPasswordPage() {
const [email, setEmail] = useState('');
const [emailSent, setEmailSent] = useState(false);
const navigate = useNavigate();
const forgotPasswordMutation = useForgotPassword();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!email) {
toast.error('Please enter your email');
return;
}
try {
await forgotPasswordMutation.mutateAsync({ email });
setEmailSent(true);
toast.success('Password reset email sent! Check your inbox.');
} catch (err) {
toast.error((err as Error).message || 'Failed to send reset email');
}
};
if (emailSent) {
return (
<div className="flex justify-center items-center min-h-screen bg-gray-50 p-4">
<div className="bg-white w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200 text-center">
<div className="mb-6">
<div className="mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4">
<span className="text-3xl"></span>
</div>
<h2 className="text-3xl font-bold text-gray-900 mb-2">
Check Your Email
</h2>
<p className="text-gray-600">
We've sent a password reset link to <strong>{email}</strong>
</p>
</div>
<div className="space-y-4">
<p className="text-sm text-gray-600">
Click the link in the email to reset your password. The link will
expire in 1 hour.
</p>
<Link to="/auth/login">
<button className="w-full py-3 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 transition-colors">
Back to Login
</button>
</Link>
<button
onClick={() => setEmailSent(false)}
className="w-full py-3 text-gray-600 hover:text-gray-900 transition-colors"
>
Send another email
</button>
</div>
</div>
</div>
);
}
return (
<div className="flex justify-center items-center min-h-screen bg-gray-50 p-4">
<div className="bg-white w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200">
<div className="flex items-center justify-between mb-6">
<button
onClick={() => navigate('/auth/login')}
className="cursor-pointer text-primary-500 hover:text-primary-600 text-base font-sans flex items-center"
>
<Icon icon="ic:baseline-chevron-left" width="24" height="24" />
Back to Login
</button>
</div>
<div className="text-center mb-8">
<h2 className="text-3xl font-bold text-gray-900 mb-2">
Forgot Password?
</h2>
<p className="text-gray-600">
No worries, we'll send you reset instructions
</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label
htmlFor="email"
className="block text-sm font-medium text-gray-700 mb-1"
>
Email Address
</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="your@email.com"
disabled={forgotPasswordMutation.isPending}
className="bg-white text-gray-900 w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
required
/>
</div>
<button
type="submit"
disabled={forgotPasswordMutation.isPending}
className="w-full py-3 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
>
{forgotPasswordMutation.isPending
? 'Sending...'
: 'Send Reset Link'}
</button>
</form>
</div>
</div>
);
}
+234
View File
@@ -0,0 +1,234 @@
import { useState, useEffect } from 'react';
import { GithubOutlined } from '@ant-design/icons';
import { useNavigate, Link } from 'react-router';
import { toast } from 'sonner';
import { Icon } from '@iconify/react';
import { useAuthStore } from '../../features/auth/store/auth.store';
export default function LoginPage() {
const navigate = useNavigate();
const login = useAuthStore((state) => state.login);
const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
const [isGithubLoading, setIsGithubLoading] = useState(false);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState<string | null>(null);
const [showPassword, setShowPassword] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
useEffect(() => {
if (isAuthenticated) {
navigate('/');
}
}, [isAuthenticated, navigate]);
// Check for password reset tokens in URL and redirect to reset-password page
useEffect(() => {
const hashParams = new URLSearchParams(
globalThis.location.hash.substring(1)
);
const urlParams = new URLSearchParams(globalThis.location.search);
const accessToken =
hashParams.get('access_token') || urlParams.get('access_token');
const type = hashParams.get('type') || urlParams.get('type');
// If we have an access_token, this is likely a password reset redirect that landed on the wrong page
if (accessToken) {
console.log(
'[Login] Detected access_token, redirecting to reset-password page'
);
// Check if it's a password recovery
if (type === 'recovery' || type === 'magiclink' || !type) {
toast.info('Redirecting to password reset...');
navigate('/auth/reset-password?access_token=' + accessToken);
}
}
}, [navigate]);
const handleEmailLogin = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
if (!email || !password) {
setError('Please enter both email and password');
return;
}
setIsSubmitting(true);
try {
const success = await login(email, password);
if (success) {
toast.success('Login successful!');
navigate('/');
} else {
setError('Login failed. Please check your credentials.');
}
} catch (err) {
console.error('[Login] Email login failed:', err);
setError('Login failed. Please try again.');
} finally {
setIsSubmitting(false);
}
};
const handleGithubLogin = async () => {
// TODO: Implement GitHub login with new auth service if needed
toast.info('GitHub login coming soon');
};
return (
<div className="flex justify-center items-center min-h-screen bg-gray-50 p-4">
<div className="bg-white w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200">
{/* <div className="flex items-center justify-between mb-6">
<button
onClick={() => navigate('/')}
className="cursor-pointer text-primary-500 hover:text-primary-600 text-base font-sans flex items-center"
>
<Icon icon="ic:baseline-chevron-left" width="24" height="24" />
Back to Homepage
</button>
</div> */}
<div className="text-center mb-8">
<h2 className="text-3xl font-bold text-gray-900 mb-2">
Welcome Back
</h2>
<p className="text-gray-600">Sign in to continue to IMPHNEN</p>
</div>
{error && (
<div className="mb-6 p-3 bg-red-50 border border-red-200 rounded-lg">
<p className="text-red-600 text-sm">{error}</p>
</div>
)}
{/* Traditional Login Form */}
<form onSubmit={handleEmailLogin} className="space-y-4 mb-6">
<div>
<label
htmlFor="email"
className="block text-sm font-medium text-gray-700 mb-1"
>
Email
</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="yourname@example.com"
disabled={isSubmitting}
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white text-gray-900 placeholder:text-gray-400 disabled:bg-gray-100 disabled:cursor-not-allowed"
required
/>
</div>
<div>
<div className="flex items-center justify-between mb-1">
<label
htmlFor="password"
className="block text-sm font-medium text-gray-700"
>
Password
</label>
<Link
to="/auth/forgot-password"
className="text-sm text-primary-600 hover:text-primary-700 font-medium"
>
Forgot password?
</Link>
</div>
<div className="relative">
<input
id="password"
type={showPassword ? 'text' : 'password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="••••••••"
disabled={isSubmitting}
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white text-gray-900 placeholder:text-gray-400 disabled:bg-gray-100 disabled:cursor-not-allowed pr-10"
required
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
>
<Icon
icon={showPassword ? 'mdi:eye-off' : 'mdi:eye'}
className="text-xl"
/>
</button>
</div>
</div>
<button
type="submit"
disabled={isSubmitting}
className="w-full py-3 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors cursor-pointer"
>
{isSubmitting ? 'Signing in...' : 'Sign in'}
</button>
</form>
<div className="relative my-6">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-gray-300"></div>
</div>
<div className="relative flex justify-center text-sm">
<span className="px-2 bg-white text-gray-500">
Or continue with
</span>
</div>
</div>
<button
onClick={handleGithubLogin}
disabled={isGithubLoading}
type="button"
className="w-full py-3 flex items-center justify-center gap-2 bg-gray-100 border border-gray-300 rounded-lg font-semibold text-gray-900 hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-400 focus:ring-offset-2 disabled:bg-gray-100 disabled:cursor-not-allowed transition-colors cursor-pointer"
>
<GithubOutlined className="text-xl" />
<span>
{isGithubLoading ? 'Connecting...' : 'Sign in with GitHub'}
</span>
</button>
<p className="mt-3 text-xs text-center text-gray-500">
Make sure your GitHub email is{' '}
<a
href="https://github.com/settings/emails"
target="_blank"
rel="noopener noreferrer"
className="text-primary-600 hover:underline"
>
set to public
</a>{' '}
for GitHub sign in to work.
</p>
<div className="mt-6 text-center">
<p className="text-gray-600 text-sm">
Don't have an account?{' '}
<Link
to="/auth/signup"
className="text-primary-600 hover:text-primary-700 font-semibold"
>
Sign up
</Link>
</p>
</div>
<div className="mt-6 text-center">
<p className="text-gray-500 text-xs">
By signing in, you agree to our Terms of Service and Privacy Policy
</p>
</div>
</div>
</div>
);
}
@@ -0,0 +1,171 @@
import { useState, useEffect } from 'react';
import {
useResetPassword,
useAuthStore,
} from '@imphnen-frontend-service/service';
import { useNavigate } from 'react-router';
import { toast } from 'sonner';
import { Icon } from '@iconify/react';
export default function ResetPasswordPage() {
const navigate = useNavigate();
const { clearSession } = useAuthStore();
const resetPasswordMutation = useResetPassword();
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [accessToken, setAccessToken] = useState<string | null>(null);
const [showPassword, setShowPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
useEffect(() => {
// Get the access_token from URL hash (Supabase sends it as hash fragment)
// or from query params (when redirected from callback page)
const hashParams = new URLSearchParams(
globalThis.location.hash.substring(1)
);
const queryParams = new URLSearchParams(globalThis.location.search);
const token =
hashParams.get('access_token') || queryParams.get('access_token');
if (token) {
setAccessToken(token);
} else {
toast.error('Invalid or expired reset link');
setTimeout(() => navigate('/auth/forgot-password'), 2000);
}
}, [navigate]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (password !== confirmPassword) {
toast.error('Passwords do not match');
return;
}
if (password.length < 6) {
toast.error('Password must be at least 6 characters');
return;
}
if (!accessToken) {
toast.error('Invalid reset token');
return;
}
try {
await resetPasswordMutation.mutateAsync({
access_token: accessToken,
new_password: password,
});
toast.success('Password updated successfully!');
// Clear session and redirect to login
clearSession();
navigate('/auth/login');
} catch (err) {
toast.error((err as Error).message || 'Failed to reset password');
}
};
if (!accessToken) {
return (
<div className="flex justify-center items-center min-h-screen bg-gray-50">
<div className="text-center">
<div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mb-4"></div>
<p className="text-gray-600">Verifying reset link...</p>
</div>
</div>
);
}
return (
<div className="flex justify-center items-center min-h-screen bg-gray-50 p-4">
<div className="bg-white w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200">
<div className="text-center mb-8">
<h2 className="text-3xl font-bold text-gray-900 mb-2">
Set New Password
</h2>
<p className="text-gray-600">Enter your new password below</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label
htmlFor="password"
className="block text-sm font-medium text-gray-700 mb-1"
>
New Password
</label>
<div className="relative">
<input
id="password"
type={showPassword ? 'text' : 'password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="••••••••"
disabled={resetPasswordMutation.isPending}
className="w-full px-4 py-2.5 pr-12 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed bg-white text-gray-900"
required
minLength={6}
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
>
<Icon
icon={showPassword ? 'mdi:eye-off' : 'mdi:eye'}
className="text-xl"
/>
</button>
</div>
</div>
<div>
<label
htmlFor="confirmPassword"
className="block text-sm font-medium text-gray-700 mb-1"
>
Confirm New Password
</label>
<div className="relative">
<input
id="confirmPassword"
type={showConfirmPassword ? 'text' : 'password'}
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
placeholder="••••••••"
disabled={resetPasswordMutation.isPending}
className="w-full px-4 py-2.5 pr-12 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed bg-white text-gray-900"
required
minLength={6}
/>
<button
type="button"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
>
<Icon
icon={showConfirmPassword ? 'mdi:eye-off' : 'mdi:eye'}
className="text-xl"
/>
</button>
</div>
</div>
<button
type="submit"
disabled={resetPasswordMutation.isPending}
className="w-full py-3 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
>
{resetPasswordMutation.isPending
? 'Updating...'
: 'Update Password'}
</button>
</form>
</div>
</div>
);
}
@@ -0,0 +1,305 @@
import { useState } from 'react';
import { useGitHubAuth } from '@imphnen-frontend-service/service';
import { GithubOutlined } from '@ant-design/icons';
import { useNavigate, Link } from 'react-router';
import { toast } from 'sonner';
import { Icon } from '@iconify/react';
import { useAuthStore } from '../../features/auth/store/auth.store';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
const signupSchema = z
.object({
fullname: z
.string()
.min(1, 'Full name is required')
.min(2, 'Full name must be at least 2 characters'),
email: z
.string()
.min(1, 'Email is required')
.email('Please enter a valid email address'),
password: z
.string()
.min(1, 'Password is required')
.min(6, 'Password must be at least 6 characters'),
confirmPassword: z.string().min(1, 'Please confirm your password'),
})
.refine((data) => data.password === data.confirmPassword, {
message: 'Passwords do not match',
path: ['confirmPassword'],
});
type SignupFormData = z.infer<typeof signupSchema>;
export default function SignupPage() {
const navigate = useNavigate();
const registerUser = useAuthStore((state) => state.register);
const { signInWithGitHub } = useGitHubAuth();
const [isGithubLoading, setIsGithubLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [showPassword, setShowPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const {
register,
handleSubmit,
formState: { errors, isValid },
} = useForm<SignupFormData>({
resolver: zodResolver(signupSchema),
mode: 'onChange',
});
const onSubmit = async (data: SignupFormData) => {
setError(null);
setIsSubmitting(true);
try {
await registerUser(data.fullname, data.email, data.password);
toast.success('Registration successful! Redirecting...');
navigate('/');
} catch (err: any) {
console.error('[Signup] Email signup failed:', err);
// Construct a user-friendly error message
const errorMessage =
err.response?.data?.message || err.message || 'Signup failed';
setError(errorMessage);
} finally {
setIsSubmitting(false);
}
};
const handleGithubLogin = async () => {
try {
setIsGithubLoading(true);
const result = await signInWithGitHub();
if (result?.url) {
globalThis.location.href = result.url;
} else {
setIsGithubLoading(false);
setError('Failed to get GitHub OAuth URL');
}
} catch (err) {
console.error('[Signup] GitHub login failed:', err);
setError((err as Error).message || 'GitHub login failed');
setIsGithubLoading(false);
}
};
const inputBaseClass =
'w-full px-4 py-2.5 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white text-gray-900 placeholder:text-gray-400 disabled:bg-gray-100 disabled:cursor-not-allowed';
const inputErrorClass = 'border-red-500';
const inputNormalClass = 'border-gray-300';
return (
<div className="flex justify-center items-center min-h-screen bg-gray-50 p-4">
<div className="bg-white w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200">
<div className="flex items-center justify-between mb-6">
<button
onClick={() => navigate('/')}
className="cursor-pointer text-primary-500 hover:text-primary-600 text-base font-sans flex items-center"
>
<Icon icon="ic:baseline-chevron-left" width="24" height="24" />
Back to Homepage
</button>
</div>
<div className="text-center mb-8">
<h2 className="text-3xl font-bold text-gray-900 mb-2">
Create Account
</h2>
<p className="text-gray-600">Join IMPHNEN community</p>
</div>
{error && (
<div className="mb-6 p-3 bg-red-50 border border-red-200 rounded-lg">
<p className="text-red-600 text-sm">{error}</p>
</div>
)}
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<label
htmlFor="fullname"
className="block text-sm font-medium text-gray-700 mb-1"
>
Full Name
</label>
<input
id="fullname"
type="text"
{...register('fullname')}
placeholder="John Doe"
disabled={isSubmitting}
className={`${inputBaseClass} ${
errors.fullname ? inputErrorClass : inputNormalClass
}`}
/>
{errors.fullname && (
<p className="mt-1 text-sm text-red-500">
{errors.fullname.message}
</p>
)}
</div>
<div>
<label
htmlFor="email"
className="block text-sm font-medium text-gray-700 mb-1"
>
Email
</label>
<input
id="email"
type="email"
{...register('email')}
placeholder="yourname@example.com"
disabled={isSubmitting}
className={`${inputBaseClass} ${
errors.email ? inputErrorClass : inputNormalClass
}`}
/>
{errors.email && (
<p className="mt-1 text-sm text-red-500">
{errors.email.message}
</p>
)}
</div>
<div>
<label
htmlFor="password"
className="block text-sm font-medium text-gray-700 mb-1"
>
Password
</label>
<div className="relative">
<input
id="password"
type={showPassword ? 'text' : 'password'}
{...register('password')}
placeholder="••••••••"
disabled={isSubmitting}
className={`${inputBaseClass} pr-12 ${
errors.password ? inputErrorClass : inputNormalClass
}`}
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
>
<Icon
icon={showPassword ? 'mdi:eye-off' : 'mdi:eye'}
className="text-xl"
/>
</button>
</div>
{errors.password && (
<p className="mt-1 text-sm text-red-500">
{errors.password.message}
</p>
)}
</div>
<div>
<label
htmlFor="confirmPassword"
className="block text-sm font-medium text-gray-700 mb-1"
>
Confirm Password
</label>
<div className="relative">
<input
id="confirmPassword"
type={showConfirmPassword ? 'text' : 'password'}
{...register('confirmPassword')}
placeholder="••••••••"
disabled={isSubmitting}
className={`${inputBaseClass} pr-12 ${
errors.confirmPassword ? inputErrorClass : inputNormalClass
}`}
/>
<button
type="button"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
>
<Icon
icon={showConfirmPassword ? 'mdi:eye-off' : 'mdi:eye'}
className="text-xl"
/>
</button>
</div>
{errors.confirmPassword && (
<p className="mt-1 text-sm text-red-500">
{errors.confirmPassword.message}
</p>
)}
</div>
<button
type="submit"
disabled={!isValid || isSubmitting}
className="w-full py-3 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors cursor-pointer"
>
{isSubmitting ? 'Creating account...' : 'Create Account'}
</button>
</form>
<div className="my-6 flex items-center">
<div className="flex-1 border-t border-gray-300"></div>
<span className="px-4 text-sm text-gray-500">OR</span>
<div className="flex-1 border-t border-gray-300"></div>
</div>
<button
onClick={handleGithubLogin}
disabled={isGithubLoading}
type="button"
className="w-full py-3 flex items-center justify-center gap-2 bg-gray-100 border border-gray-300 rounded-lg font-semibold text-gray-900 hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-400 focus:ring-offset-2 disabled:bg-gray-100 disabled:cursor-not-allowed transition-colors cursor-pointer"
>
<GithubOutlined className="text-xl" />
<span>
{isGithubLoading ? 'Connecting...' : 'Sign up with GitHub'}
</span>
</button>
<p className="mt-3 text-xs text-center text-gray-500">
Make sure your GitHub email is{' '}
<a
href="https://github.com/settings/emails"
target="_blank"
rel="noopener noreferrer"
className="text-primary-600 hover:underline"
>
set to public
</a>{' '}
for GitHub sign up to work.
</p>
<div className="mt-6 text-center">
<p className="text-gray-600 text-sm">
Already have an account?{' '}
<Link
to="/auth/login"
className="text-primary-600 hover:text-primary-700 font-semibold"
>
Sign in
</Link>
</p>
</div>
<div className="mt-6 text-center">
<p className="text-gray-500 text-xs">
By signing up, you agree to our Terms of Service and Privacy Policy
</p>
</div>
</div>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { useRouteError, isRouteErrorResponse } from 'react-router-dom';
export default function ErrorPage() {
const error = useRouteError();
let errorMessage: string;
if (isRouteErrorResponse(error)) {
errorMessage = error.statusText;
} else if (error instanceof Error) {
errorMessage = error.message;
} else if (typeof error === 'string') {
errorMessage = error;
} else {
console.error(error);
errorMessage = 'Unknown error';
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="text-center">
<h1 className="text-6xl font-bold text-red-600 mb-4">Oops!</h1>
<p className="text-xl text-gray-700 mb-2">
Sorry, an unexpected error has occurred.
</p>
<p className="text-gray-500 italic">{errorMessage}</p>
</div>
</div>
);
}
@@ -0,0 +1,56 @@
import { api } from '../../auth/api/auth.service';
// Types
export interface Campaign {
id: string;
name: string;
url: string;
is_active: boolean;
created_at: string;
updated_at: string;
}
export interface CreateCampaignRequest {
name: string;
url: string;
}
interface CampaignsResponse {
success: boolean;
message: string;
data: Campaign[];
}
interface CampaignResponse {
success: boolean;
message: string;
data: Campaign;
}
interface DeleteResponse {
success: boolean;
message: string;
}
export const campaignService = {
getCampaigns: async (): Promise<Campaign[]> => {
const response = await api.get<CampaignsResponse>('/campaigns');
return response.data.data;
},
createCampaign: async (data: CreateCampaignRequest): Promise<Campaign> => {
const response = await api.post<CampaignResponse>('/campaigns', data);
return response.data.data;
},
activateCampaign: async (campaignId: string): Promise<Campaign> => {
const response = await api.put<CampaignResponse>(
`/campaigns/${campaignId}/activate`
);
return response.data.data;
},
deleteCampaign: async (campaignId: string): Promise<void> => {
await api.delete<DeleteResponse>(`/campaigns/${campaignId}`);
},
};
@@ -0,0 +1,53 @@
import { api } from '../../auth/api/auth.service';
// Types
export interface User {
id: string;
email: string;
name: string;
role: string;
created_at: string;
updated_at: string;
}
export interface UpdateUserRoleRequest {
role: string;
}
interface UsersResponse {
success: boolean;
message: string;
data: User[];
}
interface UserResponse {
success: boolean;
message: string;
data: User;
}
interface DeleteResponse {
success: boolean;
message: string;
}
export const userService = {
getUsers: async (): Promise<User[]> => {
const response = await api.get<UsersResponse>('/users');
return response.data.data;
},
updateUserRole: async (
userId: string,
role: string
): Promise<User> => {
const response = await api.put<UserResponse>(`/users/${userId}/role`, {
role,
});
return response.data.data;
},
deleteUser: async (userId: string): Promise<void> => {
await api.delete<DeleteResponse>(`/users/${userId}`);
},
};
@@ -0,0 +1,27 @@
import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '../../auth/store/auth.store';
interface RequireAdminProps {
children: JSX.Element;
}
export const RequireAdmin = ({ children }: RequireAdminProps) => {
const user = useAuthStore((state) => state.user);
const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
const location = useLocation();
if (!isAuthenticated) {
return <Navigate to="/login" state={{ from: location }} replace />;
}
// Check if user has admin role
// user.role is now an object { id, name, permissions }
const userRole = user?.role?.name;
if (userRole !== 'Admin' && userRole !== 'Super Admin') {
// Redirect non-admins to home
return <Navigate to="/" replace />;
}
return children;
};
@@ -0,0 +1,64 @@
import { Outlet, Link, useLocation } from 'react-router-dom';
import { useAuthStore } from '../../auth/store/auth.store';
export const AdminDashboard = () => {
const logout = useAuthStore((state) => state.logout);
const location = useLocation();
const isActive = (path: string) => location.pathname.startsWith(path);
return (
<div className="min-h-screen bg-slate-100 flex">
{/* Sidebar */}
<aside className="w-64 bg-white border-r border-slate-200 flex flex-col">
<div className="p-6 border-b border-slate-200">
<h1 className="text-xl font-bold text-slate-800">Admin Panel</h1>
<p className="text-xs text-slate-500 mt-1">QR Campaign Manager</p>
</div>
<nav className="flex-1 p-4 space-y-1">
<Link
to="/admin/campaigns"
className={`block px-4 py-2 rounded-md transition-colors ${
isActive('/admin/campaigns')
? 'bg-blue-50 text-blue-700'
: 'text-slate-600 hover:bg-slate-50'
}`}
>
Campaigns
</Link>
<Link
to="/admin/users"
className={`block px-4 py-2 rounded-md transition-colors ${
isActive('/admin/users')
? 'bg-blue-50 text-blue-700'
: 'text-slate-600 hover:bg-slate-50'
}`}
>
Users
</Link>
</nav>
<div className="p-4 border-t border-slate-200">
<Link
to="/"
className="block px-4 py-2 text-sm text-slate-600 hover:text-slate-900 mb-2"
>
&larr; Back to App
</Link>
<button
onClick={logout}
className="w-full px-4 py-2 text-sm text-red-600 hover:bg-red-50 rounded-md transition-colors text-left"
>
Logout
</button>
</div>
</aside>
{/* Main Content */}
<main className="flex-1 p-8 overflow-auto">
<Outlet />
</main>
</div>
);
};
@@ -0,0 +1,237 @@
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
interface Campaign {
id: string;
name: string;
url: string;
image_url?: string; // QR code image URL if we want to show it
is_active: boolean;
created_at: string;
}
interface CreateCampaignInputs {
name: string;
url: string;
}
export const CampaignManagement = () => {
const queryClient = useQueryClient();
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm<CreateCampaignInputs>();
// Fetch Campaigns
const {
data: campaigns,
isLoading,
isError,
} = useQuery({
queryKey: ['campaigns'],
queryFn: async () => {
const res = await axios.get('http://localhost:8080/api/v1/campaigns');
return res.data.data as Campaign[];
},
});
// Create Campaign
const createMutation = useMutation({
mutationFn: async (data: CreateCampaignInputs) => {
await axios.post('http://localhost:8080/api/v1/campaigns', data);
},
onSuccess: () => {
toast.success('Campaign created successfully');
queryClient.invalidateQueries({ queryKey: ['campaigns'] });
setIsCreateModalOpen(false);
reset();
},
onError: (error: any) => {
toast.error(error.response?.data?.message || 'Failed to create campaign');
},
});
// Activate Campaign
const activateMutation = useMutation({
mutationFn: async (id: string) => {
await axios.put(`http://localhost:8080/api/v1/campaigns/${id}/activate`);
},
onSuccess: () => {
toast.success('Campaign activated');
queryClient.invalidateQueries({ queryKey: ['campaigns'] });
// Also invalidate active QR for the main app
queryClient.invalidateQueries({ queryKey: ['active-campaign-qr'] });
},
onError: () => toast.error('Failed to activate campaign'),
});
// Delete Campaign
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
await axios.delete(`http://localhost:8080/api/v1/campaigns/${id}`);
},
onSuccess: () => {
toast.success('Campaign deleted');
queryClient.invalidateQueries({ queryKey: ['campaigns'] });
},
onError: () => toast.error('Failed to delete campaign'),
});
const onCreateSubmit = (data: CreateCampaignInputs) => {
createMutation.mutate(data);
};
if (isLoading) return <div>Loading campaigns...</div>;
if (isError) return <div>Error loading campaigns.</div>;
return (
<div>
<div className="flex justify-between items-center mb-6">
<h2 className="text-2xl font-bold text-slate-800">Campaigns</h2>
<button
onClick={() => setIsCreateModalOpen(true)}
className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 transition-colors"
>
+ New Campaign
</button>
</div>
<div className="bg-white rounded-lg shadow overflow-hidden">
<table className="w-full text-left">
<thead className="bg-slate-50 text-slate-500 text-xs uppercase font-medium">
<tr>
<th className="px-6 py-3">Name</th>
<th className="px-6 py-3">URL</th>
<th className="px-6 py-3">Status</th>
<th className="px-6 py-3">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-200">
{campaigns?.map((campaign) => (
<tr key={campaign.id} className="hover:bg-slate-50">
<td className="px-6 py-4 font-medium text-slate-900">
{campaign.name}
</td>
<td className="px-6 py-4 text-slate-500 text-sm max-w-xs truncate">
{campaign.url}
</td>
<td className="px-6 py-4">
{campaign.is_active ? (
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-sm font-medium bg-green-100 text-green-800">
Active
</span>
) : (
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-800">
Inactive
</span>
)}
</td>
<td className="px-6 py-4 space-x-2">
{!campaign.is_active && (
<button
onClick={() => activateMutation.mutate(campaign.id)}
className="text-blue-600 hover:text-blue-800 text-sm font-medium"
>
Activate
</button>
)}
<button
onClick={() => {
if (
window.confirm(
'Are you sure you want to delete this campaign?'
)
) {
deleteMutation.mutate(campaign.id);
}
}}
className="text-red-600 hover:text-red-800 text-sm font-medium"
>
Delete
</button>
</td>
</tr>
))}
{campaigns?.length === 0 && (
<tr>
<td
colSpan={4}
className="px-6 py-8 text-center text-slate-500"
>
No campaigns found. Create one to get started.
</td>
</tr>
)}
</tbody>
</table>
</div>
{/* Basic Create Modal */}
{isCreateModalOpen && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
<div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
<h3 className="text-xl font-bold mb-4 text-slate-900">
Create New Campaign
</h3>
<form onSubmit={handleSubmit(onCreateSubmit)} className="space-y-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">
Campaign Name
</label>
<input
type="text"
{...register('name', { required: 'Name is required' })}
className="w-full px-3 py-2 border border-slate-300 rounded-md bg-white"
placeholder="e.g. Summer Sale 2026"
/>
{errors.name && (
<p className="text-red-500 text-sm mt-1">
{errors.name.message}
</p>
)}
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">
Target URL
</label>
<input
type="url"
{...register('url', { required: 'URL is required' })}
className="w-full px-3 py-2 border border-slate-300 rounded-md bg-white"
placeholder="https://example.com/promo"
/>
{errors.url && (
<p className="text-red-500 text-sm mt-1">
{errors.url.message}
</p>
)}
</div>
<div className="flex justify-end gap-2 mt-6">
<button
type="button"
onClick={() => setIsCreateModalOpen(false)}
className="px-4 py-2 text-slate-700 hover:bg-slate-100 rounded-md"
>
Cancel
</button>
<button
type="submit"
disabled={createMutation.isPending}
className="px-4 py-2 bg-blue-600 text-white hover:bg-blue-700 rounded-md disabled:opacity-50"
>
{createMutation.isPending ? 'Creating...' : 'Create Campaign'}
</button>
</div>
</form>
</div>
</div>
)}
</div>
);
};
@@ -0,0 +1,121 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';
import { toast } from 'sonner';
interface User {
id: string;
name: string;
email: string;
role: string;
created_at: string;
}
export const UserManagement = () => {
const queryClient = useQueryClient();
// Fetch Users
const {
data: users,
isLoading,
isError,
} = useQuery({
queryKey: ['users'],
queryFn: async () => {
const res = await axios.get('http://localhost:8080/api/v1/users');
return res.data.data as User[];
},
});
// Update Role
const updateRoleMutation = useMutation({
mutationFn: async ({ id, role }: { id: string; role: string }) => {
await axios.put(`http://localhost:8080/api/v1/users/${id}/role`, {
role,
});
},
onSuccess: () => {
toast.success('User role updated');
queryClient.invalidateQueries({ queryKey: ['users'] });
},
onError: () => toast.error('Failed to update user role'),
});
// Delete User
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
await axios.delete(`http://localhost:8080/api/v1/users/${id}`);
},
onSuccess: () => {
toast.success('User deleted');
queryClient.invalidateQueries({ queryKey: ['users'] });
},
onError: () => toast.error('Failed to delete user'),
});
if (isLoading) return <div>Loading users...</div>;
if (isError) return <div>Error loading users.</div>;
return (
<div>
<h2 className="text-2xl font-bold text-slate-800 mb-6">Users</h2>
<div className="bg-white rounded-lg shadow overflow-hidden">
<table className="w-full text-left">
<thead className="bg-slate-50 text-slate-500 text-xs uppercase font-medium">
<tr>
<th className="px-6 py-3">Name</th>
<th className="px-6 py-3">Email</th>
<th className="px-6 py-3">Role</th>
<th className="px-6 py-3">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-200">
{users?.map((user) => (
<tr key={user.id} className="hover:bg-slate-50">
<td className="px-6 py-4 font-medium text-slate-900">
{user.name}
</td>
<td className="px-6 py-4 text-slate-500 text-sm">
{user.email}
</td>
<td className="px-6 py-4">
<select
value={user.role}
onChange={(e) =>
updateRoleMutation.mutate({
id: user.id,
role: e.target.value,
})
}
disabled={user.email === 'admin@demo.com'} // Prevent changing main admin role for safety in demo
className="bg-transparent border border-slate-300 rounded text-sm px-2 py-1 text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="user">User</option>
<option value="admin">Admin</option>
</select>
</td>
<td className="px-6 py-4">
<button
onClick={() => {
if (
window.confirm(
'Are you sure you want to delete this user?'
)
) {
deleteMutation.mutate(user.id);
}
}}
disabled={user.email === 'admin@demo.com'}
className="text-red-600 hover:text-red-800 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed"
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
};
@@ -0,0 +1,129 @@
import axios from 'axios';
// Define the base URL for the API
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8080/api/v1';
// Create a configured axios instance
export const api = axios.create({
baseURL: API_URL,
headers: {
'Content-Type': 'application/json',
},
});
// Add interceptor to add token to requests
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Types
export interface LoginRequest {
email: string;
password: string;
}
export interface RegisterRequest {
name: string;
email: string;
password: string;
}
// Backend user response
interface BackendUser {
id: string;
email: string;
name: string;
role: string;
provider: string;
created_at: string;
updated_at: string;
}
// Frontend user type
export interface User {
id: string;
email: string;
fullname: string;
role?: {
id: string;
name: string;
permissions: string[];
};
}
// Backend auth response
interface BackendAuthResponse {
success: boolean;
message: string;
data: {
tokens: {
access_token: string;
refresh_token: string;
};
user: BackendUser;
};
}
export interface AuthResponse {
success: boolean;
message: string;
data: {
tokens: {
access_token: string;
refresh_token: string;
};
user: User;
};
}
// Helper to transform backend user to frontend user
const transformUser = (backendUser: BackendUser): User => {
return {
id: backendUser.id,
email: backendUser.email,
fullname: backendUser.name,
role: {
id: '',
name: backendUser.role === 'admin' ? 'Admin' : backendUser.role === 'user' ? 'User' : 'User',
permissions: [],
},
};
};
export const authService = {
login: async (data: LoginRequest): Promise<AuthResponse> => {
const response = await api.post<BackendAuthResponse>('/auth/login', data);
return {
success: response.data.success,
message: response.data.message,
data: {
tokens: response.data.data.tokens,
user: transformUser(response.data.data.user),
},
};
},
register: async (data: RegisterRequest): Promise<AuthResponse> => {
const response = await api.post<BackendAuthResponse>('/auth/register', data);
return {
success: response.data.success,
message: response.data.message,
data: {
tokens: response.data.data.tokens,
user: transformUser(response.data.data.user),
},
};
},
getProfile: async (): Promise<User> => {
const response = await api.get<User>('/users/me');
return response.data;
},
};
@@ -0,0 +1,21 @@
import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '../../../features/auth/store/auth.store';
interface RequireAuthProps {
children: JSX.Element;
}
export const RequireAuth = ({ children }: RequireAuthProps) => {
const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
const location = useLocation();
if (!isAuthenticated) {
// Redirect them to the /login page, but save the current location they were
// trying to go to when they were redirected. This allows us to send them
// along to that page after they login, which is a nicer user experience.
return <Navigate to="/login" state={{ from: location }} replace />;
}
return children;
};
@@ -0,0 +1,102 @@
import React, { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { useAuthStore } from '../store/auth.store';
import { useNavigate, useLocation } from 'react-router-dom';
// Reusing UI components logic or standard HTML for now to keep it simple and dependency-free if UI lib issues arise
// But user mentioned shared UI libs, let's try to use standard Tailwind first to ensure speed.
interface LoginFormInputs {
email: string;
pass: string;
}
export const LoginPage = () => {
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<LoginFormInputs>();
const login = useAuthStore((state) => state.login);
const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
const navigate = useNavigate();
const location = useLocation();
const from = location.state?.from?.pathname || '/';
useEffect(() => {
if (isAuthenticated) {
navigate(from, { replace: true });
}
}, [isAuthenticated, navigate, from]);
const onSubmit = async (data: LoginFormInputs) => {
const success = await login(data.email, data.pass);
if (success) {
// Get user from store to check role
const user = useAuthStore.getState().user;
const userRole = user?.role?.name;
// Redirect admin to admin dashboard
if (userRole === 'Admin' || userRole === 'Super Admin') {
navigate('/admin/campaigns', { replace: true });
} else {
navigate(from, { replace: true });
}
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-slate-50 p-4">
<div className="w-full max-w-md bg-white rounded-lg shadow-lg p-8">
<h1 className="text-2xl font-bold text-center mb-6 text-slate-800">
Login
</h1>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">
Email
</label>
<input
type="email"
{...register('email', { required: 'Email is required' })}
className="w-full px-3 py-2 border border-slate-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
{errors.email && (
<p className="text-red-500 text-sm mt-1">
{errors.email.message}
</p>
)}
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">
Password
</label>
<input
type="password"
{...register('pass', { required: 'Password is required' })}
className="w-full px-3 py-2 border border-slate-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
{errors.pass && (
<p className="text-red-500 text-sm mt-1">{errors.pass.message}</p>
)}
</div>
<button
type="submit"
disabled={isSubmitting}
className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-medium"
>
{isSubmitting ? 'Logging in...' : 'Login'}
</button>
</form>
<div className="mt-4 text-center text-sm text-slate-500">
<p>Demo credentials available in backend seeder.</p>
</div>
</div>
</div>
);
};
@@ -0,0 +1,84 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { authService, User } from '../api/auth.service';
interface AuthState {
user: User | null;
token: string | null;
isAuthenticated: boolean;
login: (email: string, pass: string) => Promise<boolean>;
register: (name: string, email: string, pass: string) => Promise<boolean>;
logout: () => void;
setUser: (user: User) => void;
}
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
user: null,
token: null,
isAuthenticated: false,
login: async (email, password) => {
try {
const response = await authService.login({ email, password });
const token = response.data.tokens.access_token;
const refreshToken = response.data.tokens.refresh_token;
localStorage.setItem('token', token);
localStorage.setItem('refreshToken', refreshToken);
set({
user: response.data.user,
token: token,
isAuthenticated: true
});
return true;
} catch (error) {
console.error('Login failed:', error);
return false;
}
},
register: async (name, email, password) => {
try {
const response = await authService.register({ name, email, password });
const token = response.data.tokens.access_token;
const refreshToken = response.data.tokens.refresh_token;
localStorage.setItem('token', token);
localStorage.setItem('refreshToken', refreshToken);
set({
user: response.data.user,
token: token,
isAuthenticated: true
});
return true;
} catch (error) {
console.error('Registration failed:', error);
throw error;
}
},
logout: () => {
localStorage.removeItem('token');
set({ user: null, token: null, isAuthenticated: false });
},
setUser: (user) => set({ user }),
}),
{
name: 'auth-storage', // name of the item in the storage (must be unique)
partialize: (state) => ({
user: state.user,
token: state.token,
isAuthenticated: state.isAuthenticated
}),
}
)
);
@@ -0,0 +1,17 @@
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
export const useActiveCampaignQR = () => {
return useQuery({
queryKey: ['active-campaign-qr'],
queryFn: async () => {
// Assuming backend is running on localhost:8080
// In production, this should be an env var or relative path if proxied
const response = await axios.get('http://localhost:8080/api/v1/campaigns/active/qr', {
responseType: 'blob',
});
return URL.createObjectURL(response.data);
},
staleTime: 1000 * 60 * 5, // 5 minutes
});
};
@@ -0,0 +1,99 @@
import React, { useCallback, useState } from 'react';
import { toast } from 'sonner';
interface DropzoneProps {
onImageDropped: (file: File) => void;
}
export const Dropzone: React.FC<DropzoneProps> = ({ onImageDropped }) => {
const [isDragging, setIsDragging] = useState(false);
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragging(true);
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragging(false);
}, []);
const handleDrop = useCallback(
(e: React.DragEvent) => {
e.preventDefault();
setIsDragging(false);
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
const file = files[0];
if (!file.type.startsWith('image/')) {
toast.error('Please upload an image file.');
return;
}
onImageDropped(file);
},
[onImageDropped]
);
const handleFileInput = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (files && files.length > 0) {
const file = files[0];
if (!file.type.startsWith('image/')) {
toast.error('Please upload an image file.');
return;
}
onImageDropped(file);
}
},
[onImageDropped]
);
return (
<div
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
className={`border-2 border-dashed rounded-lg p-12 text-center transition-colors cursor-pointer ${
isDragging
? 'border-blue-500 bg-blue-50'
: 'border-slate-300 hover:border-slate-400'
}`}
onClick={() => document.getElementById('file-upload')?.click()}
>
<input
id="file-upload"
type="file"
className="hidden"
accept="image/png, image/jpeg, image/jpg"
onChange={handleFileInput}
/>
<div className="space-y-2">
<div className="flex justify-center">
{/* Simple upload icon */}
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
className="w-12 h-12 text-slate-400"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5"
/>
</svg>
</div>
<p className="text-lg font-medium text-slate-700">
Drop your image here, or click to upload
</p>
<p className="text-sm text-slate-500">Supports JPG and PNG</p>
</div>
</div>
);
};
@@ -0,0 +1,188 @@
import React, { useState, useRef, useEffect, useCallback } from 'react';
import html2canvas from 'html2canvas';
import { toast } from 'sonner';
interface WatermarkEditorProps {
imageFile: File;
qrCodeUrl: string;
onReset: () => void;
}
export const WatermarkEditor: React.FC<WatermarkEditorProps> = ({
imageFile,
qrCodeUrl,
onReset,
}) => {
const [imageUrl, setImageUrl] = useState<string | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
const qrRef = useRef<HTMLDivElement>(null);
// State for QR code
const [position, setPosition] = useState({ x: 20, y: 20 });
const [size, setSize] = useState(100);
const [isDragging, setIsDragging] = useState(false);
const [isResizing, setIsResizing] = useState(false);
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
const [startResizePos, setStartResizePos] = useState({ x: 0, y: 0 });
const [startResizeSize, setStartResizeSize] = useState(100);
// Load image
useEffect(() => {
const url = URL.createObjectURL(imageFile);
setImageUrl(url);
return () => URL.revokeObjectURL(url);
}, [imageFile]);
// Drag handlers
const handleMouseDown = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(true);
setDragOffset({
x: e.clientX - position.x,
y: e.clientY - position.y,
});
};
const handleResizeMouseDown = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
setIsResizing(true);
setStartResizePos({ x: e.clientX, y: e.clientY });
setStartResizeSize(size);
};
const handleMouseMove = useCallback(
(e: MouseEvent) => {
if (isDragging) {
const newX = e.clientX - dragOffset.x;
const newY = e.clientY - dragOffset.y;
// Boundaries check (optional, but good UX)
if (containerRef.current) {
// const container = containerRef.current.getBoundingClientRect();
// Simple clamp? Or allow partial off-screen?
// Let's allow it to move freely within container
}
setPosition({ x: newX, y: newY });
}
if (isResizing) {
const deltaX = e.clientX - startResizePos.x;
const newSize = Math.max(50, startResizeSize + deltaX); // Min size 50px
setSize(newSize);
}
},
[isDragging, isResizing, dragOffset, startResizePos, startResizeSize]
);
const handleMouseUp = useCallback(() => {
setIsDragging(false);
setIsResizing(false);
}, []);
useEffect(() => {
if (isDragging || isResizing) {
window.addEventListener('mousemove', handleMouseMove);
window.addEventListener('mouseup', handleMouseUp);
} else {
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
}
return () => {
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
};
}, [isDragging, isResizing, handleMouseMove, handleMouseUp]);
const handleDownload = async () => {
if (!containerRef.current) return;
try {
const canvas = await html2canvas(containerRef.current, {
useCORS: true, // Important for QR if from external URL
backgroundColor: null,
});
const link = document.createElement('a');
link.download = `qr-campaign-${Date.now()}.png`;
link.href = canvas.toDataURL('image/png');
link.click();
toast.success('Image downloaded successfully!');
} catch (error) {
console.error('Download failed:', error);
toast.error('Failed to download image.');
}
};
if (!imageUrl) return <div>Loading image...</div>;
return (
<div className="flex flex-col items-center gap-4 w-full h-full">
<div className="flex gap-2 mb-4">
<button
onClick={onReset}
className="px-4 py-2 bg-slate-200 text-slate-700 rounded hover:bg-slate-300 transition-colors"
>
Change Image
</button>
<button
onClick={handleDownload}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors shadow-lg"
>
Download Image
</button>
</div>
<div className="border border-slate-200 shadow-xl rounded-lg overflow-hidden bg-slate-50 inline-block relative">
<div
ref={containerRef}
className="relative inline-block"
style={{ lineHeight: 0 }}
>
<img
src={imageUrl}
alt="Uploaded"
className="max-h-[70vh] w-auto h-auto object-contain select-none"
draggable={false}
/>
<div
ref={qrRef}
className="absolute cursor-move select-none group"
style={{
left: position.x,
top: position.y,
width: size,
height: size,
zIndex: 10,
}}
onMouseDown={handleMouseDown}
>
<img
src={qrCodeUrl}
alt="QR Code"
className="w-full h-full select-none pointer-events-none"
crossOrigin="anonymous" // Important for html2canvas
/>
{/* Outline on hover/interaction */}
<div className="absolute inset-0 border-2 border-transparent group-hover:border-blue-400 group-active:border-blue-500 pointer-events-none rounded-sm transition-colors" />
{/* Resize handle */}
<div
className="absolute bottom-0 right-0 w-4 h-4 bg-blue-500 rounded-full cursor-nwse-resize opacity-0 group-hover:opacity-100 transition-opacity"
onMouseDown={handleResizeMouseDown}
style={{ transform: 'translate(50%, 50%)' }}
/>
</div>
</div>
</div>
<p className="text-sm text-slate-500 mt-2">
Drag to move the QR code. Drag the blue dot to resize.
</p>
</div>
);
};
+83
View File
@@ -0,0 +1,83 @@
import {
Outlet,
ScrollRestoration,
useLocation,
useNavigate,
} from 'react-router-dom';
import { useEffect, useState } from 'react';
import { useAuthStore } from './features/auth/store/auth.store';
import { Sidebar } from '../components/Sidebar';
import { MenuOutlined } from '@ant-design/icons';
// Helper to determine route types
const isPublicRoute = (pathname: string) => {
return pathname.startsWith('/auth') || pathname === '/auth/callback';
};
export default function RootLayout() {
const location = useLocation();
const navigate = useNavigate();
const { isAuthenticated } = useAuthStore();
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
useEffect(() => {
// If we're on a public route, no auth check needed
if (isPublicRoute(location.pathname)) {
return;
}
// AUTH CHECK
if (!isAuthenticated) {
// No session -> Redirect to login
navigate('/auth/login', { replace: true });
return;
}
}, [location.pathname, navigate, isAuthenticated]);
// RENDER LOGIC
// 1. Public Pages (Full Layout Control)
if (isPublicRoute(location.pathname)) {
return (
<>
<Outlet />
<ScrollRestoration />
</>
);
}
// 2. Protected Pages
if (!isAuthenticated) {
return null;
}
return (
<div className="flex min-h-screen bg-gray-50">
<Sidebar
isOpen={mobileSidebarOpen}
onClose={() => setMobileSidebarOpen(false)}
/>
<div className="flex-1 flex flex-col min-w-0 overflow-hidden">
{/* Mobile Header */}
<header className="lg:hidden bg-white border-b border-gray-200 px-4 py-3 flex items-center justify-between sticky top-0 z-30">
<div className="flex items-center gap-3">
<button
onClick={() => setMobileSidebarOpen(true)}
className="p-2 -ml-2 rounded-md hover:bg-gray-100 text-gray-700"
>
<MenuOutlined className="text-lg" />
</button>
<h1 className="font-semibold text-gray-900">QR Campaign</h1>
</div>
</header>
<main className="flex-1 overflow-y-auto p-4 md:p-8">
<Outlet />
</main>
</div>
<ScrollRestoration />
</div>
);
}
-856
View File
@@ -1,856 +0,0 @@
/*
* * * * * * * * * * * * * * * * * * * * * * * * * * * *
This is a starter component and can be deleted.
* * * * * * * * * * * * * * * * * * * * * * * * * * * *
Delete this file and get started with your project!
* * * * * * * * * * * * * * * * * * * * * * * * * * * *
*/
export function NxWelcome({ title }: { title: string }) {
return (
<>
<style
dangerouslySetInnerHTML={{
__html: `
html {
-webkit-text-size-adjust: 100%;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif,
'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
'Noto Color Emoji';
line-height: 1.5;
tab-size: 4;
scroll-behavior: smooth;
}
body {
font-family: inherit;
line-height: inherit;
margin: 0;
}
h1,
h2,
p,
pre {
margin: 0;
}
*,
::before,
::after {
box-sizing: border-box;
border-width: 0;
border-style: solid;
border-color: currentColor;
}
h1,
h2 {
font-size: inherit;
font-weight: inherit;
}
a {
color: inherit;
text-decoration: inherit;
}
pre {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
'Liberation Mono', 'Courier New', monospace;
}
svg {
display: block;
vertical-align: middle;
shape-rendering: auto;
text-rendering: optimizeLegibility;
}
pre {
background-color: rgba(55, 65, 81, 1);
border-radius: 0.25rem;
color: rgba(229, 231, 235, 1);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
'Liberation Mono', 'Courier New', monospace;
overflow: auto;
padding: 0.5rem 0.75rem;
}
.shadow {
box-shadow: 0 0 #0000, 0 0 #0000, 0 10px 15px -3px rgba(0, 0, 0, 0.1),
0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
.rounded {
border-radius: 1.5rem;
}
.wrapper {
width: 100%;
}
.container {
margin-left: auto;
margin-right: auto;
max-width: 768px;
padding-bottom: 3rem;
padding-left: 1rem;
padding-right: 1rem;
color: rgba(55, 65, 81, 1);
width: 100%;
}
#welcome {
margin-top: 2.5rem;
}
#welcome h1 {
font-size: 3rem;
font-weight: 500;
letter-spacing: -0.025em;
line-height: 1;
}
#welcome span {
display: block;
font-size: 1.875rem;
font-weight: 300;
line-height: 2.25rem;
margin-bottom: 0.5rem;
}
#hero {
align-items: center;
background-color: hsla(214, 62%, 21%, 1);
border: none;
box-sizing: border-box;
color: rgba(55, 65, 81, 1);
display: grid;
grid-template-columns: 1fr;
margin-top: 3.5rem;
}
#hero .text-container {
color: rgba(255, 255, 255, 1);
padding: 3rem 2rem;
}
#hero .text-container h2 {
font-size: 1.5rem;
line-height: 2rem;
position: relative;
}
#hero .text-container h2 svg {
color: hsla(162, 47%, 50%, 1);
height: 2rem;
left: -0.25rem;
position: absolute;
top: 0;
width: 2rem;
}
#hero .text-container h2 span {
margin-left: 2.5rem;
}
#hero .text-container a {
background-color: rgba(255, 255, 255, 1);
border-radius: 0.75rem;
color: rgba(55, 65, 81, 1);
display: inline-block;
margin-top: 1.5rem;
padding: 1rem 2rem;
text-decoration: inherit;
}
#hero .logo-container {
display: none;
justify-content: center;
padding-left: 2rem;
padding-right: 2rem;
}
#hero .logo-container svg {
color: rgba(255, 255, 255, 1);
width: 66.666667%;
}
#middle-content {
align-items: flex-start;
display: grid;
grid-template-columns: 1fr;
margin-top: 3.5rem;
}
#middle-content #middle-content-container {
display: flex;
flex-direction: column;
gap: 2rem;
}
#learning-materials {
padding: 2.5rem 2rem;
}
#learning-materials h2 {
font-weight: 500;
font-size: 1.25rem;
letter-spacing: -0.025em;
line-height: 1.75rem;
padding-left: 1rem;
padding-right: 1rem;
}
.list-item-link {
align-items: center;
border-radius: 0.75rem;
display: flex;
margin-top: 1rem;
padding: 1rem;
transition-property: background-color, border-color, color, fill, stroke,
opacity, box-shadow, transform, filter, backdrop-filter,
-webkit-backdrop-filter;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
width: 100%;
}
.list-item-link svg:first-child {
margin-right: 1rem;
height: 1.5rem;
transition-property: background-color, border-color, color, fill, stroke,
opacity, box-shadow, transform, filter, backdrop-filter,
-webkit-backdrop-filter;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
width: 1.5rem;
}
.list-item-link > span {
flex-grow: 1;
font-weight: 400;
transition-property: background-color, border-color, color, fill, stroke,
opacity, box-shadow, transform, filter, backdrop-filter,
-webkit-backdrop-filter;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}
.list-item-link > span > span {
color: rgba(107, 114, 128, 1);
display: block;
flex-grow: 1;
font-size: 0.75rem;
font-weight: 300;
line-height: 1rem;
transition-property: background-color, border-color, color, fill, stroke,
opacity, box-shadow, transform, filter, backdrop-filter,
-webkit-backdrop-filter;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}
.list-item-link svg:last-child {
height: 1rem;
transition-property: all;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
width: 1rem;
}
.list-item-link:hover {
color: rgba(255, 255, 255, 1);
background-color: hsla(162, 55%, 33%, 1);
}
.list-item-link:hover > span {}
.list-item-link:hover > span > span {
color: rgba(243, 244, 246, 1);
}
.list-item-link:hover svg:last-child {
transform: translateX(0.25rem);
}
#other-links {}
.button-pill {
padding: 1.5rem 2rem;
margin-bottom: 2rem;
transition-duration: 300ms;
transition-property: background-color, border-color, color, fill, stroke,
opacity, box-shadow, transform, filter, backdrop-filter,
-webkit-backdrop-filter;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
align-items: center;
display: flex;
}
.button-pill svg {
transition-property: background-color, border-color, color, fill, stroke,
opacity, box-shadow, transform, filter, backdrop-filter,
-webkit-backdrop-filter;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
flex-shrink: 0;
width: 3rem;
}
.button-pill > span {
letter-spacing: -0.025em;
font-weight: 400;
font-size: 1.125rem;
line-height: 1.75rem;
padding-left: 1rem;
padding-right: 1rem;
}
.button-pill span span {
display: block;
font-size: 0.875rem;
font-weight: 300;
line-height: 1.25rem;
}
.button-pill:hover svg,
.button-pill:hover {
color: rgba(255, 255, 255, 1) !important;
}
#nx-console:hover {
background-color: rgba(0, 122, 204, 1);
}
#nx-console svg {
color: rgba(0, 122, 204, 1);
}
#nx-console-jetbrains {
margin-top: 2rem;
}
#nx-console-jetbrains:hover {
background-color: rgba(255, 49, 140, 1);
}
#nx-console-jetbrains svg {
color: rgba(255, 49, 140, 1);
}
#nx-repo:hover {
background-color: rgba(24, 23, 23, 1);
}
#nx-repo svg {
color: rgba(24, 23, 23, 1);
}
#nx-cloud {
margin-bottom: 2rem;
margin-top: 2rem;
padding: 2.5rem 2rem;
}
#nx-cloud > div {
align-items: center;
display: flex;
}
#nx-cloud > div svg {
border-radius: 0.375rem;
flex-shrink: 0;
width: 3rem;
}
#nx-cloud > div h2 {
font-size: 1.125rem;
font-weight: 400;
letter-spacing: -0.025em;
line-height: 1.75rem;
padding-left: 1rem;
padding-right: 1rem;
}
#nx-cloud > div h2 span {
display: block;
font-size: 0.875rem;
font-weight: 300;
line-height: 1.25rem;
}
#nx-cloud p {
font-size: 1rem;
line-height: 1.5rem;
margin-top: 1rem;
}
#nx-cloud pre {
margin-top: 1rem;
}
#nx-cloud a {
color: rgba(107, 114, 128, 1);
display: block;
font-size: 0.875rem;
line-height: 1.25rem;
margin-top: 1.5rem;
text-align: right;
}
#nx-cloud a:hover {
text-decoration: underline;
}
#commands {
padding: 2.5rem 2rem;
margin-top: 3.5rem;
}
#commands h2 {
font-size: 1.25rem;
font-weight: 400;
letter-spacing: -0.025em;
line-height: 1.75rem;
padding-left: 1rem;
padding-right: 1rem;
}
#commands p {
font-size: 1rem;
font-weight: 300;
line-height: 1.5rem;
margin-top: 1rem;
padding-left: 1rem;
padding-right: 1rem;
}
details {
align-items: center;
display: flex;
margin-top: 1rem;
padding-left: 1rem;
padding-right: 1rem;
width: 100%;
}
details pre > span {
color: rgba(181, 181, 181, 1);
display: block;
}
summary {
border-radius: 0.5rem;
display: flex;
font-weight: 400;
padding: 0.5rem;
cursor: pointer;
transition-property: background-color, border-color, color, fill, stroke,
opacity, box-shadow, transform, filter, backdrop-filter,
-webkit-backdrop-filter;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
}
summary:hover {
background-color: rgba(243, 244, 246, 1);
}
summary svg {
height: 1.5rem;
margin-right: 1rem;
width: 1.5rem;
}
#love {
color: rgba(107, 114, 128, 1);
font-size: 0.875rem;
line-height: 1.25rem;
margin-top: 3.5rem;
opacity: 0.6;
text-align: center;
}
#love svg {
color: rgba(252, 165, 165, 1);
width: 1.25rem;
height: 1.25rem;
display: inline;
margin-top: -0.25rem;
}
@media screen and (min-width: 768px) {
#hero {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
#hero .logo-container {
display: flex;
}
#middle-content {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 4rem;
}
}
`,
}}
/>
<div className="wrapper">
<div className="container">
<div id="welcome">
<h1>
<span> Hello there, </span>
Welcome {title} 👋
</h1>
</div>
<div id="hero" className="rounded">
<div className="text-container">
<h2>
<svg
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z"
/>
</svg>
<span>You&apos;re up and running</span>
</h2>
<a href="#commands"> What&apos;s next? </a>
</div>
<div className="logo-container">
<svg
fill="currentColor"
role="img"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M11.987 14.138l-3.132 4.923-5.193-8.427-.012 8.822H0V4.544h3.691l5.247 8.833.005-3.998 3.044 4.759zm.601-5.761c.024-.048 0-3.784.008-3.833h-3.65c.002.059-.005 3.776-.003 3.833h3.645zm5.634 4.134a2.061 2.061 0 0 0-1.969 1.336 1.963 1.963 0 0 1 2.343-.739c.396.161.917.422 1.33.283a2.1 2.1 0 0 0-1.704-.88zm3.39 1.061c-.375-.13-.8-.277-1.109-.681-.06-.08-.116-.17-.176-.265a2.143 2.143 0 0 0-.533-.642c-.294-.216-.68-.322-1.18-.322a2.482 2.482 0 0 0-2.294 1.536 2.325 2.325 0 0 1 4.002.388.75.75 0 0 0 .836.334c.493-.105.46.36 1.203.518v-.133c-.003-.446-.246-.55-.75-.733zm2.024 1.266a.723.723 0 0 0 .347-.638c-.01-2.957-2.41-5.487-5.37-5.487a5.364 5.364 0 0 0-4.487 2.418c-.01-.026-1.522-2.39-1.538-2.418H8.943l3.463 5.423-3.379 5.32h3.54l1.54-2.366 1.568 2.366h3.541l-3.21-5.052a.7.7 0 0 1-.084-.32 2.69 2.69 0 0 1 2.69-2.691h.001c1.488 0 1.736.89 2.057 1.308.634.826 1.9.464 1.9 1.541a.707.707 0 0 0 1.066.596zm.35.133c-.173.372-.56.338-.755.639-.176.271.114.412.114.412s.337.156.538-.311c.104-.231.14-.488.103-.74z" />
</svg>
</div>
</div>
<div id="middle-content">
<div id="middle-content-container">
<div id="learning-materials" className="rounded shadow">
<h2>Learning materials</h2>
<a
href="https://nx.dev/getting-started/intro?utm_source=nx-project"
target="_blank"
rel="noreferrer"
className="list-item-link"
>
<svg
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"
/>
</svg>
<span>
Documentation
<span> Everything is in there </span>
</span>
<svg
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M9 5l7 7-7 7"
/>
</svg>
</a>
<a
href="https://nx.dev/blog/?utm_source=nx-project"
target="_blank"
rel="noreferrer"
className="list-item-link"
>
<svg
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2m-4-3H9M7 16h6M7 8h6v4H7V8z"
/>
</svg>
<span>
Blog
<span> Changelog, features & events </span>
</span>
<svg
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M9 5l7 7-7 7"
/>
</svg>
</a>
<a
href="https://www.youtube.com/@NxDevtools/videos?utm_source=nx-project&sub_confirmation=1"
target="_blank"
rel="noreferrer"
className="list-item-link"
>
<svg
role="img"
viewBox="0 0 24 24"
fill="currentColor"
xmlns="http://www.w3.org/2000/svg"
>
<title>YouTube</title>
<path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z" />
</svg>
<span>
YouTube channel
<span> Nx Show, talks & tutorials </span>
</span>
<svg
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M9 5l7 7-7 7"
/>
</svg>
</a>
<a
href="https://nx.dev/react-tutorial/1-code-generation?utm_source=nx-project"
target="_blank"
rel="noreferrer"
className="list-item-link"
>
<svg
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M15 15l-2 5L9 9l11 4-5 2zm0 0l5 5M7.188 2.239l.777 2.897M5.136 7.965l-2.898-.777M13.95 4.05l-2.122 2.122m-5.657 5.656l-2.12 2.122"
/>
</svg>
<span>
Interactive tutorials
<span> Create an app, step-by-step </span>
</span>
<svg
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M9 5l7 7-7 7"
/>
</svg>
</a>
</div>
<a
id="nx-repo"
className="button-pill rounded shadow"
href="https://github.com/nrwl/nx?utm_source=nx-project"
target="_blank"
rel="noreferrer"
>
<svg
fill="currentColor"
role="img"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
</svg>
<span>
Nx is open source
<span> Love Nx? Give us a star! </span>
</span>
</a>
</div>
<div id="other-links">
<a
id="nx-console"
className="button-pill rounded shadow"
href="https://marketplace.visualstudio.com/items?itemName=nrwl.angular-console&utm_source=nx-project"
target="_blank"
rel="noreferrer"
>
<svg
fill="currentColor"
role="img"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<title>Visual Studio Code</title>
<path d="M23.15 2.587L18.21.21a1.494 1.494 0 0 0-1.705.29l-9.46 8.63-4.12-3.128a.999.999 0 0 0-1.276.057L.327 7.261A1 1 0 0 0 .326 8.74L3.899 12 .326 15.26a1 1 0 0 0 .001 1.479L1.65 17.94a.999.999 0 0 0 1.276.057l4.12-3.128 9.46 8.63a1.492 1.492 0 0 0 1.704.29l4.942-2.377A1.5 1.5 0 0 0 24 20.06V3.939a1.5 1.5 0 0 0-.85-1.352zm-5.146 14.861L10.826 12l7.178-5.448v10.896z" />
</svg>
<span>
Install Nx Console for VSCode
<span>The official VSCode extension for Nx.</span>
</span>
</a>
<a
id="nx-console-jetbrains"
className="button-pill rounded shadow"
href="https://plugins.jetbrains.com/plugin/21060-nx-console"
target="_blank"
rel="noreferrer"
>
<svg
height="48"
width="48"
viewBox="20 20 60 60"
xmlns="http://www.w3.org/2000/svg"
>
<path d="m22.5 22.5h60v60h-60z" />
<g fill="#fff">
<path d="m29.03 71.25h22.5v3.75h-22.5z" />
<path d="m28.09 38 1.67-1.58a1.88 1.88 0 0 0 1.47.87c.64 0 1.06-.44 1.06-1.31v-5.98h2.58v6a3.48 3.48 0 0 1 -.87 2.6 3.56 3.56 0 0 1 -2.57.95 3.84 3.84 0 0 1 -3.34-1.55z" />
<path d="m36 30h7.53v2.19h-5v1.44h4.49v2h-4.42v1.49h5v2.21h-7.6z" />
<path d="m47.23 32.29h-2.8v-2.29h8.21v2.27h-2.81v7.1h-2.6z" />
<path d="m29.13 43.08h4.42a3.53 3.53 0 0 1 2.55.83 2.09 2.09 0 0 1 .6 1.53 2.16 2.16 0 0 1 -1.44 2.09 2.27 2.27 0 0 1 1.86 2.29c0 1.61-1.31 2.59-3.55 2.59h-4.44zm5 2.89c0-.52-.42-.8-1.18-.8h-1.29v1.64h1.24c.79 0 1.25-.26 1.25-.81zm-.9 2.66h-1.57v1.73h1.62c.8 0 1.24-.31 1.24-.86 0-.5-.4-.87-1.27-.87z" />
<path d="m38 43.08h4.1a4.19 4.19 0 0 1 3 1 2.93 2.93 0 0 1 .9 2.19 3 3 0 0 1 -1.93 2.89l2.24 3.27h-3l-1.88-2.84h-.87v2.84h-2.56zm4 4.5c.87 0 1.39-.43 1.39-1.11 0-.75-.54-1.12-1.4-1.12h-1.44v2.26z" />
<path d="m49.59 43h2.5l4 9.44h-2.79l-.67-1.69h-3.63l-.67 1.69h-2.71zm2.27 5.73-1-2.65-1.06 2.65z" />
<path d="m56.46 43.05h2.6v9.37h-2.6z" />
<path d="m60.06 43.05h2.42l3.37 5v-5h2.57v9.37h-2.26l-3.53-5.14v5.14h-2.57z" />
<path d="m68.86 51 1.45-1.73a4.84 4.84 0 0 0 3 1.13c.71 0 1.08-.24 1.08-.65 0-.4-.31-.6-1.59-.91-2-.46-3.53-1-3.53-2.93 0-1.74 1.37-3 3.62-3a5.89 5.89 0 0 1 3.86 1.25l-1.26 1.84a4.63 4.63 0 0 0 -2.62-.92c-.63 0-.94.25-.94.6 0 .42.32.61 1.63.91 2.14.46 3.44 1.16 3.44 2.91 0 1.91-1.51 3-3.79 3a6.58 6.58 0 0 1 -4.35-1.5z" />
</g>
</svg>
<span>
Install Nx Console for JetBrains
<span>
Available for WebStorm, Intellij IDEA Ultimate and more!
</span>
</span>
</a>
<div id="nx-cloud" className="rounded shadow">
<div>
<svg
id="nx-cloud-logo"
role="img"
xmlns="http://www.w3.org/2000/svg"
stroke="currentColor"
fill="transparent"
viewBox="0 0 24 24"
>
<path
strokeWidth="2"
d="M23 3.75V6.5c-3.036 0-5.5 2.464-5.5 5.5s-2.464 5.5-5.5 5.5-5.5 2.464-5.5 5.5H3.75C2.232 23 1 21.768 1 20.25V3.75C1 2.232 2.232 1 3.75 1h16.5C21.768 1 23 2.232 23 3.75Z"
/>
<path
strokeWidth="2"
d="M23 6v14.1667C23 21.7307 21.7307 23 20.1667 23H6c0-3.128 2.53867-5.6667 5.6667-5.6667 3.128 0 5.6666-2.5386 5.6666-5.6666C17.3333 8.53867 19.872 6 23 6Z"
/>
</svg>
<h2>
Nx Cloud
<span>Enable faster CI & better DX</span>
</h2>
</div>
<p>
You can activate distributed tasks executions and caching by
running:
</p>
<pre>nx connect</pre>
<a
href="https://nx.dev/nx-cloud?utm_source=nx-project"
target="_blank"
rel="noreferrer"
>
{' '}
What is Nx Cloud?{' '}
</a>
</div>
</div>
</div>
<div id="commands" className="rounded shadow">
<h2>Next steps</h2>
<p>Here are some things you can do with Nx:</p>
<details>
<summary>
<svg
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
/>
</svg>
Build, test and lint your app
</summary>
<pre>
<span># Build</span>
nx build {title}
<span># Test</span>
nx test {title}
<span># Lint</span>
nx lint {title}
<span># Run them together!</span>
nx run-many -p {title} -t build test lint
</pre>
</details>
<details>
<summary>
<svg
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
/>
</svg>
View project details
</summary>
<pre>nx show project {title}</pre>
</details>
<details>
<summary>
<svg
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
/>
</svg>
View interactive project graph
</summary>
<pre>nx graph</pre>
</details>
<details>
<summary>
<svg
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
/>
</svg>
Add UI library
</summary>
<pre>
<span># Generate UI lib</span>
nx g @nx/react:lib ui
<span># Add a component</span>
nx g @nx/react:component ui/src/lib/button
</pre>
</details>
</div>
<p id="love">
Carefully crafted with
<svg
fill="currentColor"
stroke="none"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
/>
</svg>
</p>
</div>
</div>
</>
);
}
export default NxWelcome;
+136 -44
View File
@@ -1,52 +1,144 @@
// Uncomment this line to use CSS modules
// import styles from './app.module.css';
import NxWelcome from './nx-welcome';
import { useState } from 'react';
import { Dropzone } from './features/watermark/components/Dropzone';
import { Button } from '@imphnen-frontend-service/ui/atoms';
import { toast } from 'sonner';
import { api } from './features/auth/api/auth.service';
import { Route, Routes, Link } from 'react-router-dom';
export default function HomePage() {
const [imageFile, setImageFile] = useState<File | null>(null);
const [generatedImage, setGeneratedImage] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const handleImageDropped = (file: File) => {
setImageFile(file);
setGeneratedImage(null); // Reset previous result
toast.success('Image selected ready for generation!');
};
const handleReset = () => {
setImageFile(null);
setGeneratedImage(null);
};
const handleGenerate = async () => {
if (!imageFile) return;
setIsLoading(true);
const formData = new FormData();
formData.append('image', imageFile);
try {
const response = await api.post('/campaigns/process-image', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
responseType: 'blob',
});
const imageUrl = URL.createObjectURL(response.data);
setGeneratedImage(imageUrl);
toast.success('QR Code generated successfully!');
} catch (error: any) {
console.error(error);
const message =
error.response?.data?.message || 'Failed to generate QR code.';
toast.error(message);
} finally {
setIsLoading(false);
}
};
const handleDownload = () => {
if (!generatedImage) return;
const link = document.createElement('a');
link.href = generatedImage;
link.download = `qr-campaign-${Date.now()}.png`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
export function App() {
return (
<div>
<NxWelcome title="qrcampaign" />
<div className="max-w-4xl mx-auto py-8 px-4 flex flex-col gap-8">
<header className="text-center mb-8">
<h1 className="text-3xl font-bold text-gray-900 mb-2">
QR Code Generator
</h1>
<p className="text-gray-600">
Upload your image to add the campaign QR code watermark.
</p>
</header>
{/* START: routes */}
{/* These routes and navigation have been generated for you */}
{/* Feel free to move and update them to fit your needs */}
<br />
<hr />
<br />
<div role="navigation">
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/page-2">Page 2</Link>
</li>
</ul>
<div className="bg-white rounded-xl shadow-sm border border-gray-100 p-8">
{!imageFile ? (
<Dropzone onImageDropped={handleImageDropped} />
) : (
<div className="flex flex-col items-center gap-6">
<div className="relative w-full max-w-2xl bg-gray-50 rounded-lg overflow-hidden border border-gray-200">
{isLoading ? (
<div className="flex flex-col items-center justify-center p-20 gap-4">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
<p className="text-gray-500 font-medium">
Processing image...
</p>
</div>
) : generatedImage ? (
<img
src={generatedImage}
alt="Generated with QR"
className="w-full h-auto object-contain max-h-[600px]"
/>
) : (
<div className="relative">
<img
src={URL.createObjectURL(imageFile)}
alt="Original"
className="w-full h-auto object-contain max-h-[400px]"
/>
<div className="absolute inset-0 bg-black/5 flex items-center justify-center pointer-events-none">
<span className="bg-black/60 text-white px-3 py-1 rounded-2xl text-sm">
Original Image
</span>
</div>
</div>
)}
</div>
<div className="flex gap-4">
{!generatedImage && !isLoading && (
<>
<Button
variant="bordered"
onClick={handleReset}
className="w-32"
>
Cancel
</Button>
<Button
variant="primary"
onClick={handleGenerate}
className="w-40"
disabled={isLoading}
>
Generate QR
</Button>
</>
)}
{generatedImage && (
<>
<Button variant="bordered" onClick={handleReset}>
Upload Another
</Button>
<Button variant="primary" onClick={handleDownload}>
Download
</Button>
</>
)}
</div>
</div>
)}
</div>
<Routes>
<Route
path="/"
element={
<div>
This is the generated root route.{' '}
<Link to="/page-2">Click here for page 2.</Link>
</div>
}
/>
<Route
path="/page-2"
element={
<div>
<Link to="/">Click here to go back to root page.</Link>
</div>
}
/>
</Routes>
{/* END: routes */}
</div>
);
}
export default App;
+229
View File
@@ -0,0 +1,229 @@
import {
AppstoreOutlined,
UsergroupAddOutlined,
QrcodeOutlined,
LogoutOutlined,
DownOutlined,
RightOutlined,
} from '@ant-design/icons';
import { Button } from '@imphnen-frontend-service/ui/atoms';
import { FC, ReactElement, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { cn, For } from '@imphnen-frontend-service/utils';
import { useAuthStore } from '../app/features/auth/store/auth.store';
type MenuItem = {
label: string;
href?: string;
icon?: ReactElement;
children?: Array<{ label: string; href: string; icon?: ReactElement }>;
roles?: string[]; // Roles that can see this menu
};
const MENUS: MenuItem[] = [
{
label: 'QR Generator',
href: '/',
icon: <QrcodeOutlined className="text-[20px]" />,
roles: ['User', 'Admin', 'Super Admin'],
},
{
label: 'Campaign Management',
href: '/admin/campaigns',
icon: <AppstoreOutlined className="text-[20px]" />,
roles: ['Admin', 'Super Admin'],
},
{
label: 'User Management',
href: '/admin/users',
icon: <UsergroupAddOutlined className="text-[20px]" />,
roles: ['Admin', 'Super Admin'],
},
];
interface SidebarProps {
isOpen?: boolean;
onClose?: () => void;
}
export const Sidebar: FC<SidebarProps> = ({
isOpen = false,
onClose,
}): ReactElement => {
const { user, logout } = useAuthStore();
const location = useLocation();
const [openGroups, setOpenGroups] = useState<Record<string, boolean>>({});
const userRole = user?.role?.name || 'User';
const isActive = (path: string) => {
if (path === '/' && location.pathname !== '/') return false;
return location.pathname.startsWith(path);
};
const toggleGroup = (groupLabel: string) => {
setOpenGroups((prev) => ({ ...prev, [groupLabel]: !prev[groupLabel] }));
};
// Filter menus based on role
const filteredMenus = MENUS.filter((menu) => {
if (!menu.roles) return true;
return menu.roles.includes(userRole);
});
const sidebarContent = (
<div className="w-[280px] bg-white h-dvh px-7 shadow-xl flex flex-col border-r border-gray-100">
<div className="shrink-0 py-10 lg:py-[60px]">
<div className="flex justify-between lg:justify-center items-center w-full">
<img
src="/images/imphnen-logo.svg"
alt="IMPHNEN Logo"
className="w-[150px]"
/>
{onClose && (
<button
onClick={onClose}
className="lg:hidden p-2 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer"
aria-label="Close sidebar"
>
<svg
className="w-5 h-5 text-gray-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
)}
</div>
</div>
{/* Navigation - Scrollable area */}
<nav className="flex-1 flex flex-col gap-4 w-full overflow-y-auto min-h-0 pb-4">
<For data={filteredMenus}>
{(menu) =>
menu.children && menu.children.length > 0 ? (
<div key={menu.label} className="w-full">
<button
type="button"
onClick={() => toggleGroup(menu.label)}
className={cn(
'flex items-center justify-between w-full gap-3 px-2 py-2.5 rounded-md cursor-pointer',
openGroups[menu.label]
? 'bg-primary-50 text-primary-700'
: 'text-gray-700 hover:bg-gray-50'
)}
>
<div className="flex items-center gap-3">
{menu.icon}
<span className="text-sm font-medium">{menu.label}</span>
</div>
<span className="text-xs">
{openGroups[menu.label] ? (
<DownOutlined />
) : (
<RightOutlined />
)}
</span>
</button>
{openGroups[menu.label] && (
<div className="mt-2 ml-6 flex flex-col gap-2">
{menu.children.map((child) => (
<Link
key={child.href}
to={child.href}
className={cn(
'flex items-center gap-3 px-2 py-2.5 rounded-md',
isActive(child.href)
? 'bg-primary-100 text-primary-700'
: 'text-gray-600 hover:bg-gray-50'
)}
>
{child.icon}
<span className="text-sm font-medium">
{child.label}
</span>
</Link>
))}
</div>
)}
</div>
) : (
<Link
key={menu.href ?? menu.label}
to={menu.href ?? '#'}
className={cn(
'flex items-center justify-start gap-3 px-2 py-2.5 rounded-md transition-colors',
menu.href && isActive(menu.href)
? 'bg-primary-500 text-white hover:bg-primary-600 shadow-sm'
: 'text-gray-700 hover:bg-gray-100'
)}
>
{menu.icon}
<span className="text-sm font-medium">{menu.label}</span>
</Link>
)
}
</For>
</nav>
{/* Footer - Fixed at bottom */}
<div className="shrink-0 w-full pb-10 lg:pb-[60px]">
<hr className="mb-5 border-gray-100" />
<div className="px-2 mb-4">
<div className="text-xs text-gray-500 font-medium uppercase mb-2 select-none">
Signed in as
</div>
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-full bg-primary-100 flex items-center justify-center text-primary-600 font-bold text-xs ring-2 ring-white">
{user?.fullname?.charAt(0) || 'U'}
</div>
<div className="flex flex-col overflow-hidden">
<span className="text-sm font-medium truncate text-gray-900">
{user?.fullname}
</span>
<span className="text-xs text-gray-500 truncate">
{user?.role?.name}
</span>
</div>
</div>
</div>
<Button
onClick={logout}
variant="text"
className="items-center justify-start gap-3 px-2 py-2.5 text-gray-600 hover:text-red-600 dark:hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-50 transition-colors w-full rounded-md"
>
<LogoutOutlined className="text-lg" />
<span className="text-sm font-medium">Log Out</span>
</Button>
</div>
</div>
);
return (
<>
<div className="hidden lg:block sticky top-0 h-screen overflow-y-auto border-r border-gray-200">
{sidebarContent}
</div>
{isOpen && (
<div className="lg:hidden fixed inset-0 z-50">
<div
className="fixed inset-0 bg-black/50 transition-opacity backdrop-blur-sm"
onClick={onClose}
/>
<div className="fixed inset-y-0 left-0 z-50 transform transition-transform duration-300 ease-in-out">
{sidebarContent}
</div>
</div>
)}
</>
);
};
+136
View File
@@ -0,0 +1,136 @@
@import url('https://fonts.googleapis.com/css2?family=Bai+Jamjuree:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700&display=swap');
@import 'tailwindcss';
@source "../../../libs/ui/**/*.{ts,tsx}";
@theme {
--color-primary-50: #f0f8ff;
--color-primary-100: #e1f0fd;
--color-primary-200: #bce1fb;
--color-primary-300: #81cbf8;
--color-primary-400: #3eb0f2;
--color-primary-500: #23a1eb;
--color-primary-600: #0877c1;
--color-primary-700: #085f9c;
--color-primary-800: #0b5181;
--color-primary-900: #0f446b;
--color-primary-950: #0a2b47;
--color-neutral-50: #f6f6f6;
--color-neutral-100: #e7e7e7;
--color-neutral-200: #d1d1d1;
--color-neutral-300: #b0b0b0;
--color-neutral-400: #888888;
--color-neutral-500: #6e6a86;
--color-neutral-600: #56526e;
--color-neutral-700: #44415a;
--color-neutral-800: #393552;
--color-neutral-900: #2a273f;
--color-neutral-950: #232136;
--color-success-100: #e0fbd8;
--color-success-200: #bcf8b0;
--color-success-300: #8eea85;
--color-success-400: #63d564;
--color-success-500: #35ba43;
--color-success-600: #269f3e;
--color-success-700: #1a8439;
--color-success-800: #106b32;
--color-success-900: #0b592f;
--color-info-100: #ccfcfe;
--color-info-200: #9bf3fd;
--color-info-300: #67e3fb;
--color-info-400: #42cdf8;
--color-info-500: #04acf3;
--color-info-600: #0185d0;
--color-info-700: #0264af;
--color-info-800: #01478d;
--color-info-900: #003375;
--color-warning-100: #fffcd3;
--color-warning-200: #fffaa9;
--color-warning-300: #fff67d;
--color-warning-400: #fff25d;
--color-warning-500: #ffed27;
--color-warning-600: #dbc91d;
--color-warning-700: #b7a714;
--color-warning-800: #93850b;
--color-warning-900: #7a6d07;
--color-danger-100: #ffe8da;
--color-danger-200: #ffcbb3;
--color-danger-300: #ffaa8d;
--color-danger-400: #ff8870;
--color-danger-500: #ff5242;
--color-danger-600: #da3030;
--color-danger-700: #b7212d;
--color-danger-800: #93152a;
--color-danger-900: #7a0c27;
--radius-none: 0px;
--radius-sm: 2px;
--radius-md: 4px;
--radius-lg: 8px;
--radius-xl: 12px;
--radius-2xl: 16px;
--radius-3xl: 24px;
--radius-full: 50%;
--font-bai-jamjuree: 'Bai Jamjuree', sans-serif;
--text-h1: 3.833rem;
/* ~46px */
--text-h2: 3.083rem;
/* ~37px */
--text-h3: 2.417rem;
/* ~29px */
--text-p1: 1.917rem;
/* ~23px */
--text-p2: 1.583rem;
/* ~19px */
--text-p3: 1.25rem;
/* 15px */
--text-label1: 1rem;
/* 12px */
--text-label2: 0.833rem;
/* ~10px */
--text-label3: 0.677rem;
/* ~8px */
}
@layer base {
*,
::after,
::before,
::backdrop,
::file-selector-button {
border-color: var(--color-neutral-200, currentColor);
}
/* Custom scrollbar */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: var(--color-neutral-50);
}
::-webkit-scrollbar-thumb {
background: #cccccc;
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--color-neutral-300);
}
html {
font-family: 'Bai Jamjuree', sans-serif;
font-weight: 400;
font-size: 16px;
line-height: 1.2;
}
}
+36 -10
View File
@@ -1,16 +1,42 @@
import { createRoot } from 'react-dom/client';
import { StrictMode } from 'react';
import { BrowserRouter } from 'react-router-dom';
import * as ReactDOM from 'react-dom/client';
import App from './app/page';
import { createBrowserRouter, RouteObject, RouterProvider } from 'react-router';
import {
add404PageToRoutesChildren,
addErrorElementToRoutes,
convertPagesToRoute,
ModalLoginProvider,
QueryProvider,
} from '@imphnen-frontend-service/utils';
import { Toaster } from 'sonner';
import './index.css';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
const files = import.meta.glob('./app/**/*(page|layout).tsx');
const errorFiles = import.meta.glob('./app/**/*error.tsx');
const notFoundFiles = import.meta.glob('./app/**/*404.tsx');
const loadingFiles = import.meta.glob('./app/**/*loading.tsx');
root.render(
const routes = convertPagesToRoute(files, loadingFiles) as RouteObject;
addErrorElementToRoutes(errorFiles, routes);
add404PageToRoutesChildren(notFoundFiles, routes);
const router = createBrowserRouter([
{
...routes,
},
]);
const rootElement = document.getElementById('root');
if (!rootElement) throw new Error('Failed to find the root element');
createRoot(rootElement).render(
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
<QueryProvider>
<ModalLoginProvider>
<Toaster position="top-right" richColors />
<RouterProvider router={router} />
</ModalLoginProvider>
</QueryProvider>
</StrictMode>
);