Sawssen AI

This commit is contained in:
Flatlogic Bot 2026-02-03 13:32:57 +00:00
parent 1ccb97a76f
commit 3745bdf7a5
23 changed files with 1238 additions and 233 deletions

View File

@ -55,14 +55,46 @@ passport.use(new MicrosoftStrategy({
}
));
function socialStrategy(email, profile, provider, done) {
db.users.findOrCreate({where: {email, provider}}).then(([user, created]) => {
const body = {
id: user.id,
email: user.email,
name: profile.displayName,
};
const token = helpers.jwtSign({user: body});
return done(null, {token});
});
}
async function socialStrategy(email, profile, provider, done) {
try {
let user = await db.users.findOne({where: {email, provider}});
if (!user) {
// If user exists with same email but different provider, we might want to link or reject
// For now, let's just find by email if provider is not set or handle accordingly
user = await db.users.findOne({where: {email}});
if (user) {
// Update provider if not set
if (!user.provider) {
await user.update({provider});
}
} else {
// Create new user
user = await db.users.create({
email,
provider,
firstName: profile.given_name || profile.displayName?.split(' ')[0],
lastName: profile.family_name || profile.displayName?.split(' ')[1],
emailVerified: true
});
// Set default role
const role = await db.roles.findOne({
where: { name: config.roles?.user || 'Viewer' },
});
if (role) {
await user.setApp_role(role);
}
}
}
const body = {
id: user.id,
email: user.email,
name: profile.displayName,
};
const token = helpers.jwtSign({user: body});
return done(null, {token});
} catch (error) {
return done(error);
}
}

View File

@ -1,6 +1,3 @@
const os = require('os');
const config = {
@ -73,7 +70,7 @@ config.pexelsQuery = 'paper airplane over sunrise horizon';
config.host = process.env.NODE_ENV === "production" ? config.remote : "http://localhost";
config.apiUrl = `${config.host}${config.port ? `:${config.port}` : ``}/api`;
config.swaggerUrl = `${config.swaggerUI}${config.swaggerPort}`;
config.uiUrl = `${config.hostUI}${config.portUI ? `:${config.portUI}` : ``}/#`;
config.uiUrl = `${config.hostUI}${config.portUI ? `:${config.portUI}` : ``}`;
config.backUrl = `${config.hostUI}${config.portUI ? `:${config.portUI}` : ``}`;
module.exports = config;
module.exports = config;

View File

@ -1,5 +1,3 @@
module.exports = {
production: {
dialect: 'postgres',
@ -12,11 +10,12 @@ module.exports = {
seederStorage: 'sequelize',
},
development: {
username: 'postgres',
dialect: 'postgres',
password: '',
database: 'db_app_draft',
host: process.env.DB_HOST || 'localhost',
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: console.log,
seederStorage: 'sequelize',
},
@ -30,4 +29,4 @@ module.exports = {
logging: console.log,
seederStorage: 'sequelize',
}
};
};

View File

@ -0,0 +1,103 @@
module.exports = {
async up(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.createTable('services', {
id: {
type: Sequelize.DataTypes.UUID,
defaultValue: Sequelize.DataTypes.UUIDV4,
primaryKey: true,
},
title: { type: Sequelize.DataTypes.TEXT },
description: { type: Sequelize.DataTypes.TEXT },
price: { type: Sequelize.DataTypes.DECIMAL },
category: { type: Sequelize.DataTypes.TEXT },
image: { type: Sequelize.DataTypes.TEXT },
createdByUserId: {
type: Sequelize.DataTypes.UUID,
references: { model: 'users', key: 'id' },
},
updatedByUserId: {
type: Sequelize.DataTypes.UUID,
references: { model: 'users', key: 'id' },
},
createdAt: { type: Sequelize.DataTypes.DATE },
updatedAt: { type: Sequelize.DataTypes.DATE },
deletedAt: { type: Sequelize.DataTypes.DATE },
importHash: { type: Sequelize.DataTypes.STRING(255), allowNull: true, unique: true },
}, { transaction });
await queryInterface.createTable('courses', {
id: {
type: Sequelize.DataTypes.UUID,
defaultValue: Sequelize.DataTypes.UUIDV4,
primaryKey: true,
},
title: { type: Sequelize.DataTypes.TEXT },
description: { type: Sequelize.DataTypes.TEXT },
price: { type: Sequelize.DataTypes.DECIMAL },
level: { type: Sequelize.DataTypes.TEXT },
duration: { type: Sequelize.DataTypes.TEXT },
image: { type: Sequelize.DataTypes.TEXT },
createdByUserId: {
type: Sequelize.DataTypes.UUID,
references: { model: 'users', key: 'id' },
},
updatedByUserId: {
type: Sequelize.DataTypes.UUID,
references: { model: 'users', key: 'id' },
},
createdAt: { type: Sequelize.DataTypes.DATE },
updatedAt: { type: Sequelize.DataTypes.DATE },
deletedAt: { type: Sequelize.DataTypes.DATE },
importHash: { type: Sequelize.DataTypes.STRING(255), allowNull: true, unique: true },
}, { transaction });
await queryInterface.createTable('orders', {
id: {
type: Sequelize.DataTypes.UUID,
defaultValue: Sequelize.DataTypes.UUIDV4,
primaryKey: true,
},
customerName: { type: Sequelize.DataTypes.TEXT },
customerEmail: { type: Sequelize.DataTypes.TEXT },
status: {
type: Sequelize.DataTypes.ENUM,
values: ['pending', 'completed', 'cancelled'],
},
totalAmount: { type: Sequelize.DataTypes.DECIMAL },
itemType: { type: Sequelize.DataTypes.TEXT },
itemId: { type: Sequelize.DataTypes.UUID },
createdByUserId: {
type: Sequelize.DataTypes.UUID,
references: { model: 'users', key: 'id' },
},
updatedByUserId: {
type: Sequelize.DataTypes.UUID,
references: { model: 'users', key: 'id' },
},
createdAt: { type: Sequelize.DataTypes.DATE },
updatedAt: { type: Sequelize.DataTypes.DATE },
deletedAt: { type: Sequelize.DataTypes.DATE },
importHash: { type: Sequelize.DataTypes.STRING(255), allowNull: true, unique: true },
}, { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
async down(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.dropTable('orders', { transaction });
await queryInterface.dropTable('courses', { transaction });
await queryInterface.dropTable('services', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
}
};

View File

@ -0,0 +1,51 @@
module.exports = function(sequelize, DataTypes) {
const courses = sequelize.define(
'courses',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
price: {
type: DataTypes.DECIMAL,
},
level: {
type: DataTypes.TEXT,
},
duration: {
type: DataTypes.TEXT,
},
image: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
courses.associate = (db) => {
db.courses.belongsTo(db.users, {
as: 'createdBy',
});
db.courses.belongsTo(db.users, {
as: 'updatedBy',
});
};
return courses;
};

View File

@ -0,0 +1,56 @@
module.exports = function(sequelize, DataTypes) {
const orders = sequelize.define(
'orders',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
customerName: {
type: DataTypes.TEXT,
},
customerEmail: {
type: DataTypes.TEXT,
},
message: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: ['pending', 'completed', 'cancelled'],
defaultValue: 'pending',
},
totalAmount: {
type: DataTypes.DECIMAL,
},
itemType: {
type: DataTypes.TEXT, // 'service' or 'course'
},
itemId: {
type: DataTypes.UUID,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
orders.associate = (db) => {
db.orders.belongsTo(db.users, {
as: 'createdBy',
});
db.orders.belongsTo(db.users, {
as: 'updatedBy',
});
};
return orders;
};

View File

@ -0,0 +1,48 @@
module.exports = function(sequelize, DataTypes) {
const services = sequelize.define(
'services',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
price: {
type: DataTypes.DECIMAL,
},
category: {
type: DataTypes.TEXT,
},
image: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
services.associate = (db) => {
db.services.belongsTo(db.users, {
as: 'createdBy',
});
db.services.belongsTo(db.users, {
as: 'updatedBy',
});
};
return services;
};

View File

@ -0,0 +1,69 @@
module.exports = {
async up(queryInterface, Sequelize) {
const services = [
{
id: '1e2e3e4e-5e6e-7e8e-9e0e-1a2b3c4d5e6f',
title: 'AI Video Ad - Professional',
description: 'High-quality 30-second video ad generated with Gen AI, including script and voiceover.',
price: 499.00,
category: 'Video Ads',
image: 'https://images.pexels.com/photos/373543/pexels-photo-373543.jpeg',
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: '2e2e3e4e-5e6e-7e8e-9e0e-1a2b3c4d5e6f',
title: 'Social Media Pack',
description: 'Set of 5 short video ads optimized for TikTok, Reels, and YouTube Shorts.',
price: 799.00,
category: 'Video Ads',
image: 'https://images.pexels.com/photos/5053740/pexels-photo-5053740.jpeg',
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: '3e2e3e4e-5e6e-7e8e-9e0e-1a2b3c4d5e6f',
title: 'Custom AI Avatar Video',
description: 'Personalized AI avatar speaking your script. Ideal for corporate training or welcome videos.',
price: 299.00,
category: 'Video Ads',
image: 'https://images.pexels.com/photos/6146978/pexels-photo-6146978.jpeg',
createdAt: new Date(),
updatedAt: new Date(),
},
];
const courses = [
{
id: '4e2e3e4e-5e6e-7e8e-9e0e-1a2b3c4d5e6f',
title: 'Introduction to Generative AI',
description: 'Learn the fundamentals of LLMs, Image Generation, and how AI is changing industries.',
price: 99.00,
level: 'Beginner',
duration: '4 weeks',
image: 'https://images.pexels.com/photos/8386440/pexels-photo-8386440.jpeg',
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: '5e2e3e4e-5e6e-7e8e-9e0e-1a2b3c4d5e6f',
title: 'Mastering Stable Diffusion',
description: 'Deep dive into prompt engineering, LoRA training, and advanced image generation techniques.',
price: 199.00,
level: 'Intermediate',
duration: '6 weeks',
image: 'https://images.pexels.com/photos/17483874/pexels-photo-17483874.jpeg',
createdAt: new Date(),
updatedAt: new Date(),
},
];
await queryInterface.bulkInsert('services', services);
await queryInterface.bulkInsert('courses', courses);
},
async down(queryInterface, Sequelize) {
await queryInterface.bulkDelete('services', null, {});
await queryInterface.bulkDelete('courses', null, {});
}
};

View File

@ -1,4 +1,3 @@
const express = require('express');
const cors = require('cors');
const app = express();
@ -19,6 +18,9 @@ const pexelsRoutes = require('./routes/pexels');
const openaiRoutes = require('./routes/openai');
const servicesRoutes = require('./routes/services');
const coursesRoutes = require('./routes/courses');
const ordersRoutes = require('./routes/orders');
const usersRoutes = require('./routes/users');
@ -94,6 +96,10 @@ app.use('/api/file', fileRoutes);
app.use('/api/pexels', pexelsRoutes);
app.enable('trust proxy');
app.use('/api/services', servicesRoutes);
app.use('/api/courses', coursesRoutes);
app.use('/api/orders', ordersRoutes);
app.use('/api/users', passport.authenticate('jwt', {session: false}), usersRoutes);
@ -155,4 +161,4 @@ db.sequelize.sync().then(function () {
});
});
module.exports = app;
module.exports = app;

View File

@ -201,7 +201,7 @@ router.get('/signin/microsoft/callback', passport.authenticate("microsoft", {
router.use('/', require('../helpers').commonErrorHandler);
function socialRedirect(res, state, token, config) {
res.redirect(config.uiUrl + "/login?token=" + token);
res.redirect("/login?token=" + token);
}
module.exports = router;
module.exports = router;

View File

@ -0,0 +1,16 @@
const express = require('express');
const db = require('../db/models');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
router.get('/', wrapAsync(async (req, res) => {
const courses = await db.courses.findAll();
res.status(200).send({ rows: courses, count: courses.length });
}));
router.get('/:id', wrapAsync(async (req, res) => {
const course = await db.courses.findByPk(req.params.id);
res.status(200).send(course);
}));
module.exports = router;

View File

@ -0,0 +1,11 @@
const express = require('express');
const db = require('../db/models');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
router.post('/', wrapAsync(async (req, res) => {
const order = await db.orders.create(req.body.data);
res.status(200).send(order);
}));
module.exports = router;

View File

@ -0,0 +1,16 @@
const express = require('express');
const db = require('../db/models');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
router.get('/', wrapAsync(async (req, res) => {
const services = await db.services.findAll();
res.status(200).send({ rows: services, count: services.length });
}));
router.get('/:id', wrapAsync(async (req, res) => {
const service = await db.services.findByPk(req.params.id);
res.status(200).send(service);
}));
module.exports = router;

View File

@ -0,0 +1,147 @@
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import CardBox from '../CardBox';
import { Pie, Bar } from 'react-chartjs-2';
import {
Chart as ChartJS,
ArcElement,
Tooltip,
Legend,
CategoryScale,
LinearScale,
BarElement,
Title,
} from 'chart.js';
ChartJS.register(
ArcElement,
Tooltip,
Legend,
CategoryScale,
LinearScale,
BarElement,
Title
);
const DashboardCharts = () => {
const [statusData, setStatusData] = useState<any>(null);
const [priorityData, setPriorityData] = useState<any>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
const [statusRes, priorityRes] = await Promise.all([
axios.post('/sql', {
sql: 'SELECT status, COUNT(*) as count FROM tasks WHERE "deletedAt" IS NULL GROUP BY status',
}),
axios.post('/sql', {
sql: 'SELECT priority, COUNT(*) as count FROM tasks WHERE "deletedAt" IS NULL GROUP BY priority',
}),
]);
const statuses = statusRes.data.rows;
const priorities = priorityRes.data.rows;
setStatusData({
labels: statuses.map((s: any) => s.status || 'No Status'),
datasets: [
{
label: 'Tasks by Status',
data: statuses.map((s: any) => parseInt(s.count)),
backgroundColor: [
'#6366f1', // todo
'#f59e0b', // in_progress
'#ec4899', // review
'#10b981', // done
'#ef4444', // blocked
],
borderWidth: 1,
},
],
});
setPriorityData({
labels: priorities.map((p: any) => p.priority || 'No Priority'),
datasets: [
{
label: 'Tasks by Priority',
data: priorities.map((p: any) => parseInt(p.count)),
backgroundColor: '#6366f1',
borderRadius: 8,
},
],
});
} catch (error) {
console.error('Failed to fetch chart data:', error);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
if (loading) {
return (
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2 mb-6">
<CardBox className="h-80 animate-pulse bg-gray-100 dark:bg-gray-800" />
<CardBox className="h-80 animate-pulse bg-gray-100 dark:bg-gray-800" />
</div>
);
}
return (
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2 mb-6">
<CardBox className="flex flex-col">
<h3 className="text-lg font-bold mb-4 text-gray-700 dark:text-gray-200">Task Status Distribution</h3>
<div className="h-64 flex justify-center">
{statusData && (
<Pie
data={statusData}
options={{
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'right',
},
},
}}
/>
)}
</div>
</CardBox>
<CardBox className="flex flex-col">
<h3 className="text-lg font-bold mb-4 text-gray-700 dark:text-gray-200">Tasks by Priority</h3>
<div className="h-64">
{priorityData && (
<Bar
data={priorityData}
options={{
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
ticks: {
stepSize: 1,
},
},
},
plugins: {
legend: {
display: false,
},
},
}}
/>
)}
</div>
</CardBox>
</div>
);
};
export default DashboardCharts;

View File

@ -0,0 +1,107 @@
import React, { useEffect, useState } from 'react';
import * as icon from '@mdi/js';
import axios from 'axios';
import BaseIcon from '../BaseIcon';
import CardBox from '../CardBox';
import { useAppSelector } from '../../stores/hooks';
const DashboardStats = () => {
const [stats, setStats] = useState({
projects_count: 0,
tasks_count: 0,
completed_tasks_count: 0,
active_tasks_count: 0,
users_count: 0,
});
const [loading, setLoading] = useState(true);
const iconsColor = useAppSelector((state) => state.style.iconsColor);
useEffect(() => {
const fetchStats = async () => {
try {
const sql = `
SELECT
(SELECT COUNT(*) FROM projects WHERE "deletedAt" IS NULL) as projects_count,
(SELECT COUNT(*) FROM tasks WHERE "deletedAt" IS NULL) as tasks_count,
(SELECT COUNT(*) FROM tasks WHERE status = 'done' AND "deletedAt" IS NULL) as completed_tasks_count,
(SELECT COUNT(*) FROM tasks WHERE status IN ('todo', 'in_progress') AND "deletedAt" IS NULL) as active_tasks_count,
(SELECT COUNT(*) FROM users WHERE "deletedAt" IS NULL) as users_count
`;
const { data } = await axios.post('/sql', { sql });
if (data.rows && data.rows.length > 0) {
setStats(data.rows[0]);
}
} catch (error) {
console.error('Failed to fetch dashboard stats:', error);
} finally {
setLoading(false);
}
};
fetchStats();
}, []);
const statItems = [
{
label: 'Projects',
value: stats.projects_count,
icon: icon.mdiFolder,
color: 'text-blue-500',
},
{
label: 'Total Tasks',
value: stats.tasks_count,
icon: icon.mdiFormatListCheckbox,
color: 'text-indigo-500',
},
{
label: 'Active Tasks',
value: stats.active_tasks_count,
icon: icon.mdiProgressClock,
color: 'text-orange-500',
},
{
label: 'Completed',
value: stats.completed_tasks_count,
icon: icon.mdiCheckCircle,
color: 'text-emerald-500',
},
];
if (loading) {
return (
<div className="grid grid-cols-1 gap-6 lg:grid-cols-4 mb-6">
{[1, 2, 3, 4].map((i) => (
<CardBox key={i} className="animate-pulse">
<div className="h-16 bg-gray-200 dark:bg-gray-700 rounded"></div>
</CardBox>
))}
</div>
);
}
return (
<div className="grid grid-cols-1 gap-6 lg:grid-cols-4 mb-6">
{statItems.map((item, index) => (
<CardBox key={index} isHoverable>
<div className="flex justify-between items-center">
<div>
<p className="text-sm text-gray-500 dark:text-gray-400 font-medium uppercase tracking-wider">
{item.label}
</p>
<h3 className="text-3xl font-bold mt-1 text-gray-900 dark:text-white">
{item.value}
</h3>
</div>
<div className={`${item.color} bg-opacity-10 p-3 rounded-xl`}>
<BaseIcon path={item.icon} size={32} />
</div>
</div>
</CardBox>
))}
</div>
);
};
export default DashboardStats;

View File

@ -0,0 +1,114 @@
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import CardBox from '../CardBox';
import Link from 'next/link';
import BaseIcon from '../BaseIcon';
import * as icon from '@mdi/js';
const RecentTasks = () => {
const [tasks, setTasks] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchRecentTasks = async () => {
try {
const sql = `
SELECT t.id, t.title, t.status, t.priority, p.title as project_title
FROM tasks t
LEFT JOIN projects p ON t."projectId" = p.id
WHERE t."deletedAt" IS NULL
ORDER BY t."createdAt" DESC
LIMIT 5
`;
const { data } = await axios.post('/sql', { sql });
setTasks(data.rows || []);
} catch (error) {
console.error('Failed to fetch recent tasks:', error);
} finally {
setLoading(false);
}
};
fetchRecentTasks();
}, []);
const getStatusColor = (status: string) => {
switch (status) {
case 'done':
return 'bg-emerald-100 text-emerald-700';
case 'in_progress':
return 'bg-amber-100 text-amber-700';
case 'blocked':
return 'bg-rose-100 text-rose-700';
case 'todo':
return 'bg-blue-100 text-blue-700';
default:
return 'bg-gray-100 text-gray-700';
}
};
if (loading) {
return (
<CardBox className="mb-6 animate-pulse">
<div className="h-40 bg-gray-100 dark:bg-gray-800 rounded"></div>
</CardBox>
);
}
return (
<CardBox className="mb-6">
<div className="flex justify-between items-center mb-4">
<h3 className="text-lg font-bold text-gray-700 dark:text-gray-200">Recent Tasks</h3>
<Link href="/tasks/tasks-list" className="text-sm text-indigo-600 hover:text-indigo-700 font-medium">
View all tasks
</Link>
</div>
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse">
<thead>
<tr className="border-b border-gray-100 dark:border-gray-800">
<th className="py-3 px-4 text-xs font-semibold text-gray-500 uppercase tracking-wider">Task</th>
<th className="py-3 px-4 text-xs font-semibold text-gray-500 uppercase tracking-wider">Project</th>
<th className="py-3 px-4 text-xs font-semibold text-gray-500 uppercase tracking-wider">Status</th>
<th className="py-3 px-4 text-xs font-semibold text-gray-500 uppercase tracking-wider">Priority</th>
</tr>
</thead>
<tbody>
{tasks.length > 0 ? (
tasks.map((task) => (
<tr key={task.id} className="border-b border-gray-50 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
<td className="py-3 px-4">
<span className="text-sm font-medium text-gray-900 dark:text-gray-100">{task.title}</span>
</td>
<td className="py-3 px-4">
<span className="text-sm text-gray-500 dark:text-gray-400">{task.project_title || 'No Project'}</span>
</td>
<td className="py-3 px-4">
<span className={`text-xs font-bold px-2 py-1 rounded-full uppercase ${getStatusColor(task.status)}`}>
{task.status?.replace('_', ' ')}
</span>
</td>
<td className="py-3 px-4">
<div className="flex items-center text-sm text-gray-500">
<BaseIcon path={icon.mdiFlagVariant} size={16} className="mr-1" />
{task.priority}
</div>
</td>
</tr>
))
) : (
<tr>
<td colSpan={4} className="py-8 text-center text-gray-500">
No tasks found. Start by creating a project and adding tasks!
</td>
</tr>
)}
</tbody>
</table>
</div>
</CardBox>
);
};
export default RecentTasks;

View File

@ -15,6 +15,10 @@ import { fetchWidgets } from '../stores/roles/rolesSlice';
import { WidgetCreator } from '../components/WidgetCreator/WidgetCreator';
import { SmartWidget } from '../components/SmartWidget/SmartWidget';
import DashboardStats from '../components/Dashboard/DashboardStats';
import DashboardCharts from '../components/Dashboard/DashboardCharts';
import RecentTasks from '../components/Dashboard/RecentTasks';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
const Dashboard = () => {
const dispatch = useAppDispatch();
@ -94,11 +98,23 @@ const Dashboard = () => {
<SectionMain>
<SectionTitleLineWithButton
icon={icon.mdiChartTimelineVariant}
title='Overview'
title='Dashboard Overview'
main>
{''}
</SectionTitleLineWithButton>
{/* Professional Dashboard Sections */}
<DashboardStats />
<DashboardCharts />
<RecentTasks />
<SectionTitleLineWithButton
icon={icon.mdiWidgetsOutline}
title='Custom Widgets'
>
{''}
</SectionTitleLineWithButton>
{hasPermission(currentUser, 'CREATE_ROLES') && <WidgetCreator
currentUser={currentUser}
isFetchingQuery={isFetchingQuery}
@ -140,6 +156,13 @@ const Dashboard = () => {
{!!rolesWidgets.length && <hr className='my-6 ' />}
<SectionTitleLineWithButton
icon={icon.mdiDatabaseOutline}
title='System Counters'
>
{''}
</SectionTitleLineWithButton>
<div id="dashboard" className='grid grid-cols-1 gap-6 lg:grid-cols-3 mb-6'>
@ -378,4 +401,4 @@ Dashboard.getLayout = function getLayout(page: ReactElement) {
return <LayoutAuthenticated>{page}</LayoutAuthenticated>
}
export default Dashboard
export default Dashboard

View File

@ -1,166 +1,195 @@
import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import BaseButton from '../components/BaseButton';
import CardBox from '../components/CardBox';
import SectionFullScreen from '../components/SectionFullScreen';
import LayoutGuest from '../layouts/Guest';
import BaseDivider from '../components/BaseDivider';
import BaseButtons from '../components/BaseButtons';
import { getPageTitle } from '../config';
import { useAppSelector } from '../stores/hooks';
import CardBoxComponentTitle from "../components/CardBoxComponentTitle";
import { getPexelsImage, getPexelsVideo } from '../helpers/pexels';
import SectionMain from '../components/SectionMain';
import { mdiVideo, mdiSchool, mdiBrain, mdiArrowRight } from '@mdi/js';
import BaseIcon from '../components/BaseIcon';
import axios from 'axios';
export default function LandingPage() {
const title = 'GenAI Ads & Academy';
const [services, setServices] = useState([]);
const [courses, setCourses] = useState([]);
export default function Starter() {
const [illustrationImage, setIllustrationImage] = useState({
src: undefined,
photographer: undefined,
photographer_url: undefined,
})
const [illustrationVideo, setIllustrationVideo] = useState({video_files: []})
const [contentType, setContentType] = useState('video');
const [contentPosition, setContentPosition] = useState('left');
const textColor = useAppSelector((state) => state.style.linkColor);
const title = 'App Draft'
// Fetch Pexels image/video
useEffect(() => {
async function fetchData() {
const image = await getPexelsImage();
const video = await getPexelsVideo();
setIllustrationImage(image);
setIllustrationVideo(video);
}
fetchData();
}, []);
const imageBlock = (image) => (
<div
className='hidden md:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/3'
style={{
backgroundImage: `${
image
? `url(${image?.src?.original})`
: 'linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5))'
}`,
backgroundSize: 'cover',
backgroundPosition: 'left center',
backgroundRepeat: 'no-repeat',
}}
>
<div className='flex justify-center w-full bg-blue-300/20'>
<a
className='text-[8px]'
href={image?.photographer_url}
target='_blank'
rel='noreferrer'
>
Photo by {image?.photographer} on Pexels
</a>
</div>
</div>
);
const videoBlock = (video) => {
if (video?.video_files?.length > 0) {
return (
<div className='hidden md:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/3'>
<video
className='absolute top-0 left-0 w-full h-full object-cover'
autoPlay
loop
muted
>
<source src={video?.video_files[0]?.link} type='video/mp4'/>
Your browser does not support the video tag.
</video>
<div className='flex justify-center w-full bg-blue-300/20 z-10'>
<a
className='text-[8px]'
href={video?.user?.url}
target='_blank'
rel='noreferrer'
>
Video by {video.user.name} on Pexels
</a>
</div>
</div>)
}
};
useEffect(() => {
axios.get('/services').then((res) => setServices(res.data.rows || []));
axios.get('/courses').then((res) => setCourses(res.data.rows || []));
}, []);
return (
<div
style={
contentPosition === 'background'
? {
backgroundImage: `${
illustrationImage
? `url(${illustrationImage.src?.original})`
: 'linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5))'
}`,
backgroundSize: 'cover',
backgroundPosition: 'left center',
backgroundRepeat: 'no-repeat',
}
: {}
}
>
<div className="bg-white min-h-screen">
<Head>
<title>{getPageTitle('Starter Page')}</title>
<title>{getPageTitle('GenAI Services & Courses')}</title>
</Head>
<SectionFullScreen bg='violet'>
<div
className={`flex ${
contentPosition === 'right' ? 'flex-row-reverse' : 'flex-row'
} min-h-screen w-full`}
>
{contentType === 'image' && contentPosition !== 'background'
? imageBlock(illustrationImage)
: null}
{contentType === 'video' && contentPosition !== 'background'
? videoBlock(illustrationVideo)
: null}
<div className='flex items-center justify-center flex-col space-y-4 w-full lg:w-full'>
<CardBox className='w-full md:w-3/5 lg:w-2/3'>
<CardBoxComponentTitle title="Welcome to your App Draft app!"/>
<div className="space-y-3">
<p className='text-center text-gray-500'>This is a React.js/Node.js app generated by the <a className={`${textColor}`} href="https://flatlogic.com/generator">Flatlogic Web App Generator</a></p>
<p className='text-center text-gray-500'>For guides and documentation please check
your local README.md and the <a className={`${textColor}`} href="https://flatlogic.com/documentation">Flatlogic documentation</a></p>
{/* Navigation */}
<nav className="border-b border-gray-100 py-4 bg-white/80 backdrop-blur-md sticky top-0 z-50">
<div className="max-w-7xl mx-auto px-6 flex justify-between items-center">
<div className="flex items-center space-x-2">
<div className="bg-indigo-600 p-1.5 rounded-lg">
<BaseIcon path={mdiBrain} size={20} color="white" />
</div>
<BaseButtons>
<BaseButton
href='/login'
label='Login'
color='info'
className='w-full'
/>
</BaseButtons>
</CardBox>
<span className="text-xl font-bold tracking-tight text-gray-900">{title}</span>
</div>
<div className="flex items-center space-x-8">
<Link href="#services" className="text-sm font-medium text-gray-600 hover:text-indigo-600">Services</Link>
<Link href="#courses" className="text-sm font-medium text-gray-600 hover:text-indigo-600">Courses</Link>
</div>
</div>
</div>
</SectionFullScreen>
<div className='bg-black text-white flex flex-col text-center justify-center md:flex-row'>
<p className='py-6 text-sm'>© 2026 <span>{title}</span>. All rights reserved</p>
<Link className='py-6 ml-4 text-sm' href='/privacy-policy/'>
Privacy Policy
</Link>
</nav>
{/* Hero Section */}
<div className="relative overflow-hidden pt-16 pb-32">
<div className="absolute top-0 left-1/2 -translate-x-1/2 w-[1000px] h-[600px] bg-indigo-50/50 rounded-full blur-3xl -z-10 animate-pulse"></div>
<SectionMain>
<div className="flex flex-col items-center text-center space-y-8 max-w-4xl mx-auto">
<div className="inline-flex items-center space-x-2 bg-indigo-50 border border-indigo-100 px-3 py-1 rounded-full text-indigo-700 text-sm font-medium">
<span>Next-Gen Content Creation</span>
</div>
<h1 className="text-5xl md:text-7xl font-extrabold text-gray-900 tracking-tight leading-tight">
Elevate your brand with <br />
<span className="text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 to-emerald-500">
Generative AI
</span>
</h1>
<p className="text-xl text-gray-600 max-w-2xl leading-relaxed">
We create high-converting video ads and provide professional training
to help you master the latest AI tools for business.
</p>
<div className="flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4 w-full justify-center pt-4">
<Link href="#services">
<BaseButton
label="Our Services"
color="info"
className="px-10 py-4 text-lg font-bold"
rounded="rounded-xl"
icon={mdiVideo}
/>
</Link>
<Link href="#courses">
<BaseButton
label="Join Academy"
color="whiteDark"
outline
className="px-10 py-4 text-lg font-bold"
rounded="rounded-xl"
icon={mdiSchool}
/>
</Link>
</div>
</div>
</SectionMain>
</div>
{/* Services Section */}
<div id="services" className="bg-gray-50 py-24">
<SectionMain>
<div className="text-center mb-16">
<h2 className="text-4xl font-bold text-gray-900 mb-4">Video Ad Services</h2>
<p className="text-gray-600 max-w-2xl mx-auto">Professional AI-generated video content that grabs attention and drives conversions.</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
{services.map((service: any) => (
<div key={service.id} className="bg-white rounded-2xl overflow-hidden shadow-sm border border-gray-100 hover:shadow-lg transition-all flex flex-col">
<div className="h-48 bg-gray-200 relative">
<img src={service.image} alt={service.title} className="w-full h-full object-cover" />
<div className="absolute top-4 right-4 bg-indigo-600 text-white px-3 py-1 rounded-full text-sm font-bold shadow-lg">
${service.price}
</div>
</div>
<div className="p-8 flex-grow">
<h3 className="text-xl font-bold text-gray-900 mb-3">{service.title}</h3>
<p className="text-gray-600 text-sm mb-6 leading-relaxed">
{service.description}
</p>
<div className="mt-auto">
<Link href={`/order?type=service&id=${service.id}`}>
<BaseButton label="Inquire Now" color="info" outline className="w-full" rounded="rounded-lg" />
</Link>
</div>
</div>
</div>
))}
</div>
</SectionMain>
</div>
{/* Courses Section */}
<div id="courses" className="py-24">
<SectionMain>
<div className="text-center mb-16">
<h2 className="text-4xl font-bold text-gray-900 mb-4">Gen AI Academy</h2>
<p className="text-gray-600 max-w-2xl mx-auto">Master the future of work with our expert-led AI courses and workshops.</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-12">
{courses.map((course: any) => (
<div key={course.id} className="flex flex-col md:flex-row bg-white rounded-3xl overflow-hidden border border-gray-100 shadow-sm hover:shadow-md transition-shadow">
<div className="md:w-1/2 h-64 md:h-auto">
<img src={course.image} alt={course.title} className="w-full h-full object-cover" />
</div>
<div className="md:w-1/2 p-8 flex flex-col justify-center">
<div className="flex items-center space-x-2 text-indigo-600 text-xs font-bold uppercase tracking-wider mb-2">
<BaseIcon path={mdiBrain} size={14} />
<span>{course.level} {course.duration}</span>
</div>
<h3 className="text-2xl font-bold text-gray-900 mb-4">{course.title}</h3>
<p className="text-gray-600 mb-6 text-sm">
{course.description}
</p>
<div className="flex items-center justify-between mt-auto">
<span className="text-2xl font-black text-gray-900">${course.price}</span>
<Link href={`/order?type=course&id=${course.id}`}>
<BaseButton label="Enroll Now" color="info" rounded="rounded-lg" icon={mdiArrowRight} />
</Link>
</div>
</div>
</div>
))}
</div>
</SectionMain>
</div>
{/* CTA Section */}
<div className="py-24 bg-gray-900">
<SectionMain>
<div className="rounded-3xl p-12 text-center text-white relative overflow-hidden shadow-xl border border-white/10">
<div className="absolute -top-24 -right-24 w-64 h-64 bg-indigo-500/20 rounded-full blur-2xl"></div>
<div className="absolute -bottom-24 -left-24 w-64 h-64 bg-emerald-500/10 rounded-full blur-2xl"></div>
<h2 className="text-4xl font-bold mb-6 relative z-10 text-white">Ready to Transform Your Workflow?</h2>
<p className="text-gray-400 mb-10 text-lg max-w-xl mx-auto relative z-10">
Whether you need high-end production or hands-on training, we have the AI expertise to help you scale.
</p>
</div>
</SectionMain>
</div>
{/* Footer */}
<footer className="border-t border-gray-100 py-12">
<div className="max-w-7xl mx-auto px-6 flex flex-col md:flex-row justify-between items-center space-y-6 md:space-y-0">
<div className="flex items-center space-x-2 opacity-50">
<span className="text-lg font-bold tracking-tight text-gray-900">{title}</span>
<span className="text-sm text-gray-500">© 2026</span>
</div>
<div className="flex space-x-8 text-sm font-medium text-gray-500">
<Link href="#" className="hover:text-gray-900">Terms</Link>
<Link href="#" className="hover:text-gray-900">Privacy</Link>
<Link href="#" className="hover:text-gray-900">Contact</Link>
</div>
</div>
</footer>
</div>
);
}
Starter.getLayout = function getLayout(page: ReactElement) {
LandingPage.getLayout = function getLayout(page: ReactElement) {
return <LayoutGuest>{page}</LayoutGuest>;
};
};

View File

@ -1,12 +1,10 @@
import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import BaseButton from '../components/BaseButton';
import CardBox from '../components/CardBox';
import BaseIcon from "../components/BaseIcon";
import { mdiInformation, mdiEye, mdiEyeOff } from '@mdi/js';
import { mdiEye, mdiEyeOff, mdiGoogle } from '@mdi/js';
import SectionFullScreen from '../components/SectionFullScreen';
import LayoutGuest from '../layouts/Guest';
import { Field, Form, Formik } from 'formik';
@ -16,7 +14,7 @@ import BaseDivider from '../components/BaseDivider';
import BaseButtons from '../components/BaseButtons';
import { useRouter } from 'next/router';
import { getPageTitle } from '../config';
import { findMe, loginUser, resetAction } from '../stores/authSlice';
import { findMe, loginUser, resetAction, setToken } from '../stores/authSlice';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import Link from 'next/link';
import {toast, ToastContainer} from "react-toastify";
@ -26,7 +24,6 @@ export default function Login() {
const router = useRouter();
const dispatch = useAppDispatch();
const textColor = useAppSelector((state) => state.style.linkColor);
const iconsColor = useAppSelector((state) => state.style.iconsColor);
const notify = (type, msg) => toast(msg, { type });
const [ illustrationImage, setIllustrationImage ] = useState({
src: undefined,
@ -40,8 +37,8 @@ export default function Login() {
const { currentUser, isFetching, errorMessage, token, notify:notifyState } = useAppSelector(
(state) => state.auth,
);
const [initialValues, setInitialValues] = React.useState({ email:'admin@flatlogic.com',
password: '2f79a9f5',
const [initialValues, setInitialValues] = React.useState({ email:'',
password: '',
remember: true })
const title = 'App Draft'
@ -56,6 +53,15 @@ export default function Login() {
}
fetchData();
}, []);
// Handle token from social login
useEffect(() => {
if (router.query.token) {
dispatch(setToken(router.query.token));
router.push('/dashboard');
}
}, [router.query.token, dispatch, router]);
// Fetch user data
useEffect(() => {
if (token) {
@ -92,14 +98,6 @@ export default function Login() {
await dispatch(loginUser(rest));
};
const setLogin = (target: HTMLElement) => {
setInitialValues(prev => ({
...prev,
email : target.innerText.trim(),
password: target.dataset.password ?? '',
}));
};
const imageBlock = (image) => (
<div className="hidden md:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/3"
style={{
@ -163,39 +161,8 @@ export default function Login() {
{contentType === 'video' && contentPosition !== 'background' ? videoBlock(illustrationVideo) : null}
<div className='flex items-center justify-center flex-col space-y-4 w-full lg:w-full'>
<CardBox id="loginRoles" className='w-full md:w-3/5 lg:w-2/3'>
<h2 className="text-4xl font-semibold my-4">{title}</h2>
<div className='flex flex-row text-gray-500 justify-between'>
<div>
<p className='mb-2'>Use{' '}
<code className={`cursor-pointer ${textColor} `}
data-password="2f79a9f5"
onClick={(e) => setLogin(e.target)}>admin@flatlogic.com</code>{' / '}
<code className={`${textColor}`}>2f79a9f5</code>{' / '}
to login as Admin</p>
<p>Use <code
className={`cursor-pointer ${textColor} `}
data-password="4b6d7f9aa842"
onClick={(e) => setLogin(e.target)}>client@hello.com</code>{' / '}
<code className={`${textColor}`}>4b6d7f9aa842</code>{' / '}
to login as User</p>
</div>
<div>
<BaseIcon
className={`${iconsColor}`}
w='w-16'
h='h-16'
size={48}
path={mdiInformation}
/>
</div>
</div>
</CardBox>
<CardBox className='w-full md:w-3/5 lg:w-2/3'>
<h2 className="text-4xl font-semibold my-4">{title}</h2>
<Formik
initialValues={initialValues}
enableReinitialize
@ -247,6 +214,19 @@ export default function Login() {
disabled={isFetching}
/>
</BaseButtons>
<BaseDivider />
<BaseButtons>
<BaseButton
className={'w-full'}
label={'Sign in with Google'}
color='danger'
icon={mdiGoogle}
onClick={() => window.location.href = '/api/auth/signin/google'}
/>
</BaseButtons>
<br />
<p className={'text-center'}>
Dont have an account yet?{' '}

View File

@ -0,0 +1,169 @@
import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import LayoutGuest from '../layouts/Guest';
import SectionMain from '../components/SectionMain';
import CardBox from '../components/CardBox';
import FormField from '../components/FormField';
import BaseButton from '../components/BaseButton';
import { getPageTitle } from '../config';
import axios from 'axios';
import { mdiCheckCircleOutline, mdiArrowLeft } from '@mdi/js';
import BaseIcon from '../components/BaseIcon';
import Link from 'next/link';
export default function OrderPage() {
const router = useRouter();
const { type, id } = router.query;
const [item, setItem] = useState<any>(null);
const [formData, setFormData] = useState({
customerName: '',
customerEmail: '',
message: '',
});
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
useEffect(() => {
if (id && type) {
const endpoint = type === 'service' ? `/services/${id}` : `/courses/${id}`;
axios.get(endpoint).then((res) => setItem(res.data));
}
}, [id, type]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
try {
await axios.post('/orders', {
data: {
customerName: formData.customerName,
customerEmail: formData.customerEmail,
message: formData.message,
totalAmount: item?.price || 0,
itemType: type,
itemId: id,
status: 'pending',
},
});
setIsSuccess(true);
} catch (error) {
console.error('Order failed', error);
alert('Something went wrong. Please try again.');
} finally {
setIsSubmitting(false);
}
};
if (isSuccess) {
return (
<div className="bg-gray-50 min-h-screen flex items-center justify-center p-6">
<Head>
<title>{getPageTitle('Thank You')}</title>
</Head>
<CardBox className="max-w-md w-full text-center p-12">
<div className="text-emerald-500 mb-6 flex justify-center">
<BaseIcon path={mdiCheckCircleOutline} size={64} />
</div>
<h1 className="text-3xl font-bold text-gray-900 mb-4">Request Sent!</h1>
<p className="text-gray-600 mb-8">
Thank you for your interest in <strong>{item?.title}</strong>.
Our team will contact you at <strong>{formData.customerEmail}</strong> shortly.
</p>
<Link href="/">
<BaseButton label="Back to Home" color="info" rounded="rounded-lg" />
</Link>
</CardBox>
</div>
);
}
return (
<div className="bg-gray-50 min-h-screen py-12">
<Head>
<title>{getPageTitle(type === 'service' ? 'Inquire' : 'Enroll')}</title>
</Head>
<SectionMain>
<div className="max-w-4xl mx-auto">
<Link href="/" className="inline-flex items-center text-indigo-600 font-medium mb-8 hover:underline">
<BaseIcon path={mdiArrowLeft} size={20} className="mr-1" />
Back to listings
</Link>
<div className="grid grid-cols-1 md:grid-cols-2 gap-12">
<div>
<h1 className="text-4xl font-extrabold text-gray-900 mb-6">
{type === 'service' ? 'Service Inquiry' : 'Course Enrollment'}
</h1>
<p className="text-gray-600 mb-8 leading-relaxed">
Please fill out the form and our specialist will get back to you with the next steps and payment details.
</p>
{item && (
<CardBox className="bg-white border-2 border-indigo-100">
<div className="flex items-start space-x-4">
<img src={item.image} alt="" className="w-20 h-20 rounded-lg object-cover" />
<div>
<h3 className="font-bold text-gray-900">{item.title}</h3>
<p className="text-sm text-gray-500 mb-2">{item.category || item.level}</p>
<span className="text-xl font-black text-indigo-600">${item.price}</span>
</div>
</div>
</CardBox>
)}
</div>
<CardBox isForm onSubmit={handleSubmit}>
<FormField label="Your Full Name" help="Please enter your name">
<input
type="text"
placeholder="John Doe"
className="w-full h-11 px-4 rounded-lg border border-gray-300 focus:ring-2 focus:ring-indigo-600 focus:border-transparent outline-none transition-all"
required
value={formData.customerName}
onChange={(e) => setFormData({ ...formData, customerName: e.target.value })}
/>
</FormField>
<FormField label="Email Address" help="We'll use this to contact you">
<input
type="email"
placeholder="john@example.com"
className="w-full h-11 px-4 rounded-lg border border-gray-300 focus:ring-2 focus:ring-indigo-600 focus:border-transparent outline-none transition-all"
required
value={formData.customerEmail}
onChange={(e) => setFormData({ ...formData, customerEmail: e.target.value })}
/>
</FormField>
<FormField label="Additional Notes (Optional)">
<textarea
className="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-indigo-600 focus:border-transparent outline-none transition-all min-h-[120px]"
placeholder="Tell us about your project or any specific requirements..."
value={formData.message}
onChange={(e) => setFormData({ ...formData, message: e.target.value })}
/>
</FormField>
<div className="pt-4">
<BaseButton
type="submit"
label={isSubmitting ? 'Sending...' : (type === 'service' ? 'Send Inquiry' : 'Enroll Now')}
color="info"
className="w-full py-3 text-lg font-bold"
rounded="rounded-xl"
disabled={isSubmitting}
/>
</div>
</CardBox>
</div>
</div>
</SectionMain>
</div>
);
}
OrderPage.getLayout = function getLayout(page: ReactElement) {
return <LayoutGuest>{page}</LayoutGuest>;
};

View File

@ -1,4 +1,4 @@
import React from 'react';
import React, { useEffect } from 'react';
import type { ReactElement } from 'react';
import { ToastContainer, toast } from 'react-toastify';
import Head from 'next/head';
@ -12,14 +12,25 @@ import BaseDivider from '../components/BaseDivider';
import BaseButtons from '../components/BaseButtons';
import { useRouter } from 'next/router';
import { getPageTitle } from '../config';
import { mdiGoogle } from '@mdi/js';
import { setToken } from '../stores/authSlice';
import { useAppDispatch } from '../stores/hooks';
import axios from "axios";
export default function Register() {
const [loading, setLoading] = React.useState(false);
const router = useRouter();
const dispatch = useAppDispatch();
const notify = (type, msg) => toast( msg, {type, position: "bottom-center"});
// Handle token from social login
useEffect(() => {
if (router.query.token) {
dispatch(setToken(router.query.token));
router.push('/dashboard');
}
}, [router.query.token, dispatch, router]);
const handleSubmit = async (value) => {
setLoading(true)
@ -68,14 +79,34 @@ export default function Register() {
<BaseButtons>
<BaseButton
className='w-full'
type='submit'
label={loading ? 'Loading...' : 'Register' }
color='info'
/>
</BaseButtons>
<BaseDivider />
<BaseButtons>
<BaseButton
className='w-full'
label={'Sign in with Google'}
color='danger'
icon={mdiGoogle}
onClick={() => window.location.href = '/api/auth/signin/google'}
/>
</BaseButtons>
<BaseDivider />
<BaseButtons>
<BaseButton
className='w-full'
href={'/login'}
label={'Login'}
label={'Back to Login'}
color='info'
outline
/>
</BaseButtons>
</Form>
@ -89,4 +120,4 @@ export default function Register() {
Register.getLayout = function getLayout(page: ReactElement) {
return <LayoutGuest>{page}</LayoutGuest>;
};
};

View File

@ -77,6 +77,14 @@ export const authSlice = createSlice({
state.currentUser = null;
state.token = '';
},
setToken: (state, action) => {
const token = action.payload;
const user = jwt.decode(token);
state.token = token;
localStorage.setItem('token', token);
localStorage.setItem('user', JSON.stringify(user));
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}
},
extraReducers: (builder) => {
builder.addCase(loginUser.pending, (state) => {
@ -119,6 +127,6 @@ export const authSlice = createSlice({
});
// Action creators are generated for each case reducer function
export const { logoutUser } = authSlice.actions;
export const { logoutUser, setToken } = authSlice.actions;
export default authSlice.reducer;
export default authSlice.reducer;

View File

@ -20,18 +20,12 @@ export const loginSteps: Step[] = [
intro: `
<div class="text-center text-black ">
<img src="https://flatlogic.com/blog/wp-content/uploads/2024/10/good_img.png" alt="Description" class="w-full mb-2 object-cover" />
<p>Welcome to our app tutorial! Get a sneak peek into the key functionalities and learn how to navigate seamlessly. Here's a quick overview to get you started.</p>
<p>Welcome to our app! Here's a quick overview to get you started.</p>
</div>
`,
position: 'auto',
tooltipClass: ' good-img',
},
{
element: '#loginRoles',
intro:
'Choose your login role to proceed. Experience the app as Admin, or User, or create your own account to get started.',
position: 'auto',
},
];
export const appSteps: Step[] = [
@ -135,5 +129,4 @@ export const rolesSteps: Step[] = [
position: 'auto',
tooltipClass: 'end-img',
},
];
];