Autosave: 20260130-190414
This commit is contained in:
parent
6603ec27a8
commit
3c06dbfb70
@ -68,7 +68,7 @@ module.exports = class ProductsDBApi {
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
sellerId: data.sellerId || null,
|
||||
importHash: data.importHash || null,
|
||||
createdById: currentUser.id,
|
||||
updatedById: currentUser.id,
|
||||
@ -153,7 +153,7 @@ module.exports = class ProductsDBApi {
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
sellerId: item.sellerId || null,
|
||||
importHash: item.importHash || null,
|
||||
createdById: currentUser.id,
|
||||
updatedById: currentUser.id,
|
||||
@ -220,6 +220,7 @@ module.exports = class ProductsDBApi {
|
||||
|
||||
if (data.updated_on !== undefined) updatePayload.updated_on = data.updated_on;
|
||||
|
||||
if (data.sellerId !== undefined) updatePayload.sellerId = data.sellerId;
|
||||
|
||||
updatePayload.updatedById = currentUser.id;
|
||||
|
||||
@ -448,6 +449,13 @@ module.exports = class ProductsDBApi {
|
||||
};
|
||||
}
|
||||
|
||||
if (filter.sellerId) {
|
||||
where = {
|
||||
...where,
|
||||
sellerId: Utils.uuid(filter.sellerId),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
if (filter.title) {
|
||||
where = {
|
||||
@ -705,5 +713,24 @@ module.exports = class ProductsDBApi {
|
||||
}));
|
||||
}
|
||||
|
||||
static async getRecommendations(productId, limit = 4) {
|
||||
const product = await db.products.findByPk(productId);
|
||||
if (!product) return [];
|
||||
|
||||
return db.products.findAll({
|
||||
where: {
|
||||
id: { [Op.ne]: productId },
|
||||
categoryId: product.categoryId,
|
||||
active: true
|
||||
},
|
||||
include: [
|
||||
{ model: db.file, as: 'images' },
|
||||
{ model: db.categories, as: 'category' }
|
||||
],
|
||||
limit: Number(limit),
|
||||
order: db.sequelize.random() // Random recommendations from same category
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
};
|
||||
@ -1,4 +1,4 @@
|
||||
|
||||
require('dotenv').config();
|
||||
|
||||
module.exports = {
|
||||
production: {
|
||||
@ -12,11 +12,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 +31,4 @@ module.exports = {
|
||||
logging: console.log,
|
||||
seederStorage: 'sequelize',
|
||||
}
|
||||
};
|
||||
};
|
||||
16
backend/src/db/migrations/1769795556.js
Normal file
16
backend/src/db/migrations/1769795556.js
Normal file
@ -0,0 +1,16 @@
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.addColumn('products', 'sale_price', {
|
||||
type: Sequelize.DECIMAL,
|
||||
allowNull: true,
|
||||
});
|
||||
await queryInterface.addColumn('products', 'sale_ends_at', {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
});
|
||||
},
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.removeColumn('products', 'sale_price');
|
||||
await queryInterface.removeColumn('products', 'sale_ends_at');
|
||||
}
|
||||
};
|
||||
56
backend/src/db/migrations/1769796000.js
Normal file
56
backend/src/db/migrations/1769796000.js
Normal file
@ -0,0 +1,56 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.createTable('discount_codes', {
|
||||
id: {
|
||||
type: Sequelize.UUID,
|
||||
defaultValue: Sequelize.UUIDV4,
|
||||
primaryKey: true,
|
||||
},
|
||||
code: {
|
||||
type: Sequelize.STRING,
|
||||
allowNull: false,
|
||||
unique: true,
|
||||
},
|
||||
type: {
|
||||
type: Sequelize.ENUM('percent', 'fixed'),
|
||||
allowNull: false,
|
||||
defaultValue: 'percent',
|
||||
},
|
||||
value: {
|
||||
type: Sequelize.DECIMAL(10, 2),
|
||||
allowNull: false,
|
||||
},
|
||||
min_purchase: {
|
||||
type: Sequelize.DECIMAL(10, 2),
|
||||
defaultValue: 0,
|
||||
},
|
||||
starts_at: {
|
||||
type: Sequelize.DATE,
|
||||
},
|
||||
expires_at: {
|
||||
type: Sequelize.DATE,
|
||||
},
|
||||
active: {
|
||||
type: Sequelize.BOOLEAN,
|
||||
defaultValue: true,
|
||||
},
|
||||
createdAt: {
|
||||
allowNull: false,
|
||||
type: Sequelize.DATE,
|
||||
},
|
||||
updatedAt: {
|
||||
allowNull: false,
|
||||
type: Sequelize.DATE,
|
||||
},
|
||||
deletedAt: {
|
||||
type: Sequelize.DATE,
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.dropTable('discount_codes');
|
||||
},
|
||||
};
|
||||
61
backend/src/db/migrations/1769796284.js
Normal file
61
backend/src/db/migrations/1769796284.js
Normal file
@ -0,0 +1,61 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.createTable('page_views', {
|
||||
id: {
|
||||
type: Sequelize.UUID,
|
||||
defaultValue: Sequelize.UUIDV4,
|
||||
primaryKey: true,
|
||||
},
|
||||
productId: {
|
||||
type: Sequelize.UUID,
|
||||
references: {
|
||||
model: 'products',
|
||||
key: 'id',
|
||||
},
|
||||
onUpdate: 'CASCADE',
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
categoryId: {
|
||||
type: Sequelize.UUID,
|
||||
references: {
|
||||
model: 'categories',
|
||||
key: 'id',
|
||||
},
|
||||
onUpdate: 'CASCADE',
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
userId: {
|
||||
type: Sequelize.UUID,
|
||||
references: {
|
||||
model: 'users',
|
||||
key: 'id',
|
||||
},
|
||||
onUpdate: 'CASCADE',
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
ipAddress: {
|
||||
type: Sequelize.STRING,
|
||||
},
|
||||
userAgent: {
|
||||
type: Sequelize.TEXT,
|
||||
},
|
||||
createdAt: {
|
||||
allowNull: false,
|
||||
type: Sequelize.DATE,
|
||||
},
|
||||
updatedAt: {
|
||||
allowNull: false,
|
||||
type: Sequelize.DATE,
|
||||
},
|
||||
deletedAt: {
|
||||
type: Sequelize.DATE,
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.dropTable('page_views');
|
||||
},
|
||||
};
|
||||
81
backend/src/db/migrations/1769797000.js
Normal file
81
backend/src/db/migrations/1769797000.js
Normal file
@ -0,0 +1,81 @@
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const tableUsers = await queryInterface.describeTable('users');
|
||||
if (!tableUsers.shopName) {
|
||||
await queryInterface.addColumn('users', 'shopName', {
|
||||
type: Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
});
|
||||
}
|
||||
if (!tableUsers.shopDescription) {
|
||||
await queryInterface.addColumn('users', 'shopDescription', {
|
||||
type: Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
});
|
||||
}
|
||||
if (!tableUsers.sellerStatus) {
|
||||
await queryInterface.addColumn('users', 'sellerStatus', {
|
||||
type: Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
defaultValue: 'none',
|
||||
});
|
||||
}
|
||||
|
||||
const tableProducts = await queryInterface.describeTable('products');
|
||||
if (!tableProducts.sellerId) {
|
||||
await queryInterface.addColumn('products', 'sellerId', {
|
||||
type: Sequelize.UUID,
|
||||
references: {
|
||||
model: 'users',
|
||||
key: 'id',
|
||||
},
|
||||
onUpdate: 'CASCADE',
|
||||
onDelete: 'SET NULL',
|
||||
allowNull: true,
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const sellerRoleId = 'd3b3b3b3-b3b3-4b3b-b3b3-b3b3b3b3b3b3';
|
||||
|
||||
// Check if Seller role exists
|
||||
const [existingRoles] = await queryInterface.sequelize.query(
|
||||
`SELECT id FROM roles WHERE name = 'Seller' LIMIT 1`
|
||||
);
|
||||
|
||||
if (existingRoles.length === 0) {
|
||||
await queryInterface.bulkInsert('roles', [{
|
||||
id: sellerRoleId,
|
||||
name: 'Seller',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}]);
|
||||
}
|
||||
|
||||
// Grant permissions to Seller
|
||||
const permissions = await queryInterface.sequelize.query(
|
||||
`SELECT id FROM permissions WHERE name IN ('CREATE_PRODUCTS', 'READ_PRODUCTS', 'UPDATE_PRODUCTS', 'DELETE_PRODUCTS', 'READ_CATEGORIES')`
|
||||
);
|
||||
|
||||
if (permissions[0].length > 0) {
|
||||
const rolePermissions = permissions[0].map((p, i) => ({
|
||||
id: `e3b3b3b3-b3b3-4b3b-b3b3-b3b3b3b3b3b${i}`,
|
||||
roles_permissionsId: sellerRoleId,
|
||||
permissionId: p.id,
|
||||
createdAt: now,
|
||||
updatedAt: now
|
||||
}));
|
||||
|
||||
// Use a try-catch to ignore duplicates in junction table
|
||||
try {
|
||||
await queryInterface.bulkInsert('rolesPermissionsPermissions', rolePermissions);
|
||||
} catch (e) {
|
||||
console.log('Role permissions might already exist, skipping...');
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
// Standard down migration
|
||||
},
|
||||
};
|
||||
51
backend/src/db/models/discount_codes.js
Normal file
51
backend/src/db/models/discount_codes.js
Normal file
@ -0,0 +1,51 @@
|
||||
module.exports = function(sequelize, DataTypes) {
|
||||
const discount_codes = sequelize.define(
|
||||
'discount_codes',
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.UUID,
|
||||
defaultValue: DataTypes.UUIDV4,
|
||||
primaryKey: true,
|
||||
},
|
||||
code: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false,
|
||||
unique: true,
|
||||
},
|
||||
type: {
|
||||
type: DataTypes.ENUM('percent', 'fixed'),
|
||||
allowNull: false,
|
||||
defaultValue: 'percent',
|
||||
},
|
||||
value: {
|
||||
type: DataTypes.DECIMAL(10, 2),
|
||||
allowNull: false,
|
||||
},
|
||||
min_purchase: {
|
||||
type: DataTypes.DECIMAL(10, 2),
|
||||
defaultValue: 0,
|
||||
},
|
||||
starts_at: {
|
||||
type: DataTypes.DATE,
|
||||
},
|
||||
expires_at: {
|
||||
type: DataTypes.DATE,
|
||||
},
|
||||
active: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
defaultValue: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
paranoid: true,
|
||||
freezeTableName: true,
|
||||
},
|
||||
);
|
||||
|
||||
discount_codes.associate = () => {
|
||||
// Add associations if needed
|
||||
};
|
||||
|
||||
return discount_codes;
|
||||
};
|
||||
42
backend/src/db/models/page_views.js
Normal file
42
backend/src/db/models/page_views.js
Normal file
@ -0,0 +1,42 @@
|
||||
module.exports = function(sequelize, DataTypes) {
|
||||
const page_views = sequelize.define(
|
||||
'page_views',
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.UUID,
|
||||
defaultValue: DataTypes.UUIDV4,
|
||||
primaryKey: true,
|
||||
},
|
||||
ipAddress: {
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
userAgent: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
paranoid: true,
|
||||
freezeTableName: true,
|
||||
},
|
||||
);
|
||||
|
||||
page_views.associate = (db) => {
|
||||
db.page_views.belongsTo(db.users, {
|
||||
as: 'user',
|
||||
foreignKey: 'userId',
|
||||
});
|
||||
|
||||
db.page_views.belongsTo(db.products, {
|
||||
as: 'product',
|
||||
foreignKey: 'productId',
|
||||
});
|
||||
|
||||
db.page_views.belongsTo(db.categories, {
|
||||
as: 'category',
|
||||
foreignKey: 'categoryId',
|
||||
});
|
||||
};
|
||||
|
||||
return page_views;
|
||||
};
|
||||
@ -1,108 +1,119 @@
|
||||
const config = require('../../config');
|
||||
const providers = config.providers;
|
||||
const crypto = require('crypto');
|
||||
const bcrypt = require('bcrypt');
|
||||
const moment = require('moment');
|
||||
|
||||
module.exports = function(sequelize, DataTypes) {
|
||||
const products = sequelize.define(
|
||||
'products',
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.UUID,
|
||||
defaultValue: DataTypes.UUIDV4,
|
||||
primaryKey: true,
|
||||
},
|
||||
title: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
slug: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
description: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
price: {
|
||||
type: DataTypes.DECIMAL,
|
||||
},
|
||||
sku: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
stock: {
|
||||
type: DataTypes.INTEGER,
|
||||
},
|
||||
active: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
allowNull: false,
|
||||
defaultValue: false,
|
||||
},
|
||||
created_on: {
|
||||
type: DataTypes.DATE,
|
||||
},
|
||||
updated_on: {
|
||||
type: DataTypes.DATE,
|
||||
},
|
||||
importHash: {
|
||||
type: DataTypes.STRING(255),
|
||||
allowNull: true,
|
||||
unique: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
paranoid: true,
|
||||
freezeTableName: true,
|
||||
},
|
||||
);
|
||||
|
||||
products.associate = (db) => {
|
||||
db.products.hasMany(db.reviews, {
|
||||
as: 'reviews',
|
||||
foreignKey: 'productId',
|
||||
});
|
||||
|
||||
db.products.hasMany(db.order_items, {
|
||||
as: 'order_items_product',
|
||||
foreignKey: {
|
||||
name: 'productId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.products.hasMany(db.cart_items, {
|
||||
as: 'cart_items_product',
|
||||
foreignKey: {
|
||||
name: 'productId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.products.belongsTo(db.categories, {
|
||||
as: 'category',
|
||||
foreignKey: {
|
||||
name: 'categoryId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.products.hasMany(db.file, {
|
||||
as: 'images',
|
||||
foreignKey: 'belongsToId',
|
||||
constraints: false,
|
||||
scope: {
|
||||
belongsTo: db.products.getTableName(),
|
||||
belongsToColumn: 'images',
|
||||
},
|
||||
const config = require('../../config');
|
||||
const providers = config.providers;
|
||||
const crypto = require('crypto');
|
||||
const bcrypt = require('bcrypt');
|
||||
const moment = require('moment');
|
||||
|
||||
module.exports = function(sequelize, DataTypes) {
|
||||
const products = sequelize.define(
|
||||
'products',
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.UUID,
|
||||
defaultValue: DataTypes.UUIDV4,
|
||||
primaryKey: true,
|
||||
},
|
||||
title: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
slug: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
description: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
price: {
|
||||
type: DataTypes.DECIMAL,
|
||||
},
|
||||
sale_price: {
|
||||
type: DataTypes.DECIMAL,
|
||||
},
|
||||
sale_ends_at: {
|
||||
type: DataTypes.DATE,
|
||||
},
|
||||
sku: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
stock: {
|
||||
type: DataTypes.INTEGER,
|
||||
},
|
||||
active: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
allowNull: false,
|
||||
defaultValue: false,
|
||||
},
|
||||
created_on: {
|
||||
type: DataTypes.DATE,
|
||||
},
|
||||
updated_on: {
|
||||
type: DataTypes.DATE,
|
||||
},
|
||||
importHash: {
|
||||
type: DataTypes.STRING(255),
|
||||
allowNull: true,
|
||||
unique: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
paranoid: true,
|
||||
freezeTableName: true,
|
||||
},
|
||||
);
|
||||
|
||||
products.associate = (db) => {
|
||||
db.products.hasMany(db.reviews, {
|
||||
as: 'reviews',
|
||||
foreignKey: 'productId',
|
||||
});
|
||||
|
||||
db.products.hasMany(db.order_items, {
|
||||
as: 'order_items_product',
|
||||
foreignKey: {
|
||||
name: 'productId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.products.hasMany(db.cart_items, {
|
||||
as: 'cart_items_product',
|
||||
foreignKey: {
|
||||
name: 'productId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.products.belongsTo(db.categories, {
|
||||
as: 'category',
|
||||
foreignKey: {
|
||||
name: 'categoryId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.products.belongsTo(db.users, {
|
||||
as: 'createdBy',
|
||||
});
|
||||
|
||||
db.products.belongsTo(db.users, {
|
||||
as: 'updatedBy',
|
||||
});
|
||||
};
|
||||
|
||||
return products;
|
||||
as: 'seller',
|
||||
foreignKey: 'sellerId',
|
||||
});
|
||||
|
||||
db.products.hasMany(db.file, {
|
||||
as: 'images',
|
||||
foreignKey: 'belongsToId',
|
||||
constraints: false,
|
||||
scope: {
|
||||
belongsTo: db.products.getTableName(),
|
||||
belongsToColumn: 'images',
|
||||
},
|
||||
});
|
||||
|
||||
db.products.belongsTo(db.users, {
|
||||
as: 'createdBy',
|
||||
});
|
||||
|
||||
db.products.belongsTo(db.users, {
|
||||
as: 'updatedBy',
|
||||
});
|
||||
};
|
||||
|
||||
return products;
|
||||
};
|
||||
@ -1,198 +1,213 @@
|
||||
const config = require('../../config');
|
||||
const providers = config.providers;
|
||||
const crypto = require('crypto');
|
||||
const bcrypt = require('bcrypt');
|
||||
const moment = require('moment');
|
||||
|
||||
module.exports = function(sequelize, DataTypes) {
|
||||
const users = sequelize.define(
|
||||
'users',
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.UUID,
|
||||
defaultValue: DataTypes.UUIDV4,
|
||||
primaryKey: true,
|
||||
const config = require('../../config');
|
||||
const providers = config.providers;
|
||||
const crypto = require('crypto');
|
||||
const bcrypt = require('bcrypt');
|
||||
const moment = require('moment');
|
||||
|
||||
module.exports = function(sequelize, DataTypes) {
|
||||
const users = sequelize.define(
|
||||
'users',
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.UUID,
|
||||
defaultValue: DataTypes.UUIDV4,
|
||||
primaryKey: true,
|
||||
},
|
||||
|
||||
firstName: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
lastName: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
phoneNumber: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
email: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
disabled: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
allowNull: false,
|
||||
defaultValue: false,
|
||||
},
|
||||
|
||||
password: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
emailVerified: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
allowNull: false,
|
||||
defaultValue: false,
|
||||
},
|
||||
|
||||
emailVerificationToken: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
emailVerificationTokenExpiresAt: {
|
||||
type: DataTypes.DATE,
|
||||
},
|
||||
|
||||
passwordResetToken: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
passwordResetTokenExpiresAt: {
|
||||
type: DataTypes.DATE,
|
||||
},
|
||||
|
||||
provider: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
importHash: {
|
||||
type: DataTypes.STRING(255),
|
||||
allowNull: true,
|
||||
unique: true,
|
||||
},
|
||||
|
||||
address: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
city: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
zipCode: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
country: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
firstName: {
|
||||
shopName: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
lastName: {
|
||||
shopDescription: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
phoneNumber: {
|
||||
sellerStatus: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
email: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
disabled: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
allowNull: false,
|
||||
defaultValue: false,
|
||||
},
|
||||
|
||||
password: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
emailVerified: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
allowNull: false,
|
||||
defaultValue: false,
|
||||
},
|
||||
|
||||
emailVerificationToken: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
emailVerificationTokenExpiresAt: {
|
||||
type: DataTypes.DATE,
|
||||
},
|
||||
|
||||
passwordResetToken: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
passwordResetTokenExpiresAt: {
|
||||
type: DataTypes.DATE,
|
||||
},
|
||||
|
||||
provider: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
importHash: {
|
||||
type: DataTypes.STRING(255),
|
||||
allowNull: true,
|
||||
unique: true,
|
||||
},
|
||||
|
||||
address: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
city: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
zipCode: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
|
||||
country: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
paranoid: true,
|
||||
freezeTableName: true,
|
||||
},
|
||||
);
|
||||
|
||||
users.associate = (db) => {
|
||||
db.users.belongsToMany(db.permissions, {
|
||||
as: 'custom_permissions',
|
||||
foreignKey: {
|
||||
name: 'users_custom_permissionsId',
|
||||
},
|
||||
constraints: false,
|
||||
through: 'usersCustom_permissionsPermissions',
|
||||
defaultValue: 'none',
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
paranoid: true,
|
||||
freezeTableName: true,
|
||||
},
|
||||
);
|
||||
|
||||
users.associate = (db) => {
|
||||
db.users.belongsToMany(db.permissions, {
|
||||
as: 'custom_permissions',
|
||||
foreignKey: {
|
||||
name: 'users_custom_permissionsId',
|
||||
},
|
||||
constraints: false,
|
||||
through: 'usersCustom_permissionsPermissions',
|
||||
});
|
||||
|
||||
db.users.belongsToMany(db.permissions, {
|
||||
as: 'custom_permissions_filter',
|
||||
foreignKey: {
|
||||
name: 'users_custom_permissionsId',
|
||||
},
|
||||
constraints: false,
|
||||
through: 'usersCustom_permissionsPermissions',
|
||||
});
|
||||
|
||||
db.users.hasMany(db.reviews, {
|
||||
as: 'reviews',
|
||||
foreignKey: 'userId',
|
||||
});
|
||||
|
||||
db.users.hasMany(db.orders, {
|
||||
as: 'orders_user',
|
||||
foreignKey: {
|
||||
name: 'userId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.users.hasMany(db.carts, {
|
||||
as: 'carts_user',
|
||||
foreignKey: {
|
||||
name: 'userId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.users.belongsTo(db.roles, {
|
||||
as: 'app_role',
|
||||
foreignKey: {
|
||||
name: 'app_roleId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.users.hasMany(db.file, {
|
||||
as: 'avatar',
|
||||
foreignKey: 'belongsToId',
|
||||
constraints: false,
|
||||
scope: {
|
||||
belongsTo: db.users.getTableName(),
|
||||
belongsToColumn: 'avatar',
|
||||
},
|
||||
});
|
||||
|
||||
db.users.belongsToMany(db.permissions, {
|
||||
as: 'custom_permissions_filter',
|
||||
foreignKey: {
|
||||
name: 'users_custom_permissionsId',
|
||||
},
|
||||
constraints: false,
|
||||
through: 'usersCustom_permissionsPermissions',
|
||||
});
|
||||
|
||||
db.users.hasMany(db.reviews, {
|
||||
as: 'reviews',
|
||||
foreignKey: 'userId',
|
||||
});
|
||||
|
||||
db.users.hasMany(db.orders, {
|
||||
as: 'orders_user',
|
||||
foreignKey: {
|
||||
name: 'userId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.users.hasMany(db.carts, {
|
||||
as: 'carts_user',
|
||||
foreignKey: {
|
||||
name: 'userId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.users.belongsTo(db.roles, {
|
||||
as: 'app_role',
|
||||
foreignKey: {
|
||||
name: 'app_roleId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.users.hasMany(db.file, {
|
||||
as: 'avatar',
|
||||
foreignKey: 'belongsToId',
|
||||
constraints: false,
|
||||
scope: {
|
||||
belongsTo: db.users.getTableName(),
|
||||
belongsToColumn: 'avatar',
|
||||
},
|
||||
});
|
||||
|
||||
db.users.belongsTo(db.users, {
|
||||
as: 'createdBy',
|
||||
});
|
||||
|
||||
db.users.belongsTo(db.users, {
|
||||
as: 'updatedBy',
|
||||
});
|
||||
};
|
||||
|
||||
users.beforeCreate((users, options) => {
|
||||
users = trimStringFields(users);
|
||||
|
||||
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
|
||||
users.emailVerified = true;
|
||||
|
||||
if (!users.password) {
|
||||
const password = crypto
|
||||
.randomBytes(20)
|
||||
.toString('hex');
|
||||
|
||||
const hashedPassword = bcrypt.hashSync(
|
||||
password,
|
||||
config.bcrypt.saltRounds,
|
||||
);
|
||||
|
||||
users.password = hashedPassword
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
users.beforeUpdate((users, options) => {
|
||||
users = trimStringFields(users);
|
||||
});
|
||||
|
||||
return users;
|
||||
};
|
||||
|
||||
function trimStringFields(users) {
|
||||
users.email = users.email.trim();
|
||||
users.firstName = users.firstName ? users.firstName.trim() : null;
|
||||
users.lastName = users.lastName ? users.lastName.trim() : null;
|
||||
return users;
|
||||
db.users.hasMany(db.products, {
|
||||
as: 'seller_products',
|
||||
foreignKey: 'sellerId',
|
||||
});
|
||||
|
||||
db.users.belongsTo(db.users, {
|
||||
as: 'createdBy',
|
||||
});
|
||||
|
||||
db.users.belongsTo(db.users, {
|
||||
as: 'updatedBy',
|
||||
});
|
||||
};
|
||||
|
||||
users.beforeCreate((users, options) => {
|
||||
users = trimStringFields(users);
|
||||
|
||||
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
|
||||
users.emailVerified = true;
|
||||
|
||||
if (!users.password) {
|
||||
const password = crypto
|
||||
.randomBytes(20)
|
||||
.toString('hex');
|
||||
|
||||
const hashedPassword = bcrypt.hashSync(
|
||||
password,
|
||||
config.bcrypt.saltRounds,
|
||||
);
|
||||
|
||||
users.password = hashedPassword
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
users.beforeUpdate((users, options) => {
|
||||
users = trimStringFields(users);
|
||||
});
|
||||
|
||||
return users;
|
||||
};
|
||||
|
||||
function trimStringFields(users) {
|
||||
users.email = users.email.trim();
|
||||
users.firstName = users.firstName ? users.firstName.trim() : null;
|
||||
users.lastName = users.lastName ? users.lastName.trim() : null;
|
||||
return users;
|
||||
}
|
||||
24
backend/src/db/seeders/1769795566.js
Normal file
24
backend/src/db/seeders/1769795566.js
Normal file
@ -0,0 +1,24 @@
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const products = await queryInterface.sequelize.query(
|
||||
`SELECT id FROM products LIMIT 5;`
|
||||
);
|
||||
|
||||
if (products[0].length > 0) {
|
||||
const now = new Date();
|
||||
const saleEnd = new Date(now.getTime() + (24 * 60 * 60 * 1000)); // 24 hours from now
|
||||
|
||||
for (const product of products[0]) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE products SET sale_price = price * 0.8, sale_ends_at = '${saleEnd.toISOString()}' WHERE id = '${product.id}';`
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE products SET sale_price = NULL, sale_ends_at = NULL;`
|
||||
);
|
||||
}
|
||||
};
|
||||
36
backend/src/db/seeders/1769796010.js
Normal file
36
backend/src/db/seeders/1769796010.js
Normal file
@ -0,0 +1,36 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
return queryInterface.bulkInsert('discount_codes', [
|
||||
{
|
||||
id: '99999999-9999-9999-9999-999999999991',
|
||||
code: 'SAVE10',
|
||||
type: 'percent',
|
||||
value: 10.00,
|
||||
min_purchase: 50.00,
|
||||
starts_at: new Date(),
|
||||
expires_at: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
|
||||
active: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
{
|
||||
id: '99999999-9999-9999-9999-999999999992',
|
||||
code: 'WELCOME20',
|
||||
type: 'fixed',
|
||||
value: 20.00,
|
||||
min_purchase: 100.00,
|
||||
starts_at: new Date(),
|
||||
expires_at: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
|
||||
active: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
}
|
||||
]);
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
return queryInterface.bulkDelete('discount_codes', null, {});
|
||||
}
|
||||
};
|
||||
@ -32,6 +32,7 @@ const wishlistsRoutes = require('./routes/wishlists');
|
||||
|
||||
const categoriesRoutes = require('./routes/categories');
|
||||
|
||||
const aiRecommendationsRoutes = require('./routes/aiRecommendations');
|
||||
const ordersRoutes = require('./routes/orders');
|
||||
|
||||
const order_itemsRoutes = require('./routes/order_items');
|
||||
@ -42,6 +43,8 @@ const cart_itemsRoutes = require('./routes/cart_items');
|
||||
|
||||
const paymentsRoutes = require('./routes/payments');
|
||||
const checkoutRoutes = require('./routes/checkout');
|
||||
const analyticsRoutes = require('./routes/analytics');
|
||||
const sellerRoutes = require('./routes/seller');
|
||||
|
||||
|
||||
const getBaseUrl = (url) => {
|
||||
@ -124,6 +127,9 @@ app.use('/api/cart_items', passport.authenticate('jwt', {session: false}), cart_
|
||||
|
||||
app.use('/api/payments', passport.authenticate('jwt', {session: false}), paymentsRoutes);
|
||||
app.use('/api/checkout', (req, res, next) => { if (req.path === '/webhook') return next(); passport.authenticate('jwt', {session: false}, (err, user) => { req.currentUser = user; next(); })(req, res, next); }, checkoutRoutes);
|
||||
app.use('/api/analytics', analyticsRoutes);
|
||||
app.use('/api/seller', sellerRoutes);
|
||||
app.use('/api/recommendations', aiRecommendationsRoutes);
|
||||
|
||||
app.use(
|
||||
'/api/openai',
|
||||
|
||||
23
backend/src/routes/aiRecommendations.js
Normal file
23
backend/src/routes/aiRecommendations.js
Normal file
@ -0,0 +1,23 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const AIRecommendationsService = require('../services/aiRecommendations');
|
||||
const { wrapAsync } = require('../helpers');
|
||||
const passport = require('passport');
|
||||
|
||||
router.get(
|
||||
'/',
|
||||
(req, res, next) => {
|
||||
passport.authenticate('jwt', { session: false }, (err, user) => {
|
||||
req.user = user || null;
|
||||
next();
|
||||
})(req, res, next);
|
||||
},
|
||||
wrapAsync(async (req, res) => {
|
||||
const userId = req.user ? req.user.id : null;
|
||||
const limit = parseInt(req.query.limit) || 4;
|
||||
const recommendations = await AIRecommendationsService.getRecommendations(userId, limit);
|
||||
res.status(200).send(recommendations);
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
34
backend/src/routes/analytics.js
Normal file
34
backend/src/routes/analytics.js
Normal file
@ -0,0 +1,34 @@
|
||||
const express = require('express');
|
||||
const passport = require('passport');
|
||||
const AnalyticsService = require('../services/analytics');
|
||||
const { wrapAsync } = require('../helpers');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.post(
|
||||
'/record',
|
||||
wrapAsync(async (req, res) => {
|
||||
const payload = await AnalyticsService.recordView(req.body, req);
|
||||
res.status(200).send(payload);
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/top-products',
|
||||
passport.authenticate('jwt', { session: false }),
|
||||
wrapAsync(async (req, res) => {
|
||||
const payload = await AnalyticsService.getTopProducts(req.query.limit);
|
||||
res.status(200).send(payload);
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/stats',
|
||||
passport.authenticate('jwt', { session: false }),
|
||||
wrapAsync(async (req, res) => {
|
||||
const payload = await AnalyticsService.getViewStats();
|
||||
res.status(200).send(payload);
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
@ -1,10 +1,9 @@
|
||||
|
||||
const express = require('express');
|
||||
|
||||
const CartsService = require('../services/carts');
|
||||
const CartsDBApi = require('../db/api/carts');
|
||||
const wrapAsync = require('../helpers').wrapAsync;
|
||||
|
||||
const AbandonedCartService = require('../services/notifications/abandonedCart');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@ -15,6 +14,11 @@ const {
|
||||
checkCrudPermissions,
|
||||
} = require('../middlewares/check-permissions');
|
||||
|
||||
router.post('/process-abandoned', wrapAsync(async (req, res) => {
|
||||
const result = await AbandonedCartService.processAbandonedCarts();
|
||||
res.status(200).send(result);
|
||||
}));
|
||||
|
||||
router.use(checkCrudPermissions('carts'));
|
||||
|
||||
|
||||
@ -426,4 +430,4 @@ router.get('/:id', wrapAsync(async (req, res) => {
|
||||
|
||||
router.use('/', require('../helpers').commonErrorHandler);
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
@ -3,34 +3,99 @@ const stripe = require('stripe');
|
||||
const config = require('../config');
|
||||
const wrapAsync = require('../helpers').wrapAsync;
|
||||
const db = require('../db/models');
|
||||
const { Op } = require('sequelize');
|
||||
const LowStockNotificationService = require('../services/notifications/lowStock');
|
||||
|
||||
const router = express.Router();
|
||||
// Initialize stripe only if key is available, or use a placeholder to avoid crash
|
||||
const stripeClient = config.stripe.secretKey ? stripe(config.stripe.secretKey) : null;
|
||||
|
||||
router.post('/validate-discount', wrapAsync(async (req, res) => {
|
||||
const { code, total } = req.body;
|
||||
|
||||
if (!code) {
|
||||
return res.status(400).send({ message: 'Discount code is required' });
|
||||
}
|
||||
|
||||
const discount = await db.discount_codes.findOne({
|
||||
where: {
|
||||
code: code,
|
||||
active: true,
|
||||
starts_at: { [Op.lte]: new Date() },
|
||||
expires_at: { [Op.gte]: new Date() },
|
||||
}
|
||||
});
|
||||
|
||||
if (!discount) {
|
||||
return res.status(404).send({ message: 'Invalid or expired discount code' });
|
||||
}
|
||||
|
||||
if (total < parseFloat(discount.min_purchase)) {
|
||||
return res.status(400).send({
|
||||
message: `Minimum purchase of $${discount.min_purchase} required for this code`
|
||||
});
|
||||
}
|
||||
|
||||
res.status(200).send(discount);
|
||||
}));
|
||||
|
||||
router.post('/create-session', wrapAsync(async (req, res) => {
|
||||
if (!stripeClient) {
|
||||
return res.status(500).send({ error: 'Stripe is not configured on the server' });
|
||||
}
|
||||
|
||||
const { items, successUrl, cancelUrl } = req.body;
|
||||
const { items, successUrl, cancelUrl, discountCode } = req.body;
|
||||
const currentUser = req.currentUser;
|
||||
|
||||
if (!items || items.length === 0) {
|
||||
return res.status(400).send({ error: 'No items in cart' });
|
||||
}
|
||||
|
||||
const lineItems = items.map(item => ({
|
||||
price_data: {
|
||||
currency: 'usd',
|
||||
product_data: {
|
||||
name: item.title,
|
||||
images: item.image ? [item.image] : [],
|
||||
let discount = null;
|
||||
if (discountCode) {
|
||||
discount = await db.discount_codes.findOne({
|
||||
where: {
|
||||
code: discountCode,
|
||||
active: true,
|
||||
starts_at: { [Op.lte]: new Date() },
|
||||
expires_at: { [Op.gte]: new Date() },
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const totalBeforeDiscount = items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
|
||||
let discountAmount = 0;
|
||||
|
||||
if (discount && totalBeforeDiscount >= parseFloat(discount.min_purchase)) {
|
||||
if (discount.type === 'percent') {
|
||||
discountAmount = totalBeforeDiscount * (parseFloat(discount.value) / 100);
|
||||
} else {
|
||||
discountAmount = parseFloat(discount.value);
|
||||
}
|
||||
}
|
||||
|
||||
// Cap discount at total
|
||||
discountAmount = Math.min(discountAmount, totalBeforeDiscount);
|
||||
|
||||
const lineItems = items.map(item => {
|
||||
const itemTotal = item.price * item.quantity;
|
||||
const ratio = itemTotal / totalBeforeDiscount;
|
||||
const itemDiscount = discountAmount * ratio;
|
||||
const discountedItemTotal = itemTotal - itemDiscount;
|
||||
const discountedUnitPrice = discountedItemTotal / item.quantity;
|
||||
|
||||
return {
|
||||
price_data: {
|
||||
currency: 'usd',
|
||||
product_data: {
|
||||
name: item.title,
|
||||
images: item.image ? [item.image] : [],
|
||||
},
|
||||
unit_amount: Math.max(0, Math.round(discountedUnitPrice * 100)),
|
||||
},
|
||||
unit_amount: Math.round(item.price * 100),
|
||||
},
|
||||
quantity: item.quantity,
|
||||
}));
|
||||
quantity: item.quantity,
|
||||
};
|
||||
});
|
||||
|
||||
const session = await stripeClient.checkout.sessions.create({
|
||||
payment_method_types: ['card'],
|
||||
@ -41,6 +106,8 @@ router.post('/create-session', wrapAsync(async (req, res) => {
|
||||
customer_email: currentUser ? currentUser.email : undefined,
|
||||
metadata: {
|
||||
userId: currentUser ? currentUser.id : 'guest',
|
||||
discountCode: discountCode || '',
|
||||
discountAmount: discountAmount.toString(),
|
||||
items: JSON.stringify(items.map(i => ({
|
||||
id: i.productId,
|
||||
quantity: i.quantity,
|
||||
@ -88,7 +155,7 @@ router.post('/webhook', async (req, res) => {
|
||||
userId: userId !== 'guest' ? userId : null,
|
||||
}, { transaction });
|
||||
|
||||
// Create Order Items
|
||||
// Create Order Items and update stock
|
||||
for (const item of items) {
|
||||
await db.order_items.create({
|
||||
orderId: order.id,
|
||||
@ -98,6 +165,18 @@ router.post('/webhook', async (req, res) => {
|
||||
total_price: item.price * item.quantity,
|
||||
name: item.title
|
||||
}, { transaction });
|
||||
|
||||
// Update product stock
|
||||
const product = await db.products.findByPk(item.id, { transaction });
|
||||
if (product) {
|
||||
const newStock = Math.max(0, (product.stock || 0) - item.quantity);
|
||||
await product.update({ stock: newStock }, { transaction });
|
||||
|
||||
// Check for low stock after transaction commits (async)
|
||||
transaction.afterCommit(() => {
|
||||
LowStockNotificationService.notify(product.id);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Create Payment record
|
||||
@ -111,7 +190,7 @@ router.post('/webhook', async (req, res) => {
|
||||
}, { transaction });
|
||||
|
||||
await transaction.commit();
|
||||
console.log('Order fulfilled successfully');
|
||||
console.log('Order fulfilled successfully and stock updated');
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
console.error('Order fulfillment failed:', error);
|
||||
@ -121,4 +200,4 @@ router.post('/webhook', async (req, res) => {
|
||||
res.json({ received: true });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
@ -1,4 +1,3 @@
|
||||
|
||||
const express = require('express');
|
||||
|
||||
const ProductsService = require('../services/products');
|
||||
@ -15,6 +14,11 @@ const {
|
||||
checkCrudPermissions,
|
||||
} = require('../middlewares/check-permissions');
|
||||
|
||||
router.get('/:id/recommendations', wrapAsync(async (req, res) => {
|
||||
const payload = await ProductsDBApi.getRecommendations(req.params.id, req.query.limit);
|
||||
res.status(200).send(payload);
|
||||
}));
|
||||
|
||||
router.use(checkCrudPermissions('products'));
|
||||
|
||||
|
||||
@ -441,4 +445,4 @@ router.get('/:id', wrapAsync(async (req, res) => {
|
||||
|
||||
router.use('/', require('../helpers').commonErrorHandler);
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
@ -1,37 +1,23 @@
|
||||
const express = require('express');
|
||||
const SearchService = require('../services/search');
|
||||
|
||||
const passport = require('passport');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const { checkCrudPermissions } = require('../middlewares/check-permissions');
|
||||
router.use(checkCrudPermissions('search'));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* path:
|
||||
* /api/search:
|
||||
* post:
|
||||
* summary: Search
|
||||
* description: Search results across multiple tables
|
||||
* requestBody:
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* searchQuery:
|
||||
* type: string
|
||||
* required:
|
||||
* - searchQuery
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Successful request
|
||||
* 400:
|
||||
* description: Invalid request
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.get('/autocomplete', async (req, res) => {
|
||||
const { query } = req.query;
|
||||
|
||||
// Try to get user if token present, but don't require it
|
||||
passport.authenticate('jwt', { session: false }, async (err, user) => {
|
||||
try {
|
||||
const results = await SearchService.autocomplete(query, user || null);
|
||||
res.json(results);
|
||||
} catch (error) {
|
||||
console.error('Autocomplete API Error:', error);
|
||||
res.status(500).json({ error: 'Internal Server Error' });
|
||||
}
|
||||
})(req, res);
|
||||
});
|
||||
|
||||
router.post('/', async (req, res) => {
|
||||
const { searchQuery } = req.body;
|
||||
@ -40,13 +26,15 @@ router.post('/', async (req, res) => {
|
||||
return res.status(400).json({ error: 'Please enter a search query' });
|
||||
}
|
||||
|
||||
try {
|
||||
const foundMatches = await SearchService.search(searchQuery, req.currentUser );
|
||||
res.json(foundMatches);
|
||||
} catch (error) {
|
||||
console.error('Internal Server Error', error);
|
||||
res.status(500).json({ error: 'Internal Server Error' });
|
||||
}
|
||||
});
|
||||
passport.authenticate('jwt', { session: false }, async (err, user) => {
|
||||
try {
|
||||
const foundMatches = await SearchService.search(searchQuery, user || null);
|
||||
res.json(foundMatches);
|
||||
} catch (error) {
|
||||
console.error('Search API Error', error);
|
||||
res.status(500).json({ error: 'Internal Server Error' });
|
||||
}
|
||||
})(req, res);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
|
||||
55
backend/src/routes/seller.js
Normal file
55
backend/src/routes/seller.js
Normal file
@ -0,0 +1,55 @@
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const SellerService = require('../services/seller');
|
||||
const { wrapAsync } = require('../helpers');
|
||||
const passport = require('passport');
|
||||
|
||||
router.post(
|
||||
'/apply',
|
||||
passport.authenticate('jwt', { session: false }),
|
||||
wrapAsync(async (req, res) => {
|
||||
const { shopName, shopDescription } = req.body;
|
||||
const result = await SellerService.apply(req.currentUser.id, { shopName, shopDescription });
|
||||
res.status(200).send(result);
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/status',
|
||||
passport.authenticate('jwt', { session: false }),
|
||||
wrapAsync(async (req, res) => {
|
||||
const result = await SellerService.getStatus(req.currentUser.id);
|
||||
res.status(200).send(result);
|
||||
})
|
||||
);
|
||||
|
||||
// Admin only: list pending applications
|
||||
router.get(
|
||||
'/admin/pending',
|
||||
passport.authenticate('jwt', { session: false }),
|
||||
wrapAsync(async (req, res) => {
|
||||
// Check if admin (simplified for now)
|
||||
if (req.currentUser.app_role.name !== 'Administrator') {
|
||||
return res.status(403).send({ message: 'Forbidden' });
|
||||
}
|
||||
const result = await SellerService.getPendingApplications();
|
||||
res.status(200).send(result);
|
||||
})
|
||||
);
|
||||
|
||||
// Admin only: approve/reject
|
||||
router.post(
|
||||
'/admin/review/:userId',
|
||||
passport.authenticate('jwt', { session: false }),
|
||||
wrapAsync(async (req, res) => {
|
||||
if (req.currentUser.app_role.name !== 'Administrator') {
|
||||
return res.status(403).send({ message: 'Forbidden' });
|
||||
}
|
||||
const { status } = req.body; // approved or rejected
|
||||
const result = await SellerService.reviewApplication(req.params.userId, status);
|
||||
res.status(200).send(result);
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
81
backend/src/services/aiRecommendations.js
Normal file
81
backend/src/services/aiRecommendations.js
Normal file
@ -0,0 +1,81 @@
|
||||
const { LocalAIApi, decodeJsonFromResponse } = require('../ai/LocalAIApi');
|
||||
const db = require('../db/models');
|
||||
|
||||
class AIRecommendationsService {
|
||||
static async getRecommendations(userId, limit = 4) {
|
||||
try {
|
||||
// 1. Get recent product views
|
||||
const recentViews = await db.page_views.findAll({
|
||||
where: { userId },
|
||||
include: [{ model: db.products, as: 'product' }],
|
||||
order: [['createdAt', 'DESC']],
|
||||
limit: 10
|
||||
});
|
||||
|
||||
// 2. Get current cart items
|
||||
const cart = await db.carts.findOne({
|
||||
where: { userId },
|
||||
include: [{
|
||||
model: db.cart_items,
|
||||
as: 'cart_items_cart',
|
||||
include: [{ model: db.products, as: 'product' }]
|
||||
}]
|
||||
});
|
||||
|
||||
const viewedProducts = [...new Set(recentViews.map(v => v.product?.title).filter(Boolean))];
|
||||
const cartProducts = cart?.cart_items_cart?.map(i => i.product?.title).filter(Boolean) || [];
|
||||
|
||||
if (viewedProducts.length === 0 && cartProducts.length === 0) {
|
||||
// Return top products as fallback
|
||||
return await db.products.findAll({ limit });
|
||||
}
|
||||
|
||||
// 3. Get all available product titles for catalog
|
||||
const allProducts = await db.products.findAll({ attributes: ['id', 'title'], limit: 50 });
|
||||
const productListString = allProducts.map(p => p.title).join(', ');
|
||||
|
||||
const prompt = `
|
||||
A user has viewed these products: ${viewedProducts.join(', ')}.
|
||||
They have these products in their cart: ${cartProducts.join(', ')}.
|
||||
Based on this, recommend up to ${limit} products from the following catalog: ${productListString}.
|
||||
Focus on similar categories or complementary items.
|
||||
Return ONLY a JSON array of strings containing the recommended product titles exactly as they appear in the catalog.
|
||||
`;
|
||||
|
||||
const aiResponse = await LocalAIApi.createResponse({
|
||||
input: [
|
||||
{ role: 'system', content: 'You are an e-commerce recommendation engine. Return only JSON array of strings.' },
|
||||
{ role: 'user', content: prompt }
|
||||
]
|
||||
});
|
||||
|
||||
if (aiResponse.success) {
|
||||
try {
|
||||
const recommendedTitles = decodeJsonFromResponse(aiResponse);
|
||||
if (Array.isArray(recommendedTitles)) {
|
||||
const recommendedProducts = await db.products.findAll({
|
||||
where: {
|
||||
title: { [db.Sequelize.Op.in]: recommendedTitles }
|
||||
},
|
||||
limit
|
||||
});
|
||||
if (recommendedProducts.length > 0) return recommendedProducts;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('AI JSON parse error:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Return some products if AI fails or no recommendations
|
||||
return await db.products.findAll({
|
||||
order: db.sequelize.random(),
|
||||
limit
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error in AIRecommendationsService:', error);
|
||||
return await db.products.findAll({ limit });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = AIRecommendationsService;
|
||||
78
backend/src/services/analytics.js
Normal file
78
backend/src/services/analytics.js
Normal file
@ -0,0 +1,78 @@
|
||||
const db = require('../db/models');
|
||||
const Sequelize = db.Sequelize;
|
||||
const Op = Sequelize.Op;
|
||||
|
||||
module.exports = class AnalyticsService {
|
||||
static async recordView(data, req) {
|
||||
return await db.page_views.create({
|
||||
productId: data.productId || null,
|
||||
categoryId: data.categoryId || null,
|
||||
userId: req.user ? req.user.id : null,
|
||||
ipAddress: req.ip,
|
||||
userAgent: req.headers['user-agent']
|
||||
});
|
||||
}
|
||||
|
||||
static async getTopProducts(limit = 5) {
|
||||
// Use a simpler query to avoid complex group by issues with nested includes
|
||||
const topViewedIds = await db.page_views.findAll({
|
||||
attributes: [
|
||||
'productId',
|
||||
[Sequelize.fn('COUNT', Sequelize.col('productId')), 'viewCount']
|
||||
],
|
||||
where: {
|
||||
productId: { [Op.ne]: null }
|
||||
},
|
||||
group: ['productId'],
|
||||
order: [[Sequelize.literal('"viewCount"'), 'DESC']],
|
||||
limit: Number(limit),
|
||||
raw: true
|
||||
});
|
||||
|
||||
if (topViewedIds.length === 0) return [];
|
||||
|
||||
const productIds = topViewedIds.map(v => v.productId);
|
||||
const products = await db.products.findAll({
|
||||
where: { id: { [Op.in]: productIds } },
|
||||
include: [{ model: db.file, as: 'images' }]
|
||||
});
|
||||
|
||||
// Map counts back to products
|
||||
return products.map(p => {
|
||||
const viewData = topViewedIds.find(v => v.productId === p.id);
|
||||
return {
|
||||
...p.get({ plain: true }),
|
||||
viewCount: viewData ? parseInt(viewData.viewCount) : 0
|
||||
};
|
||||
}).sort((a, b) => b.viewCount - a.viewCount);
|
||||
}
|
||||
|
||||
static async getViewStats() {
|
||||
const totalViews = await db.page_views.count();
|
||||
const productViews = await db.page_views.count({ where: { productId: { [Op.ne]: null } } });
|
||||
const categoryViews = await db.page_views.count({ where: { categoryId: { [Op.ne]: null } } });
|
||||
|
||||
// Last 7 days views
|
||||
const sevenDaysAgo = new Date();
|
||||
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
|
||||
|
||||
const dailyViews = await db.page_views.findAll({
|
||||
attributes: [
|
||||
[Sequelize.fn('DATE', Sequelize.col('createdAt')), 'date'],
|
||||
[Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
|
||||
],
|
||||
where: {
|
||||
createdAt: { [Op.gte]: sevenDaysAgo }
|
||||
},
|
||||
group: [Sequelize.fn('DATE', Sequelize.col('createdAt'))],
|
||||
order: [[Sequelize.fn('DATE', Sequelize.col('createdAt')), 'ASC']]
|
||||
});
|
||||
|
||||
return {
|
||||
totalViews,
|
||||
productViews,
|
||||
categoryViews,
|
||||
dailyViews
|
||||
};
|
||||
}
|
||||
};
|
||||
@ -0,0 +1,43 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Abandoned Cart</title>
|
||||
<style>
|
||||
body { font-family: sans-serif; line-height: 1.6; color: #333; }
|
||||
.container { width: 80%; margin: 20px auto; padding: 20px; border: 1px solid #ddd; border-radius: 8px; }
|
||||
.header { background-color: #f8f8f8; padding: 10px; text-align: center; border-bottom: 1px solid #ddd; }
|
||||
.content { padding: 20px; }
|
||||
.footer { font-size: 0.8em; color: #777; text-align: center; margin-top: 20px; }
|
||||
.button {
|
||||
background-color: #4F46E5;
|
||||
color: white !important;
|
||||
padding: 12px 24px;
|
||||
text-decoration: none;
|
||||
border-radius: 5px;
|
||||
display: inline-block;
|
||||
font-weight: bold;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h2>{appTitle}</h2>
|
||||
</div>
|
||||
<div class="content">
|
||||
<p>Hello {userName},</p>
|
||||
<p>We noticed you left some items in your shopping cart. Don't miss out on these great products!</p>
|
||||
<p>Click below to return to your cart and complete your purchase:</p>
|
||||
<p style="text-align: center; margin-top: 30px;">
|
||||
<a href="{cartUrl}" class="button">Return to Cart</a>
|
||||
</p>
|
||||
<p>If you have any questions, feel free to reply to this email.</p>
|
||||
<p>Thanks,<br>The {appTitle} team</p>
|
||||
</div>
|
||||
<div class="footer">
|
||||
© 2026 {appTitle}. All rights reserved.
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@ -0,0 +1,39 @@
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Low Stock Alert</title>
|
||||
<style>
|
||||
body { font-family: sans-serif; line-height: 1.6; color: #333; }
|
||||
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
||||
.header { background: #f44336; color: white; padding: 20px; text-align: center; border-radius: 8px 8px 0 0; }
|
||||
.content { padding: 20px; border: 1px solid #eee; border-top: none; border-radius: 0 0 8px 8px; }
|
||||
.product-card { background: #f9f9f9; padding: 15px; margin: 15px 0; border-radius: 8px; border-left: 5px solid #f44336; }
|
||||
.btn { display: inline-block; padding: 12px 24px; background: #2196f3; color: white; text-decoration: none; border-radius: 4px; font-weight: bold; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Low Stock Alert!</h1>
|
||||
</div>
|
||||
<div class="content">
|
||||
<p>Hello Admin,</p>
|
||||
<p>The following product is running low on stock and needs your attention:</p>
|
||||
|
||||
<div class="product-card">
|
||||
<h2 style="margin-top: 0;">{{productTitle}}</h2>
|
||||
<p><strong>Current Stock:</strong> <span style="color: #f44336; font-size: 1.2em;">{{currentStock}}</span></p>
|
||||
<p><strong>SKU:</strong> {{productSku}}</p>
|
||||
</div>
|
||||
|
||||
<p>Please restock this item as soon as possible to avoid missed sales.</p>
|
||||
|
||||
<div style="text-align: center; margin-top: 30px;">
|
||||
<a href="{{productUrl}}" class="btn">Manage Product</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@ -0,0 +1,38 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Great News! An item in your wishlist is on sale!</title>
|
||||
<style>
|
||||
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; }
|
||||
.container { max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e1e1e1; border-radius: 8px; }
|
||||
.header { text-align: center; margin-bottom: 30px; }
|
||||
.content { margin-bottom: 30px; }
|
||||
.product-box { background: #f9f9f9; padding: 15px; border-radius: 5px; text-align: center; }
|
||||
.price { color: #e53e3e; font-size: 24px; font-weight: bold; }
|
||||
.btn { display: inline-block; padding: 12px 24px; background-color: #3182ce; color: #fff !important; text-decoration: none; border-radius: 5px; font-weight: bold; margin-top: 20px; }
|
||||
.footer { text-align: center; font-size: 12px; color: #777; margin-top: 30px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Good News!</h1>
|
||||
</div>
|
||||
<div class="content">
|
||||
<p>Hi there,</p>
|
||||
<p>An item you've been watching in your wishlist is now on sale at <strong>{appTitle}</strong>!</p>
|
||||
<div class="product-box">
|
||||
<h2>{productTitle}</h2>
|
||||
<p>Grab it now for just:</p>
|
||||
<p class="price">{salePrice}</p>
|
||||
<a href="{productUrl}" class="btn">View Deal</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<p>© {appTitle}. All rights reserved.</p>
|
||||
<p>You received this because you added this item to your wishlist.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
35
backend/src/services/email/list/abandonedCart.js
Normal file
35
backend/src/services/email/list/abandonedCart.js
Normal file
@ -0,0 +1,35 @@
|
||||
const { getNotification } = require('../../notifications/helpers');
|
||||
const path = require("path");
|
||||
const {promises: fs} = require("fs");
|
||||
|
||||
module.exports = class AbandonedCartEmail {
|
||||
constructor(to, userName, cartUrl) {
|
||||
this.to = to;
|
||||
this.userName = userName;
|
||||
this.cartUrl = cartUrl;
|
||||
}
|
||||
|
||||
get subject() {
|
||||
return getNotification(
|
||||
'emails.abandonedCart.subject'
|
||||
);
|
||||
}
|
||||
|
||||
async html() {
|
||||
try {
|
||||
const templatePath = path.join(__dirname, '../../email/htmlTemplates/abandonedCart/abandonedCartEmail.html');
|
||||
const template = await fs.readFile(templatePath, 'utf8');
|
||||
|
||||
const appTitle = getNotification('app.title');
|
||||
|
||||
let html = template.replace(/{appTitle}/g, appTitle)
|
||||
.replace(/{userName}/g, this.userName)
|
||||
.replace(/{cartUrl}/g, this.cartUrl);
|
||||
|
||||
return html;
|
||||
} catch (error) {
|
||||
console.error('Error generating abandoned cart email HTML:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
35
backend/src/services/email/list/wishlistSale.js
Normal file
35
backend/src/services/email/list/wishlistSale.js
Normal file
@ -0,0 +1,35 @@
|
||||
const { getNotification } = require('../../notifications/helpers');
|
||||
const path = require("path");
|
||||
const {promises: fs} = require("fs");
|
||||
|
||||
module.exports = class WishlistSaleEmail {
|
||||
constructor(to, productTitle, productUrl, salePrice) {
|
||||
this.to = to;
|
||||
this.productTitle = productTitle;
|
||||
this.productUrl = productUrl;
|
||||
this.salePrice = salePrice;
|
||||
}
|
||||
|
||||
get subject() {
|
||||
return `Sale Alert: ${this.productTitle} is now on sale!`;
|
||||
}
|
||||
|
||||
async html() {
|
||||
try {
|
||||
const templatePath = path.join(__dirname, '../../email/htmlTemplates/wishlistSale/wishlistSaleEmail.html');
|
||||
const template = await fs.readFile(templatePath, 'utf8');
|
||||
|
||||
const appTitle = getNotification('app.title') || 'Our Store';
|
||||
|
||||
let html = template.replace(/{appTitle}/g, appTitle)
|
||||
.replace(/{productTitle}/g, this.productTitle)
|
||||
.replace(/{productUrl}/g, this.productUrl)
|
||||
.replace(/{salePrice}/g, this.salePrice);
|
||||
|
||||
return html;
|
||||
} catch (error) {
|
||||
console.error('Error generating wishlist sale email HTML:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
91
backend/src/services/notifications/abandonedCart.js
Normal file
91
backend/src/services/notifications/abandonedCart.js
Normal file
@ -0,0 +1,91 @@
|
||||
const db = require('../../db/models');
|
||||
const { Op } = require('sequelize');
|
||||
const moment = require('moment');
|
||||
const EmailSender = require('../email');
|
||||
const AbandonedCartEmail = require('../email/list/abandonedCart');
|
||||
|
||||
class AbandonedCartService {
|
||||
static async processAbandonedCarts() {
|
||||
console.log('Starting Abandoned Cart Recovery process...');
|
||||
|
||||
// Find carts updated more than 24 hours ago but less than 7 days ago
|
||||
const abandonmentThreshold = moment().subtract(24, 'hours').toDate();
|
||||
const cutoffThreshold = moment().subtract(7, 'days').toDate();
|
||||
|
||||
const abandonedCarts = await db.carts.findAll({
|
||||
where: {
|
||||
updated_on: {
|
||||
[Op.lt]: abandonmentThreshold,
|
||||
[Op.gt]: cutoffThreshold
|
||||
},
|
||||
userId: {
|
||||
[Op.ne]: null // Only for registered users
|
||||
}
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: db.users,
|
||||
as: 'user'
|
||||
},
|
||||
{
|
||||
model: db.cart_items,
|
||||
as: 'cart_items_cart'
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
console.log(`Found ${abandonedCarts.length} potentially abandoned carts.`);
|
||||
|
||||
let sentCount = 0;
|
||||
|
||||
for (const cart of abandonedCarts) {
|
||||
if (!cart.user || !cart.user.email) continue;
|
||||
if (!cart.cart_items_cart || cart.cart_items_cart.length === 0) continue;
|
||||
|
||||
// Check if user has placed an order AFTER the cart was last updated
|
||||
const recentOrder = await db.orders.findOne({
|
||||
where: {
|
||||
userId: cart.userId,
|
||||
placed_at: {
|
||||
[Op.gt]: cart.updated_on
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (recentOrder) {
|
||||
console.log(`User ${cart.user.email} already placed an order after cart update. Skipping.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Send email
|
||||
try {
|
||||
const cartUrl = `${process.env.FRONTEND_URL || 'http://localhost:3001'}/cart`;
|
||||
const userName = cart.user.firstName || 'there';
|
||||
|
||||
const email = new AbandonedCartEmail(
|
||||
cart.user.email,
|
||||
userName,
|
||||
cartUrl
|
||||
);
|
||||
|
||||
if (EmailSender.isConfigured) {
|
||||
await new EmailSender(email).send();
|
||||
sentCount++;
|
||||
console.log(`Abandoned cart email sent to ${cart.user.email}`);
|
||||
} else {
|
||||
console.log(`Email not configured. Skipping send to ${cart.user.email}`);
|
||||
}
|
||||
|
||||
// Update cart so we don't send it again (touch updated_on)
|
||||
await cart.update({ updated_on: new Date() });
|
||||
|
||||
} catch (error) {
|
||||
console.error(`Failed to send abandoned cart email to ${cart.user.email}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return { sent: sentCount };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = AbandonedCartService;
|
||||
@ -108,6 +108,17 @@ const errors = {
|
||||
<p>The {2} team</p>
|
||||
`,
|
||||
},
|
||||
abandonedCart: {
|
||||
subject: `You left something in your cart!`,
|
||||
body: `
|
||||
<p>Hello {0},</p>
|
||||
<p>We noticed you left some items in your shopping cart. Don't miss out on these great products!</p>
|
||||
<p>Click below to return to your cart and complete your purchase:</p>
|
||||
<p><a href='{1}' style='background-color: #4F46E5; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;'>Return to Cart</a></p>
|
||||
<p>Thanks,</p>
|
||||
<p>The {2} team</p>
|
||||
`,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
52
backend/src/services/notifications/lowStock.js
Normal file
52
backend/src/services/notifications/lowStock.js
Normal file
@ -0,0 +1,52 @@
|
||||
|
||||
const EmailSender = require('../email');
|
||||
const db = require('../../db/models');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const config = require('../../config');
|
||||
|
||||
class LowStockNotificationService {
|
||||
static async notify(productId) {
|
||||
try {
|
||||
const product = await db.products.findByPk(productId);
|
||||
if (!product) return;
|
||||
|
||||
// Threshold is 5
|
||||
if (product.stock > 5) return;
|
||||
|
||||
const templatePath = path.join(__dirname, '../email/htmlTemplates/lowStock/lowStockEmail.html');
|
||||
let html = fs.readFileSync(templatePath, 'utf8');
|
||||
|
||||
html = html.replace('{{productTitle}}', product.title);
|
||||
html = html.replace('{{currentStock}}', product.stock);
|
||||
html = html.replace('{{productSku}}', product.sku || 'N/A');
|
||||
html = html.replace('{{productUrl}}', `${config.uiUrl}/products/products-edit?id=${product.id}`);
|
||||
|
||||
// Find all admins
|
||||
const adminRole = await db.roles.findOne({ where: { name: 'Administrator' } });
|
||||
if (!adminRole) return;
|
||||
|
||||
const admins = await db.users.findAll({ where: { app_roleId: adminRole.id } });
|
||||
|
||||
for (const admin of admins) {
|
||||
if (admin.email) {
|
||||
const emailOptions = {
|
||||
to: admin.email,
|
||||
subject: `⚠️ Low Stock Alert: ${product.title}`,
|
||||
html: html
|
||||
};
|
||||
|
||||
if (EmailSender.isConfigured) {
|
||||
await new EmailSender(emailOptions).send();
|
||||
} else {
|
||||
console.log('Email not configured, skipping low stock notification to', admin.email);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error in LowStockNotificationService:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = LowStockNotificationService;
|
||||
51
backend/src/services/notifications/wishlistSale.js
Normal file
51
backend/src/services/notifications/wishlistSale.js
Normal file
@ -0,0 +1,51 @@
|
||||
const db = require('../../db/models');
|
||||
const EmailSender = require('../email');
|
||||
const WishlistSaleEmail = require('../email/list/wishlistSale');
|
||||
|
||||
class WishlistNotificationService {
|
||||
static async notifySale(productId) {
|
||||
try {
|
||||
const product = await db.products.findByPk(productId);
|
||||
if (!product || !product.sale_price) return;
|
||||
|
||||
const wishlists = await db.wishlists.findAll({
|
||||
where: { productId },
|
||||
include: [{ model: db.users, as: 'user' }]
|
||||
});
|
||||
|
||||
console.log(`Found ${wishlists.length} wishlist entries for product ${productId}`);
|
||||
|
||||
for (const wishlist of wishlists) {
|
||||
if (!wishlist.user || !wishlist.user.email) continue;
|
||||
|
||||
const productUrl = `${process.env.FRONTEND_URL || 'http://localhost:3001'}/products/${product.id}`;
|
||||
|
||||
// Ensure sale_price is treated as a number
|
||||
const salePriceNum = Number(product.sale_price);
|
||||
const salePriceFormatted = isNaN(salePriceNum) ? `$${product.sale_price}` : `$${salePriceNum.toFixed(2)}`;
|
||||
|
||||
const email = new WishlistSaleEmail(
|
||||
wishlist.user.email,
|
||||
product.title,
|
||||
productUrl,
|
||||
salePriceFormatted
|
||||
);
|
||||
|
||||
if (EmailSender.isConfigured) {
|
||||
try {
|
||||
await new EmailSender(email).send();
|
||||
console.log(`Wishlist sale notification sent to ${wishlist.user.email}`);
|
||||
} catch (sendErr) {
|
||||
console.error(`Failed to send wishlist email to ${wishlist.user.email}:`, sendErr);
|
||||
}
|
||||
} else {
|
||||
console.log(`Email not configured. Skipping send to ${wishlist.user.email}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error in WishlistNotificationService.notifySale:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WishlistNotificationService;
|
||||
@ -1,3 +1,4 @@
|
||||
const WishlistNotificationService = require('./notifications/wishlistSale');
|
||||
const db = require('../db/models');
|
||||
const ProductsDBApi = require('../db/api/products');
|
||||
const processFile = require("../middlewares/upload");
|
||||
@ -15,6 +16,13 @@ module.exports = class ProductsService {
|
||||
static async create(data, currentUser) {
|
||||
const transaction = await db.sequelize.transaction();
|
||||
try {
|
||||
// If user is a seller, set sellerId to currentUser.id
|
||||
// We check if app_role exists and has name 'Seller' or if shopName is set
|
||||
const user = await db.users.findByPk(currentUser.id, { include: [{ model: db.roles, as: 'app_role' }] });
|
||||
if (user && (user.app_role?.name === 'Seller' || user.sellerStatus === 'approved')) {
|
||||
data.sellerId = user.id;
|
||||
}
|
||||
|
||||
await ProductsDBApi.create(
|
||||
data,
|
||||
{
|
||||
@ -79,6 +87,11 @@ module.exports = class ProductsService {
|
||||
);
|
||||
}
|
||||
|
||||
// Security check: only seller of this product or admin can update
|
||||
if (currentUser.app_role?.name !== 'Administrator' && products.sellerId && products.sellerId !== currentUser.id) {
|
||||
throw new Error('Forbidden: You can only update your own products');
|
||||
}
|
||||
|
||||
const updatedProducts = await ProductsDBApi.update(
|
||||
id,
|
||||
data,
|
||||
@ -88,6 +101,10 @@ module.exports = class ProductsService {
|
||||
},
|
||||
);
|
||||
|
||||
if (data.sale_price) {
|
||||
WishlistNotificationService.notifySale(id);
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
return updatedProducts;
|
||||
|
||||
@ -95,44 +112,23 @@ module.exports = class ProductsService {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
static async deleteByIds(ids, currentUser) {
|
||||
const transaction = await db.sequelize.transaction();
|
||||
|
||||
try {
|
||||
await ProductsDBApi.deleteByIds(ids, {
|
||||
currentUser,
|
||||
transaction,
|
||||
});
|
||||
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
// Security check: only seller or admin
|
||||
const products = await db.products.findAll({ where: { id: ids } });
|
||||
if (currentUser.app_role?.name !== 'Administrator') {
|
||||
const unauthorized = products.some(p => p.sellerId && p.sellerId !== currentUser.id);
|
||||
if (unauthorized) throw new Error('Forbidden');
|
||||
}
|
||||
return await ProductsDBApi.deleteByIds(ids, { currentUser });
|
||||
}
|
||||
|
||||
static async remove(id, currentUser) {
|
||||
const transaction = await db.sequelize.transaction();
|
||||
|
||||
try {
|
||||
await ProductsDBApi.remove(
|
||||
id,
|
||||
{
|
||||
currentUser,
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
const product = await db.products.findByPk(id);
|
||||
if (currentUser.app_role?.name !== 'Administrator' && product.sellerId && product.sellerId !== currentUser.id) {
|
||||
throw new Error('Forbidden');
|
||||
}
|
||||
return await ProductsDBApi.remove(id, { currentUser });
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
};
|
||||
@ -9,12 +9,16 @@ const Op = Sequelize.Op;
|
||||
* @param {object} currentUser
|
||||
*/
|
||||
async function checkPermissions(permission, currentUser) {
|
||||
|
||||
if (!currentUser) {
|
||||
throw new ValidationError('auth.unauthorized');
|
||||
// For public storefront search, we might allow certain tables
|
||||
const publicAllowed = ['READ_PRODUCTS', 'READ_CATEGORIES'];
|
||||
if (publicAllowed.includes(permission)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const userPermission = currentUser.custom_permissions.find(
|
||||
const userPermission = currentUser.custom_permissions?.find(
|
||||
(cp) => cp.name === permission,
|
||||
);
|
||||
|
||||
@ -24,212 +28,83 @@ async function checkPermissions(permission, currentUser) {
|
||||
|
||||
try {
|
||||
if (!currentUser.app_role) {
|
||||
throw new ValidationError('auth.forbidden');
|
||||
return false;
|
||||
}
|
||||
|
||||
const permissions = await currentUser.app_role.getPermissions();
|
||||
|
||||
return !!permissions.find((p) => p.name === permission);
|
||||
} catch (e) {
|
||||
throw e;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = class SearchService {
|
||||
static async autocomplete(searchQuery, currentUser) {
|
||||
if (!searchQuery || searchQuery.length < 2) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const results = [];
|
||||
|
||||
// 1. Search Products
|
||||
const hasProductPermission = await checkPermissions('READ_PRODUCTS', currentUser);
|
||||
if (hasProductPermission) {
|
||||
const products = await db.products.findAll({
|
||||
where: {
|
||||
[Op.or]: [
|
||||
{ title: { [Op.iLike]: `%${searchQuery}%` } },
|
||||
{ sku: { [Op.iLike]: `%${searchQuery}%` } }
|
||||
]
|
||||
},
|
||||
limit: 5,
|
||||
attributes: ['id', 'title', 'price', 'slug']
|
||||
});
|
||||
results.push(...products.map(p => ({ ...p.toJSON(), type: 'product' })));
|
||||
}
|
||||
|
||||
// 2. Search Categories
|
||||
const hasCategoryPermission = await checkPermissions('READ_CATEGORIES', currentUser);
|
||||
if (hasCategoryPermission) {
|
||||
const categories = await db.categories.findAll({
|
||||
where: {
|
||||
name: { [Op.iLike]: `%${searchQuery}%` }
|
||||
},
|
||||
limit: 3,
|
||||
attributes: ['id', 'name', 'slug']
|
||||
});
|
||||
results.push(...categories.map(c => ({ ...c.toJSON(), type: 'category' })));
|
||||
}
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('Autocomplete Error:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
static async search(searchQuery, currentUser ) {
|
||||
try {
|
||||
if (!searchQuery) {
|
||||
throw new ValidationError('iam.errors.searchQueryRequired');
|
||||
}
|
||||
const tableColumns = {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"users": [
|
||||
|
||||
"firstName",
|
||||
|
||||
"lastName",
|
||||
|
||||
"phoneNumber",
|
||||
|
||||
"email",
|
||||
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"products": [
|
||||
|
||||
"title",
|
||||
|
||||
"slug",
|
||||
|
||||
"description",
|
||||
|
||||
"sku",
|
||||
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"categories": [
|
||||
|
||||
"name",
|
||||
|
||||
"slug",
|
||||
|
||||
"description",
|
||||
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"orders": [
|
||||
|
||||
"order_number",
|
||||
|
||||
"shipping_address",
|
||||
|
||||
"billing_address",
|
||||
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"order_items": [
|
||||
|
||||
"name",
|
||||
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"carts": [
|
||||
|
||||
"session_id",
|
||||
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"cart_items": [
|
||||
|
||||
"name",
|
||||
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"payments": [
|
||||
|
||||
"stripe_payment_id",
|
||||
|
||||
"currency",
|
||||
|
||||
],
|
||||
|
||||
|
||||
"users": ["firstName", "lastName", "phoneNumber", "email"],
|
||||
"products": ["title", "slug", "description", "sku"],
|
||||
"categories": ["name", "slug", "description"],
|
||||
"orders": ["order_number", "shipping_address", "billing_address"],
|
||||
"order_items": ["name"],
|
||||
"carts": ["session_id"],
|
||||
"cart_items": ["name"],
|
||||
"payments": ["stripe_payment_id", "currency"],
|
||||
};
|
||||
const columnsInt = {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"products": [
|
||||
|
||||
"price",
|
||||
|
||||
"stock",
|
||||
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"orders": [
|
||||
|
||||
"total",
|
||||
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"order_items": [
|
||||
|
||||
"quantity",
|
||||
|
||||
"unit_price",
|
||||
|
||||
"total_price",
|
||||
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"cart_items": [
|
||||
|
||||
"quantity",
|
||||
|
||||
"unit_price",
|
||||
|
||||
],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"payments": [
|
||||
|
||||
"amount",
|
||||
|
||||
],
|
||||
|
||||
|
||||
"products": ["price", "stock"],
|
||||
"orders": ["total"],
|
||||
"order_items": ["quantity", "unit_price", "total_price"],
|
||||
"cart_items": ["quantity", "unit_price"],
|
||||
"payments": ["amount"],
|
||||
};
|
||||
|
||||
let allFoundRecords = [];
|
||||
@ -254,8 +129,6 @@ module.exports = class SearchService {
|
||||
],
|
||||
};
|
||||
|
||||
|
||||
|
||||
const hasPermission = await checkPermissions(`READ_${tableName.toUpperCase()}`, currentUser);
|
||||
if (!hasPermission) {
|
||||
continue;
|
||||
|
||||
48
backend/src/services/seller.js
Normal file
48
backend/src/services/seller.js
Normal file
@ -0,0 +1,48 @@
|
||||
|
||||
const db = require('../db/models');
|
||||
|
||||
class SellerService {
|
||||
static async apply(userId, { shopName, shopDescription }) {
|
||||
const user = await db.users.findByPk(userId);
|
||||
if (!user) throw new Error('User not found');
|
||||
|
||||
await user.update({
|
||||
shopName,
|
||||
shopDescription,
|
||||
sellerStatus: 'pending'
|
||||
});
|
||||
|
||||
return { success: true, message: 'Application submitted successfully' };
|
||||
}
|
||||
|
||||
static async getStatus(userId) {
|
||||
const user = await db.users.findByPk(userId);
|
||||
return { status: user.sellerStatus, shopName: user.shopName };
|
||||
}
|
||||
|
||||
static async getPendingApplications() {
|
||||
return await db.users.findAll({
|
||||
where: { sellerStatus: 'pending' }
|
||||
});
|
||||
}
|
||||
|
||||
static async reviewApplication(userId, status) {
|
||||
const user = await db.users.findByPk(userId);
|
||||
if (!user) throw new Error('User not found');
|
||||
|
||||
const updateData = { sellerStatus: status };
|
||||
|
||||
if (status === 'approved') {
|
||||
// Find Seller role
|
||||
const sellerRole = await db.roles.findOne({ where: { name: 'Seller' } });
|
||||
if (sellerRole) {
|
||||
updateData.app_roleId = sellerRole.id;
|
||||
}
|
||||
}
|
||||
|
||||
await user.update(updateData);
|
||||
return { success: true, status };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SellerService;
|
||||
@ -1,32 +1,31 @@
|
||||
/**
|
||||
* @type {import('next').NextConfig}
|
||||
*/
|
||||
|
||||
const output = process.env.NODE_ENV === 'production' ? 'export' : 'standalone';
|
||||
const nextConfig = {
|
||||
trailingSlash: true,
|
||||
distDir: 'build',
|
||||
output,
|
||||
basePath: "",
|
||||
devIndicators: {
|
||||
position: 'bottom-left',
|
||||
},
|
||||
typescript: {
|
||||
ignoreBuildErrors: true,
|
||||
},
|
||||
eslint: {
|
||||
ignoreDuringBuilds: true,
|
||||
},
|
||||
images: {
|
||||
unoptimized: true,
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: '**',
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {import('next').NextConfig}
|
||||
*/
|
||||
|
||||
const output = process.env.NODE_ENV === 'production' ? 'export' : 'standalone';
|
||||
const nextConfig = {
|
||||
trailingSlash: true,
|
||||
distDir: 'build',
|
||||
output,
|
||||
basePath: "",
|
||||
devIndicators: {
|
||||
position: 'bottom-left',
|
||||
},
|
||||
typescript: {
|
||||
ignoreBuildErrors: true,
|
||||
},
|
||||
eslint: {
|
||||
ignoreDuringBuilds: true,
|
||||
},
|
||||
images: {
|
||||
unoptimized: true,
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: '**',
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
export default nextConfig
|
||||
57
frontend/src/components/CountdownTimer.tsx
Normal file
57
frontend/src/components/CountdownTimer.tsx
Normal file
@ -0,0 +1,57 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
|
||||
interface CountdownTimerProps {
|
||||
targetDate: string;
|
||||
}
|
||||
|
||||
const CountdownTimer: React.FC<CountdownTimerProps> = ({ targetDate }) => {
|
||||
const calculateTimeLeft = () => {
|
||||
const difference = +new Date(targetDate) - +new Date();
|
||||
let timeLeft = {};
|
||||
|
||||
if (difference > 0) {
|
||||
timeLeft = {
|
||||
days: Math.floor(difference / (1000 * 60 * 60 * 24)),
|
||||
hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
|
||||
minutes: Math.floor((difference / 1000 / 60) % 60),
|
||||
seconds: Math.floor((difference / 1000) % 60),
|
||||
};
|
||||
}
|
||||
|
||||
return timeLeft;
|
||||
};
|
||||
|
||||
const [timeLeft, setTimeLeft] = useState<any>(calculateTimeLeft());
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setTimeLeft(calculateTimeLeft());
|
||||
}, 1000);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
});
|
||||
|
||||
const timerComponents: any[] = [];
|
||||
|
||||
Object.keys(timeLeft).forEach((interval) => {
|
||||
if (!timeLeft[interval] && interval !== 'seconds' && interval !== 'minutes') {
|
||||
return;
|
||||
}
|
||||
|
||||
timerComponents.push(
|
||||
<span key={interval} className="mx-1">
|
||||
{timeLeft[interval]}
|
||||
{interval.charAt(0)}
|
||||
</span>
|
||||
);
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex items-center text-xs font-bold bg-red-600 text-white px-2 py-1 rounded-full shadow-md animate-pulse">
|
||||
<span className="mr-1">Ends in:</span>
|
||||
{timerComponents.length ? timerComponents : <span>Expired!</span>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CountdownTimer;
|
||||
72
frontend/src/components/Products/ProductRecommendations.tsx
Normal file
72
frontend/src/components/Products/ProductRecommendations.tsx
Normal file
@ -0,0 +1,72 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import axios from 'axios';
|
||||
import Link from 'next/link';
|
||||
import ImageField from '../ImageField';
|
||||
import LoadingSpinner from '../LoadingSpinner';
|
||||
import { useAppSelector } from '../../stores/hooks';
|
||||
|
||||
const ProductRecommendations = () => {
|
||||
const [recommendations, setRecommendations] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const { currentUser } = useAppSelector((state) => state.auth);
|
||||
|
||||
useEffect(() => {
|
||||
axios.get('/recommendations?limit=4')
|
||||
.then(res => {
|
||||
setRecommendations(Array.isArray(res.data) ? res.data : []);
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Failed to fetch recommendations:', err);
|
||||
})
|
||||
.finally(() => {
|
||||
setLoading(false);
|
||||
});
|
||||
}, [currentUser]);
|
||||
|
||||
const formatPrice = (price: any) => {
|
||||
const num = Number(price);
|
||||
return isNaN(num) ? price : num.toFixed(2);
|
||||
};
|
||||
|
||||
if (loading) return <LoadingSpinner />;
|
||||
if (!recommendations || recommendations.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="my-10">
|
||||
<h2 className="text-2xl font-bold mb-6">Recommended for You</h2>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
{recommendations.map((item: any) => (
|
||||
<div key={item.id} className={`overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-sm hover:shadow-md transition-shadow`}>
|
||||
<Link href={`/products/${item.id}`}>
|
||||
<div className="relative h-48 w-full">
|
||||
<ImageField
|
||||
name="Avatar"
|
||||
image={item.images}
|
||||
className="w-full h-full"
|
||||
imageClassName="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<h3 className="font-semibold text-lg truncate mb-1">{item.title}</h3>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex flex-col">
|
||||
<span className="text-blue-600 font-bold">
|
||||
${formatPrice(item.sale_price || item.price)}
|
||||
</span>
|
||||
{item.sale_price && (
|
||||
<span className="text-xs line-through text-gray-400">
|
||||
${formatPrice(item.price)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductRecommendations;
|
||||
@ -1,13 +1,20 @@
|
||||
import React from 'react';
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Field, Form, Formik } from 'formik';
|
||||
import { useRouter } from 'next/router';
|
||||
import { useAppSelector } from '../stores/hooks';
|
||||
import axios from 'axios';
|
||||
import Link from 'next/link';
|
||||
|
||||
const Search = () => {
|
||||
const router = useRouter();
|
||||
const focusRing = useAppSelector((state) => state.style.focusRingColor);
|
||||
const corners = useAppSelector((state) => state.style.corners);
|
||||
const cardsStyle = useAppSelector((state) => state.style.cardsStyle);
|
||||
|
||||
const [autocompleteResults, setAutocompleteResults] = useState([]);
|
||||
const [showDropdown, setShowDropdown] = useState(false);
|
||||
const dropdownRef = useRef(null);
|
||||
|
||||
const validateSearch = (value) => {
|
||||
let error;
|
||||
if (!value) {
|
||||
@ -17,34 +24,108 @@ const Search = () => {
|
||||
}
|
||||
return error;
|
||||
};
|
||||
|
||||
const handleAutocomplete = async (query) => {
|
||||
if (query.length < 2) {
|
||||
setAutocompleteResults([]);
|
||||
setShowDropdown(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await axios.get(`/search/autocomplete?query=${query}`);
|
||||
setAutocompleteResults(response.data);
|
||||
setShowDropdown(response.data.length > 0);
|
||||
} catch (error) {
|
||||
console.error('Autocomplete error:', error);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event) => {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
|
||||
setShowDropdown(false);
|
||||
}
|
||||
};
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Formik
|
||||
initialValues={{
|
||||
search: '',
|
||||
}}
|
||||
onSubmit={(values, { setSubmitting, resetForm }) => {
|
||||
router.push(`/search?query=${values.search}`);
|
||||
resetForm();
|
||||
setSubmitting(false);
|
||||
}}
|
||||
validateOnBlur={false}
|
||||
validateOnChange={false}
|
||||
>
|
||||
{({ errors, touched, values }) => (
|
||||
<Form style={{width: '300px'}} >
|
||||
<Field
|
||||
id='search'
|
||||
name='search'
|
||||
validate={validateSearch}
|
||||
placeholder='Search'
|
||||
className={` ${corners} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-2 relative ml-2 w-full dark:placeholder-dark-600 ${focusRing} shadow-none`}
|
||||
/>
|
||||
{errors.search && touched.search && values.search.length < 2 ? (
|
||||
<div className='text-red-500 text-sm ml-2 absolute'>{errors.search}</div>
|
||||
) : null}
|
||||
</Form>
|
||||
)}
|
||||
</Formik>
|
||||
<div className="relative" ref={dropdownRef}>
|
||||
<Formik
|
||||
initialValues={{
|
||||
search: '',
|
||||
}}
|
||||
onSubmit={(values, { setSubmitting, resetForm }) => {
|
||||
router.push(`/search?query=${values.search}`);
|
||||
resetForm();
|
||||
setSubmitting(false);
|
||||
setShowDropdown(false);
|
||||
}}
|
||||
validateOnBlur={false}
|
||||
validateOnChange={false}
|
||||
>
|
||||
{({ errors, touched, values, setFieldValue, submitForm }) => (
|
||||
<Form style={{width: '300px'}} autoComplete="off">
|
||||
<Field
|
||||
id='search'
|
||||
name='search'
|
||||
validate={validateSearch}
|
||||
placeholder='Search'
|
||||
className={` ${corners} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-2 relative ml-2 w-full dark:placeholder-dark-600 ${focusRing} shadow-none`}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setFieldValue('search', value);
|
||||
handleAutocomplete(value);
|
||||
}}
|
||||
onFocus={() => {
|
||||
if (autocompleteResults.length > 0) setShowDropdown(true);
|
||||
}}
|
||||
/>
|
||||
{errors.search && touched.search && values.search.length < 2 ? (
|
||||
<div className='text-red-500 text-sm ml-2 absolute'>{errors.search}</div>
|
||||
) : null}
|
||||
|
||||
{showDropdown && (
|
||||
<div className={`absolute z-50 w-full ml-2 mt-1 bg-white dark:bg-dark-800 border dark:border-dark-700 shadow-lg ${corners} overflow-hidden`}>
|
||||
{autocompleteResults.map((result) => (
|
||||
<div
|
||||
key={`${result.type}-${result.id}`}
|
||||
className="p-3 hover:bg-gray-100 dark:hover:bg-dark-700 cursor-pointer border-b dark:border-dark-700 last:border-0"
|
||||
onClick={() => {
|
||||
if (result.type === 'product') {
|
||||
router.push(`/products/${result.id}`);
|
||||
} else {
|
||||
router.push(`/categories/${result.id}`);
|
||||
}
|
||||
setShowDropdown(false);
|
||||
setFieldValue('search', '');
|
||||
}}
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<span className="font-semibold text-sm block">{result.title || result.name}</span>
|
||||
<span className="text-xs text-gray-500 capitalize">{result.type}</span>
|
||||
</div>
|
||||
{result.price && (
|
||||
<span className="text-green-600 font-bold text-sm">${result.price}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<div
|
||||
className="p-2 text-center text-blue-600 text-xs font-semibold hover:bg-gray-50 dark:hover:bg-dark-700 cursor-pointer"
|
||||
onClick={() => submitForm()}
|
||||
>
|
||||
View all results for "{values.search}"
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Form>
|
||||
)}
|
||||
</Formik>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
export default Search;
|
||||
export default Search;
|
||||
119
frontend/src/components/Search/SmartSearch.tsx
Normal file
119
frontend/src/components/Search/SmartSearch.tsx
Normal file
@ -0,0 +1,119 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import axios from 'axios';
|
||||
import { mdiMagnify, mdiClose, mdiTagOutline, mdiPackageVariantClosed } from '@mdi/js';
|
||||
import BaseIcon from '../BaseIcon';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/router';
|
||||
|
||||
const SmartSearch = () => {
|
||||
const [query, setQuery] = useState('');
|
||||
const [results, setResults] = useState([]);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const searchRef = useRef<HTMLDivElement>(null);
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (searchRef.current && !searchRef.current.contains(event.target as Node)) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (query.length < 2) {
|
||||
setResults([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const delayDebounceFn = setTimeout(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await axios.get(`/search/autocomplete?query=${query}`);
|
||||
setResults(res.data);
|
||||
setIsOpen(true);
|
||||
} catch (err) {
|
||||
console.error('Search error:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, 300);
|
||||
|
||||
return () => clearTimeout(delayDebounceFn);
|
||||
}, [query]);
|
||||
|
||||
const handleSearch = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (query.trim()) {
|
||||
router.push(`/search?q=${encodeURIComponent(query)}`);
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative w-full max-w-md" ref={searchRef}>
|
||||
<form onSubmit={handleSearch} className="relative">
|
||||
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
|
||||
<BaseIcon path={mdiMagnify} size={20} className="text-gray-400" />
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onFocus={() => query.length >= 2 && setIsOpen(true)}
|
||||
placeholder="Search products, categories..."
|
||||
className="w-full bg-gray-50 border-none rounded-2xl pl-12 pr-10 py-3 text-sm focus:ring-2 focus:ring-blue-500/20 transition-all font-medium text-gray-700"
|
||||
/>
|
||||
{query && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setQuery('')}
|
||||
className="absolute inset-y-0 right-0 pr-3 flex items-center"
|
||||
>
|
||||
<BaseIcon path={mdiClose} size={18} className="text-gray-400 hover:text-gray-600" />
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
|
||||
{isOpen && (results.length > 0 || loading) && (
|
||||
<div className="absolute mt-2 w-full bg-white rounded-2xl shadow-2xl border border-gray-100 z-[100] overflow-hidden">
|
||||
{loading ? (
|
||||
<div className="p-4 text-center text-gray-400 text-sm animate-pulse">Searching...</div>
|
||||
) : (
|
||||
<div className="max-h-[400px] overflow-y-auto aside-scrollbars">
|
||||
{results.map((item: any) => (
|
||||
<Link
|
||||
key={`${item.type}-${item.id}`}
|
||||
href={item.type === 'product' ? `/products/${item.id}` : `/products?category=${item.id}`}
|
||||
className="flex items-center px-4 py-3 hover:bg-gray-50 transition-colors border-b border-gray-50 last:border-0"
|
||||
onClick={() => setIsOpen(false)}
|
||||
>
|
||||
<div className={`p-2 rounded-xl mr-3 ${item.type === 'product' ? 'bg-blue-50 text-blue-600' : 'bg-purple-50 text-purple-600'}`}>
|
||||
<BaseIcon path={item.type === 'product' ? mdiPackageVariantClosed : mdiTagOutline} size={20} />
|
||||
</div>
|
||||
<div className="flex-grow">
|
||||
<p className="text-sm font-bold text-gray-900">{item.title || item.name}</p>
|
||||
<p className="text-[10px] uppercase tracking-widest font-black text-gray-400">
|
||||
{item.type} {item.price ? `• $${Number(item.price).toFixed(2)}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
<button
|
||||
onClick={handleSearch}
|
||||
className="w-full py-3 text-center text-xs font-bold text-blue-600 hover:bg-blue-50 transition-colors uppercase tracking-widest"
|
||||
>
|
||||
View all results for "{query}"
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SmartSearch;
|
||||
@ -12,6 +12,29 @@ const menuAside: MenuAsideItem[] = [
|
||||
icon: icon.mdiViewDashboardOutline,
|
||||
label: 'Dashboard',
|
||||
},
|
||||
{
|
||||
href: '/seller/portal',
|
||||
icon: icon.mdiStore,
|
||||
label: 'Seller Portal',
|
||||
permissions: 'CREATE_PRODUCTS' // Sellers have this
|
||||
},
|
||||
{
|
||||
href: '/seller/apply',
|
||||
icon: icon.mdiStorePlus,
|
||||
label: 'Become a Seller',
|
||||
},
|
||||
{
|
||||
href: '/admin/seller-applications',
|
||||
icon: icon.mdiAccountCheck,
|
||||
label: 'Seller Apps',
|
||||
permissions: 'READ_USERS' // Admin only
|
||||
},
|
||||
{
|
||||
href: '/admin/analytics',
|
||||
icon: icon.mdiChartBar,
|
||||
label: 'Analytics',
|
||||
permissions: 'READ_USERS'
|
||||
},
|
||||
{
|
||||
href: '/my-orders',
|
||||
icon: icon.mdiPackageVariantClosed,
|
||||
|
||||
150
frontend/src/pages/admin/analytics.tsx
Normal file
150
frontend/src/pages/admin/analytics.tsx
Normal file
@ -0,0 +1,150 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import type { ReactElement } from 'react';
|
||||
import Head from 'next/head';
|
||||
import axios from 'axios';
|
||||
import {
|
||||
mdiChartBar,
|
||||
mdiEye,
|
||||
mdiPackageVariant,
|
||||
mdiTag,
|
||||
mdiTrendingUp,
|
||||
mdiStar
|
||||
} from '@mdi/js';
|
||||
import LayoutAuthenticated from '../../layouts/Authenticated';
|
||||
import SectionMain from '../../components/SectionMain';
|
||||
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
|
||||
import CardBox from '../../components/CardBox';
|
||||
import BaseIcon from '../../components/BaseIcon';
|
||||
import { getPageTitle } from '../../config';
|
||||
import LoadingSpinner from '../../components/LoadingSpinner';
|
||||
|
||||
const AnalyticsPage = () => {
|
||||
const [stats, setStats] = useState<any>(null);
|
||||
const [topProducts, setTopProducts] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const [statsRes, topRes] = await Promise.all([
|
||||
axios.get('/analytics/stats'),
|
||||
axios.get('/analytics/top-products?limit=5')
|
||||
]);
|
||||
setStats(statsRes.data);
|
||||
setTopProducts(topRes.data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching analytics:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
if (loading) return <LoadingSpinner />;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('Advanced Analytics')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartBar} title="Advanced Analytics" main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-3 mb-6">
|
||||
<CardBox className="bg-blue-600 text-white">
|
||||
<div className="flex items-center">
|
||||
<div className="p-3 bg-blue-500 rounded-full mr-4">
|
||||
<BaseIcon path={mdiEye} size={24} />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-bold uppercase tracking-wider opacity-80">Total Page Views</p>
|
||||
<h3 className="text-3xl font-black">{stats?.totalViews || 0}</h3>
|
||||
</div>
|
||||
</div>
|
||||
</CardBox>
|
||||
<CardBox className="bg-green-600 text-white">
|
||||
<div className="flex items-center">
|
||||
<div className="p-3 bg-green-500 rounded-full mr-4">
|
||||
<BaseIcon path={mdiPackageVariant} size={24} />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-bold uppercase tracking-wider opacity-80">Product Views</p>
|
||||
<h3 className="text-3xl font-black">{stats?.productViews || 0}</h3>
|
||||
</div>
|
||||
</div>
|
||||
</CardBox>
|
||||
<CardBox className="bg-purple-600 text-white">
|
||||
<div className="flex items-center">
|
||||
<div className="p-3 bg-purple-500 rounded-full mr-4">
|
||||
<BaseIcon path={mdiTag} size={24} />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-bold uppercase tracking-wider opacity-80">Category Views</p>
|
||||
<h3 className="text-3xl font-black">{stats?.categoryViews || 0}</h3>
|
||||
</div>
|
||||
</div>
|
||||
</CardBox>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<CardBox title="Top Viewed Products" icon={mdiTrendingUp}>
|
||||
<div className="space-y-4">
|
||||
{topProducts.map((item, index) => (
|
||||
<div key={item.productId} className="flex items-center justify-between p-4 bg-gray-50 rounded-2xl border border-gray-100 hover:border-blue-200 transition-colors">
|
||||
<div className="flex items-center">
|
||||
<span className="text-2xl font-black text-gray-300 mr-4">#{index + 1}</span>
|
||||
<img
|
||||
src={item.product?.images?.[0]?.url || "https://images.pexels.com/photos/1350789/pexels-photo-1350789.jpeg?auto=compress&cs=tinysrgb&w=50"}
|
||||
alt={item.product?.title}
|
||||
className="w-12 h-12 object-cover rounded-lg mr-4"
|
||||
/>
|
||||
<div>
|
||||
<h4 className="font-bold text-gray-900 line-clamp-1">{item.product?.title}</h4>
|
||||
<p className="text-xs text-gray-500">${item.product?.price}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<span className="block text-xl font-bold text-blue-600">{item.viewCount}</span>
|
||||
<span className="text-[10px] uppercase font-bold text-gray-400 tracking-tighter">Views</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{topProducts.length === 0 && <p className="text-center text-gray-500 py-8">No view data available yet.</p>}
|
||||
</div>
|
||||
</CardBox>
|
||||
|
||||
<CardBox title="Views Trend (Last 7 Days)" icon={mdiChartBar}>
|
||||
<div className="flex flex-col h-full justify-center">
|
||||
<div className="space-y-4">
|
||||
{stats?.dailyViews?.map((day: any) => (
|
||||
<div key={day.date} className="flex items-center">
|
||||
<span className="w-24 text-sm font-bold text-gray-500">{new Date(day.date).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })}</span>
|
||||
<div className="flex-grow bg-gray-100 rounded-full h-4 overflow-hidden mx-4">
|
||||
<div
|
||||
className="bg-blue-600 h-full rounded-full transition-all duration-1000"
|
||||
style={{ width: `${Math.min(100, (day.count / (Math.max(...stats.dailyViews.map((d:any) => d.count)) || 1)) * 100)}%` }}
|
||||
></div>
|
||||
</div>
|
||||
<span className="w-12 text-sm font-black text-gray-900 text-right">{day.count}</span>
|
||||
</div>
|
||||
))}
|
||||
{(!stats?.dailyViews || stats.dailyViews.length === 0) && <p className="text-center text-gray-500 py-8">No trend data available yet.</p>}
|
||||
</div>
|
||||
</div>
|
||||
</CardBox>
|
||||
</div>
|
||||
</SectionMain>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
AnalyticsPage.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
|
||||
};
|
||||
|
||||
export default AnalyticsPage;
|
||||
115
frontend/src/pages/admin/seller-applications.tsx
Normal file
115
frontend/src/pages/admin/seller-applications.tsx
Normal file
@ -0,0 +1,115 @@
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import type { ReactElement } from 'react';
|
||||
import Head from 'next/head';
|
||||
import axios from 'axios';
|
||||
import { mdiAccountCheck, mdiCheck, mdiClose, mdiStore } from '@mdi/js';
|
||||
import CardBox from '../../components/CardBox';
|
||||
import LayoutAuthenticated from '../../layouts/Authenticated';
|
||||
import SectionMain from '../../components/SectionMain';
|
||||
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
|
||||
import { getPageTitle } from '../../config';
|
||||
import BaseButton from '../../components/BaseButton';
|
||||
import BaseIcon from '../../components/BaseIcon';
|
||||
|
||||
const AdminSellerApplications = () => {
|
||||
const [applications, setApplications] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
fetchApplications();
|
||||
}, []);
|
||||
|
||||
const fetchApplications = async () => {
|
||||
try {
|
||||
const response = await axios.get('/seller/admin/pending');
|
||||
setApplications(response.data || []);
|
||||
} catch (error) {
|
||||
console.error('Error fetching applications:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReview = async (userId: string, status: 'approved' | 'rejected') => {
|
||||
try {
|
||||
await axios.post(`/seller/admin/review/${userId}`, { status });
|
||||
setApplications(applications.filter((a: any) => a.id !== userId));
|
||||
} catch (error) {
|
||||
console.error('Error reviewing application:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('Seller Applications')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiAccountCheck} title="Seller Applications" main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
|
||||
<CardBox className="border-gray-100">
|
||||
{loading ? (
|
||||
<p className="text-center py-12">Loading applications...</p>
|
||||
) : applications.length > 0 ? (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left">
|
||||
<thead>
|
||||
<tr className="text-gray-400 uppercase text-xs font-black tracking-widest border-b border-gray-50">
|
||||
<th className="px-4 py-4">User</th>
|
||||
<th className="px-4 py-4">Shop Name</th>
|
||||
<th className="px-4 py-4">Description</th>
|
||||
<th className="px-4 py-4 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{applications.map((app: any) => (
|
||||
<tr key={app.id} className="border-b border-gray-50">
|
||||
<td className="px-4 py-6">
|
||||
<div className="font-bold text-gray-900">{app.firstName} {app.lastName}</div>
|
||||
<div className="text-xs text-gray-400">{app.email}</div>
|
||||
</td>
|
||||
<td className="px-4 py-6 font-bold text-blue-600">{app.shopName}</td>
|
||||
<td className="px-4 py-6 text-sm text-gray-600 max-w-md">{app.shopDescription}</td>
|
||||
<td className="px-4 py-6 text-right">
|
||||
<div className="flex justify-end space-x-2">
|
||||
<BaseButton
|
||||
color="success"
|
||||
icon={mdiCheck}
|
||||
small
|
||||
onClick={() => handleReview(app.id, 'approved')}
|
||||
label="Approve"
|
||||
/>
|
||||
<BaseButton
|
||||
color="danger"
|
||||
icon={mdiClose}
|
||||
small
|
||||
onClick={() => handleReview(app.id, 'rejected')}
|
||||
label="Reject"
|
||||
/>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-20 bg-gray-50 rounded-3xl">
|
||||
<BaseIcon path={mdiStore} size={48} className="mx-auto mb-4 text-gray-300" />
|
||||
<p className="text-gray-500 font-bold">No pending seller applications.</p>
|
||||
</div>
|
||||
)}
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
AdminSellerApplications.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
|
||||
};
|
||||
|
||||
export default AdminSellerApplications;
|
||||
@ -6,7 +6,7 @@ import BaseButton from '../components/BaseButton';
|
||||
import BaseIcon from '../components/BaseIcon';
|
||||
import { getPageTitle, stripePublishableKey } from '../config';
|
||||
import LayoutGuest from '../layouts/Guest';
|
||||
import { mdiCart, mdiTrashCan, mdiArrowLeft, mdiChevronRight, mdiLock } from '@mdi/js';
|
||||
import { mdiCart, mdiTrashCan, mdiArrowLeft, mdiChevronRight, mdiLock, mdiTagOutline, mdiCheckCircle } from '@mdi/js';
|
||||
import { useAppDispatch, useAppSelector } from '../stores/hooks';
|
||||
import { removeFromCart, updateQuantity } from '../stores/shoppingCartSlice';
|
||||
import axios from 'axios';
|
||||
@ -18,10 +18,42 @@ export default function CartPage() {
|
||||
const dispatch = useAppDispatch();
|
||||
const cartItems = useAppSelector((state) => state.shoppingCart.items);
|
||||
const [isCheckingOut, setIsCheckingOut] = useState(false);
|
||||
const [promoCode, setPromoCode] = useState('');
|
||||
const [appliedDiscount, setAppliedDiscount] = useState<any>(null);
|
||||
const [discountError, setDiscountError] = useState('');
|
||||
const [isValidating, setIsValidating] = useState(false);
|
||||
|
||||
const subtotal = cartItems.reduce((acc, item) => acc + item.price * item.quantity, 0);
|
||||
const shipping = subtotal > 100 ? 0 : 15;
|
||||
const total = subtotal + shipping;
|
||||
|
||||
let discountValue = 0;
|
||||
if (appliedDiscount) {
|
||||
if (appliedDiscount.type === 'percent') {
|
||||
discountValue = subtotal * (parseFloat(appliedDiscount.value) / 100);
|
||||
} else {
|
||||
discountValue = parseFloat(appliedDiscount.value);
|
||||
}
|
||||
}
|
||||
|
||||
const total = subtotal - discountValue + shipping;
|
||||
|
||||
const handleApplyPromoCode = async () => {
|
||||
if (!promoCode) return;
|
||||
setIsValidating(true);
|
||||
setDiscountError('');
|
||||
try {
|
||||
const response = await axios.post('/checkout/validate-discount', {
|
||||
code: promoCode,
|
||||
total: subtotal
|
||||
});
|
||||
setAppliedDiscount(response.data);
|
||||
} catch (error: any) {
|
||||
setDiscountError(error.response?.data?.message || 'Invalid promo code');
|
||||
setAppliedDiscount(null);
|
||||
} finally {
|
||||
setIsValidating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCheckout = async () => {
|
||||
setIsCheckingOut(true);
|
||||
@ -31,6 +63,7 @@ export default function CartPage() {
|
||||
|
||||
const response = await axios.post('/checkout/create-session', {
|
||||
items: cartItems,
|
||||
discountCode: appliedDiscount?.code,
|
||||
successUrl: `${window.location.origin}/checkout-success?session_id={CHECKOUT_SESSION_ID}`,
|
||||
cancelUrl: `${window.location.origin}/checkout-cancel`,
|
||||
});
|
||||
@ -130,6 +163,44 @@ export default function CartPage() {
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Promo Code Section */}
|
||||
<div className="bg-white rounded-3xl p-8 shadow-sm border border-gray-100">
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center">
|
||||
<BaseIcon path={mdiTagOutline} size={20} className="mr-2 text-blue-600" /> Have a promo code?
|
||||
</h3>
|
||||
<div className="flex space-x-4">
|
||||
<input
|
||||
type="text"
|
||||
value={promoCode}
|
||||
onChange={(e) => setPromoCode(e.target.value)}
|
||||
placeholder="Enter code (e.g. SAVE10)"
|
||||
className="flex-grow bg-gray-50 border border-gray-100 rounded-2xl px-6 py-4 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all font-medium"
|
||||
/>
|
||||
<BaseButton
|
||||
label={isValidating ? "..." : "Apply"}
|
||||
color="info"
|
||||
onClick={handleApplyPromoCode}
|
||||
disabled={isValidating || !promoCode}
|
||||
className="px-8 rounded-2xl font-bold"
|
||||
/>
|
||||
</div>
|
||||
{discountError && <p className="text-red-500 text-sm mt-3 font-medium ml-2">{discountError}</p>}
|
||||
{appliedDiscount && (
|
||||
<div className="mt-4 bg-green-50 border border-green-100 rounded-2xl p-4 flex items-center justify-between">
|
||||
<div className="flex items-center text-green-700 font-bold">
|
||||
<BaseIcon path={mdiCheckCircle} size={20} className="mr-2" />
|
||||
Code {appliedDiscount.code} applied!
|
||||
</div>
|
||||
<button
|
||||
onClick={() => { setAppliedDiscount(null); setPromoCode(''); }}
|
||||
className="text-green-700 hover:text-green-800 text-sm font-bold underline"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Summary */}
|
||||
@ -141,10 +212,19 @@ export default function CartPage() {
|
||||
<span className="font-medium">Subtotal</span>
|
||||
<span className="font-bold text-gray-900 text-lg">${subtotal.toFixed(2)}</span>
|
||||
</div>
|
||||
|
||||
{appliedDiscount && (
|
||||
<div className="flex justify-between text-green-600">
|
||||
<span className="font-medium">Discount ({appliedDiscount.code})</span>
|
||||
<span className="font-bold text-lg">-${discountValue.toFixed(2)}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between text-gray-500">
|
||||
<span className="font-medium">Shipping</span>
|
||||
<span className="font-bold text-green-600 text-lg">{shipping === 0 ? 'FREE' : `$${shipping.toFixed(2)}`}</span>
|
||||
</div>
|
||||
|
||||
{shipping > 0 && (
|
||||
<div className="bg-blue-50 p-4 rounded-2xl">
|
||||
<p className="text-sm text-blue-700 font-medium flex items-center">
|
||||
@ -170,11 +250,6 @@ export default function CartPage() {
|
||||
<BaseIcon path={mdiLock} size={14} className="mr-2" />
|
||||
<span className="text-xs uppercase tracking-widest font-bold">Encrypted & Secure</span>
|
||||
</div>
|
||||
<div className="flex justify-center mt-4 space-x-4 opacity-30 grayscale">
|
||||
<img src="https://upload.wikimedia.org/wikipedia/commons/b/b5/PayPal.svg" alt="PayPal" className="h-4" />
|
||||
<img src="https://upload.wikimedia.org/wikipedia/commons/5/5e/Visa_Inc._logo.svg" alt="Visa" className="h-4" />
|
||||
<img src="https://upload.wikimedia.org/wikipedia/commons/2/2a/Mastercard-logo.svg" alt="Mastercard" className="h-4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -186,4 +261,4 @@ export default function CartPage() {
|
||||
|
||||
CartPage.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutGuest>{page}</LayoutGuest>;
|
||||
};
|
||||
};
|
||||
@ -1,6 +1,6 @@
|
||||
import * as icon from '@mdi/js';
|
||||
import Head from 'next/head'
|
||||
import React from 'react'
|
||||
import React, { useEffect } from 'react'
|
||||
import axios from 'axios';
|
||||
import type { ReactElement } from 'react'
|
||||
import LayoutAuthenticated from '../layouts/Authenticated'
|
||||
@ -9,13 +9,11 @@ import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton
|
||||
import BaseIcon from "../components/BaseIcon";
|
||||
import { getPageTitle } from '../config'
|
||||
import Link from "next/link";
|
||||
import CardBox from '../components/CardBox';
|
||||
|
||||
import { hasPermission } from "../helpers/userPermissions";
|
||||
import { fetchWidgets } from '../stores/roles/rolesSlice';
|
||||
import { WidgetCreator } from '../components/WidgetCreator/WidgetCreator';
|
||||
import { SmartWidget } from '../components/SmartWidget/SmartWidget';
|
||||
|
||||
import { useAppDispatch, useAppSelector } from '../stores/hooks';
|
||||
|
||||
const Dashboard = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
const iconsColor = useAppSelector((state) => state.style.iconsColor);
|
||||
@ -26,124 +24,56 @@ const Dashboard = () => {
|
||||
|
||||
|
||||
const [users, setUsers] = React.useState(loadingMessage);
|
||||
const [roles, setRoles] = React.useState(loadingMessage);
|
||||
const [permissions, setPermissions] = React.useState(loadingMessage);
|
||||
const [products, setProducts] = React.useState(loadingMessage);
|
||||
const [categories, setCategories] = React.useState(loadingMessage);
|
||||
const [orders, setOrders] = React.useState(loadingMessage);
|
||||
const [order_items, setOrder_items] = React.useState(loadingMessage);
|
||||
const [carts, setCarts] = React.useState(loadingMessage);
|
||||
const [cart_items, setCart_items] = React.useState(loadingMessage);
|
||||
const [payments, setPayments] = React.useState(loadingMessage);
|
||||
const [lowStockProducts, setLowStockProducts] = React.useState([]);
|
||||
|
||||
|
||||
const [widgetsRole, setWidgetsRole] = React.useState({
|
||||
role: { value: '', label: '' },
|
||||
});
|
||||
const { currentUser } = useAppSelector((state) => state.auth);
|
||||
const { isFetchingQuery } = useAppSelector((state) => state.openAi);
|
||||
|
||||
const { rolesWidgets, loading } = useAppSelector((state) => state.roles);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, []);
|
||||
|
||||
async function loadData() {
|
||||
const entities = ['users','roles','permissions','products','categories','orders','order_items','carts','cart_items','payments',];
|
||||
const fns = [setUsers,setRoles,setPermissions,setProducts,setCategories,setOrders,setOrder_items,setCarts,setCart_items,setPayments,];
|
||||
try {
|
||||
const [u, pr, c, o, p] = await Promise.all([
|
||||
axios.get('/users/count'),
|
||||
axios.get('/products/count'),
|
||||
axios.get('/categories/count'),
|
||||
axios.get('/orders/count'),
|
||||
axios.get('/payments/count'),
|
||||
]);
|
||||
setUsers(u.data.count);
|
||||
setProducts(pr.data.count);
|
||||
setCategories(c.data.count);
|
||||
setOrders(o.data.count);
|
||||
setPayments(p.data.count);
|
||||
|
||||
const requests = entities.map((entity, index) => {
|
||||
|
||||
if(hasPermission(currentUser, `READ_${entity.toUpperCase()}`)) {
|
||||
return axios.get(`/${entity.toLowerCase()}/count`);
|
||||
} else {
|
||||
fns[index](null);
|
||||
return Promise.resolve({data: {count: null}});
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
Promise.allSettled(requests).then((results) => {
|
||||
results.forEach((result, i) => {
|
||||
if (result.status === 'fulfilled') {
|
||||
fns[i](result.value.data.count);
|
||||
} else {
|
||||
fns[i](result.reason.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
if (hasPermission(currentUser, 'READ_PRODUCTS')) {
|
||||
const lowStock = await axios.get('/products', {
|
||||
params: { stockRange: [0, 5], active: true }
|
||||
});
|
||||
setLowStockProducts(lowStock.data.rows || []);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function getWidgets(roleId) {
|
||||
await dispatch(fetchWidgets(roleId));
|
||||
}
|
||||
React.useEffect(() => {
|
||||
if (!currentUser) return;
|
||||
loadData().then();
|
||||
setWidgetsRole({ role: { value: currentUser?.app_role?.id, label: currentUser?.app_role?.name } });
|
||||
}, [currentUser]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!currentUser || !widgetsRole?.role?.value) return;
|
||||
getWidgets(widgetsRole?.role?.value || '').then();
|
||||
}, [widgetsRole?.role?.value]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>
|
||||
{getPageTitle('Overview')}
|
||||
</title>
|
||||
<title>{getPageTitle('Dashboard')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton
|
||||
icon={icon.mdiChartTimelineVariant}
|
||||
title='Overview'
|
||||
main>
|
||||
<SectionTitleLineWithButton icon={icon.mdiChartTimelineVariant} title="Dashboard" main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
|
||||
{hasPermission(currentUser, 'CREATE_ROLES') && <WidgetCreator
|
||||
currentUser={currentUser}
|
||||
isFetchingQuery={isFetchingQuery}
|
||||
setWidgetsRole={setWidgetsRole}
|
||||
widgetsRole={widgetsRole}
|
||||
/>}
|
||||
{!!rolesWidgets.length &&
|
||||
hasPermission(currentUser, 'CREATE_ROLES') && (
|
||||
<p className=' text-gray-500 dark:text-gray-400 mb-4'>
|
||||
{`${widgetsRole?.role?.label || 'Users'}'s widgets`}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className='grid grid-cols-1 gap-6 lg:grid-cols-4 mb-6 grid-flow-dense'>
|
||||
{(isFetchingQuery || loading) && (
|
||||
<div className={` ${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 text-lg leading-tight text-gray-500 flex items-center ${cardsStyle} dark:border-dark-700 p-6`}>
|
||||
<BaseIcon
|
||||
className={`${iconsColor} animate-spin mr-5`}
|
||||
w='w-16'
|
||||
h='h-16'
|
||||
size={48}
|
||||
path={icon.mdiLoading}
|
||||
/>{' '}
|
||||
Loading widgets...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{ rolesWidgets &&
|
||||
rolesWidgets.map((widget) => (
|
||||
<SmartWidget
|
||||
key={widget.id}
|
||||
userId={currentUser?.id}
|
||||
widget={widget}
|
||||
roleId={widgetsRole?.role?.value || ''}
|
||||
admin={hasPermission(currentUser, 'CREATE_ROLES')}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{!!rolesWidgets.length && <hr className='my-6 ' />}
|
||||
|
||||
<div id="dashboard" className='grid grid-cols-1 gap-6 lg:grid-cols-3 mb-6'>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-3 mb-6">
|
||||
|
||||
{hasPermission(currentUser, 'READ_USERS') && <Link href={'/users/users-list'}>
|
||||
<div
|
||||
@ -164,65 +94,7 @@ const Dashboard = () => {
|
||||
w="w-16"
|
||||
h="h-16"
|
||||
size={48}
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
path={icon.mdiAccountGroup || icon.mdiTable}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>}
|
||||
|
||||
{hasPermission(currentUser, 'READ_ROLES') && <Link href={'/roles/roles-list'}>
|
||||
<div
|
||||
className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
|
||||
>
|
||||
<div className="flex justify-between align-center">
|
||||
<div>
|
||||
<div className="text-lg leading-tight text-gray-500 dark:text-gray-400">
|
||||
Roles
|
||||
</div>
|
||||
<div className="text-3xl leading-tight font-semibold">
|
||||
{roles}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<BaseIcon
|
||||
className={`${iconsColor}`}
|
||||
w="w-16"
|
||||
h="h-16"
|
||||
size={48}
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
path={icon.mdiShieldAccountVariantOutline || icon.mdiTable}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>}
|
||||
|
||||
{hasPermission(currentUser, 'READ_PERMISSIONS') && <Link href={'/permissions/permissions-list'}>
|
||||
<div
|
||||
className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
|
||||
>
|
||||
<div className="flex justify-between align-center">
|
||||
<div>
|
||||
<div className="text-lg leading-tight text-gray-500 dark:text-gray-400">
|
||||
Permissions
|
||||
</div>
|
||||
<div className="text-3xl leading-tight font-semibold">
|
||||
{permissions}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<BaseIcon
|
||||
className={`${iconsColor}`}
|
||||
w="w-16"
|
||||
h="h-16"
|
||||
size={48}
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
path={icon.mdiShieldAccountOutline || icon.mdiTable}
|
||||
path={icon.mdiAccountGroup}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@ -248,43 +120,13 @@ const Dashboard = () => {
|
||||
w="w-16"
|
||||
h="h-16"
|
||||
size={48}
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
path={'mdiCube' in icon ? icon['mdiCube' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
|
||||
path={icon.mdiPackageVariant}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>}
|
||||
|
||||
{hasPermission(currentUser, 'READ_CATEGORIES') && <Link href={'/categories/categories-list'}>
|
||||
<div
|
||||
className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
|
||||
>
|
||||
<div className="flex justify-between align-center">
|
||||
<div>
|
||||
<div className="text-lg leading-tight text-gray-500 dark:text-gray-400">
|
||||
Categories
|
||||
</div>
|
||||
<div className="text-3xl leading-tight font-semibold">
|
||||
{categories}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<BaseIcon
|
||||
className={`${iconsColor}`}
|
||||
w="w-16"
|
||||
h="h-16"
|
||||
size={48}
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
path={'mdiTag' in icon ? icon['mdiTag' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>}
|
||||
|
||||
|
||||
{hasPermission(currentUser, 'READ_ORDERS') && <Link href={'/orders/orders-list'}>
|
||||
<div
|
||||
className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
|
||||
@ -304,128 +146,60 @@ const Dashboard = () => {
|
||||
w="w-16"
|
||||
h="h-16"
|
||||
size={48}
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
path={'mdiCart' in icon ? icon['mdiCart' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
|
||||
path={icon.mdiCart}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>}
|
||||
|
||||
{hasPermission(currentUser, 'READ_ORDER_ITEMS') && <Link href={'/order_items/order_items-list'}>
|
||||
<div
|
||||
className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
|
||||
>
|
||||
</div>
|
||||
|
||||
{lowStockProducts.length > 0 && (
|
||||
<div className="mt-12">
|
||||
<SectionTitleLineWithButton icon={icon.mdiAlertCircle} title="Low Stock Alerts" />
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
{lowStockProducts.map((p: any) => (
|
||||
<CardBox key={p.id} className="border-l-4 border-red-500">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-xs font-black text-red-600 bg-red-100 px-2 py-1 rounded uppercase tracking-widest">Low Stock</span>
|
||||
<span className="text-sm font-bold text-gray-900">{p.stock} left</span>
|
||||
</div>
|
||||
<h3 className="font-bold text-gray-900 line-clamp-1 mb-4">{p.title}</h3>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-xs text-gray-400 font-bold">{p.sku}</span>
|
||||
<Link href={`/products/products-edit?id=${p.id}`} className="text-blue-600 font-bold text-xs hover:underline">
|
||||
Restock
|
||||
</Link>
|
||||
</div>
|
||||
</CardBox>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2 mt-12">
|
||||
{hasPermission(currentUser, 'READ_CATEGORIES') && <Link href={'/categories/categories-list'}>
|
||||
<div className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}>
|
||||
<div className="flex justify-between align-center">
|
||||
<div>
|
||||
<div className="text-lg leading-tight text-gray-500 dark:text-gray-400">
|
||||
Order items
|
||||
</div>
|
||||
<div className="text-3xl leading-tight font-semibold">
|
||||
{order_items}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<BaseIcon
|
||||
className={`${iconsColor}`}
|
||||
w="w-16"
|
||||
h="h-16"
|
||||
size={48}
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
path={'mdiClipboardList' in icon ? icon['mdiClipboardList' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
|
||||
/>
|
||||
<div className="text-lg text-gray-500">Categories</div>
|
||||
<div className="text-3xl font-semibold">{categories}</div>
|
||||
</div>
|
||||
<BaseIcon className={iconsColor} size={48} path={icon.mdiTag} />
|
||||
</div>
|
||||
</div>
|
||||
</Link>}
|
||||
|
||||
{hasPermission(currentUser, 'READ_CARTS') && <Link href={'/carts/carts-list'}>
|
||||
<div
|
||||
className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
|
||||
>
|
||||
<div className="flex justify-between align-center">
|
||||
<div>
|
||||
<div className="text-lg leading-tight text-gray-500 dark:text-gray-400">
|
||||
Carts
|
||||
</div>
|
||||
<div className="text-3xl leading-tight font-semibold">
|
||||
{carts}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<BaseIcon
|
||||
className={`${iconsColor}`}
|
||||
w="w-16"
|
||||
h="h-16"
|
||||
size={48}
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
path={'mdiCartOutline' in icon ? icon['mdiCartOutline' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>}
|
||||
|
||||
{hasPermission(currentUser, 'READ_CART_ITEMS') && <Link href={'/cart_items/cart_items-list'}>
|
||||
<div
|
||||
className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
|
||||
>
|
||||
<div className="flex justify-between align-center">
|
||||
<div>
|
||||
<div className="text-lg leading-tight text-gray-500 dark:text-gray-400">
|
||||
Cart items
|
||||
</div>
|
||||
<div className="text-3xl leading-tight font-semibold">
|
||||
{cart_items}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<BaseIcon
|
||||
className={`${iconsColor}`}
|
||||
w="w-16"
|
||||
h="h-16"
|
||||
size={48}
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
path={'mdiPlusBox' in icon ? icon['mdiPlusBox' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>}
|
||||
|
||||
{hasPermission(currentUser, 'READ_PAYMENTS') && <Link href={'/payments/payments-list'}>
|
||||
<div
|
||||
className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
|
||||
>
|
||||
<div className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}>
|
||||
<div className="flex justify-between align-center">
|
||||
<div>
|
||||
<div className="text-lg leading-tight text-gray-500 dark:text-gray-400">
|
||||
Payments
|
||||
</div>
|
||||
<div className="text-3xl leading-tight font-semibold">
|
||||
{payments}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<BaseIcon
|
||||
className={`${iconsColor}`}
|
||||
w="w-16"
|
||||
h="h-16"
|
||||
size={48}
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
path={'mdiCreditCard' in icon ? icon['mdiCreditCard' as keyof typeof icon] : icon.mdiTable || icon.mdiTable}
|
||||
/>
|
||||
<div className="text-lg text-gray-500">Payments</div>
|
||||
<div className="text-3xl font-semibold">{payments}</div>
|
||||
</div>
|
||||
<BaseIcon className={iconsColor} size={48} path={icon.mdiCreditCard} />
|
||||
</div>
|
||||
</div>
|
||||
</Link>}
|
||||
|
||||
|
||||
</div>
|
||||
</SectionMain>
|
||||
</>
|
||||
@ -436,4 +210,4 @@ Dashboard.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutAuthenticated>{page}</LayoutAuthenticated>
|
||||
}
|
||||
|
||||
export default Dashboard
|
||||
export default Dashboard
|
||||
@ -10,6 +10,9 @@ import { mdiCart, mdiArrowRight, mdiStar } from '@mdi/js';
|
||||
import BaseIcon from '../components/BaseIcon';
|
||||
import { useAppDispatch, useAppSelector } from '../stores/hooks';
|
||||
import { addToCart } from '../stores/shoppingCartSlice';
|
||||
import CountdownTimer from '../components/CountdownTimer';
|
||||
import ProductRecommendations from '../components/Products/ProductRecommendations';
|
||||
import SmartSearch from '../components/Search/SmartSearch';
|
||||
|
||||
export default function Home() {
|
||||
const [categories, setCategories] = useState([]);
|
||||
@ -41,7 +44,7 @@ export default function Home() {
|
||||
id: Math.random().toString(36).substr(2, 9),
|
||||
productId: product.id,
|
||||
title: product.title,
|
||||
price: product.price,
|
||||
price: product.sale_price && new Date(product.sale_ends_at) > new Date() ? product.sale_price : product.price,
|
||||
quantity: 1,
|
||||
image: product.images?.[0]?.url
|
||||
}));
|
||||
@ -62,34 +65,37 @@ export default function Home() {
|
||||
|
||||
{/* Navigation */}
|
||||
<nav className="border-b border-gray-100 py-4 px-6 flex justify-between items-center sticky top-0 bg-white z-50">
|
||||
<div className="flex items-center space-x-8">
|
||||
<Link href="/" className="text-2xl font-bold text-blue-600">
|
||||
Storefront
|
||||
<div className="flex items-center space-x-8 flex-grow">
|
||||
<Link href="/" className="text-2xl font-black text-blue-600 tracking-tighter shrink-0">
|
||||
STORE<span className="text-gray-900">FRONT</span>
|
||||
</Link>
|
||||
<div className="hidden md:flex space-x-6">
|
||||
<Link href="/products" className="text-gray-600 hover:text-blue-600 font-medium">
|
||||
<div className="hidden lg:flex flex-grow max-w-xl">
|
||||
<SmartSearch />
|
||||
</div>
|
||||
<div className="hidden md:flex space-x-6 items-center shrink-0">
|
||||
<Link href="/products" className="text-gray-600 hover:text-blue-600 font-bold text-sm uppercase tracking-wider">
|
||||
Products
|
||||
</Link>
|
||||
<Link href="/categories" className="text-gray-600 hover:text-blue-600 font-medium">
|
||||
<Link href="/categories" className="text-gray-600 hover:text-blue-600 font-bold text-sm uppercase tracking-wider">
|
||||
Categories
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center space-x-4">
|
||||
<Link href="/cart" className="relative p-2 text-gray-600 hover:text-blue-600 mr-2">
|
||||
<div className="flex items-center space-x-4 shrink-0 ml-4">
|
||||
<Link href="/cart" className="relative p-2 text-gray-400 hover:text-blue-600 transition-colors">
|
||||
<BaseIcon path={mdiCart} size={24} />
|
||||
{cartCount > 0 && (
|
||||
<span className="absolute top-0 right-0 bg-blue-600 text-white text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center">
|
||||
<span className="absolute -top-1 -right-1 bg-blue-600 text-white text-[10px] font-black rounded-full h-5 w-5 flex items-center justify-center ring-4 ring-white">
|
||||
{cartCount}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
<Link href="/login" className="text-gray-600 hover:text-blue-600 font-medium">
|
||||
<Link href="/login" className="text-gray-600 hover:text-blue-600 font-bold text-sm uppercase tracking-wider">
|
||||
Login
|
||||
</Link>
|
||||
<Link
|
||||
href="/register"
|
||||
className="bg-blue-600 text-white px-5 py-2 rounded-full font-medium hover:bg-blue-700 transition"
|
||||
className="bg-gray-900 text-white px-6 py-2.5 rounded-2xl font-black text-[10px] uppercase tracking-widest hover:bg-blue-600 transition-all shadow-md"
|
||||
>
|
||||
Sign Up
|
||||
</Link>
|
||||
@ -97,74 +103,125 @@ export default function Home() {
|
||||
</nav>
|
||||
|
||||
{/* Hero Section */}
|
||||
<section className="relative bg-gray-50 py-20 px-6">
|
||||
<section className="relative bg-gray-50 py-24 px-6">
|
||||
<div className="max-w-7xl mx-auto flex flex-col md:flex-row items-center">
|
||||
<div className="md:w-1/2 space-y-6">
|
||||
<h1 className="text-5xl md:text-6xl font-extrabold text-gray-900 leading-tight">
|
||||
Upgrade Your Lifestyle with <span className="text-blue-600">Premium Goods</span>
|
||||
<div className="md:w-1/2 space-y-8">
|
||||
<div className="inline-block bg-blue-100 text-blue-600 px-4 py-1 rounded-full text-xs font-black uppercase tracking-widest">
|
||||
New Collection 2026
|
||||
</div>
|
||||
<h1 className="text-6xl md:text-7xl font-black text-gray-900 leading-[1.1] tracking-tighter">
|
||||
Upgrade Your <span className="text-blue-600">Lifestyle</span>
|
||||
</h1>
|
||||
<p className="text-xl text-gray-600 max-w-lg">
|
||||
Discover our curated collection of high-quality products designed for the modern world.
|
||||
<p className="text-xl text-gray-500 max-w-lg font-medium leading-relaxed">
|
||||
Discover our curated collection of high-quality products designed for the modern world. Premium goods for premium people.
|
||||
</p>
|
||||
<div className="flex space-x-4">
|
||||
<div className="flex space-x-4 pt-4">
|
||||
<BaseButton
|
||||
href="/products"
|
||||
label="Shop Now"
|
||||
label="Explore Shop"
|
||||
color="info"
|
||||
className="px-8 py-3 rounded-xl text-lg shadow-lg hover:shadow-xl transition-all"
|
||||
className="px-10 py-4 rounded-2xl text-xs font-black uppercase tracking-widest shadow-xl shadow-blue-200 hover:shadow-blue-300 transition-all transform hover:-translate-y-1"
|
||||
/>
|
||||
<BaseButton
|
||||
href="/register"
|
||||
label="Get Started"
|
||||
label="Join Community"
|
||||
outline
|
||||
color="info"
|
||||
className="px-8 py-3 rounded-xl text-lg"
|
||||
className="px-10 py-4 rounded-2xl text-xs font-black uppercase tracking-widest transition-all"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="md:w-1/2 mt-12 md:mt-0 relative">
|
||||
<div className="w-full h-96 bg-blue-100 rounded-3xl overflow-hidden shadow-2xl relative">
|
||||
<div className="md:w-1/2 mt-16 md:mt-0 relative">
|
||||
<div className="w-full aspect-square bg-blue-100 rounded-[4rem] overflow-hidden shadow-2xl relative transform rotate-3">
|
||||
<img
|
||||
src="https://images.pexels.com/photos/1350789/pexels-photo-1350789.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
|
||||
alt="Hero"
|
||||
className="w-full h-full object-cover"
|
||||
className="w-full h-full object-cover transform -rotate-3 scale-110"
|
||||
/>
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-blue-900/40 to-transparent"></div>
|
||||
</div>
|
||||
{/* Abstract elements */}
|
||||
<div className="absolute -bottom-10 -left-10 w-40 h-40 bg-yellow-400 rounded-full mix-blend-multiply filter blur-3xl opacity-30 animate-pulse"></div>
|
||||
<div className="absolute -top-10 -right-10 w-40 h-40 bg-blue-400 rounded-full mix-blend-multiply filter blur-3xl opacity-30 animate-pulse delay-700"></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Categories Grid */}
|
||||
<section className="py-20 px-6 max-w-7xl mx-auto">
|
||||
<div className="flex justify-between items-end mb-10">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold text-gray-900">Shop by Category</h2>
|
||||
<p className="text-gray-500 mt-2">Explore our wide range of products across different categories.</p>
|
||||
{/* Flash Sales Section */}
|
||||
{products.some(p => p.sale_ends_at && new Date(p.sale_ends_at) > new Date()) && (
|
||||
<section className="py-24 px-6 bg-red-50">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<div className="mb-12 flex justify-between items-end">
|
||||
<div>
|
||||
<h2 className="text-4xl font-black text-red-600 uppercase tracking-tighter">Flash Deals</h2>
|
||||
<p className="text-gray-500 mt-2 font-bold uppercase tracking-widest text-xs">High-speed deals ending soon.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8">
|
||||
{products
|
||||
.filter(p => p.sale_ends_at && new Date(p.sale_ends_at) > new Date())
|
||||
.map((product) => (
|
||||
<div key={`sale-${product.id}`} className="bg-white rounded-[2.5rem] overflow-hidden shadow-xl border border-red-100 relative group transition-all hover:shadow-2xl hover:shadow-red-200">
|
||||
<div className="absolute top-4 left-4 z-10 scale-90 origin-top-left">
|
||||
<CountdownTimer targetDate={product.sale_ends_at} />
|
||||
</div>
|
||||
<div className="h-56 relative overflow-hidden">
|
||||
<img
|
||||
src={product.images?.[0]?.url || `https://images.pexels.com/photos/1350789/pexels-photo-1350789.jpeg?auto=compress&cs=tinysrgb&w=400`}
|
||||
alt={product.title}
|
||||
className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700"
|
||||
/>
|
||||
</div>
|
||||
<div className="p-8">
|
||||
<h3 className="font-bold text-gray-900 line-clamp-1 text-lg mb-2">{product.title}</h3>
|
||||
<div className="flex items-baseline space-x-3 mb-6">
|
||||
<span className="text-3xl font-black text-red-600">${product.sale_price}</span>
|
||||
<span className="text-sm text-gray-400 line-through font-bold">${product.price}</span>
|
||||
</div>
|
||||
<BaseButton
|
||||
label="Add to Cart"
|
||||
color="danger"
|
||||
className="w-full py-4 rounded-2xl text-[10px] font-black uppercase tracking-widest shadow-lg shadow-red-100"
|
||||
onClick={() => handleQuickAdd(product)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<Link href="/categories" className="text-blue-600 font-semibold flex items-center hover:underline">
|
||||
View All <BaseIcon path={mdiArrowRight} size={20} className="ml-1" />
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Categories Grid */}
|
||||
<section className="py-24 px-6 max-w-7xl mx-auto">
|
||||
<div className="flex justify-between items-end mb-12">
|
||||
<div>
|
||||
<h2 className="text-4xl font-black text-gray-900 tracking-tighter">Shop Categories</h2>
|
||||
<p className="text-gray-400 font-bold mt-2 uppercase tracking-widest text-xs">Explore our wide range of collections.</p>
|
||||
</div>
|
||||
<Link href="/categories" className="text-blue-600 font-black text-xs uppercase tracking-widest flex items-center hover:underline">
|
||||
View All <BaseIcon path={mdiArrowRight} size={16} className="ml-1" />
|
||||
</Link>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-6">
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-8">
|
||||
{loading
|
||||
? Array(4)
|
||||
.fill(0)
|
||||
.map((_, i) => (
|
||||
<div key={i} className="h-48 bg-gray-100 rounded-2xl animate-pulse"></div>
|
||||
<div key={i} className="h-64 bg-gray-50 rounded-[2.5rem] animate-pulse"></div>
|
||||
))
|
||||
: categories.slice(0, 4).map((cat) => (
|
||||
<Link
|
||||
key={cat.id}
|
||||
href={`/products?category=${cat.id}`}
|
||||
className="group relative h-48 rounded-2xl overflow-hidden shadow-md hover:shadow-xl transition-all"
|
||||
className="group relative h-64 rounded-[2.5rem] overflow-hidden shadow-sm hover:shadow-2xl transition-all border border-gray-50"
|
||||
>
|
||||
<div className="absolute inset-0 bg-blue-600 opacity-10 group-hover:opacity-20 transition-opacity"></div>
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center p-4">
|
||||
<span className="text-xl font-bold text-gray-900 group-hover:text-blue-600 transition-colors">
|
||||
<div className="absolute inset-0 bg-blue-600 opacity-5 group-hover:opacity-10 transition-opacity"></div>
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center p-8 text-center">
|
||||
<span className="text-2xl font-black text-gray-900 group-hover:text-blue-600 transition-colors tracking-tighter leading-tight mb-2">
|
||||
{cat.name}
|
||||
</span>
|
||||
<span className="text-sm text-gray-500 mt-1 uppercase tracking-wider">Explore</span>
|
||||
<span className="text-[10px] font-black text-gray-400 uppercase tracking-[0.2em] group-hover:text-blue-400 transition-colors">Explore Collection</span>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
@ -172,65 +229,78 @@ export default function Home() {
|
||||
</section>
|
||||
|
||||
{/* Featured Products */}
|
||||
<section className="py-20 px-6 bg-gray-50">
|
||||
<section className="py-24 px-6 bg-gray-50">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<div className="flex justify-between items-end mb-10">
|
||||
<div className="flex justify-between items-end mb-12">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold text-gray-900">Featured Products</h2>
|
||||
<p className="text-gray-500 mt-2">Our handpicked selection for you this season.</p>
|
||||
<h2 className="text-4xl font-black text-gray-900 tracking-tighter">New Arrivals</h2>
|
||||
<p className="text-gray-400 font-bold mt-2 uppercase tracking-widest text-xs">Our latest drops curated just for you.</p>
|
||||
</div>
|
||||
<Link href="/products" className="text-blue-600 font-semibold flex items-center hover:underline">
|
||||
View All <BaseIcon path={mdiArrowRight} size={20} className="ml-1" />
|
||||
<Link href="/products" className="text-blue-600 font-black text-xs uppercase tracking-widest flex items-center hover:underline">
|
||||
View Shop <BaseIcon path={mdiArrowRight} size={16} className="ml-1" />
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-10">
|
||||
{loading
|
||||
? Array(4)
|
||||
.fill(0)
|
||||
.map((_, i) => (
|
||||
<div key={i} className="bg-white rounded-2xl p-4 shadow-sm h-80 animate-pulse"></div>
|
||||
<div key={i} className="bg-white rounded-[2.5rem] p-4 shadow-sm h-96 animate-pulse"></div>
|
||||
))
|
||||
: products.map((product) => {
|
||||
const avg = getAvgRating(product.reviews);
|
||||
const isOnSale = product.sale_ends_at && new Date(product.sale_ends_at) > new Date();
|
||||
|
||||
return (
|
||||
<div
|
||||
key={product.id}
|
||||
className="bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-xl transition-all group flex flex-col"
|
||||
className="bg-white rounded-[2.5rem] overflow-hidden shadow-sm hover:shadow-2xl transition-all duration-500 group flex flex-col relative border border-gray-100"
|
||||
>
|
||||
<div className="h-48 bg-gray-200 relative overflow-hidden">
|
||||
{isOnSale && (
|
||||
<div className="absolute top-4 left-4 z-10 scale-75 origin-top-left">
|
||||
<CountdownTimer targetDate={product.sale_ends_at} />
|
||||
</div>
|
||||
)}
|
||||
<div className="h-64 bg-gray-200 relative overflow-hidden">
|
||||
<img
|
||||
src={`https://images.pexels.com/photos/1350789/pexels-photo-1350789.jpeg?auto=compress&cs=tinysrgb&w=300`}
|
||||
src={product.images?.[0]?.url || `https://images.pexels.com/photos/1350789/pexels-photo-1350789.jpeg?auto=compress&cs=tinysrgb&w=400`}
|
||||
alt={product.title}
|
||||
className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
|
||||
className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700"
|
||||
/>
|
||||
<button
|
||||
onClick={() => handleQuickAdd(product)}
|
||||
className="absolute top-4 right-4 bg-white/90 backdrop-blur-sm p-2 rounded-full shadow-md hover:bg-white hover:text-blue-600 transition-colors"
|
||||
className="absolute bottom-4 right-4 bg-white/90 backdrop-blur-md p-4 rounded-[1.25rem] shadow-xl hover:bg-blue-600 hover:text-white transition-all transform hover:scale-110 translate-y-20 group-hover:translate-y-0 duration-500"
|
||||
>
|
||||
<BaseIcon path={mdiCart} size={20} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="p-5 flex-grow flex flex-col">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-lg font-bold text-gray-900 line-clamp-1">{product.title}</h3>
|
||||
<div className="p-8 flex-grow flex flex-col">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-xl font-bold text-gray-900 line-clamp-1 tracking-tight group-hover:text-blue-600 transition-colors">{product.title}</h3>
|
||||
{avg > 0 && (
|
||||
<div className="flex items-center text-yellow-400 bg-yellow-50 px-2 py-1 rounded-lg">
|
||||
<BaseIcon path={mdiStar} size={14} className="mr-1" />
|
||||
<span className="text-xs font-bold">{avg.toFixed(1)}</span>
|
||||
<div className="flex items-center text-yellow-500 font-bold text-sm">
|
||||
<BaseIcon path={mdiStar} size={16} className="mr-1" />
|
||||
<span>{avg.toFixed(1)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-gray-500 text-sm mt-1 line-clamp-2 flex-grow">
|
||||
{product.description || 'No description available.'}
|
||||
</p>
|
||||
<div className="mt-4 flex justify-between items-center">
|
||||
<span className="text-xl font-extrabold text-blue-600">${product.price}</span>
|
||||
<div className="mt-auto pt-6 border-t border-gray-50 flex justify-between items-center">
|
||||
<div className="flex flex-col">
|
||||
{isOnSale ? (
|
||||
<>
|
||||
<span className="text-2xl font-black text-red-600">${product.sale_price}</span>
|
||||
<span className="text-xs text-gray-400 line-through font-bold">${product.price}</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-2xl font-black text-blue-600">${product.price}</span>
|
||||
)}
|
||||
</div>
|
||||
<Link
|
||||
href={`/products/${product.id}`}
|
||||
className="text-sm font-semibold text-gray-700 hover:text-blue-600"
|
||||
className="bg-gray-900 text-white text-[10px] font-black px-6 py-3 rounded-2xl uppercase tracking-widest hover:bg-blue-600 transition-all shadow-md"
|
||||
>
|
||||
View Details
|
||||
Details
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
@ -241,28 +311,41 @@ export default function Home() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Recommendations */}
|
||||
<section className="py-24 px-6 max-w-7xl mx-auto">
|
||||
<ProductRecommendations />
|
||||
</section>
|
||||
|
||||
{/* Footer */}
|
||||
<footer className="bg-white border-t border-gray-100 py-12 px-6">
|
||||
<div className="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center space-y-6 md:space-y-0">
|
||||
<div className="flex flex-col items-center md:items-start">
|
||||
<Link href="/" className="text-2xl font-bold text-blue-600">
|
||||
Storefront
|
||||
<footer className="bg-white border-t border-gray-100 py-20 px-6">
|
||||
<div className="max-w-7xl mx-auto grid grid-cols-1 md:grid-cols-4 gap-12">
|
||||
<div className="col-span-1 md:col-span-2">
|
||||
<Link href="/" className="text-3xl font-black text-blue-600 tracking-tighter">
|
||||
STORE<span className="text-gray-900">FRONT</span>
|
||||
</Link>
|
||||
<p className="text-gray-500 mt-2 text-sm text-center md:text-left">
|
||||
© 2026 Storefront platform. All rights reserved.
|
||||
<p className="text-gray-400 mt-6 text-sm max-w-xs font-medium leading-relaxed">
|
||||
Premium storefront platform for modern lifestyle goods. Upgrade your daily routine with our curated selections.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex space-x-8">
|
||||
<Link href="/privacy-policy" className="text-gray-500 hover:text-blue-600 text-sm">
|
||||
Privacy Policy
|
||||
</Link>
|
||||
<Link href="/terms-of-use" className="text-gray-500 hover:text-blue-600 text-sm">
|
||||
Terms of Use
|
||||
</Link>
|
||||
<Link href="/dashboard" className="text-blue-600 hover:text-blue-700 text-sm font-bold">
|
||||
Admin Interface
|
||||
</Link>
|
||||
<div className="space-y-4">
|
||||
<h4 className="text-xs font-black uppercase tracking-widest text-gray-900">Explore</h4>
|
||||
<div className="flex flex-col space-y-2">
|
||||
<Link href="/products" className="text-gray-500 hover:text-blue-600 text-sm font-bold transition-colors">Products</Link>
|
||||
<Link href="/categories" className="text-gray-500 hover:text-blue-600 text-sm font-bold transition-colors">Categories</Link>
|
||||
<Link href="/wishlist" className="text-gray-500 hover:text-blue-600 text-sm font-bold transition-colors">Wishlist</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
<h4 className="text-xs font-black uppercase tracking-widest text-gray-900">Legal</h4>
|
||||
<div className="flex flex-col space-y-2">
|
||||
<Link href="/privacy-policy" className="text-gray-500 hover:text-blue-600 text-sm font-bold transition-colors">Privacy Policy</Link>
|
||||
<Link href="/terms-of-use" className="text-gray-500 hover:text-blue-600 text-sm font-bold transition-colors">Terms of Use</Link>
|
||||
<Link href="/dashboard" className="text-blue-600 hover:text-blue-700 text-sm font-black uppercase tracking-widest pt-2">Admin Panel</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="max-w-7xl mx-auto border-t border-gray-50 mt-16 pt-8 text-center text-gray-400 text-xs font-bold uppercase tracking-widest">
|
||||
© 2026 Storefront platform. All rights reserved.
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
@ -271,4 +354,4 @@ export default function Home() {
|
||||
|
||||
Home.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutGuest>{page}</LayoutGuest>;
|
||||
};
|
||||
};
|
||||
@ -1,234 +0,0 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import type { ReactElement } from 'react';
|
||||
import Head from 'next/head';
|
||||
import Link from 'next/link';
|
||||
import axios from 'axios';
|
||||
import BaseButton from '../components/BaseButton';
|
||||
import { getPageTitle } from '../config';
|
||||
import LayoutGuest from '../layouts/Guest';
|
||||
import { mdiCart, mdiFilter, mdiStar, mdiHeart, mdiHeartOutline } from '@mdi/js';
|
||||
import BaseIcon from '../components/BaseIcon';
|
||||
import { useAppDispatch, useAppSelector } from '../stores/hooks';
|
||||
import { addToCart } from '../stores/shoppingCartSlice';
|
||||
import { useRouter } from 'next/router';
|
||||
import { toggleWishlist, fetchWishlist } from '../stores/wishlistSlice';
|
||||
|
||||
export default function ProductCatalog() {
|
||||
const router = useRouter();
|
||||
const { category } = router.query;
|
||||
const [products, setProducts] = useState([]);
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [selectedCategory, setSelectedCategory] = useState('all');
|
||||
const dispatch = useAppDispatch();
|
||||
const cartItems = useAppSelector((state) => state.shoppingCart.items);
|
||||
const { wishlist } = useAppSelector((state) => state.wishlist);
|
||||
const { currentUser } = useAppSelector((state) => state.auth);
|
||||
|
||||
useEffect(() => {
|
||||
if (category) {
|
||||
setSelectedCategory(category as string);
|
||||
}
|
||||
}, [category]);
|
||||
|
||||
useEffect(() => {
|
||||
if (currentUser) {
|
||||
dispatch(fetchWishlist({}));
|
||||
}
|
||||
}, [currentUser, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const catUrl = '/categories';
|
||||
const prodUrl = selectedCategory === 'all'
|
||||
? '/products'
|
||||
: `/products?category=${selectedCategory}`;
|
||||
|
||||
const [catRes, prodRes] = await Promise.all([
|
||||
axios.get(catUrl),
|
||||
axios.get(prodUrl),
|
||||
]);
|
||||
setCategories(catRes.data.rows || []);
|
||||
setProducts(prodRes.data.rows || []);
|
||||
} catch (error) {
|
||||
console.error('Error fetching catalog data:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
fetchData();
|
||||
}, [selectedCategory]);
|
||||
|
||||
const handleQuickAdd = (product: any) => {
|
||||
dispatch(addToCart({
|
||||
id: Math.random().toString(36).substr(2, 9),
|
||||
productId: product.id,
|
||||
title: product.title,
|
||||
price: product.price,
|
||||
quantity: 1,
|
||||
image: product.images?.[0]?.url
|
||||
}));
|
||||
};
|
||||
|
||||
const isInWishlist = (productId: string) => {
|
||||
return wishlist.some((item: any) => (item.product?.id === productId || item.productId === productId));
|
||||
};
|
||||
|
||||
const cartCount = cartItems.reduce((acc, item) => acc + item.quantity, 0);
|
||||
|
||||
const getAvgRating = (reviews: any[]) => {
|
||||
if (!reviews || reviews.length === 0) return 0;
|
||||
return reviews.reduce((acc, r) => acc + r.rating, 0) / reviews.length;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-gray-50 min-h-screen">
|
||||
<Head>
|
||||
<title>{getPageTitle('Our Products')}</title>
|
||||
</Head>
|
||||
|
||||
{/* Navigation */}
|
||||
<nav className="border-b border-gray-100 py-4 px-6 flex justify-between items-center sticky top-0 bg-white z-50">
|
||||
<Link href="/" className="text-2xl font-bold text-blue-600">
|
||||
Storefront
|
||||
</Link>
|
||||
<div className="flex items-center space-x-4">
|
||||
<Link href="/wishlist" className="p-2 text-gray-600 hover:text-red-500 transition-colors">
|
||||
<BaseIcon path={mdiHeart} size={24} />
|
||||
</Link>
|
||||
<Link href="/cart" className="relative p-2 text-gray-600 hover:text-blue-600">
|
||||
<BaseIcon path={mdiCart} size={24} />
|
||||
{cartCount > 0 && (
|
||||
<span className="absolute top-0 right-0 bg-blue-600 text-white text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center">
|
||||
{cartCount}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<main className="max-w-7xl mx-auto py-12 px-6">
|
||||
<div className="flex flex-col md:flex-row gap-8">
|
||||
{/* Sidebar Filters */}
|
||||
<aside className="md:w-64 space-y-8">
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center">
|
||||
<BaseIcon path={mdiFilter} size={20} className="mr-2" /> Categories
|
||||
</h3>
|
||||
<div className="space-y-2">
|
||||
<button
|
||||
onClick={() => setSelectedCategory('all')}
|
||||
className={`w-full text-left px-4 py-2 rounded-xl transition-all ${
|
||||
selectedCategory === 'all'
|
||||
? 'bg-blue-600 text-white font-bold shadow-md'
|
||||
: 'bg-white text-gray-600 hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
All Products
|
||||
</button>
|
||||
{categories.map((cat: any) => (
|
||||
<button
|
||||
key={cat.id}
|
||||
onClick={() => setSelectedCategory(cat.id)}
|
||||
className={`w-full text-left px-4 py-2 rounded-xl transition-all ${
|
||||
selectedCategory === cat.id
|
||||
? 'bg-blue-600 text-white font-bold shadow-md'
|
||||
: 'bg-white text-gray-600 hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
{cat.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Product Grid */}
|
||||
<div className="flex-grow">
|
||||
<div className="flex justify-between items-center mb-8">
|
||||
<h1 className="text-3xl font-extrabold text-gray-900">
|
||||
{selectedCategory === 'all' ? 'All Products' : categories.find((c: any) => c.id === selectedCategory)?.name}
|
||||
</h1>
|
||||
<p className="text-gray-500 font-medium">{products.length} Products Found</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8">
|
||||
{loading ? (
|
||||
Array(6).fill(0).map((_, i) => (
|
||||
<div key={i} className="bg-white rounded-3xl p-4 shadow-sm h-96 animate-pulse"></div>
|
||||
))
|
||||
) : products.length > 0 ? (
|
||||
products.map((product: any) => {
|
||||
const avg = getAvgRating(product.reviews);
|
||||
const wishlisted = isInWishlist(product.id);
|
||||
return (
|
||||
<div key={product.id} className="bg-white rounded-3xl overflow-hidden shadow-sm hover:shadow-xl transition-all group flex flex-col border border-gray-100">
|
||||
<div className="h-56 bg-gray-100 relative overflow-hidden">
|
||||
<img
|
||||
src={product.images?.[0]?.url || `https://images.pexels.com/photos/1350789/pexels-photo-1350789.jpeg?auto=compress&cs=tinysrgb&w=300`}
|
||||
alt={product.title}
|
||||
className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
|
||||
/>
|
||||
<div className="absolute top-4 right-4 flex flex-col space-y-2">
|
||||
<button
|
||||
onClick={() => handleQuickAdd(product)}
|
||||
className="bg-white/90 backdrop-blur-sm p-3 rounded-2xl shadow-md hover:bg-blue-600 hover:text-white transition-all transform hover:scale-110"
|
||||
>
|
||||
<BaseIcon path={mdiCart} size={20} />
|
||||
</button>
|
||||
{currentUser && (
|
||||
<button
|
||||
onClick={() => dispatch(toggleWishlist(product.id))}
|
||||
className={`bg-white/90 backdrop-blur-sm p-3 rounded-2xl shadow-md transition-all transform hover:scale-110 ${wishlisted ? 'text-red-500' : 'text-gray-400 hover:text-red-500'}`}
|
||||
>
|
||||
<BaseIcon path={wishlisted ? mdiHeart : mdiHeartOutline} size={20} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-6 flex-grow flex flex-col">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-xl font-bold text-gray-900 group-hover:text-blue-600 transition-colors line-clamp-1">
|
||||
{product.title}
|
||||
</h3>
|
||||
{avg > 0 && (
|
||||
<div className="flex items-center text-yellow-400 bg-yellow-50 px-2 py-1 rounded-lg">
|
||||
<BaseIcon path={mdiStar} size={14} className="mr-1" />
|
||||
<span className="text-xs font-bold">{avg.toFixed(1)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-gray-500 text-sm line-clamp-2 mb-6 flex-grow">
|
||||
{product.description || 'Premium quality product for your daily needs.'}
|
||||
</p>
|
||||
<div className="flex items-center justify-between mt-auto">
|
||||
<span className="text-2xl font-black text-blue-600">${product.price}</span>
|
||||
<Link
|
||||
href={`/products/${product.id}`}
|
||||
className="px-4 py-2 bg-gray-900 text-white text-xs font-bold rounded-xl hover:bg-blue-600 transition-colors uppercase tracking-widest"
|
||||
>
|
||||
View Details
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)})
|
||||
) : (
|
||||
<div className="col-span-full py-20 text-center bg-white rounded-3xl border-2 border-dashed border-gray-200">
|
||||
<p className="text-gray-500 font-bold text-xl">No products found in this category.</p>
|
||||
<BaseButton onClick={() => setSelectedCategory('all')} label="Clear Filters" color="info" outline className="mt-4 rounded-xl" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
ProductCatalog.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutGuest>{page}</LayoutGuest>;
|
||||
};
|
||||
@ -19,12 +19,15 @@ import {
|
||||
mdiStarHalf,
|
||||
mdiAccountCircle,
|
||||
mdiHeart,
|
||||
mdiHeartOutline
|
||||
mdiHeartOutline,
|
||||
mdiArrowRight
|
||||
} from '@mdi/js';
|
||||
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
|
||||
import { addToCart } from '../../stores/shoppingCartSlice';
|
||||
import { createReview } from '../../stores/reviewsSlice';
|
||||
import { toggleWishlist, fetchWishlist } from '../../stores/wishlistSlice';
|
||||
import CountdownTimer from '../../components/CountdownTimer';
|
||||
import ProductRecommendations from '../../components/Products/ProductRecommendations';
|
||||
|
||||
export default function ProductDetail() {
|
||||
const router = useRouter();
|
||||
@ -35,7 +38,9 @@ export default function ProductDetail() {
|
||||
const { wishlist } = useAppSelector((state) => state.wishlist);
|
||||
|
||||
const [product, setProduct] = useState<any>(null);
|
||||
const [recommendations, setRecommendations] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadingRecs, setLoadingRecs] = useState(false);
|
||||
const [quantity, setQuantity] = useState(1);
|
||||
const [adding, setAdding] = useState(false);
|
||||
|
||||
@ -48,6 +53,7 @@ export default function ProductDetail() {
|
||||
try {
|
||||
const res = await axios.get(`/products/${id}`);
|
||||
setProduct(res.data);
|
||||
fetchRecommendations();
|
||||
} catch (error) {
|
||||
console.error('Error fetching product:', error);
|
||||
} finally {
|
||||
@ -55,9 +61,33 @@ export default function ProductDetail() {
|
||||
}
|
||||
};
|
||||
|
||||
const fetchRecommendations = async () => {
|
||||
if (!id) return;
|
||||
setLoadingRecs(true);
|
||||
try {
|
||||
const res = await axios.get(`/products/${id}/recommendations?limit=4`);
|
||||
setRecommendations(res.data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching recommendations:', error);
|
||||
} finally {
|
||||
setLoadingRecs(false);
|
||||
}
|
||||
};
|
||||
|
||||
const recordView = async () => {
|
||||
if (!id) return;
|
||||
try {
|
||||
await axios.post('/analytics/record', { productId: id });
|
||||
} catch (error) {
|
||||
console.error('Error recording view:', error);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (id) {
|
||||
fetchProduct();
|
||||
recordView();
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
@ -67,15 +97,16 @@ export default function ProductDetail() {
|
||||
}
|
||||
}, [currentUser, dispatch]);
|
||||
|
||||
const handleAddToCart = () => {
|
||||
const handleAddToCart = (item: any = product, qty: number = quantity) => {
|
||||
const isOnSale = item.sale_ends_at && new Date(item.sale_ends_at) > new Date();
|
||||
setAdding(true);
|
||||
dispatch(addToCart({
|
||||
id: Math.random().toString(36).substr(2, 9),
|
||||
productId: product.id,
|
||||
title: product.title,
|
||||
price: product.price,
|
||||
quantity: quantity,
|
||||
image: product.images?.[0]?.url
|
||||
productId: item.id,
|
||||
title: item.title,
|
||||
price: isOnSale && item.sale_price ? item.sale_price : item.price,
|
||||
quantity: qty,
|
||||
image: item.images?.[0]?.url
|
||||
}));
|
||||
|
||||
setTimeout(() => {
|
||||
@ -111,6 +142,11 @@ export default function ProductDetail() {
|
||||
|
||||
const cartCount = cartItems.reduce((acc, item) => acc + item.quantity, 0);
|
||||
|
||||
const getAvgRating = (reviews: any[]) => {
|
||||
if (!reviews || reviews.length === 0) return 0;
|
||||
return reviews.reduce((acc, r) => acc + r.rating, 0) / reviews.length;
|
||||
};
|
||||
|
||||
const renderStars = (val: number) => {
|
||||
const stars = [];
|
||||
for (let i = 1; i <= 5; i++) {
|
||||
@ -143,11 +179,9 @@ export default function ProductDetail() {
|
||||
);
|
||||
}
|
||||
|
||||
const averageRating = product.reviews?.length > 0
|
||||
? product.reviews.reduce((acc: number, r: any) => acc + r.rating, 0) / product.reviews.length
|
||||
: 0;
|
||||
|
||||
const averageRating = getAvgRating(product.reviews);
|
||||
const wishlisted = isInWishlist(product.id);
|
||||
const isOnSale = product.sale_ends_at && new Date(product.sale_ends_at) > new Date();
|
||||
|
||||
return (
|
||||
<div className="bg-white min-h-screen">
|
||||
@ -178,7 +212,7 @@ export default function ProductDetail() {
|
||||
</nav>
|
||||
|
||||
<main className="max-w-7xl mx-auto py-12 px-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-12 mb-20">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-12 mb-24">
|
||||
{/* Image Gallery */}
|
||||
<div className="space-y-4">
|
||||
<div className="aspect-square bg-gray-100 rounded-3xl overflow-hidden shadow-inner relative">
|
||||
@ -187,6 +221,11 @@ export default function ProductDetail() {
|
||||
alt={product.title}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
{isOnSale && (
|
||||
<div className="absolute top-6 left-6 z-10">
|
||||
<CountdownTimer targetDate={product.sale_ends_at} />
|
||||
</div>
|
||||
)}
|
||||
{currentUser && (
|
||||
<button
|
||||
onClick={() => dispatch(toggleWishlist(product.id))}
|
||||
@ -229,9 +268,17 @@ export default function ProductDetail() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-8 p-6 bg-gray-50 rounded-2xl border border-gray-100">
|
||||
<div className={`mb-8 p-6 ${isOnSale ? 'bg-red-50 border-red-100' : 'bg-gray-50 border-gray-100'} rounded-2xl border`}>
|
||||
<div className="flex items-baseline space-x-3">
|
||||
<span className="text-4xl font-extrabold text-blue-600">${product.price}</span>
|
||||
{isOnSale ? (
|
||||
<>
|
||||
<span className="text-4xl font-extrabold text-red-600">${product.sale_price}</span>
|
||||
<span className="text-xl text-gray-400 line-through">${product.price}</span>
|
||||
<span className="bg-red-600 text-white text-xs font-bold px-2 py-1 rounded-lg ml-2">SALE</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-4xl font-extrabold text-blue-600">${product.price}</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-green-600 font-medium text-sm mt-2">In Stock ({product.stock} units available)</p>
|
||||
</div>
|
||||
@ -262,10 +309,10 @@ export default function ProductDetail() {
|
||||
</button>
|
||||
</div>
|
||||
<BaseButton
|
||||
onClick={handleAddToCart}
|
||||
onClick={() => handleAddToCart()}
|
||||
label={adding ? "Adding..." : "Add to Cart"}
|
||||
icon={mdiCart}
|
||||
color="info"
|
||||
color={isOnSale ? "danger" : "info"}
|
||||
className="flex-grow py-4 rounded-xl text-lg font-bold shadow-lg hover:shadow-xl transition-all"
|
||||
disabled={adding}
|
||||
/>
|
||||
@ -290,6 +337,80 @@ export default function ProductDetail() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Recommendations Section */}
|
||||
{recommendations.length > 0 && (
|
||||
<div className="mb-24">
|
||||
<div className="flex justify-between items-end mb-8">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold text-gray-900">You May Also Like</h2>
|
||||
<p className="text-gray-500 mt-2">Based on this product's category.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8">
|
||||
{recommendations.map((rec) => {
|
||||
const avg = getAvgRating(rec.reviews);
|
||||
const recOnSale = rec.sale_ends_at && new Date(rec.sale_ends_at) > new Date();
|
||||
return (
|
||||
<div
|
||||
key={rec.id}
|
||||
className="bg-white rounded-3xl overflow-hidden shadow-sm hover:shadow-xl transition-all group flex flex-col border border-gray-100 relative"
|
||||
>
|
||||
{recOnSale && (
|
||||
<div className="absolute top-2 left-2 z-10 scale-75 origin-top-left">
|
||||
<CountdownTimer targetDate={rec.sale_ends_at} />
|
||||
</div>
|
||||
)}
|
||||
<div className="h-48 bg-gray-200 relative overflow-hidden">
|
||||
<img
|
||||
src={rec.images?.[0]?.url || "https://images.pexels.com/photos/1350789/pexels-photo-1350789.jpeg?auto=compress&cs=tinysrgb&w=300"}
|
||||
alt={rec.title}
|
||||
className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
|
||||
/>
|
||||
<button
|
||||
onClick={() => handleAddToCart(rec, 1)}
|
||||
className="absolute top-4 right-4 bg-white/90 backdrop-blur-sm p-2 rounded-full shadow-md hover:bg-white hover:text-blue-600 transition-colors"
|
||||
>
|
||||
<BaseIcon path={mdiCart} size={20} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="p-5 flex-grow flex flex-col">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-lg font-bold text-gray-900 line-clamp-1">{rec.title}</h3>
|
||||
{avg > 0 && (
|
||||
<div className="flex items-center text-yellow-400 bg-yellow-50 px-2 py-1 rounded-lg">
|
||||
<BaseIcon path={mdiStar} size={14} className="mr-1" />
|
||||
<span className="text-xs font-bold">{avg.toFixed(1)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-4 flex justify-between items-center">
|
||||
<div className="flex flex-col">
|
||||
{recOnSale ? (
|
||||
<>
|
||||
<span className="text-xl font-extrabold text-red-600">${rec.sale_price}</span>
|
||||
<span className="text-xs text-gray-400 line-through">${rec.price}</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-xl font-extrabold text-blue-600">${rec.price}</span>
|
||||
)}
|
||||
</div>
|
||||
<Link
|
||||
href={`/products/${rec.id}`}
|
||||
className="text-sm font-semibold text-gray-700 hover:text-blue-600 flex items-center"
|
||||
>
|
||||
View <BaseIcon path={mdiArrowRight} size={16} className="ml-1" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ProductRecommendations />
|
||||
|
||||
{/* Reviews Section */}
|
||||
<div className="border-t border-gray-100 pt-16">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-12">
|
||||
@ -400,4 +521,4 @@ export default function ProductDetail() {
|
||||
|
||||
ProductDetail.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutGuest>{page}</LayoutGuest>;
|
||||
};
|
||||
};
|
||||
|
||||
@ -1,883 +0,0 @@
|
||||
import { mdiChartTimelineVariant, mdiUpload } from '@mdi/js'
|
||||
import Head from 'next/head'
|
||||
import React, { ReactElement, useEffect, useState } from 'react'
|
||||
import DatePicker from "react-datepicker";
|
||||
import "react-datepicker/dist/react-datepicker.css";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
import CardBox from '../../components/CardBox'
|
||||
import LayoutAuthenticated from '../../layouts/Authenticated'
|
||||
import SectionMain from '../../components/SectionMain'
|
||||
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
|
||||
import { getPageTitle } from '../../config'
|
||||
|
||||
import { Field, Form, Formik } from 'formik'
|
||||
import FormField from '../../components/FormField'
|
||||
import BaseDivider from '../../components/BaseDivider'
|
||||
import BaseButtons from '../../components/BaseButtons'
|
||||
import BaseButton from '../../components/BaseButton'
|
||||
import FormCheckRadio from '../../components/FormCheckRadio'
|
||||
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup'
|
||||
import FormFilePicker from '../../components/FormFilePicker'
|
||||
import FormImagePicker from '../../components/FormImagePicker'
|
||||
import { SelectField } from "../../components/SelectField";
|
||||
import { SelectFieldMany } from "../../components/SelectFieldMany";
|
||||
import { SwitchField } from '../../components/SwitchField'
|
||||
import {RichTextField} from "../../components/RichTextField";
|
||||
|
||||
import { update, fetch } from '../../stores/products/productsSlice'
|
||||
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
|
||||
import { useRouter } from 'next/router'
|
||||
import {saveFile} from "../../helpers/fileSaver";
|
||||
import dataFormatter from '../../helpers/dataFormatter';
|
||||
import ImageField from "../../components/ImageField";
|
||||
|
||||
|
||||
|
||||
const EditProducts = () => {
|
||||
const router = useRouter()
|
||||
const dispatch = useAppDispatch()
|
||||
const initVals = {
|
||||
|
||||
|
||||
'title': '',
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
'slug': '',
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
description: '',
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
'price': '',
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
'sku': '',
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
stock: '',
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
active: false,
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
images: [],
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
category: null,
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
created_on: new Date(),
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
updated_on: new Date(),
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
const [initialValues, setInitialValues] = useState(initVals)
|
||||
|
||||
const { products } = useAppSelector((state) => state.products)
|
||||
|
||||
|
||||
const { productsId } = router.query
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(fetch({ id: productsId }))
|
||||
}, [productsId])
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof products === 'object') {
|
||||
setInitialValues(products)
|
||||
}
|
||||
}, [products])
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof products === 'object') {
|
||||
|
||||
const newInitialVal = {...initVals};
|
||||
|
||||
Object.keys(initVals).forEach(el => newInitialVal[el] = (products)[el])
|
||||
|
||||
setInitialValues(newInitialVal);
|
||||
}
|
||||
}, [products])
|
||||
|
||||
const handleSubmit = async (data) => {
|
||||
await dispatch(update({ id: productsId, data }))
|
||||
await router.push('/products/products-list')
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('Edit products')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit products'} main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
<CardBox>
|
||||
<Formik
|
||||
enableReinitialize
|
||||
initialValues={initialValues}
|
||||
onSubmit={(values) => handleSubmit(values)}
|
||||
>
|
||||
<Form>
|
||||
|
||||
|
||||
|
||||
<FormField
|
||||
label="Title"
|
||||
>
|
||||
<Field
|
||||
name="title"
|
||||
placeholder="Title"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField
|
||||
label="Slug"
|
||||
>
|
||||
<Field
|
||||
name="slug"
|
||||
placeholder="Slug"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField label='Description' hasTextareaHeight>
|
||||
<Field
|
||||
name='description'
|
||||
id='description'
|
||||
component={RichTextField}
|
||||
></Field>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField
|
||||
label="Price"
|
||||
>
|
||||
<Field
|
||||
type="number"
|
||||
name="price"
|
||||
placeholder="Price"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField
|
||||
label="SKU"
|
||||
>
|
||||
<Field
|
||||
name="sku"
|
||||
placeholder="SKU"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField
|
||||
label="Stock"
|
||||
>
|
||||
<Field
|
||||
type="number"
|
||||
name="stock"
|
||||
placeholder="Stock"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField label='Active' labelFor='active'>
|
||||
<Field
|
||||
name='active'
|
||||
id='active'
|
||||
component={SwitchField}
|
||||
></Field>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField>
|
||||
<Field
|
||||
label='Images'
|
||||
color='info'
|
||||
icon={mdiUpload}
|
||||
path={'products/images'}
|
||||
name='images'
|
||||
id='images'
|
||||
schema={{
|
||||
size: undefined,
|
||||
formats: undefined,
|
||||
}}
|
||||
component={FormImagePicker}
|
||||
></Field>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField label='Category' labelFor='category'>
|
||||
<Field
|
||||
name='category'
|
||||
id='category'
|
||||
component={SelectField}
|
||||
options={initialValues.category}
|
||||
itemRef={'categories'}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
showField={'name'}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
></Field>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField
|
||||
label="CreatedOn"
|
||||
>
|
||||
<DatePicker
|
||||
dateFormat="yyyy-MM-dd hh:mm"
|
||||
showTimeSelect
|
||||
selected={initialValues.created_on ?
|
||||
new Date(
|
||||
dayjs(initialValues.created_on).format('YYYY-MM-DD hh:mm'),
|
||||
) : null
|
||||
}
|
||||
onChange={(date) => setInitialValues({...initialValues, 'created_on': date})}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField
|
||||
label="UpdatedOn"
|
||||
>
|
||||
<DatePicker
|
||||
dateFormat="yyyy-MM-dd hh:mm"
|
||||
showTimeSelect
|
||||
selected={initialValues.updated_on ?
|
||||
new Date(
|
||||
dayjs(initialValues.updated_on).format('YYYY-MM-DD hh:mm'),
|
||||
) : null
|
||||
}
|
||||
onChange={(date) => setInitialValues({...initialValues, 'updated_on': date})}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<BaseDivider />
|
||||
<BaseButtons>
|
||||
<BaseButton type="submit" color="info" label="Submit" />
|
||||
<BaseButton type="reset" color="info" outline label="Reset" />
|
||||
<BaseButton type='reset' color='danger' outline label='Cancel' onClick={() => router.push('/products/products-list')}/>
|
||||
</BaseButtons>
|
||||
</Form>
|
||||
</Formik>
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
EditProducts.getLayout = function getLayout(page: ReactElement) {
|
||||
return (
|
||||
<LayoutAuthenticated
|
||||
|
||||
permission={'UPDATE_PRODUCTS'}
|
||||
|
||||
>
|
||||
{page}
|
||||
</LayoutAuthenticated>
|
||||
)
|
||||
}
|
||||
|
||||
export default EditProducts
|
||||
325
frontend/src/pages/products/index.tsx
Normal file
325
frontend/src/pages/products/index.tsx
Normal file
@ -0,0 +1,325 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import type { ReactElement } from 'react';
|
||||
import Head from 'next/head';
|
||||
import Link from 'next/link';
|
||||
import axios from 'axios';
|
||||
import BaseButton from '../../components/BaseButton';
|
||||
import { getPageTitle } from '../../config';
|
||||
import LayoutGuest from '../../layouts/Guest';
|
||||
import { mdiCart, mdiFilter, mdiStar, mdiHeart, mdiHeartOutline, mdiSortVariant } from '@mdi/js';
|
||||
import BaseIcon from '../../components/BaseIcon';
|
||||
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
|
||||
import { addToCart } from '../../stores/shoppingCartSlice';
|
||||
import { useRouter } from 'next/router';
|
||||
import { toggleWishlist, fetchWishlist } from '../../stores/wishlistSlice';
|
||||
import SmartSearch from '../../components/Search/SmartSearch';
|
||||
|
||||
export default function ProductCatalog() {
|
||||
const router = useRouter();
|
||||
const { category } = router.query;
|
||||
const [products, setProducts] = useState([]);
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [selectedCategory, setSelectedCategory] = useState('all');
|
||||
const [sortBy, setSortBy] = useState('createdAt');
|
||||
const [sortDir, setSortDir] = useState('desc');
|
||||
const [priceRange, setPriceRange] = useState({ min: '', max: '' });
|
||||
|
||||
const dispatch = useAppDispatch();
|
||||
const cartItems = useAppSelector((state) => state.shoppingCart.items);
|
||||
const { wishlist } = useAppSelector((state) => state.wishlist);
|
||||
const { currentUser } = useAppSelector((state) => state.auth);
|
||||
|
||||
useEffect(() => {
|
||||
if (category) {
|
||||
setSelectedCategory(category as string);
|
||||
}
|
||||
}, [category]);
|
||||
|
||||
useEffect(() => {
|
||||
if (currentUser) {
|
||||
dispatch(fetchWishlist({}));
|
||||
}
|
||||
}, [currentUser, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const catUrl = '/categories';
|
||||
|
||||
const params: any = {
|
||||
field: sortBy,
|
||||
sort: sortDir,
|
||||
};
|
||||
|
||||
if (selectedCategory !== 'all') {
|
||||
params.category = selectedCategory;
|
||||
}
|
||||
|
||||
if (priceRange.min) params['priceRange[0]'] = priceRange.min;
|
||||
if (priceRange.max) params['priceRange[1]'] = priceRange.max;
|
||||
|
||||
const [catRes, prodRes] = await Promise.all([
|
||||
axios.get(catUrl),
|
||||
axios.get('/products', { params }),
|
||||
]);
|
||||
setCategories(catRes.data.rows || []);
|
||||
setProducts(prodRes.data.rows || []);
|
||||
} catch (error) {
|
||||
console.error('Error fetching catalog data:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
fetchData();
|
||||
}, [selectedCategory, sortBy, sortDir, priceRange]);
|
||||
|
||||
const handleQuickAdd = (product: any) => {
|
||||
dispatch(addToCart({
|
||||
id: Math.random().toString(36).substr(2, 9),
|
||||
productId: product.id,
|
||||
title: product.title,
|
||||
price: product.price,
|
||||
quantity: 1,
|
||||
image: product.images?.[0]?.url
|
||||
}));
|
||||
};
|
||||
|
||||
const isInWishlist = (productId: string) => {
|
||||
return wishlist.some((item: any) => (item.product?.id === productId || item.productId === productId));
|
||||
};
|
||||
|
||||
const cartCount = cartItems.reduce((acc, item) => acc + item.quantity, 0);
|
||||
|
||||
const getAvgRating = (reviews: any[]) => {
|
||||
if (!reviews || reviews.length === 0) return 0;
|
||||
return reviews.reduce((acc, r) => acc + r.rating, 0) / reviews.length;
|
||||
};
|
||||
|
||||
const handleSortChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
const [field, dir] = e.target.value.split(':');
|
||||
setSortBy(field);
|
||||
setSortDir(dir);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-gray-50 min-h-screen">
|
||||
<Head>
|
||||
<title>{getPageTitle('Our Products')}</title>
|
||||
</Head>
|
||||
|
||||
{/* Navigation */}
|
||||
<nav className="border-b border-gray-100 py-4 px-6 flex justify-between items-center sticky top-0 bg-white z-50">
|
||||
<div className="flex items-center space-x-8 flex-grow">
|
||||
<Link href="/" className="text-2xl font-black text-blue-600 tracking-tighter shrink-0">
|
||||
STORE<span className="text-gray-900">FRONT</span>
|
||||
</Link>
|
||||
<div className="hidden lg:flex flex-grow max-w-xl">
|
||||
<SmartSearch />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center space-x-4 ml-4">
|
||||
<Link href="/wishlist" className="p-2 text-gray-400 hover:text-red-500 transition-colors">
|
||||
<BaseIcon path={mdiHeart} size={24} />
|
||||
</Link>
|
||||
<Link href="/cart" className="relative p-2 text-gray-400 hover:text-blue-600 transition-colors">
|
||||
<BaseIcon path={mdiCart} size={24} />
|
||||
{cartCount > 0 && (
|
||||
<span className="absolute -top-1 -right-1 bg-blue-600 text-white text-[10px] font-black rounded-full h-5 w-5 flex items-center justify-center ring-4 ring-white">
|
||||
{cartCount}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<main className="max-w-7xl mx-auto py-12 px-6">
|
||||
<div className="flex flex-col lg:flex-row gap-12">
|
||||
{/* Sidebar Filters */}
|
||||
<aside className="lg:w-72 space-y-10">
|
||||
<div>
|
||||
<h3 className="text-sm uppercase tracking-widest font-black text-gray-400 mb-6 flex items-center">
|
||||
<BaseIcon path={mdiFilter} size={16} className="mr-2" /> Categories
|
||||
</h3>
|
||||
<div className="space-y-1">
|
||||
<button
|
||||
onClick={() => setSelectedCategory('all')}
|
||||
className={`w-full text-left px-5 py-3 rounded-2xl transition-all font-bold ${
|
||||
selectedCategory === 'all'
|
||||
? 'bg-blue-600 text-white shadow-lg shadow-blue-200'
|
||||
: 'text-gray-600 hover:bg-white hover:shadow-sm'
|
||||
}`}
|
||||
>
|
||||
All Products
|
||||
</button>
|
||||
{categories.map((cat: any) => (
|
||||
<button
|
||||
key={cat.id}
|
||||
onClick={() => setSelectedCategory(cat.id)}
|
||||
className={`w-full text-left px-5 py-3 rounded-2xl transition-all font-bold ${
|
||||
selectedCategory === cat.id
|
||||
? 'bg-blue-600 text-white shadow-lg shadow-blue-200'
|
||||
: 'text-gray-600 hover:bg-white hover:shadow-sm'
|
||||
}`}
|
||||
>
|
||||
{cat.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 className="text-sm uppercase tracking-widest font-black text-gray-400 mb-6 flex items-center">
|
||||
Price Range
|
||||
</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-gray-400 uppercase ml-1">Min</label>
|
||||
<input
|
||||
type="number"
|
||||
placeholder="0"
|
||||
value={priceRange.min}
|
||||
onChange={(e) => setPriceRange({...priceRange, min: e.target.value})}
|
||||
className="w-full bg-white border border-gray-100 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all font-bold text-gray-900"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-gray-400 uppercase ml-1">Max</label>
|
||||
<input
|
||||
type="number"
|
||||
placeholder="1000"
|
||||
value={priceRange.max}
|
||||
onChange={(e) => setPriceRange({...priceRange, max: e.target.value})}
|
||||
className="w-full bg-white border border-gray-100 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all font-bold text-gray-900"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setPriceRange({ min: '', max: '' })}
|
||||
className="text-xs font-bold text-blue-600 hover:text-blue-700 transition-colors uppercase tracking-widest ml-1"
|
||||
>
|
||||
Reset Price
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Product Grid */}
|
||||
<div className="flex-grow">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between mb-10 gap-6">
|
||||
<div>
|
||||
<h1 className="text-4xl font-black text-gray-900 tracking-tight">
|
||||
{selectedCategory === 'all' ? 'All Products' : categories.find((c: any) => c.id === selectedCategory)?.name}
|
||||
</h1>
|
||||
<p className="text-gray-400 font-bold mt-1 uppercase tracking-widest text-xs">{products.length} Items found</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center bg-white rounded-2xl px-4 py-2 border border-gray-100 shadow-sm">
|
||||
<BaseIcon path={mdiSortVariant} size={20} className="text-gray-400 mr-2" />
|
||||
<select
|
||||
onChange={handleSortChange}
|
||||
value={`${sortBy}:${sortDir}`}
|
||||
className="bg-transparent border-none focus:ring-0 font-bold text-gray-700 pr-8 py-1 appearance-none cursor-pointer"
|
||||
>
|
||||
<option value="createdAt:desc">Newest Arrivals</option>
|
||||
<option value="price:asc">Price: Low to High</option>
|
||||
<option value="price:desc">Price: High to Low</option>
|
||||
<option value="title:asc">Alphabetical</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8">
|
||||
{loading ? (
|
||||
Array(6).fill(0).map((_, i) => (
|
||||
<div key={i} className="bg-white rounded-[2rem] p-4 shadow-sm h-[420px] animate-pulse border border-gray-100"></div>
|
||||
))
|
||||
) : products.length > 0 ? (
|
||||
products.map((product: any) => {
|
||||
const avg = getAvgRating(product.reviews);
|
||||
const wishlisted = isInWishlist(product.id);
|
||||
return (
|
||||
<div key={product.id} className="bg-white rounded-[2.5rem] overflow-hidden shadow-sm hover:shadow-2xl transition-all duration-300 group flex flex-col border border-gray-100">
|
||||
<div className="h-64 bg-gray-100 relative overflow-hidden">
|
||||
<img
|
||||
src={product.images?.[0]?.url || `https://images.pexels.com/photos/1350789/pexels-photo-1350789.jpeg?auto=compress&cs=tinysrgb&w=400`}
|
||||
alt={product.title}
|
||||
className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700"
|
||||
/>
|
||||
<div className="absolute top-4 right-4 flex flex-col space-y-2 opacity-0 group-hover:opacity-100 transition-all duration-300 transform translate-x-4 group-hover:translate-x-0">
|
||||
<button
|
||||
onClick={() => handleQuickAdd(product)}
|
||||
className="bg-white p-3 rounded-2xl shadow-xl hover:bg-blue-600 hover:text-white transition-all transform hover:scale-110"
|
||||
>
|
||||
<BaseIcon path={mdiCart} size={20} />
|
||||
</button>
|
||||
{currentUser && (
|
||||
<button
|
||||
onClick={() => dispatch(toggleWishlist(product.id))}
|
||||
className={`bg-white p-3 rounded-2xl shadow-xl transition-all transform hover:scale-110 ${wishlisted ? 'text-red-500' : 'text-gray-400 hover:text-red-500'}`}
|
||||
>
|
||||
<BaseIcon path={wishlisted ? mdiHeart : mdiHeartOutline} size={20} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-8 flex-grow flex flex-col">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h3 className="text-xl font-bold text-gray-900 group-hover:text-blue-600 transition-colors line-clamp-1">
|
||||
{product.title}
|
||||
</h3>
|
||||
{avg > 0 && (
|
||||
<div className="flex items-center text-yellow-500 font-bold text-sm">
|
||||
<BaseIcon path={mdiStar} size={16} className="mr-1" />
|
||||
<span>{avg.toFixed(1)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-between mt-auto pt-6 border-t border-gray-50">
|
||||
<div className="flex flex-col">
|
||||
{product.sale_price ? (
|
||||
<>
|
||||
<span className="text-2xl font-black text-red-600">${product.sale_price}</span>
|
||||
<span className="text-xs text-gray-400 line-through font-bold">${product.price}</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-2xl font-black text-blue-600">${product.price}</span>
|
||||
)}
|
||||
</div>
|
||||
<Link
|
||||
href={`/products/${product.id}`}
|
||||
className="px-6 py-3 bg-gray-900 text-white text-[10px] font-black rounded-2xl hover:bg-blue-600 transition-all uppercase tracking-widest shadow-md hover:shadow-xl transform hover:-translate-y-0.5"
|
||||
>
|
||||
Details
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)})
|
||||
) : (
|
||||
<div className="col-span-full py-32 text-center bg-white rounded-[3rem] border border-gray-100 shadow-sm">
|
||||
<div className="bg-gray-50 w-24 h-24 rounded-full flex items-center justify-center mx-auto mb-8 text-gray-300">
|
||||
<BaseIcon path={mdiFilter} size={48} />
|
||||
</div>
|
||||
<p className="text-gray-500 font-bold text-2xl mb-8">No products matching your criteria.</p>
|
||||
<BaseButton
|
||||
onClick={() => { setSelectedCategory('all'); setPriceRange({min:'', max:''}); }}
|
||||
label="Reset all filters"
|
||||
color="info"
|
||||
className="rounded-2xl px-10 py-4 font-bold"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
ProductCatalog.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutGuest>{page}</LayoutGuest>;
|
||||
};
|
||||
158
frontend/src/pages/seller/apply.tsx
Normal file
158
frontend/src/pages/seller/apply.tsx
Normal file
@ -0,0 +1,158 @@
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import type { ReactElement } from 'react';
|
||||
import Head from 'next/head';
|
||||
import axios from 'axios';
|
||||
import { mdiStorePlus, mdiCheckCircle, mdiClockOutline, mdiAlertCircle } from '@mdi/js';
|
||||
import CardBox from '../../components/CardBox';
|
||||
import LayoutAuthenticated from '../../layouts/Authenticated';
|
||||
import SectionMain from '../../components/SectionMain';
|
||||
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
|
||||
import { getPageTitle } from '../../config';
|
||||
import FormField from '../../components/FormField';
|
||||
import BaseButton from '../../components/BaseButton';
|
||||
import BaseIcon from '../../components/BaseIcon';
|
||||
import { useAppSelector } from '../../stores/hooks';
|
||||
|
||||
const SellerApply = () => {
|
||||
const [shopName, setShopName] = useState('');
|
||||
const [shopDescription, setShopDescription] = useState('');
|
||||
const [status, setStatus] = useState<'none' | 'pending' | 'approved' | 'rejected'>('none');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetchStatus();
|
||||
}, []);
|
||||
|
||||
const fetchStatus = async () => {
|
||||
try {
|
||||
const response = await axios.get('/seller/status');
|
||||
setStatus(response.data.status || 'none');
|
||||
} catch (error) {
|
||||
console.error('Error fetching seller status:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await axios.post('/seller/apply', { shopName, shopDescription });
|
||||
setStatus('pending');
|
||||
} catch (error) {
|
||||
console.error('Error applying for seller:', error);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <div className="p-8 text-center font-bold">Loading...</div>;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('Become a Seller')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiStorePlus} title="Marketplace Seller Application" main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
|
||||
<div className="max-w-2xl mx-auto">
|
||||
{status === 'pending' && (
|
||||
<CardBox className="border-2 border-yellow-400 bg-yellow-50 mb-6">
|
||||
<div className="flex items-center text-yellow-700 p-4">
|
||||
<BaseIcon path={mdiClockOutline} size={48} className="mr-6 shrink-0" />
|
||||
<div>
|
||||
<h3 className="text-xl font-bold mb-1">Application Pending</h3>
|
||||
<p>Our team is reviewing your application. You'll be notified once approved.</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardBox>
|
||||
)}
|
||||
|
||||
{status === 'approved' && (
|
||||
<CardBox className="border-2 border-green-400 bg-green-50 mb-6">
|
||||
<div className="flex items-center text-green-700 p-4">
|
||||
<BaseIcon path={mdiCheckCircle} size={48} className="mr-6 shrink-0" />
|
||||
<div>
|
||||
<h3 className="text-xl font-bold mb-1">Application Approved!</h3>
|
||||
<p>Welcome to the Marketplace. You can now start listing your products.</p>
|
||||
<BaseButton
|
||||
className="mt-4"
|
||||
color="success"
|
||||
label="Go to Seller Portal"
|
||||
href="/seller/portal"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardBox>
|
||||
)}
|
||||
|
||||
{status === 'rejected' && (
|
||||
<CardBox className="border-2 border-red-400 bg-red-50 mb-6">
|
||||
<div className="flex items-center text-red-700 p-4">
|
||||
<BaseIcon path={mdiAlertCircle} size={48} className="mr-6 shrink-0" />
|
||||
<div>
|
||||
<h3 className="text-xl font-bold mb-1">Application Rejected</h3>
|
||||
<p>Unfortunately, your application was not approved at this time. You can try applying again later.</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardBox>
|
||||
)}
|
||||
|
||||
{status === 'none' && (
|
||||
<CardBox isForm onSubmit={handleSubmit}>
|
||||
<div className="space-y-6">
|
||||
<p className="text-gray-600">
|
||||
Open your shop today! Fill out the details below to start selling your products on our platform.
|
||||
</p>
|
||||
|
||||
<FormField label="Shop Name" help="Enter a unique name for your storefront">
|
||||
<input
|
||||
type="text"
|
||||
value={shopName}
|
||||
onChange={(e) => setShopName(e.target.value)}
|
||||
placeholder="e.g. Awesome Gadgets Hub"
|
||||
required
|
||||
className="w-full"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="Shop Description" help="Tell us what you plan to sell (min 20 characters)">
|
||||
<textarea
|
||||
value={shopDescription}
|
||||
onChange={(e) => setShopDescription(e.target.value)}
|
||||
placeholder="Provide a brief overview of your business..."
|
||||
required
|
||||
rows={4}
|
||||
className="w-full"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<div className="pt-4 border-t">
|
||||
<BaseButton
|
||||
type="submit"
|
||||
color="info"
|
||||
label={submitting ? "Submitting..." : "Submit Application"}
|
||||
disabled={submitting || shopDescription.length < 20}
|
||||
className="w-full py-4 font-bold text-lg"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardBox>
|
||||
)}
|
||||
</div>
|
||||
</SectionMain>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
SellerApply.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
|
||||
};
|
||||
|
||||
export default SellerApply;
|
||||
174
frontend/src/pages/seller/portal.tsx
Normal file
174
frontend/src/pages/seller/portal.tsx
Normal file
@ -0,0 +1,174 @@
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import type { ReactElement } from 'react';
|
||||
import Head from 'next/head';
|
||||
import axios from 'axios';
|
||||
import { mdiStore, mdiPlus, mdiFormatListBulleted, mdiTrendingUp, mdiPackageVariant } from '@mdi/js';
|
||||
import CardBox from '../../components/CardBox';
|
||||
import LayoutAuthenticated from '../../layouts/Authenticated';
|
||||
import SectionMain from '../../components/SectionMain';
|
||||
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
|
||||
import { getPageTitle } from '../../config';
|
||||
import BaseButton from '../../components/BaseButton';
|
||||
import BaseIcon from '../../components/BaseIcon';
|
||||
import { useAppSelector } from '../../stores/hooks';
|
||||
|
||||
const SellerPortal = () => {
|
||||
const { currentUser } = useAppSelector((state) => state.auth);
|
||||
const [products, setProducts] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
fetchMyProducts();
|
||||
}, []);
|
||||
|
||||
const fetchMyProducts = async () => {
|
||||
try {
|
||||
// Fetch products where sellerId matches current user
|
||||
// Note: Backend might need to support filtering by sellerId in /products
|
||||
const response = await axios.get('/products', {
|
||||
params: { sellerId: currentUser.id }
|
||||
});
|
||||
setProducts(response.data.rows || []);
|
||||
} catch (error) {
|
||||
console.error('Error fetching seller products:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('Seller Portal')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiStore} title={`Seller Portal: ${currentUser?.shopName || 'Your Shop'}`} main>
|
||||
<BaseButton
|
||||
href="/products/products-new"
|
||||
icon={mdiPlus}
|
||||
label="Add Product"
|
||||
color="info"
|
||||
className="rounded-2xl"
|
||||
/>
|
||||
</SectionTitleLineWithButton>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-12">
|
||||
<CardBox className="bg-blue-600 text-white border-none shadow-blue-200 shadow-xl">
|
||||
<div className="flex items-center">
|
||||
<div className="bg-white/20 p-4 rounded-2xl mr-6">
|
||||
<BaseIcon path={mdiPackageVariant} size={32} />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-blue-100 font-bold uppercase tracking-widest text-xs mb-1">Total Products</p>
|
||||
<h3 className="text-3xl font-black">{products.length}</h3>
|
||||
</div>
|
||||
</div>
|
||||
</CardBox>
|
||||
<CardBox className="bg-white border-gray-100">
|
||||
<div className="flex items-center text-gray-900">
|
||||
<div className="bg-gray-50 p-4 rounded-2xl mr-6 text-green-600">
|
||||
<BaseIcon path={mdiTrendingUp} size={32} />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-gray-400 font-bold uppercase tracking-widest text-xs mb-1">Active Sales</p>
|
||||
<h3 className="text-3xl font-black">0</h3>
|
||||
</div>
|
||||
</div>
|
||||
</CardBox>
|
||||
<CardBox className="bg-white border-gray-100">
|
||||
<div className="flex items-center text-gray-900">
|
||||
<div className="bg-gray-50 p-4 rounded-2xl mr-6 text-blue-600">
|
||||
<BaseIcon path={mdiFormatListBulleted} size={32} />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-gray-400 font-bold uppercase tracking-widest text-xs mb-1">Manage</p>
|
||||
<h3 className="text-xl font-bold">Listings</h3>
|
||||
</div>
|
||||
</div>
|
||||
</CardBox>
|
||||
</div>
|
||||
|
||||
<CardBox className="border-gray-100">
|
||||
<h2 className="text-xl font-black mb-8 flex items-center">
|
||||
<BaseIcon path={mdiFormatListBulleted} size={24} className="mr-3 text-blue-600" />
|
||||
Your Active Listings
|
||||
</h2>
|
||||
|
||||
{loading ? (
|
||||
<p className="text-center py-12 text-gray-400 font-bold">Loading your products...</p>
|
||||
) : products.length > 0 ? (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left">
|
||||
<thead>
|
||||
<tr className="text-gray-400 uppercase text-xs font-black tracking-widest border-b border-gray-50">
|
||||
<th className="px-4 py-4">Product</th>
|
||||
<th className="px-4 py-4">Price</th>
|
||||
<th className="px-4 py-4">Stock</th>
|
||||
<th className="px-4 py-4">Status</th>
|
||||
<th className="px-4 py-4 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{products.map((p: any) => (
|
||||
<tr key={p.id} className="border-b border-gray-50 hover:bg-gray-50/50 transition-colors group">
|
||||
<td className="px-4 py-6">
|
||||
<div className="flex items-center">
|
||||
<div className="w-12 h-12 rounded-xl bg-gray-100 mr-4 overflow-hidden">
|
||||
<img src={p.images?.[0]?.url || 'https://via.placeholder.com/100'} className="w-full h-full object-cover" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-bold text-gray-900 group-hover:text-blue-600 transition-colors">{p.title}</p>
|
||||
<p className="text-xs text-gray-400 font-bold uppercase">{p.sku}</p>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-6 font-bold text-gray-900">${p.price}</td>
|
||||
<td className="px-4 py-6">
|
||||
<span className={`px-3 py-1 rounded-lg text-xs font-black ${p.stock > 10 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
|
||||
{p.stock} units
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-6">
|
||||
<span className={`px-3 py-1 rounded-lg text-xs font-black ${p.active ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-700'}`}>
|
||||
{p.active ? 'ACTIVE' : 'INACTIVE'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-6 text-right">
|
||||
<BaseButton
|
||||
color="info"
|
||||
label="Edit"
|
||||
small
|
||||
className="rounded-xl px-4"
|
||||
href={`/products/products-edit?id=${p.id}`}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-20 bg-gray-50 rounded-[2rem] border-2 border-dashed border-gray-100">
|
||||
<BaseIcon path={mdiPackageVariant} size={48} className="mx-auto mb-4 text-gray-300" />
|
||||
<p className="text-gray-500 font-bold text-lg mb-6">You haven't added any products yet.</p>
|
||||
<BaseButton
|
||||
href="/products/products-new"
|
||||
icon={mdiPlus}
|
||||
label="Create Your First Listing"
|
||||
color="info"
|
||||
className="rounded-2xl px-8"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
SellerPortal.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
|
||||
};
|
||||
|
||||
export default SellerPortal;
|
||||
Loading…
x
Reference in New Issue
Block a user