This commit is contained in:
Flatlogic Bot 2025-05-24 09:46:54 +00:00
parent 7f865aad3b
commit 5c2617a1e3
89 changed files with 8695 additions and 20 deletions

File diff suppressed because one or more lines are too long

View File

@ -169,6 +169,10 @@ module.exports = class BookingsDBApi {
transaction, transaction,
}); });
output.redemption_booking = await bookings.getRedemption_booking({
transaction,
});
output.customer = await bookings.getCustomer({ output.customer = await bookings.getCustomer({
transaction, transaction,
}); });

View File

@ -16,6 +16,9 @@ module.exports = class LoyaltytierDBApi {
id: data.id || undefined, id: data.id || undefined,
name: data.name || null, name: data.name || null,
annualfee: data.annualfee || null,
pointspersar: data.pointspersar || null,
description: data.description || null,
importHash: data.importHash || null, importHash: data.importHash || null,
createdById: currentUser.id, createdById: currentUser.id,
updatedById: currentUser.id, updatedById: currentUser.id,
@ -35,6 +38,9 @@ module.exports = class LoyaltytierDBApi {
id: item.id || undefined, id: item.id || undefined,
name: item.name || null, name: item.name || null,
annualfee: item.annualfee || null,
pointspersar: item.pointspersar || null,
description: item.description || null,
importHash: item.importHash || null, importHash: item.importHash || null,
createdById: currentUser.id, createdById: currentUser.id,
updatedById: currentUser.id, updatedById: currentUser.id,
@ -61,6 +67,14 @@ module.exports = class LoyaltytierDBApi {
if (data.name !== undefined) updatePayload.name = data.name; if (data.name !== undefined) updatePayload.name = data.name;
if (data.annualfee !== undefined) updatePayload.annualfee = data.annualfee;
if (data.pointspersar !== undefined)
updatePayload.pointspersar = data.pointspersar;
if (data.description !== undefined)
updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id; updatePayload.updatedById = currentUser.id;
await loyaltytier.update(updatePayload, { transaction }); await loyaltytier.update(updatePayload, { transaction });
@ -129,6 +143,10 @@ module.exports = class LoyaltytierDBApi {
const output = loyaltytier.get({ plain: true }); const output = loyaltytier.get({ plain: true });
output.users_loyaltytier = await loyaltytier.getUsers_loyaltytier({
transaction,
});
return output; return output;
} }
@ -161,6 +179,65 @@ module.exports = class LoyaltytierDBApi {
}; };
} }
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'loyaltytier',
'description',
filter.description,
),
};
}
if (filter.annualfeeRange) {
const [start, end] = filter.annualfeeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
annualfee: {
...where.annualfee,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
annualfee: {
...where.annualfee,
[Op.lte]: end,
},
};
}
}
if (filter.pointspersarRange) {
const [start, end] = filter.pointspersarRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
pointspersar: {
...where.pointspersar,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
pointspersar: {
...where.pointspersar,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) { if (filter.active !== undefined) {
where = { where = {
...where, ...where,

View File

@ -0,0 +1,402 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class RedemptionDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const redemption = await db.redemption.create(
{
id: data.id || undefined,
pointsused: data.pointsused || null,
redemptiontype: data.redemptiontype || null,
discountvalue: data.discountvalue || null,
status: data.status || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await redemption.setUser(data.user || null, {
transaction,
});
await redemption.setBooking(data.booking || null, {
transaction,
});
return redemption;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const redemptionData = data.map((item, index) => ({
id: item.id || undefined,
pointsused: item.pointsused || null,
redemptiontype: item.redemptiontype || null,
discountvalue: item.discountvalue || null,
status: item.status || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const redemption = await db.redemption.bulkCreate(redemptionData, {
transaction,
});
// For each item created, replace relation files
return redemption;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const redemption = await db.redemption.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.pointsused !== undefined)
updatePayload.pointsused = data.pointsused;
if (data.redemptiontype !== undefined)
updatePayload.redemptiontype = data.redemptiontype;
if (data.discountvalue !== undefined)
updatePayload.discountvalue = data.discountvalue;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await redemption.update(updatePayload, { transaction });
if (data.user !== undefined) {
await redemption.setUser(
data.user,
{ transaction },
);
}
if (data.booking !== undefined) {
await redemption.setBooking(
data.booking,
{ transaction },
);
}
return redemption;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const redemption = await db.redemption.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of redemption) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of redemption) {
await record.destroy({ transaction });
}
});
return redemption;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const redemption = await db.redemption.findByPk(id, options);
await redemption.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await redemption.destroy({
transaction,
});
return redemption;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const redemption = await db.redemption.findOne({ where }, { transaction });
if (!redemption) {
return redemption;
}
const output = redemption.get({ plain: true });
output.user = await redemption.getUser({
transaction,
});
output.booking = await redemption.getBooking({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'user',
where: filter.user
? {
[Op.or]: [
{
id: {
[Op.in]: filter.user
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
firstName: {
[Op.or]: filter.user
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.bookings,
as: 'booking',
where: filter.booking
? {
[Op.or]: [
{
id: {
[Op.in]: filter.booking
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
service_type: {
[Op.or]: filter.booking
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.pointsusedRange) {
const [start, end] = filter.pointsusedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
pointsused: {
...where.pointsused,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
pointsused: {
...where.pointsused,
[Op.lte]: end,
},
};
}
}
if (filter.discountvalueRange) {
const [start, end] = filter.discountvalueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
discountvalue: {
...where.discountvalue,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
discountvalue: {
...where.discountvalue,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.redemptiontype) {
where = {
...where,
redemptiontype: filter.redemptiontype,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order:
filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log,
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.redemption.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count,
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('redemption', 'id', query),
],
};
}
const records = await db.redemption.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,306 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ReferralDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referral = await db.referral.create(
{
id: data.id || undefined,
referredemail: data.referredemail || null,
status: data.status || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await referral.setReferrer(data.referrer || null, {
transaction,
});
return referral;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const referralData = data.map((item, index) => ({
id: item.id || undefined,
referredemail: item.referredemail || null,
status: item.status || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const referral = await db.referral.bulkCreate(referralData, {
transaction,
});
// For each item created, replace relation files
return referral;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referral = await db.referral.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.referredemail !== undefined)
updatePayload.referredemail = data.referredemail;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await referral.update(updatePayload, { transaction });
if (data.referrer !== undefined) {
await referral.setReferrer(
data.referrer,
{ transaction },
);
}
return referral;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referral = await db.referral.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of referral) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of referral) {
await record.destroy({ transaction });
}
});
return referral;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referral = await db.referral.findByPk(id, options);
await referral.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await referral.destroy({
transaction,
});
return referral;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const referral = await db.referral.findOne({ where }, { transaction });
if (!referral) {
return referral;
}
const output = referral.get({ plain: true });
output.referrer = await referral.getReferrer({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'referrer',
where: filter.referrer
? {
[Op.or]: [
{
id: {
[Op.in]: filter.referrer
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
firstName: {
[Op.or]: filter.referrer
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.referredemail) {
where = {
...where,
[Op.and]: Utils.ilike(
'referral',
'referredemail',
filter.referredemail,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order:
filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log,
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.referral.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count,
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('referral', 'id', query),
],
};
}
const records = await db.referral.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -34,6 +34,8 @@ module.exports = class UsersDBApi {
passwordResetTokenExpiresAt: passwordResetTokenExpiresAt:
data.data.passwordResetTokenExpiresAt || null, data.data.passwordResetTokenExpiresAt || null,
provider: data.data.provider || null, provider: data.data.provider || null,
pointsbalance: data.data.pointsbalance || null,
referralcode: data.data.referralcode || null,
importHash: data.data.importHash || null, importHash: data.data.importHash || null,
createdById: currentUser.id, createdById: currentUser.id,
updatedById: currentUser.id, updatedById: currentUser.id,
@ -56,6 +58,10 @@ module.exports = class UsersDBApi {
}); });
} }
await users.setLoyaltytier(data.data.loyaltytier || null, {
transaction,
});
await users.setCustom_permissions(data.data.custom_permissions || [], { await users.setCustom_permissions(data.data.custom_permissions || [], {
transaction, transaction,
}); });
@ -96,6 +102,8 @@ module.exports = class UsersDBApi {
passwordResetToken: item.passwordResetToken || null, passwordResetToken: item.passwordResetToken || null,
passwordResetTokenExpiresAt: item.passwordResetTokenExpiresAt || null, passwordResetTokenExpiresAt: item.passwordResetTokenExpiresAt || null,
provider: item.provider || null, provider: item.provider || null,
pointsbalance: item.pointsbalance || null,
referralcode: item.referralcode || null,
importHash: item.importHash || null, importHash: item.importHash || null,
createdById: currentUser.id, createdById: currentUser.id,
updatedById: currentUser.id, updatedById: currentUser.id,
@ -178,6 +186,12 @@ module.exports = class UsersDBApi {
if (data.provider !== undefined) updatePayload.provider = data.provider; if (data.provider !== undefined) updatePayload.provider = data.provider;
if (data.pointsbalance !== undefined)
updatePayload.pointsbalance = data.pointsbalance;
if (data.referralcode !== undefined)
updatePayload.referralcode = data.referralcode;
updatePayload.updatedById = currentUser.id; updatePayload.updatedById = currentUser.id;
await users.update(updatePayload, { transaction }); await users.update(updatePayload, { transaction });
@ -190,6 +204,14 @@ module.exports = class UsersDBApi {
); );
} }
if (data.loyaltytier !== undefined) {
await users.setLoyaltytier(
data.loyaltytier,
{ transaction },
);
}
if (data.custom_permissions !== undefined) { if (data.custom_permissions !== undefined) {
await users.setCustom_permissions(data.custom_permissions, { await users.setCustom_permissions(data.custom_permissions, {
transaction, transaction,
@ -267,6 +289,14 @@ module.exports = class UsersDBApi {
const output = users.get({ plain: true }); const output = users.get({ plain: true });
output.referral_referrer = await users.getReferral_referrer({
transaction,
});
output.redemption_user = await users.getRedemption_user({
transaction,
});
output.avatar = await users.getAvatar({ output.avatar = await users.getAvatar({
transaction, transaction,
}); });
@ -285,6 +315,10 @@ module.exports = class UsersDBApi {
transaction, transaction,
}); });
output.loyaltytier = await users.getLoyaltytier({
transaction,
});
return output; return output;
} }
@ -327,6 +361,32 @@ module.exports = class UsersDBApi {
: {}, : {},
}, },
{
model: db.loyaltytier,
as: 'loyaltytier',
where: filter.loyaltytier
? {
[Op.or]: [
{
id: {
[Op.in]: filter.loyaltytier
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
name: {
[Op.or]: filter.loyaltytier
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{ {
model: db.permissions, model: db.permissions,
as: 'custom_permissions', as: 'custom_permissions',
@ -411,6 +471,13 @@ module.exports = class UsersDBApi {
}; };
} }
if (filter.referralcode) {
where = {
...where,
[Op.and]: Utils.ilike('users', 'referralcode', filter.referralcode),
};
}
if (filter.emailVerificationTokenExpiresAtRange) { if (filter.emailVerificationTokenExpiresAtRange) {
const [start, end] = filter.emailVerificationTokenExpiresAtRange; const [start, end] = filter.emailVerificationTokenExpiresAtRange;
@ -459,6 +526,30 @@ module.exports = class UsersDBApi {
} }
} }
if (filter.pointsbalanceRange) {
const [start, end] = filter.pointsbalanceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
pointsbalance: {
...where.pointsbalance,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
pointsbalance: {
...where.pointsbalance,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) { if (filter.active !== undefined) {
where = { where = {
...where, ...where,

View File

@ -0,0 +1,49 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'loyaltytier',
'annualfee',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('loyaltytier', 'annualfee', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,49 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'loyaltytier',
'pointspersar',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('loyaltytier', 'pointspersar', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,49 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'loyaltytier',
'description',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('loyaltytier', 'description', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,54 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'users',
'loyaltytierId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'loyaltytier',
key: 'id',
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('users', 'loyaltytierId', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,49 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'users',
'pointsbalance',
{
type: Sequelize.DataTypes.INTEGER,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('users', 'pointsbalance', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,49 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'users',
'referralcode',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('users', 'referralcode', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,72 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.createTable(
'referral',
{
id: {
type: Sequelize.DataTypes.UUID,
defaultValue: Sequelize.DataTypes.UUIDV4,
primaryKey: true,
},
createdById: {
type: Sequelize.DataTypes.UUID,
references: {
key: 'id',
model: 'users',
},
},
updatedById: {
type: Sequelize.DataTypes.UUID,
references: {
key: 'id',
model: 'users',
},
},
createdAt: { type: Sequelize.DataTypes.DATE },
updatedAt: { type: Sequelize.DataTypes.DATE },
deletedAt: { type: Sequelize.DataTypes.DATE },
importHash: {
type: Sequelize.DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.dropTable('referral', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,54 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'referral',
'referrerId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'users',
key: 'id',
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('referral', 'referrerId', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,49 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'referral',
'referredemail',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('referral', 'referredemail', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,49 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'referral',
'status',
{
type: Sequelize.DataTypes.ENUM,
values: ['value'],
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('referral', 'status', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,72 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.createTable(
'redemption',
{
id: {
type: Sequelize.DataTypes.UUID,
defaultValue: Sequelize.DataTypes.UUIDV4,
primaryKey: true,
},
createdById: {
type: Sequelize.DataTypes.UUID,
references: {
key: 'id',
model: 'users',
},
},
updatedById: {
type: Sequelize.DataTypes.UUID,
references: {
key: 'id',
model: 'users',
},
},
createdAt: { type: Sequelize.DataTypes.DATE },
updatedAt: { type: Sequelize.DataTypes.DATE },
deletedAt: { type: Sequelize.DataTypes.DATE },
importHash: {
type: Sequelize.DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.dropTable('redemption', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,54 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'redemption',
'userId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'users',
key: 'id',
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('redemption', 'userId', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,49 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'redemption',
'pointsused',
{
type: Sequelize.DataTypes.INTEGER,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('redemption', 'pointsused', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,51 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'redemption',
'redemptiontype',
{
type: Sequelize.DataTypes.ENUM,
values: ['value'],
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('redemption', 'redemptiontype', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,49 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'redemption',
'discountvalue',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('redemption', 'discountvalue', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,51 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'redemption',
'status',
{
type: Sequelize.DataTypes.ENUM,
values: ['value'],
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('redemption', 'status', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,54 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'redemption',
'bookingId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'bookings',
key: 'id',
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('redemption', 'bookingId', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -60,6 +60,14 @@ module.exports = function (sequelize, DataTypes) {
constraints: false, constraints: false,
}); });
db.bookings.hasMany(db.redemption, {
as: 'redemption_booking',
foreignKey: {
name: 'bookingId',
},
constraints: false,
});
//end loop //end loop
db.bookings.belongsTo(db.customers, { db.bookings.belongsTo(db.customers, {

View File

@ -18,6 +18,18 @@ module.exports = function (sequelize, DataTypes) {
type: DataTypes.TEXT, type: DataTypes.TEXT,
}, },
annualfee: {
type: DataTypes.DECIMAL,
},
pointspersar: {
type: DataTypes.DECIMAL,
},
description: {
type: DataTypes.TEXT,
},
importHash: { importHash: {
type: DataTypes.STRING(255), type: DataTypes.STRING(255),
allowNull: true, allowNull: true,
@ -34,6 +46,14 @@ module.exports = function (sequelize, DataTypes) {
loyaltytier.associate = (db) => { loyaltytier.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity /// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.loyaltytier.hasMany(db.users, {
as: 'users_loyaltytier',
foreignKey: {
name: 'loyaltytierId',
},
constraints: false,
});
//end loop //end loop
db.loyaltytier.belongsTo(db.users, { db.loyaltytier.belongsTo(db.users, {

View File

@ -0,0 +1,81 @@
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 redemption = sequelize.define(
'redemption',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
pointsused: {
type: DataTypes.INTEGER,
},
redemptiontype: {
type: DataTypes.ENUM,
values: ['value'],
},
discountvalue: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: ['value'],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
redemption.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.redemption.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.redemption.belongsTo(db.bookings, {
as: 'booking',
foreignKey: {
name: 'bookingId',
},
constraints: false,
});
db.redemption.belongsTo(db.users, {
as: 'createdBy',
});
db.redemption.belongsTo(db.users, {
as: 'updatedBy',
});
};
return redemption;
};

View File

@ -0,0 +1,63 @@
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 referral = sequelize.define(
'referral',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
referredemail: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: ['value'],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
referral.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.referral.belongsTo(db.users, {
as: 'referrer',
foreignKey: {
name: 'referrerId',
},
constraints: false,
});
db.referral.belongsTo(db.users, {
as: 'createdBy',
});
db.referral.belongsTo(db.users, {
as: 'updatedBy',
});
};
return referral;
};

View File

@ -68,6 +68,14 @@ module.exports = function (sequelize, DataTypes) {
type: DataTypes.TEXT, type: DataTypes.TEXT,
}, },
pointsbalance: {
type: DataTypes.INTEGER,
},
referralcode: {
type: DataTypes.TEXT,
},
importHash: { importHash: {
type: DataTypes.STRING(255), type: DataTypes.STRING(255),
allowNull: true, allowNull: true,
@ -102,6 +110,22 @@ module.exports = function (sequelize, DataTypes) {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity /// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.users.hasMany(db.referral, {
as: 'referral_referrer',
foreignKey: {
name: 'referrerId',
},
constraints: false,
});
db.users.hasMany(db.redemption, {
as: 'redemption_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
//end loop //end loop
db.users.belongsTo(db.roles, { db.users.belongsTo(db.roles, {
@ -112,6 +136,14 @@ module.exports = function (sequelize, DataTypes) {
constraints: false, constraints: false,
}); });
db.users.belongsTo(db.loyaltytier, {
as: 'loyaltytier',
foreignKey: {
name: 'loyaltytierId',
},
constraints: false,
});
db.users.hasMany(db.file, { db.users.hasMany(db.file, {
as: 'avatar', as: 'avatar',
foreignKey: 'belongsToId', foreignKey: 'belongsToId',

View File

@ -103,6 +103,8 @@ module.exports = {
'roles', 'roles',
'permissions', 'permissions',
'loyaltytier', 'loyaltytier',
'referral',
'redemption',
, ,
]; ];
await queryInterface.bulkInsert( await queryInterface.bulkInsert(
@ -712,6 +714,56 @@ primary key ("roles_permissionsId", "permissionId")
permissionId: getId('DELETE_LOYALTYTIER'), permissionId: getId('DELETE_LOYALTYTIER'),
}, },
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('CREATE_REFERRAL'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('READ_REFERRAL'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('UPDATE_REFERRAL'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('DELETE_REFERRAL'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('CREATE_REDEMPTION'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('READ_REDEMPTION'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('UPDATE_REDEMPTION'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('DELETE_REDEMPTION'),
},
{ {
createdAt, createdAt,
updatedAt, updatedAt,

View File

@ -13,6 +13,10 @@ const Vouchers = db.vouchers;
const Loyaltytier = db.loyaltytier; const Loyaltytier = db.loyaltytier;
const Referral = db.referral;
const Redemption = db.redemption;
const AgentsData = [ const AgentsData = [
{ {
name: 'Agent A', name: 'Agent A',
@ -45,13 +49,21 @@ const AgentsData = [
phone_number: '4564564567', phone_number: '4564564567',
}, },
{
name: 'Agent E',
email: 'agent.e@example.com',
phone_number: '5675675678',
},
]; ];
const BookingsData = [ const BookingsData = [
{ {
// type code here for "relation_one" field // type code here for "relation_one" field
service_type: 'Hotel', service_type: 'Package',
booking_date: new Date('2023-11-01T10:00:00Z'), booking_date: new Date('2023-11-01T10:00:00Z'),
@ -63,7 +75,7 @@ const BookingsData = [
{ {
// type code here for "relation_one" field // type code here for "relation_one" field
service_type: 'Package', service_type: 'Tour',
booking_date: new Date('2023-11-02T12:00:00Z'), booking_date: new Date('2023-11-02T12:00:00Z'),
@ -75,7 +87,7 @@ const BookingsData = [
{ {
// type code here for "relation_one" field // type code here for "relation_one" field
service_type: 'Hotel', service_type: 'Tour',
booking_date: new Date('2023-11-03T14:00:00Z'), booking_date: new Date('2023-11-03T14:00:00Z'),
@ -87,7 +99,7 @@ const BookingsData = [
{ {
// type code here for "relation_one" field // type code here for "relation_one" field
service_type: 'Hotel', service_type: 'Package',
booking_date: new Date('2023-11-04T16:00:00Z'), booking_date: new Date('2023-11-04T16:00:00Z'),
@ -95,6 +107,18 @@ const BookingsData = [
// type code here for "relation_one" field // type code here for "relation_one" field
}, },
{
// type code here for "relation_one" field
service_type: 'Tour',
booking_date: new Date('2023-11-05T18:00:00Z'),
total_amount: 450,
// type code here for "relation_one" field
},
]; ];
const CustomersData = [ const CustomersData = [
@ -137,6 +161,16 @@ const CustomersData = [
phone_number: '5566778899', phone_number: '5566778899',
}, },
{
first_name: 'Charlie',
last_name: 'Davis',
email: 'charlie.davis@example.com',
phone_number: '6677889900',
},
]; ];
const PaymentsData = [ const PaymentsData = [
@ -147,7 +181,7 @@ const PaymentsData = [
amount: 500, amount: 500,
status: 'Failed', status: 'Pending',
}, },
{ {
@ -157,7 +191,7 @@ const PaymentsData = [
amount: 300, amount: 300,
status: 'Pending', status: 'Failed',
}, },
{ {
@ -167,7 +201,7 @@ const PaymentsData = [
amount: 800, amount: 800,
status: 'Pending', status: 'Completed',
}, },
{ {
@ -179,6 +213,16 @@ const PaymentsData = [
status: 'Pending', status: 'Pending',
}, },
{
// type code here for "relation_one" field
payment_date: new Date('2023-11-05T19:00:00Z'),
amount: 450,
status: 'Failed',
},
]; ];
const VouchersData = [ const VouchersData = [
@ -213,28 +257,241 @@ const VouchersData = [
issue_date: new Date('2023-11-04T18:00:00Z'), issue_date: new Date('2023-11-04T18:00:00Z'),
}, },
{
// type code here for "relation_one" field
voucher_code: 'VCH56789',
issue_date: new Date('2023-11-05T20:00:00Z'),
},
]; ];
const LoyaltytierData = [ const LoyaltytierData = [
{
name: 'John Dalton',
annualfee: 74.62,
pointspersar: 51.91,
description: 'Jean Baptiste Lamarck',
},
{ {
name: 'B. F. Skinner', name: 'B. F. Skinner',
annualfee: 10.09,
pointspersar: 44.45,
description: 'Werner Heisenberg',
}, },
{ {
name: 'Carl Gauss (Karl Friedrich Gauss)', name: 'Tycho Brahe',
annualfee: 86.15,
pointspersar: 10.74,
description: 'Emil Fischer',
}, },
{ {
name: 'August Kekule', name: 'Francis Crick',
annualfee: 20.76,
pointspersar: 72.74,
description: 'William Bayliss',
}, },
{ {
name: 'James Watson', name: 'Thomas Hunt Morgan',
annualfee: 97.56,
pointspersar: 39.08,
description: 'Johannes Kepler',
},
];
const ReferralData = [
{
// type code here for "relation_one" field
referredemail: 'Ernst Haeckel',
status: 'value',
},
{
// type code here for "relation_one" field
referredemail: 'Heike Kamerlingh Onnes',
status: 'value',
},
{
// type code here for "relation_one" field
referredemail: 'Robert Koch',
status: 'value',
},
{
// type code here for "relation_one" field
referredemail: 'Jean Piaget',
status: 'value',
},
{
// type code here for "relation_one" field
referredemail: 'Jean Baptiste Lamarck',
status: 'value',
},
];
const RedemptionData = [
{
// type code here for "relation_one" field
pointsused: 5,
redemptiontype: 'value',
discountvalue: 62.55,
status: 'value',
// type code here for "relation_one" field
},
{
// type code here for "relation_one" field
pointsused: 5,
redemptiontype: 'value',
discountvalue: 99.45,
status: 'value',
// type code here for "relation_one" field
},
{
// type code here for "relation_one" field
pointsused: 8,
redemptiontype: 'value',
discountvalue: 29.35,
status: 'value',
// type code here for "relation_one" field
},
{
// type code here for "relation_one" field
pointsused: 5,
redemptiontype: 'value',
discountvalue: 91.62,
status: 'value',
// type code here for "relation_one" field
},
{
// type code here for "relation_one" field
pointsused: 9,
redemptiontype: 'value',
discountvalue: 87.53,
status: 'value',
// type code here for "relation_one" field
}, },
]; ];
// Similar logic for "relation_many" // Similar logic for "relation_many"
async function associateUserWithLoyaltytier() {
const relatedLoyaltytier0 = await Loyaltytier.findOne({
offset: Math.floor(Math.random() * (await Loyaltytier.count())),
});
const User0 = await Users.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (User0?.setLoyaltytier) {
await User0.setLoyaltytier(relatedLoyaltytier0);
}
const relatedLoyaltytier1 = await Loyaltytier.findOne({
offset: Math.floor(Math.random() * (await Loyaltytier.count())),
});
const User1 = await Users.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (User1?.setLoyaltytier) {
await User1.setLoyaltytier(relatedLoyaltytier1);
}
const relatedLoyaltytier2 = await Loyaltytier.findOne({
offset: Math.floor(Math.random() * (await Loyaltytier.count())),
});
const User2 = await Users.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (User2?.setLoyaltytier) {
await User2.setLoyaltytier(relatedLoyaltytier2);
}
const relatedLoyaltytier3 = await Loyaltytier.findOne({
offset: Math.floor(Math.random() * (await Loyaltytier.count())),
});
const User3 = await Users.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (User3?.setLoyaltytier) {
await User3.setLoyaltytier(relatedLoyaltytier3);
}
const relatedLoyaltytier4 = await Loyaltytier.findOne({
offset: Math.floor(Math.random() * (await Loyaltytier.count())),
});
const User4 = await Users.findOne({
order: [['id', 'ASC']],
offset: 4,
});
if (User4?.setLoyaltytier) {
await User4.setLoyaltytier(relatedLoyaltytier4);
}
}
async function associateBookingWithCustomer() { async function associateBookingWithCustomer() {
const relatedCustomer0 = await Customers.findOne({ const relatedCustomer0 = await Customers.findOne({
offset: Math.floor(Math.random() * (await Customers.count())), offset: Math.floor(Math.random() * (await Customers.count())),
@ -279,6 +536,17 @@ async function associateBookingWithCustomer() {
if (Booking3?.setCustomer) { if (Booking3?.setCustomer) {
await Booking3.setCustomer(relatedCustomer3); await Booking3.setCustomer(relatedCustomer3);
} }
const relatedCustomer4 = await Customers.findOne({
offset: Math.floor(Math.random() * (await Customers.count())),
});
const Booking4 = await Bookings.findOne({
order: [['id', 'ASC']],
offset: 4,
});
if (Booking4?.setCustomer) {
await Booking4.setCustomer(relatedCustomer4);
}
} }
async function associateBookingWithAgent() { async function associateBookingWithAgent() {
@ -325,6 +593,17 @@ async function associateBookingWithAgent() {
if (Booking3?.setAgent) { if (Booking3?.setAgent) {
await Booking3.setAgent(relatedAgent3); await Booking3.setAgent(relatedAgent3);
} }
const relatedAgent4 = await Agents.findOne({
offset: Math.floor(Math.random() * (await Agents.count())),
});
const Booking4 = await Bookings.findOne({
order: [['id', 'ASC']],
offset: 4,
});
if (Booking4?.setAgent) {
await Booking4.setAgent(relatedAgent4);
}
} }
async function associatePaymentWithBooking() { async function associatePaymentWithBooking() {
@ -371,6 +650,17 @@ async function associatePaymentWithBooking() {
if (Payment3?.setBooking) { if (Payment3?.setBooking) {
await Payment3.setBooking(relatedBooking3); await Payment3.setBooking(relatedBooking3);
} }
const relatedBooking4 = await Bookings.findOne({
offset: Math.floor(Math.random() * (await Bookings.count())),
});
const Payment4 = await Payments.findOne({
order: [['id', 'ASC']],
offset: 4,
});
if (Payment4?.setBooking) {
await Payment4.setBooking(relatedBooking4);
}
} }
async function associateVoucherWithBooking() { async function associateVoucherWithBooking() {
@ -417,6 +707,188 @@ async function associateVoucherWithBooking() {
if (Voucher3?.setBooking) { if (Voucher3?.setBooking) {
await Voucher3.setBooking(relatedBooking3); await Voucher3.setBooking(relatedBooking3);
} }
const relatedBooking4 = await Bookings.findOne({
offset: Math.floor(Math.random() * (await Bookings.count())),
});
const Voucher4 = await Vouchers.findOne({
order: [['id', 'ASC']],
offset: 4,
});
if (Voucher4?.setBooking) {
await Voucher4.setBooking(relatedBooking4);
}
}
async function associateReferralWithReferrer() {
const relatedReferrer0 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Referral0 = await Referral.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Referral0?.setReferrer) {
await Referral0.setReferrer(relatedReferrer0);
}
const relatedReferrer1 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Referral1 = await Referral.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Referral1?.setReferrer) {
await Referral1.setReferrer(relatedReferrer1);
}
const relatedReferrer2 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Referral2 = await Referral.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Referral2?.setReferrer) {
await Referral2.setReferrer(relatedReferrer2);
}
const relatedReferrer3 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Referral3 = await Referral.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (Referral3?.setReferrer) {
await Referral3.setReferrer(relatedReferrer3);
}
const relatedReferrer4 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Referral4 = await Referral.findOne({
order: [['id', 'ASC']],
offset: 4,
});
if (Referral4?.setReferrer) {
await Referral4.setReferrer(relatedReferrer4);
}
}
async function associateRedemptionWithUser() {
const relatedUser0 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Redemption0 = await Redemption.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Redemption0?.setUser) {
await Redemption0.setUser(relatedUser0);
}
const relatedUser1 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Redemption1 = await Redemption.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Redemption1?.setUser) {
await Redemption1.setUser(relatedUser1);
}
const relatedUser2 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Redemption2 = await Redemption.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Redemption2?.setUser) {
await Redemption2.setUser(relatedUser2);
}
const relatedUser3 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Redemption3 = await Redemption.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (Redemption3?.setUser) {
await Redemption3.setUser(relatedUser3);
}
const relatedUser4 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Redemption4 = await Redemption.findOne({
order: [['id', 'ASC']],
offset: 4,
});
if (Redemption4?.setUser) {
await Redemption4.setUser(relatedUser4);
}
}
async function associateRedemptionWithBooking() {
const relatedBooking0 = await Bookings.findOne({
offset: Math.floor(Math.random() * (await Bookings.count())),
});
const Redemption0 = await Redemption.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Redemption0?.setBooking) {
await Redemption0.setBooking(relatedBooking0);
}
const relatedBooking1 = await Bookings.findOne({
offset: Math.floor(Math.random() * (await Bookings.count())),
});
const Redemption1 = await Redemption.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Redemption1?.setBooking) {
await Redemption1.setBooking(relatedBooking1);
}
const relatedBooking2 = await Bookings.findOne({
offset: Math.floor(Math.random() * (await Bookings.count())),
});
const Redemption2 = await Redemption.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Redemption2?.setBooking) {
await Redemption2.setBooking(relatedBooking2);
}
const relatedBooking3 = await Bookings.findOne({
offset: Math.floor(Math.random() * (await Bookings.count())),
});
const Redemption3 = await Redemption.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (Redemption3?.setBooking) {
await Redemption3.setBooking(relatedBooking3);
}
const relatedBooking4 = await Bookings.findOne({
offset: Math.floor(Math.random() * (await Bookings.count())),
});
const Redemption4 = await Redemption.findOne({
order: [['id', 'ASC']],
offset: 4,
});
if (Redemption4?.setBooking) {
await Redemption4.setBooking(relatedBooking4);
}
} }
module.exports = { module.exports = {
@ -433,9 +905,15 @@ module.exports = {
await Loyaltytier.bulkCreate(LoyaltytierData); await Loyaltytier.bulkCreate(LoyaltytierData);
await Referral.bulkCreate(ReferralData);
await Redemption.bulkCreate(RedemptionData);
await Promise.all([ await Promise.all([
// Similar logic for "relation_many" // Similar logic for "relation_many"
await associateUserWithLoyaltytier(),
await associateBookingWithCustomer(), await associateBookingWithCustomer(),
await associateBookingWithAgent(), await associateBookingWithAgent(),
@ -443,6 +921,12 @@ module.exports = {
await associatePaymentWithBooking(), await associatePaymentWithBooking(),
await associateVoucherWithBooking(), await associateVoucherWithBooking(),
await associateReferralWithReferrer(),
await associateRedemptionWithUser(),
await associateRedemptionWithBooking(),
]); ]);
}, },
@ -458,5 +942,9 @@ module.exports = {
await queryInterface.bulkDelete('vouchers', null, {}); await queryInterface.bulkDelete('vouchers', null, {});
await queryInterface.bulkDelete('loyaltytier', null, {}); await queryInterface.bulkDelete('loyaltytier', null, {});
await queryInterface.bulkDelete('referral', null, {});
await queryInterface.bulkDelete('redemption', null, {});
}, },
}; };

View File

@ -0,0 +1,87 @@
const { v4: uuid } = require('uuid');
const db = require('../models');
const Sequelize = require('sequelize');
const config = require('../../config');
module.exports = {
/**
* @param{import("sequelize").QueryInterface} queryInterface
* @return {Promise<void>}
*/
async up(queryInterface) {
const createdAt = new Date();
const updatedAt = new Date();
/** @type {Map<string, string>} */
const idMap = new Map();
/**
* @param {string} key
* @return {string}
*/
function getId(key) {
if (idMap.has(key)) {
return idMap.get(key);
}
const id = uuid();
idMap.set(key, id);
return id;
}
/**
* @param {string} name
*/
function createPermissions(name) {
return [
{
id: getId(`CREATE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `CREATE_${name.toUpperCase()}`,
},
{
id: getId(`READ_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `READ_${name.toUpperCase()}`,
},
{
id: getId(`UPDATE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `UPDATE_${name.toUpperCase()}`,
},
{
id: getId(`DELETE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `DELETE_${name.toUpperCase()}`,
},
];
}
const entities = ['referral'];
const createdPermissions = entities.flatMap(createPermissions);
// Add permissions to database
await queryInterface.bulkInsert('permissions', createdPermissions);
// Get permissions ids
const permissionsIds = createdPermissions.map((p) => p.id);
// Get admin role
const adminRole = await db.roles.findOne({
where: { name: config.roles.admin },
});
if (adminRole) {
// Add permissions to admin role if it exists
await adminRole.addPermissions(permissionsIds);
}
},
down: async (queryInterface, Sequelize) => {
await queryInterface.bulkDelete(
'permissions',
entities.flatMap(createPermissions),
);
},
};

View File

@ -0,0 +1,87 @@
const { v4: uuid } = require('uuid');
const db = require('../models');
const Sequelize = require('sequelize');
const config = require('../../config');
module.exports = {
/**
* @param{import("sequelize").QueryInterface} queryInterface
* @return {Promise<void>}
*/
async up(queryInterface) {
const createdAt = new Date();
const updatedAt = new Date();
/** @type {Map<string, string>} */
const idMap = new Map();
/**
* @param {string} key
* @return {string}
*/
function getId(key) {
if (idMap.has(key)) {
return idMap.get(key);
}
const id = uuid();
idMap.set(key, id);
return id;
}
/**
* @param {string} name
*/
function createPermissions(name) {
return [
{
id: getId(`CREATE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `CREATE_${name.toUpperCase()}`,
},
{
id: getId(`READ_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `READ_${name.toUpperCase()}`,
},
{
id: getId(`UPDATE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `UPDATE_${name.toUpperCase()}`,
},
{
id: getId(`DELETE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `DELETE_${name.toUpperCase()}`,
},
];
}
const entities = ['redemption'];
const createdPermissions = entities.flatMap(createPermissions);
// Add permissions to database
await queryInterface.bulkInsert('permissions', createdPermissions);
// Get permissions ids
const permissionsIds = createdPermissions.map((p) => p.id);
// Get admin role
const adminRole = await db.roles.findOne({
where: { name: config.roles.admin },
});
if (adminRole) {
// Add permissions to admin role if it exists
await adminRole.addPermissions(permissionsIds);
}
},
down: async (queryInterface, Sequelize) => {
await queryInterface.bulkDelete(
'permissions',
entities.flatMap(createPermissions),
);
},
};

View File

@ -37,6 +37,10 @@ const permissionsRoutes = require('./routes/permissions');
const loyaltytierRoutes = require('./routes/loyaltytier'); const loyaltytierRoutes = require('./routes/loyaltytier');
const referralRoutes = require('./routes/referral');
const redemptionRoutes = require('./routes/redemption');
const getBaseUrl = (url) => { const getBaseUrl = (url) => {
if (!url) return ''; if (!url) return '';
return url.endsWith('/api') ? url.slice(0, -4) : url; return url.endsWith('/api') ? url.slice(0, -4) : url;
@ -156,6 +160,18 @@ app.use(
loyaltytierRoutes, loyaltytierRoutes,
); );
app.use(
'/api/referral',
passport.authenticate('jwt', { session: false }),
referralRoutes,
);
app.use(
'/api/redemption',
passport.authenticate('jwt', { session: false }),
redemptionRoutes,
);
app.use( app.use(
'/api/openai', '/api/openai',
passport.authenticate('jwt', { session: false }), passport.authenticate('jwt', { session: false }),

View File

@ -23,6 +23,16 @@ router.use(checkCrudPermissions('loyaltytier'));
* name: * name:
* type: string * type: string
* default: name * default: name
* description:
* type: string
* default: description
* annualfee:
* type: integer
* format: int64
* pointspersar:
* type: integer
* format: int64
*/ */
@ -308,7 +318,7 @@ router.get(
const currentUser = req.currentUser; const currentUser = req.currentUser;
const payload = await LoyaltytierDBApi.findAll(req.query, { currentUser }); const payload = await LoyaltytierDBApi.findAll(req.query, { currentUser });
if (filetype && filetype === 'csv') { if (filetype && filetype === 'csv') {
const fields = ['id', 'name']; const fields = ['id', 'name', 'description', 'annualfee', 'pointspersar'];
const opts = { fields }; const opts = { fields };
try { try {
const csv = parse(payload.rows, opts); const csv = parse(payload.rows, opts);

View File

@ -0,0 +1,444 @@
const express = require('express');
const RedemptionService = require('../services/redemption');
const RedemptionDBApi = require('../db/api/redemption');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const { checkCrudPermissions } = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('redemption'));
/**
* @swagger
* components:
* schemas:
* Redemption:
* type: object
* properties:
* pointsused:
* type: integer
* format: int64
* discountvalue:
* type: integer
* format: int64
*
*
*/
/**
* @swagger
* tags:
* name: Redemption
* description: The Redemption managing API
*/
/**
* @swagger
* /api/redemption:
* post:
* security:
* - bearerAuth: []
* tags: [Redemption]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Redemption"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Redemption"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post(
'/',
wrapAsync(async (req, res) => {
const referer =
req.headers.referer ||
`${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await RedemptionService.create(
req.body.data,
req.currentUser,
true,
link.host,
);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Redemption]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Redemption"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Redemption"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post(
'/bulk-import',
wrapAsync(async (req, res) => {
const referer =
req.headers.referer ||
`${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await RedemptionService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/redemption/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Redemption]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Redemption"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Redemption"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put(
'/:id',
wrapAsync(async (req, res) => {
await RedemptionService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/redemption/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Redemption]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Redemption"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete(
'/:id',
wrapAsync(async (req, res) => {
await RedemptionService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/redemption/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Redemption]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Redemption"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post(
'/deleteByIds',
wrapAsync(async (req, res) => {
await RedemptionService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/redemption:
* get:
* security:
* - bearerAuth: []
* tags: [Redemption]
* summary: Get all redemption
* description: Get all redemption
* responses:
* 200:
* description: Redemption list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Redemption"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get(
'/',
wrapAsync(async (req, res) => {
const filetype = req.query.filetype;
const currentUser = req.currentUser;
const payload = await RedemptionDBApi.findAll(req.query, { currentUser });
if (filetype && filetype === 'csv') {
const fields = ['id', 'pointsused', 'discountvalue'];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv);
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}),
);
/**
* @swagger
* /api/redemption/count:
* get:
* security:
* - bearerAuth: []
* tags: [Redemption]
* summary: Count all redemption
* description: Count all redemption
* responses:
* 200:
* description: Redemption count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Redemption"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get(
'/count',
wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await RedemptionDBApi.findAll(req.query, null, {
countOnly: true,
currentUser,
});
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/redemption/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Redemption]
* summary: Find all redemption that match search criteria
* description: Find all redemption that match search criteria
* responses:
* 200:
* description: Redemption list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Redemption"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await RedemptionDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/redemption/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Redemption]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Redemption"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get(
'/:id',
wrapAsync(async (req, res) => {
const payload = await RedemptionDBApi.findBy({ id: req.params.id });
res.status(200).send(payload);
}),
);
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,439 @@
const express = require('express');
const ReferralService = require('../services/referral');
const ReferralDBApi = require('../db/api/referral');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const { checkCrudPermissions } = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('referral'));
/**
* @swagger
* components:
* schemas:
* Referral:
* type: object
* properties:
* referredemail:
* type: string
* default: referredemail
*
*/
/**
* @swagger
* tags:
* name: Referral
* description: The Referral managing API
*/
/**
* @swagger
* /api/referral:
* post:
* security:
* - bearerAuth: []
* tags: [Referral]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Referral"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Referral"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post(
'/',
wrapAsync(async (req, res) => {
const referer =
req.headers.referer ||
`${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await ReferralService.create(
req.body.data,
req.currentUser,
true,
link.host,
);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Referral]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Referral"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Referral"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post(
'/bulk-import',
wrapAsync(async (req, res) => {
const referer =
req.headers.referer ||
`${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await ReferralService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/referral/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Referral]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Referral"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Referral"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put(
'/:id',
wrapAsync(async (req, res) => {
await ReferralService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/referral/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Referral]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Referral"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete(
'/:id',
wrapAsync(async (req, res) => {
await ReferralService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/referral/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Referral]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Referral"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post(
'/deleteByIds',
wrapAsync(async (req, res) => {
await ReferralService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/referral:
* get:
* security:
* - bearerAuth: []
* tags: [Referral]
* summary: Get all referral
* description: Get all referral
* responses:
* 200:
* description: Referral list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Referral"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get(
'/',
wrapAsync(async (req, res) => {
const filetype = req.query.filetype;
const currentUser = req.currentUser;
const payload = await ReferralDBApi.findAll(req.query, { currentUser });
if (filetype && filetype === 'csv') {
const fields = ['id', 'referredemail'];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv);
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}),
);
/**
* @swagger
* /api/referral/count:
* get:
* security:
* - bearerAuth: []
* tags: [Referral]
* summary: Count all referral
* description: Count all referral
* responses:
* 200:
* description: Referral count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Referral"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get(
'/count',
wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await ReferralDBApi.findAll(req.query, null, {
countOnly: true,
currentUser,
});
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/referral/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Referral]
* summary: Find all referral that match search criteria
* description: Find all referral that match search criteria
* responses:
* 200:
* description: Referral list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Referral"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await ReferralDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/referral/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Referral]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Referral"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get(
'/:id',
wrapAsync(async (req, res) => {
const payload = await ReferralDBApi.findBy({ id: req.params.id });
res.status(200).send(payload);
}),
);
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -32,6 +32,13 @@ router.use(checkCrudPermissions('users'));
* email: * email:
* type: string * type: string
* default: email * default: email
* referralcode:
* type: string
* default: referralcode
* pointsbalance:
* type: integer
* format: int64
*/ */
@ -308,7 +315,15 @@ router.get(
const currentUser = req.currentUser; const currentUser = req.currentUser;
const payload = await UsersDBApi.findAll(req.query, { currentUser }); const payload = await UsersDBApi.findAll(req.query, { currentUser });
if (filetype && filetype === 'csv') { if (filetype && filetype === 'csv') {
const fields = ['id', 'firstName', 'lastName', 'phoneNumber', 'email']; const fields = [
'id',
'firstName',
'lastName',
'phoneNumber',
'email',
'referralcode',
'pointsbalance',
];
const opts = { fields }; const opts = { fields };
try { try {
const csv = parse(payload.rows, opts); const csv = parse(payload.rows, opts);

View File

@ -0,0 +1,114 @@
const db = require('../db/models');
const RedemptionDBApi = require('../db/api/redemption');
const processFile = require('../middlewares/upload');
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
module.exports = class RedemptionService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await RedemptionDBApi.create(data, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
try {
await processFile(req, res);
const bufferStream = new stream.PassThrough();
const results = [];
await bufferStream.end(Buffer.from(req.file.buffer, 'utf-8')); // convert Buffer to Stream
await new Promise((resolve, reject) => {
bufferStream
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
console.log('CSV results', results);
resolve();
})
.on('error', (error) => reject(error));
});
await RedemptionDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
let redemption = await RedemptionDBApi.findBy({ id }, { transaction });
if (!redemption) {
throw new ValidationError('redemptionNotFound');
}
const updatedRedemption = await RedemptionDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedRedemption;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await RedemptionDBApi.deleteByIds(ids, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async remove(id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await RedemptionDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,114 @@
const db = require('../db/models');
const ReferralDBApi = require('../db/api/referral');
const processFile = require('../middlewares/upload');
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
module.exports = class ReferralService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await ReferralDBApi.create(data, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
try {
await processFile(req, res);
const bufferStream = new stream.PassThrough();
const results = [];
await bufferStream.end(Buffer.from(req.file.buffer, 'utf-8')); // convert Buffer to Stream
await new Promise((resolve, reject) => {
bufferStream
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
console.log('CSV results', results);
resolve();
})
.on('error', (error) => reject(error));
});
await ReferralDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
let referral = await ReferralDBApi.findBy({ id }, { transaction });
if (!referral) {
throw new ValidationError('referralNotFound');
}
const updatedReferral = await ReferralDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedReferral;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await ReferralDBApi.deleteByIds(ids, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async remove(id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await ReferralDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -41,7 +41,17 @@ module.exports = class SearchService {
throw new ValidationError('iam.errors.searchQueryRequired'); throw new ValidationError('iam.errors.searchQueryRequired');
} }
const tableColumns = { const tableColumns = {
users: ['firstName', 'lastName', 'phoneNumber', 'email'], users: [
'firstName',
'lastName',
'phoneNumber',
'email',
'referralcode',
],
agents: ['name', 'email', 'phone_number'], agents: ['name', 'email', 'phone_number'],
@ -49,12 +59,20 @@ module.exports = class SearchService {
vouchers: ['voucher_code'], vouchers: ['voucher_code'],
loyaltytier: ['name'], loyaltytier: ['name', 'description'],
referral: ['referredemail'],
}; };
const columnsInt = { const columnsInt = {
users: ['pointsbalance'],
bookings: ['total_amount'], bookings: ['total_amount'],
payments: ['amount'], payments: ['amount'],
loyaltytier: ['annualfee', 'pointspersar'],
redemption: ['pointsused', 'discountvalue'],
}; };
let allFoundRecords = []; let allFoundRecords = [];

View File

@ -82,6 +82,39 @@ const CardLoyaltytier = ({
<div className='font-medium line-clamp-4'>{item.name}</div> <div className='font-medium line-clamp-4'>{item.name}</div>
</dd> </dd>
</div> </div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Annualfee
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.annualfee}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Pointspersar
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.pointspersar}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Description
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.description}
</div>
</dd>
</div>
</dl> </dl>
</li> </li>
))} ))}

View File

@ -57,6 +57,21 @@ const ListLoyaltytier = ({
<p className={'text-xs text-gray-500 '}>Name</p> <p className={'text-xs text-gray-500 '}>Name</p>
<p className={'line-clamp-2'}>{item.name}</p> <p className={'line-clamp-2'}>{item.name}</p>
</div> </div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Annualfee</p>
<p className={'line-clamp-2'}>{item.annualfee}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Pointspersar</p>
<p className={'line-clamp-2'}>{item.pointspersar}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Description</p>
<p className={'line-clamp-2'}>{item.description}</p>
</div>
</Link> </Link>
<ListActionsPopover <ListActionsPopover
onDelete={onDelete} onDelete={onDelete}

View File

@ -50,6 +50,46 @@ export const loadColumns = async (
editable: hasUpdatePermission, editable: hasUpdatePermission,
}, },
{
field: 'annualfee',
headerName: 'Annualfee',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
type: 'number',
},
{
field: 'pointspersar',
headerName: 'Pointspersar',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
type: 'number',
},
{
field: 'description',
headerName: 'Description',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
},
{ {
field: 'actions', field: 'actions',
type: 'actions', type: 'actions',

View File

@ -0,0 +1,162 @@
import React from 'react';
import ImageField from '../ImageField';
import ListActionsPopover from '../ListActionsPopover';
import { useAppSelector } from '../../stores/hooks';
import dataFormatter from '../../helpers/dataFormatter';
import { Pagination } from '../Pagination';
import { saveFile } from '../../helpers/fileSaver';
import LoadingSpinner from '../LoadingSpinner';
import Link from 'next/link';
import { hasPermission } from '../../helpers/userPermissions';
type Props = {
redemption: any[];
loading: boolean;
onDelete: (id: string) => void;
currentPage: number;
numPages: number;
onPageChange: (page: number) => void;
};
const CardRedemption = ({
redemption,
loading,
onDelete,
currentPage,
numPages,
onPageChange,
}: Props) => {
const asideScrollbarsStyle = useAppSelector(
(state) => state.style.asideScrollbarsStyle,
);
const bgColor = useAppSelector((state) => state.style.cardsColor);
const darkMode = useAppSelector((state) => state.style.darkMode);
const corners = useAppSelector((state) => state.style.corners);
const focusRing = useAppSelector((state) => state.style.focusRingColor);
const currentUser = useAppSelector((state) => state.auth.currentUser);
const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_REDEMPTION');
return (
<div className={'p-4'}>
{loading && <LoadingSpinner />}
<ul
role='list'
className='grid grid-cols-1 gap-x-6 gap-y-8 lg:grid-cols-3 2xl:grid-cols-4 xl:gap-x-8'
>
{!loading &&
redemption.map((item, index) => (
<li
key={item.id}
className={`overflow-hidden ${
corners !== 'rounded-full' ? corners : 'rounded-3xl'
} border ${focusRing} border-gray-200 dark:border-dark-700 ${
darkMode ? 'aside-scrollbars-[slate]' : asideScrollbarsStyle
}`}
>
<div
className={`flex items-center ${bgColor} p-6 gap-x-4 border-b border-gray-900/5 bg-gray-50 dark:bg-dark-800 relative`}
>
<Link
href={`/redemption/redemption-view/?id=${item.id}`}
className='text-lg font-bold leading-6 line-clamp-1'
>
{item.id}
</Link>
<div className='ml-auto '>
<ListActionsPopover
onDelete={onDelete}
itemId={item.id}
pathEdit={`/redemption/redemption-edit/?id=${item.id}`}
pathView={`/redemption/redemption-view/?id=${item.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>
</div>
<dl className='divide-y divide-gray-600 dark:divide-dark-700 px-6 py-4 text-sm leading-6 h-64 overflow-y-auto'>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>User</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{dataFormatter.usersOneListFormatter(item.user)}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Pointsused
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.pointsused}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Redemptiontype
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.redemptiontype}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Discountvalue
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.discountvalue}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Status
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.status}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Booking
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{dataFormatter.bookingsOneListFormatter(item.booking)}
</div>
</dd>
</div>
</dl>
</li>
))}
{!loading && redemption.length === 0 && (
<div className='col-span-full flex items-center justify-center h-40'>
<p className=''>No data to display</p>
</div>
)}
</ul>
<div className={'flex items-center justify-center my-6'}>
<Pagination
currentPage={currentPage}
numPages={numPages}
setCurrentPage={onPageChange}
/>
</div>
</div>
);
};
export default CardRedemption;

View File

@ -0,0 +1,122 @@
import React from 'react';
import CardBox from '../CardBox';
import ImageField from '../ImageField';
import dataFormatter from '../../helpers/dataFormatter';
import { saveFile } from '../../helpers/fileSaver';
import ListActionsPopover from '../ListActionsPopover';
import { useAppSelector } from '../../stores/hooks';
import { Pagination } from '../Pagination';
import LoadingSpinner from '../LoadingSpinner';
import Link from 'next/link';
import { hasPermission } from '../../helpers/userPermissions';
type Props = {
redemption: any[];
loading: boolean;
onDelete: (id: string) => void;
currentPage: number;
numPages: number;
onPageChange: (page: number) => void;
};
const ListRedemption = ({
redemption,
loading,
onDelete,
currentPage,
numPages,
onPageChange,
}: Props) => {
const currentUser = useAppSelector((state) => state.auth.currentUser);
const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_REDEMPTION');
const corners = useAppSelector((state) => state.style.corners);
const bgColor = useAppSelector((state) => state.style.cardsColor);
return (
<>
<div className='relative overflow-x-auto p-4 space-y-4'>
{loading && <LoadingSpinner />}
{!loading &&
redemption.map((item) => (
<div key={item.id}>
<CardBox hasTable isList className={'rounded shadow-none'}>
<div
className={`flex ${bgColor} ${
corners !== 'rounded-full' ? corners : 'rounded-3xl'
} dark:bg-dark-900 border border-gray-600 items-center overflow-hidden`}
>
<Link
href={`/redemption/redemption-view/?id=${item.id}`}
className={
'flex-1 px-4 py-6 h-24 flex divide-x-2 divide-gray-600 items-center overflow-hidden`}> dark:divide-dark-700 overflow-x-auto'
}
>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>User</p>
<p className={'line-clamp-2'}>
{dataFormatter.usersOneListFormatter(item.user)}
</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Pointsused</p>
<p className={'line-clamp-2'}>{item.pointsused}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>
Redemptiontype
</p>
<p className={'line-clamp-2'}>{item.redemptiontype}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>
Discountvalue
</p>
<p className={'line-clamp-2'}>{item.discountvalue}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Status</p>
<p className={'line-clamp-2'}>{item.status}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Booking</p>
<p className={'line-clamp-2'}>
{dataFormatter.bookingsOneListFormatter(item.booking)}
</p>
</div>
</Link>
<ListActionsPopover
onDelete={onDelete}
itemId={item.id}
pathEdit={`/redemption/redemption-edit/?id=${item.id}`}
pathView={`/redemption/redemption-view/?id=${item.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>
</CardBox>
</div>
))}
{!loading && redemption.length === 0 && (
<div className='col-span-full flex items-center justify-center h-40'>
<p className=''>No data to display</p>
</div>
)}
</div>
<div className={'flex items-center justify-center my-6'}>
<Pagination
currentPage={currentPage}
numPages={numPages}
setCurrentPage={onPageChange}
/>
</div>
</>
);
};
export default ListRedemption;

View File

@ -0,0 +1,487 @@
import React, { useEffect, useState, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { ToastContainer, toast } from 'react-toastify';
import BaseButton from '../BaseButton';
import CardBoxModal from '../CardBoxModal';
import CardBox from '../CardBox';
import {
fetch,
update,
deleteItem,
setRefetch,
deleteItemsByIds,
} from '../../stores/redemption/redemptionSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { Field, Form, Formik } from 'formik';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { loadColumns } from './configureRedemptionCols';
import _ from 'lodash';
import dataFormatter from '../../helpers/dataFormatter';
import { dataGridStyles } from '../../styles';
const perPage = 10;
const TableSampleRedemption = ({
filterItems,
setFilterItems,
filters,
showGrid,
}) => {
const notify = (type, msg) => toast(msg, { type, position: 'bottom-center' });
const dispatch = useAppDispatch();
const router = useRouter();
const pagesList = [];
const [id, setId] = useState(null);
const [currentPage, setCurrentPage] = useState(0);
const [filterRequest, setFilterRequest] = React.useState('');
const [columns, setColumns] = useState<GridColDef[]>([]);
const [selectedRows, setSelectedRows] = useState([]);
const [sortModel, setSortModel] = useState([
{
field: '',
sort: 'desc',
},
]);
const {
redemption,
loading,
count,
notify: redemptionNotify,
refetch,
} = useAppSelector((state) => state.redemption);
const { currentUser } = useAppSelector((state) => state.auth);
const focusRing = useAppSelector((state) => state.style.focusRingColor);
const bgColor = useAppSelector((state) => state.style.bgLayoutColor);
const corners = useAppSelector((state) => state.style.corners);
const numPages =
Math.floor(count / perPage) === 0 ? 1 : Math.ceil(count / perPage);
for (let i = 0; i < numPages; i++) {
pagesList.push(i);
}
const loadData = async (page = currentPage, request = filterRequest) => {
if (page !== currentPage) setCurrentPage(page);
if (request !== filterRequest) setFilterRequest(request);
const { sort, field } = sortModel[0];
const query = `?page=${page}&limit=${perPage}${request}&sort=${sort}&field=${field}`;
dispatch(fetch({ limit: perPage, page, query }));
};
useEffect(() => {
if (redemptionNotify.showNotification) {
notify(
redemptionNotify.typeNotification,
redemptionNotify.textNotification,
);
}
}, [redemptionNotify.showNotification]);
useEffect(() => {
if (!currentUser) return;
loadData();
}, [sortModel, currentUser]);
useEffect(() => {
if (refetch) {
loadData(0);
dispatch(setRefetch(false));
}
}, [refetch, dispatch]);
const [isModalInfoActive, setIsModalInfoActive] = useState(false);
const [isModalTrashActive, setIsModalTrashActive] = useState(false);
const handleModalAction = () => {
setIsModalInfoActive(false);
setIsModalTrashActive(false);
};
const handleDeleteModalAction = (id: string) => {
setId(id);
setIsModalTrashActive(true);
};
const handleDeleteAction = async () => {
if (id) {
await dispatch(deleteItem(id));
await loadData(0);
setIsModalTrashActive(false);
}
};
const generateFilterRequests = useMemo(() => {
let request = '&';
filterItems.forEach((item) => {
const isRangeFilter = filters.find(
(filter) =>
filter.title === item.fields.selectedField &&
(filter.number || filter.date),
);
if (isRangeFilter) {
const from = item.fields.filterValueFrom;
const to = item.fields.filterValueTo;
if (from) {
request += `${item.fields.selectedField}Range=${from}&`;
}
if (to) {
request += `${item.fields.selectedField}Range=${to}&`;
}
} else {
const value = item.fields.filterValue;
if (value) {
request += `${item.fields.selectedField}=${value}&`;
}
}
});
return request;
}, [filterItems, filters]);
const deleteFilter = (value) => {
const newItems = filterItems.filter((item) => item.id !== value);
if (newItems.length) {
setFilterItems(newItems);
} else {
loadData(0, '');
setFilterItems(newItems);
}
};
const handleSubmit = () => {
loadData(0, generateFilterRequests);
};
const handleChange = (id) => (e) => {
const value = e.target.value;
const name = e.target.name;
setFilterItems(
filterItems.map((item) => {
if (item.id !== id) return item;
if (name === 'selectedField') return { id, fields: { [name]: value } };
return { id, fields: { ...item.fields, [name]: value } };
}),
);
};
const handleReset = () => {
setFilterItems([]);
loadData(0, '');
};
const onPageChange = (page: number) => {
loadData(page);
setCurrentPage(page);
};
useEffect(() => {
if (!currentUser) return;
loadColumns(handleDeleteModalAction, `redemption`, currentUser).then(
(newCols) => setColumns(newCols),
);
}, [currentUser]);
const handleTableSubmit = async (id: string, data) => {
if (!_.isEmpty(data)) {
await dispatch(update({ id, data }))
.unwrap()
.then((res) => res)
.catch((err) => {
throw new Error(err);
});
}
};
const onDeleteRows = async (selectedRows) => {
await dispatch(deleteItemsByIds(selectedRows));
await loadData(0);
};
const controlClasses =
'w-full py-2 px-2 my-2 rounded dark:placeholder-gray-400 ' +
` ${bgColor} ${focusRing} ${corners} ` +
'dark:bg-slate-800 border';
const dataGrid = (
<div className='relative overflow-x-auto'>
<DataGrid
autoHeight
rowHeight={64}
sx={dataGridStyles}
className={'datagrid--table'}
getRowClassName={() => `datagrid--row`}
rows={redemption ?? []}
columns={columns}
initialState={{
pagination: {
paginationModel: {
pageSize: 10,
},
},
}}
disableRowSelectionOnClick
onProcessRowUpdateError={(params) => {
console.log('Error', params);
}}
processRowUpdate={async (newRow, oldRow) => {
const data = dataFormatter.dataGridEditFormatter(newRow);
try {
await handleTableSubmit(newRow.id, data);
return newRow;
} catch {
return oldRow;
}
}}
sortingMode={'server'}
checkboxSelection
onRowSelectionModelChange={(ids) => {
setSelectedRows(ids);
}}
onSortModelChange={(params) => {
params.length
? setSortModel(params)
: setSortModel([{ field: '', sort: 'desc' }]);
}}
rowCount={count}
pageSizeOptions={[10]}
paginationMode={'server'}
loading={loading}
onPaginationModelChange={(params) => {
onPageChange(params.page);
}}
/>
</div>
);
return (
<>
{filterItems && Array.isArray(filterItems) && filterItems.length ? (
<CardBox>
<Formik
initialValues={{
checkboxes: ['lorem'],
switches: ['lorem'],
radio: 'lorem',
}}
onSubmit={() => null}
>
<Form>
<>
{filterItems &&
filterItems.map((filterItem) => {
return (
<div key={filterItem.id} className='flex mb-4'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
Filter
</div>
<Field
className={controlClasses}
name='selectedField'
id='selectedField'
component='select'
value={filterItem?.fields?.selectedField || ''}
onChange={handleChange(filterItem.id)}
>
{filters.map((selectOption) => (
<option
key={selectOption.title}
value={`${selectOption.title}`}
>
{selectOption.label}
</option>
))}
</Field>
</div>
{filters.find(
(filter) =>
filter.title === filterItem?.fields?.selectedField,
)?.type === 'enum' ? (
<div className='flex flex-col w-full mr-3'>
<div className='text-gray-500 font-bold'>Value</div>
<Field
className={controlClasses}
name='filterValue'
id='filterValue'
component='select'
value={filterItem?.fields?.filterValue || ''}
onChange={handleChange(filterItem.id)}
>
<option value=''>Select Value</option>
{filters
.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)
?.options?.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</Field>
</div>
) : filters.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)?.number ? (
<div className='flex flex-row w-full mr-3'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
From
</div>
<Field
className={controlClasses}
name='filterValueFrom'
placeholder='From'
id='filterValueFrom'
value={
filterItem?.fields?.filterValueFrom || ''
}
onChange={handleChange(filterItem.id)}
/>
</div>
<div className='flex flex-col w-full'>
<div className=' text-gray-500 font-bold'>
To
</div>
<Field
className={controlClasses}
name='filterValueTo'
placeholder='to'
id='filterValueTo'
value={filterItem?.fields?.filterValueTo || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
</div>
) : filters.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)?.date ? (
<div className='flex flex-row w-full mr-3'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
From
</div>
<Field
className={controlClasses}
name='filterValueFrom'
placeholder='From'
id='filterValueFrom'
type='datetime-local'
value={
filterItem?.fields?.filterValueFrom || ''
}
onChange={handleChange(filterItem.id)}
/>
</div>
<div className='flex flex-col w-full'>
<div className=' text-gray-500 font-bold'>
To
</div>
<Field
className={controlClasses}
name='filterValueTo'
placeholder='to'
id='filterValueTo'
type='datetime-local'
value={filterItem?.fields?.filterValueTo || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
</div>
) : (
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
Contains
</div>
<Field
className={controlClasses}
name='filterValue'
placeholder='Contained'
id='filterValue'
value={filterItem?.fields?.filterValue || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
)}
<div className='flex flex-col'>
<div className=' text-gray-500 font-bold'>
Action
</div>
<BaseButton
className='my-2'
type='reset'
color='danger'
label='Delete'
onClick={() => {
deleteFilter(filterItem.id);
}}
/>
</div>
</div>
);
})}
<div className='flex'>
<BaseButton
className='my-2 mr-3'
type='submit'
color='info'
label='Apply'
onClick={handleSubmit}
/>
<BaseButton
className='my-2'
type='reset'
color='info'
outline
label='Cancel'
onClick={handleReset}
/>
</div>
</>
</Form>
</Formik>
</CardBox>
) : null}
<CardBoxModal
title='Please confirm'
buttonColor='info'
buttonLabel={loading ? 'Deleting...' : 'Confirm'}
isActive={isModalTrashActive}
onConfirm={handleDeleteAction}
onCancel={handleModalAction}
>
<p>Are you sure you want to delete this item?</p>
</CardBoxModal>
{dataGrid}
{selectedRows.length > 0 &&
createPortal(
<BaseButton
className='me-4'
color='danger'
label={`Delete ${selectedRows.length === 1 ? 'Row' : 'Rows'}`}
onClick={() => onDeleteRows(selectedRows)}
/>,
document.getElementById('delete-rows-button'),
)}
<ToastContainer />
</>
);
};
export default TableSampleRedemption;

View File

@ -0,0 +1,160 @@
import React from 'react';
import BaseIcon from '../BaseIcon';
import { mdiEye, mdiTrashCan, mdiPencilOutline } from '@mdi/js';
import axios from 'axios';
import {
GridActionsCellItem,
GridRowParams,
GridValueGetterParams,
} from '@mui/x-data-grid';
import ImageField from '../ImageField';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import DataGridMultiSelect from '../DataGridMultiSelect';
import ListActionsPopover from '../ListActionsPopover';
import { hasPermission } from '../../helpers/userPermissions';
type Params = (id: string) => void;
export const loadColumns = async (
onDelete: Params,
entityName: string,
user,
) => {
async function callOptionsApi(entityName: string) {
if (!hasPermission(user, 'READ_' + entityName.toUpperCase())) return [];
try {
const data = await axios(`/${entityName}/autocomplete?limit=100`);
return data.data;
} catch (error) {
console.log(error);
return [];
}
}
const hasUpdatePermission = hasPermission(user, 'UPDATE_REDEMPTION');
return [
{
field: 'user',
headerName: 'User',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
sortable: false,
type: 'singleSelect',
getOptionValue: (value: any) => value?.id,
getOptionLabel: (value: any) => value?.label,
valueOptions: await callOptionsApi('users'),
valueGetter: (params: GridValueGetterParams) =>
params?.value?.id ?? params?.value,
},
{
field: 'pointsused',
headerName: 'Pointsused',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
type: 'number',
},
{
field: 'redemptiontype',
headerName: 'Redemptiontype',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
type: 'singleSelect',
valueOptions: ['value'],
},
{
field: 'discountvalue',
headerName: 'Discountvalue',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
type: 'number',
},
{
field: 'status',
headerName: 'Status',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
type: 'singleSelect',
valueOptions: ['value'],
},
{
field: 'booking',
headerName: 'Booking',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
sortable: false,
type: 'singleSelect',
getOptionValue: (value: any) => value?.id,
getOptionLabel: (value: any) => value?.label,
valueOptions: await callOptionsApi('bookings'),
valueGetter: (params: GridValueGetterParams) =>
params?.value?.id ?? params?.value,
},
{
field: 'actions',
type: 'actions',
minWidth: 30,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
getActions: (params: GridRowParams) => {
return [
<div key={params?.row?.id}>
<ListActionsPopover
onDelete={onDelete}
itemId={params?.row?.id}
pathEdit={`/redemption/redemption-edit/?id=${params?.row?.id}`}
pathView={`/redemption/redemption-view/?id=${params?.row?.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>,
];
},
},
];
};

View File

@ -0,0 +1,131 @@
import React from 'react';
import ImageField from '../ImageField';
import ListActionsPopover from '../ListActionsPopover';
import { useAppSelector } from '../../stores/hooks';
import dataFormatter from '../../helpers/dataFormatter';
import { Pagination } from '../Pagination';
import { saveFile } from '../../helpers/fileSaver';
import LoadingSpinner from '../LoadingSpinner';
import Link from 'next/link';
import { hasPermission } from '../../helpers/userPermissions';
type Props = {
referral: any[];
loading: boolean;
onDelete: (id: string) => void;
currentPage: number;
numPages: number;
onPageChange: (page: number) => void;
};
const CardReferral = ({
referral,
loading,
onDelete,
currentPage,
numPages,
onPageChange,
}: Props) => {
const asideScrollbarsStyle = useAppSelector(
(state) => state.style.asideScrollbarsStyle,
);
const bgColor = useAppSelector((state) => state.style.cardsColor);
const darkMode = useAppSelector((state) => state.style.darkMode);
const corners = useAppSelector((state) => state.style.corners);
const focusRing = useAppSelector((state) => state.style.focusRingColor);
const currentUser = useAppSelector((state) => state.auth.currentUser);
const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_REFERRAL');
return (
<div className={'p-4'}>
{loading && <LoadingSpinner />}
<ul
role='list'
className='grid grid-cols-1 gap-x-6 gap-y-8 lg:grid-cols-3 2xl:grid-cols-4 xl:gap-x-8'
>
{!loading &&
referral.map((item, index) => (
<li
key={item.id}
className={`overflow-hidden ${
corners !== 'rounded-full' ? corners : 'rounded-3xl'
} border ${focusRing} border-gray-200 dark:border-dark-700 ${
darkMode ? 'aside-scrollbars-[slate]' : asideScrollbarsStyle
}`}
>
<div
className={`flex items-center ${bgColor} p-6 gap-x-4 border-b border-gray-900/5 bg-gray-50 dark:bg-dark-800 relative`}
>
<Link
href={`/referral/referral-view/?id=${item.id}`}
className='text-lg font-bold leading-6 line-clamp-1'
>
{item.id}
</Link>
<div className='ml-auto '>
<ListActionsPopover
onDelete={onDelete}
itemId={item.id}
pathEdit={`/referral/referral-edit/?id=${item.id}`}
pathView={`/referral/referral-view/?id=${item.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>
</div>
<dl className='divide-y divide-gray-600 dark:divide-dark-700 px-6 py-4 text-sm leading-6 h-64 overflow-y-auto'>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Referrer
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{dataFormatter.usersOneListFormatter(item.referrer)}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Referredemail
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.referredemail}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Status
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.status}
</div>
</dd>
</div>
</dl>
</li>
))}
{!loading && referral.length === 0 && (
<div className='col-span-full flex items-center justify-center h-40'>
<p className=''>No data to display</p>
</div>
)}
</ul>
<div className={'flex items-center justify-center my-6'}>
<Pagination
currentPage={currentPage}
numPages={numPages}
setCurrentPage={onPageChange}
/>
</div>
</div>
);
};
export default CardReferral;

View File

@ -0,0 +1,103 @@
import React from 'react';
import CardBox from '../CardBox';
import ImageField from '../ImageField';
import dataFormatter from '../../helpers/dataFormatter';
import { saveFile } from '../../helpers/fileSaver';
import ListActionsPopover from '../ListActionsPopover';
import { useAppSelector } from '../../stores/hooks';
import { Pagination } from '../Pagination';
import LoadingSpinner from '../LoadingSpinner';
import Link from 'next/link';
import { hasPermission } from '../../helpers/userPermissions';
type Props = {
referral: any[];
loading: boolean;
onDelete: (id: string) => void;
currentPage: number;
numPages: number;
onPageChange: (page: number) => void;
};
const ListReferral = ({
referral,
loading,
onDelete,
currentPage,
numPages,
onPageChange,
}: Props) => {
const currentUser = useAppSelector((state) => state.auth.currentUser);
const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_REFERRAL');
const corners = useAppSelector((state) => state.style.corners);
const bgColor = useAppSelector((state) => state.style.cardsColor);
return (
<>
<div className='relative overflow-x-auto p-4 space-y-4'>
{loading && <LoadingSpinner />}
{!loading &&
referral.map((item) => (
<div key={item.id}>
<CardBox hasTable isList className={'rounded shadow-none'}>
<div
className={`flex ${bgColor} ${
corners !== 'rounded-full' ? corners : 'rounded-3xl'
} dark:bg-dark-900 border border-gray-600 items-center overflow-hidden`}
>
<Link
href={`/referral/referral-view/?id=${item.id}`}
className={
'flex-1 px-4 py-6 h-24 flex divide-x-2 divide-gray-600 items-center overflow-hidden`}> dark:divide-dark-700 overflow-x-auto'
}
>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Referrer</p>
<p className={'line-clamp-2'}>
{dataFormatter.usersOneListFormatter(item.referrer)}
</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>
Referredemail
</p>
<p className={'line-clamp-2'}>{item.referredemail}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Status</p>
<p className={'line-clamp-2'}>{item.status}</p>
</div>
</Link>
<ListActionsPopover
onDelete={onDelete}
itemId={item.id}
pathEdit={`/referral/referral-edit/?id=${item.id}`}
pathView={`/referral/referral-view/?id=${item.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>
</CardBox>
</div>
))}
{!loading && referral.length === 0 && (
<div className='col-span-full flex items-center justify-center h-40'>
<p className=''>No data to display</p>
</div>
)}
</div>
<div className={'flex items-center justify-center my-6'}>
<Pagination
currentPage={currentPage}
numPages={numPages}
setCurrentPage={onPageChange}
/>
</div>
</>
);
};
export default ListReferral;

View File

@ -0,0 +1,484 @@
import React, { useEffect, useState, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { ToastContainer, toast } from 'react-toastify';
import BaseButton from '../BaseButton';
import CardBoxModal from '../CardBoxModal';
import CardBox from '../CardBox';
import {
fetch,
update,
deleteItem,
setRefetch,
deleteItemsByIds,
} from '../../stores/referral/referralSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { Field, Form, Formik } from 'formik';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { loadColumns } from './configureReferralCols';
import _ from 'lodash';
import dataFormatter from '../../helpers/dataFormatter';
import { dataGridStyles } from '../../styles';
const perPage = 10;
const TableSampleReferral = ({
filterItems,
setFilterItems,
filters,
showGrid,
}) => {
const notify = (type, msg) => toast(msg, { type, position: 'bottom-center' });
const dispatch = useAppDispatch();
const router = useRouter();
const pagesList = [];
const [id, setId] = useState(null);
const [currentPage, setCurrentPage] = useState(0);
const [filterRequest, setFilterRequest] = React.useState('');
const [columns, setColumns] = useState<GridColDef[]>([]);
const [selectedRows, setSelectedRows] = useState([]);
const [sortModel, setSortModel] = useState([
{
field: '',
sort: 'desc',
},
]);
const {
referral,
loading,
count,
notify: referralNotify,
refetch,
} = useAppSelector((state) => state.referral);
const { currentUser } = useAppSelector((state) => state.auth);
const focusRing = useAppSelector((state) => state.style.focusRingColor);
const bgColor = useAppSelector((state) => state.style.bgLayoutColor);
const corners = useAppSelector((state) => state.style.corners);
const numPages =
Math.floor(count / perPage) === 0 ? 1 : Math.ceil(count / perPage);
for (let i = 0; i < numPages; i++) {
pagesList.push(i);
}
const loadData = async (page = currentPage, request = filterRequest) => {
if (page !== currentPage) setCurrentPage(page);
if (request !== filterRequest) setFilterRequest(request);
const { sort, field } = sortModel[0];
const query = `?page=${page}&limit=${perPage}${request}&sort=${sort}&field=${field}`;
dispatch(fetch({ limit: perPage, page, query }));
};
useEffect(() => {
if (referralNotify.showNotification) {
notify(referralNotify.typeNotification, referralNotify.textNotification);
}
}, [referralNotify.showNotification]);
useEffect(() => {
if (!currentUser) return;
loadData();
}, [sortModel, currentUser]);
useEffect(() => {
if (refetch) {
loadData(0);
dispatch(setRefetch(false));
}
}, [refetch, dispatch]);
const [isModalInfoActive, setIsModalInfoActive] = useState(false);
const [isModalTrashActive, setIsModalTrashActive] = useState(false);
const handleModalAction = () => {
setIsModalInfoActive(false);
setIsModalTrashActive(false);
};
const handleDeleteModalAction = (id: string) => {
setId(id);
setIsModalTrashActive(true);
};
const handleDeleteAction = async () => {
if (id) {
await dispatch(deleteItem(id));
await loadData(0);
setIsModalTrashActive(false);
}
};
const generateFilterRequests = useMemo(() => {
let request = '&';
filterItems.forEach((item) => {
const isRangeFilter = filters.find(
(filter) =>
filter.title === item.fields.selectedField &&
(filter.number || filter.date),
);
if (isRangeFilter) {
const from = item.fields.filterValueFrom;
const to = item.fields.filterValueTo;
if (from) {
request += `${item.fields.selectedField}Range=${from}&`;
}
if (to) {
request += `${item.fields.selectedField}Range=${to}&`;
}
} else {
const value = item.fields.filterValue;
if (value) {
request += `${item.fields.selectedField}=${value}&`;
}
}
});
return request;
}, [filterItems, filters]);
const deleteFilter = (value) => {
const newItems = filterItems.filter((item) => item.id !== value);
if (newItems.length) {
setFilterItems(newItems);
} else {
loadData(0, '');
setFilterItems(newItems);
}
};
const handleSubmit = () => {
loadData(0, generateFilterRequests);
};
const handleChange = (id) => (e) => {
const value = e.target.value;
const name = e.target.name;
setFilterItems(
filterItems.map((item) => {
if (item.id !== id) return item;
if (name === 'selectedField') return { id, fields: { [name]: value } };
return { id, fields: { ...item.fields, [name]: value } };
}),
);
};
const handleReset = () => {
setFilterItems([]);
loadData(0, '');
};
const onPageChange = (page: number) => {
loadData(page);
setCurrentPage(page);
};
useEffect(() => {
if (!currentUser) return;
loadColumns(handleDeleteModalAction, `referral`, currentUser).then(
(newCols) => setColumns(newCols),
);
}, [currentUser]);
const handleTableSubmit = async (id: string, data) => {
if (!_.isEmpty(data)) {
await dispatch(update({ id, data }))
.unwrap()
.then((res) => res)
.catch((err) => {
throw new Error(err);
});
}
};
const onDeleteRows = async (selectedRows) => {
await dispatch(deleteItemsByIds(selectedRows));
await loadData(0);
};
const controlClasses =
'w-full py-2 px-2 my-2 rounded dark:placeholder-gray-400 ' +
` ${bgColor} ${focusRing} ${corners} ` +
'dark:bg-slate-800 border';
const dataGrid = (
<div className='relative overflow-x-auto'>
<DataGrid
autoHeight
rowHeight={64}
sx={dataGridStyles}
className={'datagrid--table'}
getRowClassName={() => `datagrid--row`}
rows={referral ?? []}
columns={columns}
initialState={{
pagination: {
paginationModel: {
pageSize: 10,
},
},
}}
disableRowSelectionOnClick
onProcessRowUpdateError={(params) => {
console.log('Error', params);
}}
processRowUpdate={async (newRow, oldRow) => {
const data = dataFormatter.dataGridEditFormatter(newRow);
try {
await handleTableSubmit(newRow.id, data);
return newRow;
} catch {
return oldRow;
}
}}
sortingMode={'server'}
checkboxSelection
onRowSelectionModelChange={(ids) => {
setSelectedRows(ids);
}}
onSortModelChange={(params) => {
params.length
? setSortModel(params)
: setSortModel([{ field: '', sort: 'desc' }]);
}}
rowCount={count}
pageSizeOptions={[10]}
paginationMode={'server'}
loading={loading}
onPaginationModelChange={(params) => {
onPageChange(params.page);
}}
/>
</div>
);
return (
<>
{filterItems && Array.isArray(filterItems) && filterItems.length ? (
<CardBox>
<Formik
initialValues={{
checkboxes: ['lorem'],
switches: ['lorem'],
radio: 'lorem',
}}
onSubmit={() => null}
>
<Form>
<>
{filterItems &&
filterItems.map((filterItem) => {
return (
<div key={filterItem.id} className='flex mb-4'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
Filter
</div>
<Field
className={controlClasses}
name='selectedField'
id='selectedField'
component='select'
value={filterItem?.fields?.selectedField || ''}
onChange={handleChange(filterItem.id)}
>
{filters.map((selectOption) => (
<option
key={selectOption.title}
value={`${selectOption.title}`}
>
{selectOption.label}
</option>
))}
</Field>
</div>
{filters.find(
(filter) =>
filter.title === filterItem?.fields?.selectedField,
)?.type === 'enum' ? (
<div className='flex flex-col w-full mr-3'>
<div className='text-gray-500 font-bold'>Value</div>
<Field
className={controlClasses}
name='filterValue'
id='filterValue'
component='select'
value={filterItem?.fields?.filterValue || ''}
onChange={handleChange(filterItem.id)}
>
<option value=''>Select Value</option>
{filters
.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)
?.options?.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</Field>
</div>
) : filters.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)?.number ? (
<div className='flex flex-row w-full mr-3'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
From
</div>
<Field
className={controlClasses}
name='filterValueFrom'
placeholder='From'
id='filterValueFrom'
value={
filterItem?.fields?.filterValueFrom || ''
}
onChange={handleChange(filterItem.id)}
/>
</div>
<div className='flex flex-col w-full'>
<div className=' text-gray-500 font-bold'>
To
</div>
<Field
className={controlClasses}
name='filterValueTo'
placeholder='to'
id='filterValueTo'
value={filterItem?.fields?.filterValueTo || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
</div>
) : filters.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)?.date ? (
<div className='flex flex-row w-full mr-3'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
From
</div>
<Field
className={controlClasses}
name='filterValueFrom'
placeholder='From'
id='filterValueFrom'
type='datetime-local'
value={
filterItem?.fields?.filterValueFrom || ''
}
onChange={handleChange(filterItem.id)}
/>
</div>
<div className='flex flex-col w-full'>
<div className=' text-gray-500 font-bold'>
To
</div>
<Field
className={controlClasses}
name='filterValueTo'
placeholder='to'
id='filterValueTo'
type='datetime-local'
value={filterItem?.fields?.filterValueTo || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
</div>
) : (
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
Contains
</div>
<Field
className={controlClasses}
name='filterValue'
placeholder='Contained'
id='filterValue'
value={filterItem?.fields?.filterValue || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
)}
<div className='flex flex-col'>
<div className=' text-gray-500 font-bold'>
Action
</div>
<BaseButton
className='my-2'
type='reset'
color='danger'
label='Delete'
onClick={() => {
deleteFilter(filterItem.id);
}}
/>
</div>
</div>
);
})}
<div className='flex'>
<BaseButton
className='my-2 mr-3'
type='submit'
color='info'
label='Apply'
onClick={handleSubmit}
/>
<BaseButton
className='my-2'
type='reset'
color='info'
outline
label='Cancel'
onClick={handleReset}
/>
</div>
</>
</Form>
</Formik>
</CardBox>
) : null}
<CardBoxModal
title='Please confirm'
buttonColor='info'
buttonLabel={loading ? 'Deleting...' : 'Confirm'}
isActive={isModalTrashActive}
onConfirm={handleDeleteAction}
onCancel={handleModalAction}
>
<p>Are you sure you want to delete this item?</p>
</CardBoxModal>
{dataGrid}
{selectedRows.length > 0 &&
createPortal(
<BaseButton
className='me-4'
color='danger'
label={`Delete ${selectedRows.length === 1 ? 'Row' : 'Rows'}`}
onClick={() => onDeleteRows(selectedRows)}
/>,
document.getElementById('delete-rows-button'),
)}
<ToastContainer />
</>
);
};
export default TableSampleReferral;

View File

@ -0,0 +1,109 @@
import React from 'react';
import BaseIcon from '../BaseIcon';
import { mdiEye, mdiTrashCan, mdiPencilOutline } from '@mdi/js';
import axios from 'axios';
import {
GridActionsCellItem,
GridRowParams,
GridValueGetterParams,
} from '@mui/x-data-grid';
import ImageField from '../ImageField';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import DataGridMultiSelect from '../DataGridMultiSelect';
import ListActionsPopover from '../ListActionsPopover';
import { hasPermission } from '../../helpers/userPermissions';
type Params = (id: string) => void;
export const loadColumns = async (
onDelete: Params,
entityName: string,
user,
) => {
async function callOptionsApi(entityName: string) {
if (!hasPermission(user, 'READ_' + entityName.toUpperCase())) return [];
try {
const data = await axios(`/${entityName}/autocomplete?limit=100`);
return data.data;
} catch (error) {
console.log(error);
return [];
}
}
const hasUpdatePermission = hasPermission(user, 'UPDATE_REFERRAL');
return [
{
field: 'referrer',
headerName: 'Referrer',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
sortable: false,
type: 'singleSelect',
getOptionValue: (value: any) => value?.id,
getOptionLabel: (value: any) => value?.label,
valueOptions: await callOptionsApi('users'),
valueGetter: (params: GridValueGetterParams) =>
params?.value?.id ?? params?.value,
},
{
field: 'referredemail',
headerName: 'Referredemail',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
},
{
field: 'status',
headerName: 'Status',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
type: 'singleSelect',
valueOptions: ['value'],
},
{
field: 'actions',
type: 'actions',
minWidth: 30,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
getActions: (params: GridRowParams) => {
return [
<div key={params?.row?.id}>
<ListActionsPopover
onDelete={onDelete}
itemId={params?.row?.id}
pathEdit={`/referral/referral-edit/?id=${params?.row?.id}`}
pathView={`/referral/referral-view/?id=${params?.row?.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>,
];
},
},
];
};

View File

@ -173,6 +173,41 @@ const CardUsers = ({
</div> </div>
</dd> </dd>
</div> </div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Loyaltytier
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{dataFormatter.loyaltytierOneListFormatter(
item.loyaltytier,
)}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Pointsbalance
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.pointsbalance}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Referralcode
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.referralcode}
</div>
</dd>
</div>
</dl> </dl>
</li> </li>
))} ))}

View File

@ -115,6 +115,27 @@ const ListUsers = ({
.join(', ')} .join(', ')}
</p> </p>
</div> </div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Loyaltytier</p>
<p className={'line-clamp-2'}>
{dataFormatter.loyaltytierOneListFormatter(
item.loyaltytier,
)}
</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>
Pointsbalance
</p>
<p className={'line-clamp-2'}>{item.pointsbalance}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Referralcode</p>
<p className={'line-clamp-2'}>{item.referralcode}</p>
</div>
</Link> </Link>
<ListActionsPopover <ListActionsPopover
onDelete={onDelete} onDelete={onDelete}

View File

@ -159,6 +159,52 @@ export const loadColumns = async (
), ),
}, },
{
field: 'loyaltytier',
headerName: 'Loyaltytier',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
sortable: false,
type: 'singleSelect',
getOptionValue: (value: any) => value?.id,
getOptionLabel: (value: any) => value?.label,
valueOptions: await callOptionsApi('loyaltytier'),
valueGetter: (params: GridValueGetterParams) =>
params?.value?.id ?? params?.value,
},
{
field: 'pointsbalance',
headerName: 'Pointsbalance',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
type: 'number',
},
{
field: 'referralcode',
headerName: 'Referralcode',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
},
{ {
field: 'actions', field: 'actions',
type: 'actions', type: 'actions',

View File

@ -17,7 +17,7 @@ export default function WebSiteFooter({ projectName }: WebSiteFooterProps) {
const borders = useAppSelector((state) => state.style.borders); const borders = useAppSelector((state) => state.style.borders);
const websiteHeder = useAppSelector((state) => state.style.websiteHeder); const websiteHeder = useAppSelector((state) => state.style.websiteHeder);
const style = FooterStyle.WITH_PAGES; const style = FooterStyle.WITH_PROJECT_NAME;
const design = FooterDesigns.DEFAULT_DESIGN; const design = FooterDesigns.DEFAULT_DESIGN;

View File

@ -19,7 +19,7 @@ export default function WebSiteHeader({ projectName }: WebSiteHeaderProps) {
const style = HeaderStyle.PAGES_LEFT; const style = HeaderStyle.PAGES_LEFT;
const design = HeaderDesigns.DESIGN_DIVERSITY; const design = HeaderDesigns.DEFAULT_DESIGN;
return ( return (
<header id='websiteHeader' className='overflow-hidden'> <header id='websiteHeader' className='overflow-hidden'>
<div <div

View File

@ -39,6 +39,25 @@ export default {
}); });
}, },
usersManyListFormatter(val) {
if (!val || !val.length) return [];
return val.map((item) => item.firstName);
},
usersOneListFormatter(val) {
if (!val) return '';
return val.firstName;
},
usersManyListFormatterEdit(val) {
if (!val || !val.length) return [];
return val.map((item) => {
return { id: item.id, label: item.firstName };
});
},
usersOneListFormatterEdit(val) {
if (!val) return '';
return { label: val.firstName, id: val.id };
},
agentsManyListFormatter(val) { agentsManyListFormatter(val) {
if (!val || !val.length) return []; if (!val || !val.length) return [];
return val.map((item) => item.name); return val.map((item) => item.name);
@ -133,4 +152,23 @@ export default {
if (!val) return ''; if (!val) return '';
return { label: val.name, id: val.id }; return { label: val.name, id: val.id };
}, },
loyaltytierManyListFormatter(val) {
if (!val || !val.length) return [];
return val.map((item) => item.name);
},
loyaltytierOneListFormatter(val) {
if (!val) return '';
return val.name;
},
loyaltytierManyListFormatterEdit(val) {
if (!val || !val.length) return [];
return val.map((item) => {
return { id: item.id, label: item.name };
});
},
loyaltytierOneListFormatterEdit(val) {
if (!val) return '';
return { label: val.name, id: val.id };
},
}; };

View File

@ -95,6 +95,22 @@ const menuAside: MenuAsideItem[] = [
icon: icon.mdiTable ?? icon.mdiTable, icon: icon.mdiTable ?? icon.mdiTable,
permissions: 'READ_LOYALTYTIER', permissions: 'READ_LOYALTYTIER',
}, },
{
href: '/referral/referral-list',
label: 'Referral',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: icon.mdiTable ?? icon.mdiTable,
permissions: 'READ_REFERRAL',
},
{
href: '/redemption/redemption-list',
label: 'Redemption',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: icon.mdiTable ?? icon.mdiTable,
permissions: 'READ_REDEMPTION',
},
{ {
href: '/profile', href: '/profile',
label: 'Profile', label: 'Profile',

View File

@ -185,6 +185,59 @@ const BookingsView = () => {
</CardBox> </CardBox>
</> </>
<>
<p className={'block font-bold mb-2'}>Redemption Booking</p>
<CardBox
className='mb-6 border border-gray-300 rounded overflow-hidden'
hasTable
>
<div className='overflow-x-auto'>
<table>
<thead>
<tr>
<th>Pointsused</th>
<th>Redemptiontype</th>
<th>Discountvalue</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{bookings.redemption_booking &&
Array.isArray(bookings.redemption_booking) &&
bookings.redemption_booking.map((item: any) => (
<tr
key={item.id}
onClick={() =>
router.push(
`/redemption/redemption-view/?id=${item.id}`,
)
}
>
<td data-label='pointsused'>{item.pointsused}</td>
<td data-label='redemptiontype'>
{item.redemptiontype}
</td>
<td data-label='discountvalue'>
{item.discountvalue}
</td>
<td data-label='status'>{item.status}</td>
</tr>
))}
</tbody>
</table>
</div>
{!bookings?.redemption_booking?.length && (
<div className={'text-center py-4'}>No data</div>
)}
</CardBox>
</>
<BaseDivider /> <BaseDivider />
<BaseButton <BaseButton

View File

@ -37,6 +37,8 @@ const Dashboard = () => {
const [roles, setRoles] = React.useState(loadingMessage); const [roles, setRoles] = React.useState(loadingMessage);
const [permissions, setPermissions] = React.useState(loadingMessage); const [permissions, setPermissions] = React.useState(loadingMessage);
const [loyaltytier, setLoyaltytier] = React.useState(loadingMessage); const [loyaltytier, setLoyaltytier] = React.useState(loadingMessage);
const [referral, setReferral] = React.useState(loadingMessage);
const [redemption, setRedemption] = React.useState(loadingMessage);
const [widgetsRole, setWidgetsRole] = React.useState({ const [widgetsRole, setWidgetsRole] = React.useState({
role: { value: '', label: '' }, role: { value: '', label: '' },
@ -57,6 +59,8 @@ const Dashboard = () => {
'roles', 'roles',
'permissions', 'permissions',
'loyaltytier', 'loyaltytier',
'referral',
'redemption',
]; ];
const fns = [ const fns = [
setUsers, setUsers,
@ -68,6 +72,8 @@ const Dashboard = () => {
setRoles, setRoles,
setPermissions, setPermissions,
setLoyaltytier, setLoyaltytier,
setReferral,
setRedemption,
]; ];
const requests = entities.map((entity, index) => { const requests = entities.map((entity, index) => {
@ -491,6 +497,70 @@ const Dashboard = () => {
</div> </div>
</Link> </Link>
)} )}
{hasPermission(currentUser, 'READ_REFERRAL') && (
<Link href={'/referral/referral-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'>
Referral
</div>
<div className='text-3xl leading-tight font-semibold'>
{referral}
</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.mdiTable || icon.mdiTable}
/>
</div>
</div>
</div>
</Link>
)}
{hasPermission(currentUser, 'READ_REDEMPTION') && (
<Link href={'/redemption/redemption-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'>
Redemption
</div>
<div className='text-3xl leading-tight font-semibold'>
{redemption}
</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.mdiTable || icon.mdiTable}
/>
</div>
</div>
</div>
</Link>
)}
</div> </div>
</SectionMain> </SectionMain>
</> </>

View File

@ -37,6 +37,12 @@ const EditLoyaltytier = () => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const initVals = { const initVals = {
name: '', name: '',
annualfee: '',
pointspersar: '',
description: '',
}; };
const [initialValues, setInitialValues] = useState(initVals); const [initialValues, setInitialValues] = useState(initVals);
@ -95,6 +101,22 @@ const EditLoyaltytier = () => {
<Field name='name' placeholder='Name' /> <Field name='name' placeholder='Name' />
</FormField> </FormField>
<FormField label='Annualfee'>
<Field type='number' name='annualfee' placeholder='Annualfee' />
</FormField>
<FormField label='Pointspersar'>
<Field
type='number'
name='pointspersar'
placeholder='Pointspersar'
/>
</FormField>
<FormField label='Description'>
<Field name='description' placeholder='Description' />
</FormField>
<BaseDivider /> <BaseDivider />
<BaseButtons> <BaseButtons>
<BaseButton type='submit' color='info' label='Submit' /> <BaseButton type='submit' color='info' label='Submit' />

View File

@ -37,6 +37,12 @@ const EditLoyaltytierPage = () => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const initVals = { const initVals = {
name: '', name: '',
annualfee: '',
pointspersar: '',
description: '',
}; };
const [initialValues, setInitialValues] = useState(initVals); const [initialValues, setInitialValues] = useState(initVals);
@ -93,6 +99,22 @@ const EditLoyaltytierPage = () => {
<Field name='name' placeholder='Name' /> <Field name='name' placeholder='Name' />
</FormField> </FormField>
<FormField label='Annualfee'>
<Field type='number' name='annualfee' placeholder='Annualfee' />
</FormField>
<FormField label='Pointspersar'>
<Field
type='number'
name='pointspersar'
placeholder='Pointspersar'
/>
</FormField>
<FormField label='Description'>
<Field name='description' placeholder='Description' />
</FormField>
<BaseDivider /> <BaseDivider />
<BaseButtons> <BaseButtons>
<BaseButton type='submit' color='info' label='Submit' /> <BaseButton type='submit' color='info' label='Submit' />

View File

@ -31,7 +31,13 @@ const LoyaltytierTablesPage = () => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const [filters] = useState([{ label: 'Name', title: 'name' }]); const [filters] = useState([
{ label: 'Name', title: 'name' },
{ label: 'Description', title: 'description' },
{ label: 'Annualfee', title: 'annualfee', number: 'true' },
{ label: 'Pointspersar', title: 'pointspersar', number: 'true' },
]);
const hasCreatePermission = const hasCreatePermission =
currentUser && hasPermission(currentUser, 'CREATE_LOYALTYTIER'); currentUser && hasPermission(currentUser, 'CREATE_LOYALTYTIER');

View File

@ -34,6 +34,12 @@ import moment from 'moment';
const initialValues = { const initialValues = {
name: '', name: '',
annualfee: '',
pointspersar: '',
description: '',
}; };
const LoyaltytierNew = () => { const LoyaltytierNew = () => {
@ -67,6 +73,22 @@ const LoyaltytierNew = () => {
<Field name='name' placeholder='Name' /> <Field name='name' placeholder='Name' />
</FormField> </FormField>
<FormField label='Annualfee'>
<Field type='number' name='annualfee' placeholder='Annualfee' />
</FormField>
<FormField label='Pointspersar'>
<Field
type='number'
name='pointspersar'
placeholder='Pointspersar'
/>
</FormField>
<FormField label='Description'>
<Field name='description' placeholder='Description' />
</FormField>
<BaseDivider /> <BaseDivider />
<BaseButtons> <BaseButtons>
<BaseButton type='submit' color='info' label='Submit' /> <BaseButton type='submit' color='info' label='Submit' />

View File

@ -31,7 +31,13 @@ const LoyaltytierTablesPage = () => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const [filters] = useState([{ label: 'Name', title: 'name' }]); const [filters] = useState([
{ label: 'Name', title: 'name' },
{ label: 'Description', title: 'description' },
{ label: 'Annualfee', title: 'annualfee', number: 'true' },
{ label: 'Pointspersar', title: 'pointspersar', number: 'true' },
]);
const hasCreatePermission = const hasCreatePermission =
currentUser && hasPermission(currentUser, 'CREATE_LOYALTYTIER'); currentUser && hasPermission(currentUser, 'CREATE_LOYALTYTIER');

View File

@ -59,6 +59,84 @@ const LoyaltytierView = () => {
<p>{loyaltytier?.name}</p> <p>{loyaltytier?.name}</p>
</div> </div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Annualfee</p>
<p>{loyaltytier?.annualfee || 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Pointspersar</p>
<p>{loyaltytier?.pointspersar || 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Description</p>
<p>{loyaltytier?.description}</p>
</div>
<>
<p className={'block font-bold mb-2'}>Users Loyaltytier</p>
<CardBox
className='mb-6 border border-gray-300 rounded overflow-hidden'
hasTable
>
<div className='overflow-x-auto'>
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
<th>E-Mail</th>
<th>Disabled</th>
<th>Pointsbalance</th>
<th>Referralcode</th>
</tr>
</thead>
<tbody>
{loyaltytier.users_loyaltytier &&
Array.isArray(loyaltytier.users_loyaltytier) &&
loyaltytier.users_loyaltytier.map((item: any) => (
<tr
key={item.id}
onClick={() =>
router.push(`/users/users-view/?id=${item.id}`)
}
>
<td data-label='firstName'>{item.firstName}</td>
<td data-label='lastName'>{item.lastName}</td>
<td data-label='phoneNumber'>{item.phoneNumber}</td>
<td data-label='email'>{item.email}</td>
<td data-label='disabled'>
{dataFormatter.booleanFormatter(item.disabled)}
</td>
<td data-label='pointsbalance'>
{item.pointsbalance}
</td>
<td data-label='referralcode'>{item.referralcode}</td>
</tr>
))}
</tbody>
</table>
</div>
{!loyaltytier?.users_loyaltytier?.length && (
<div className={'text-center py-4'}>No data</div>
)}
</CardBox>
</>
<BaseDivider /> <BaseDivider />
<BaseButton <BaseButton

View File

@ -0,0 +1,186 @@
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/redemption/redemptionSlice';
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 EditRedemption = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const initVals = {
user: null,
pointsused: '',
redemptiontype: '',
discountvalue: '',
status: '',
booking: null,
};
const [initialValues, setInitialValues] = useState(initVals);
const { redemption } = useAppSelector((state) => state.redemption);
const { redemptionId } = router.query;
useEffect(() => {
dispatch(fetch({ id: redemptionId }));
}, [redemptionId]);
useEffect(() => {
if (typeof redemption === 'object') {
setInitialValues(redemption);
}
}, [redemption]);
useEffect(() => {
if (typeof redemption === 'object') {
const newInitialVal = { ...initVals };
Object.keys(initVals).forEach(
(el) => (newInitialVal[el] = redemption[el]),
);
setInitialValues(newInitialVal);
}
}, [redemption]);
const handleSubmit = async (data) => {
await dispatch(update({ id: redemptionId, data }));
await router.push('/redemption/redemption-list');
};
return (
<>
<Head>
<title>{getPageTitle('Edit redemption')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={'Edit redemption'}
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
enableReinitialize
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='User' labelFor='user'>
<Field
name='user'
id='user'
component={SelectField}
options={initialValues.user}
itemRef={'users'}
showField={'firstName'}
></Field>
</FormField>
<FormField label='Pointsused'>
<Field
type='number'
name='pointsused'
placeholder='Pointsused'
/>
</FormField>
<FormField label='Redemptiontype'>
<FormCheckRadioGroup>
<FormCheckRadio type='radio' label='value'>
<Field type='radio' name='redemptiontype' value='value' />
</FormCheckRadio>
</FormCheckRadioGroup>
</FormField>
<FormField label='Discountvalue'>
<Field
type='number'
name='discountvalue'
placeholder='Discountvalue'
/>
</FormField>
<FormField label='Status'>
<FormCheckRadioGroup>
<FormCheckRadio type='radio' label='value'>
<Field type='radio' name='status' value='value' />
</FormCheckRadio>
</FormCheckRadioGroup>
</FormField>
<FormField label='Booking' labelFor='booking'>
<Field
name='booking'
id='booking'
component={SelectField}
options={initialValues.booking}
itemRef={'bookings'}
showField={'service_type'}
></Field>
</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('/redemption/redemption-list')}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
EditRedemption.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'UPDATE_REDEMPTION'}>
{page}
</LayoutAuthenticated>
);
};
export default EditRedemption;

View File

@ -0,0 +1,184 @@
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/redemption/redemptionSlice';
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 EditRedemptionPage = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const initVals = {
user: null,
pointsused: '',
redemptiontype: '',
discountvalue: '',
status: '',
booking: null,
};
const [initialValues, setInitialValues] = useState(initVals);
const { redemption } = useAppSelector((state) => state.redemption);
const { id } = router.query;
useEffect(() => {
dispatch(fetch({ id: id }));
}, [id]);
useEffect(() => {
if (typeof redemption === 'object') {
setInitialValues(redemption);
}
}, [redemption]);
useEffect(() => {
if (typeof redemption === 'object') {
const newInitialVal = { ...initVals };
Object.keys(initVals).forEach(
(el) => (newInitialVal[el] = redemption[el]),
);
setInitialValues(newInitialVal);
}
}, [redemption]);
const handleSubmit = async (data) => {
await dispatch(update({ id: id, data }));
await router.push('/redemption/redemption-list');
};
return (
<>
<Head>
<title>{getPageTitle('Edit redemption')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={'Edit redemption'}
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
enableReinitialize
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='User' labelFor='user'>
<Field
name='user'
id='user'
component={SelectField}
options={initialValues.user}
itemRef={'users'}
showField={'firstName'}
></Field>
</FormField>
<FormField label='Pointsused'>
<Field
type='number'
name='pointsused'
placeholder='Pointsused'
/>
</FormField>
<FormField label='Redemptiontype'>
<FormCheckRadioGroup>
<FormCheckRadio type='radio' label='value'>
<Field type='radio' name='redemptiontype' value='value' />
</FormCheckRadio>
</FormCheckRadioGroup>
</FormField>
<FormField label='Discountvalue'>
<Field
type='number'
name='discountvalue'
placeholder='Discountvalue'
/>
</FormField>
<FormField label='Status'>
<FormCheckRadioGroup>
<FormCheckRadio type='radio' label='value'>
<Field type='radio' name='status' value='value' />
</FormCheckRadio>
</FormCheckRadioGroup>
</FormField>
<FormField label='Booking' labelFor='booking'>
<Field
name='booking'
id='booking'
component={SelectField}
options={initialValues.booking}
itemRef={'bookings'}
showField={'service_type'}
></Field>
</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('/redemption/redemption-list')}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
EditRedemptionPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'UPDATE_REDEMPTION'}>
{page}
</LayoutAuthenticated>
);
};
export default EditRedemptionPage;

View File

@ -0,0 +1,177 @@
import { mdiChartTimelineVariant } from '@mdi/js';
import Head from 'next/head';
import { uniqueId } from 'lodash';
import React, { ReactElement, useState } from 'react';
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 TableRedemption from '../../components/Redemption/TableRedemption';
import BaseButton from '../../components/BaseButton';
import axios from 'axios';
import Link from 'next/link';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import CardBoxModal from '../../components/CardBoxModal';
import DragDropFilePicker from '../../components/DragDropFilePicker';
import { setRefetch, uploadCsv } from '../../stores/redemption/redemptionSlice';
import { hasPermission } from '../../helpers/userPermissions';
const RedemptionTablesPage = () => {
const [filterItems, setFilterItems] = useState([]);
const [csvFile, setCsvFile] = useState<File | null>(null);
const [isModalActive, setIsModalActive] = useState(false);
const [showTableView, setShowTableView] = useState(false);
const { currentUser } = useAppSelector((state) => state.auth);
const dispatch = useAppDispatch();
const [filters] = useState([
{ label: 'Pointsused', title: 'pointsused', number: 'true' },
{ label: 'Discountvalue', title: 'discountvalue', number: 'true' },
{ label: 'User', title: 'user' },
{ label: 'Booking', title: 'booking' },
{
label: 'Redemptiontype',
title: 'redemptiontype',
type: 'enum',
options: ['value'],
},
{ label: 'Status', title: 'status', type: 'enum', options: ['value'] },
]);
const hasCreatePermission =
currentUser && hasPermission(currentUser, 'CREATE_REDEMPTION');
const addFilter = () => {
const newItem = {
id: uniqueId(),
fields: {
filterValue: '',
filterValueFrom: '',
filterValueTo: '',
selectedField: '',
},
};
newItem.fields.selectedField = filters[0].title;
setFilterItems([...filterItems, newItem]);
};
const getRedemptionCSV = async () => {
const response = await axios({
url: '/redemption?filetype=csv',
method: 'GET',
responseType: 'blob',
});
const type = response.headers['content-type'];
const blob = new Blob([response.data], { type: type });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'redemptionCSV.csv';
link.click();
};
const onModalConfirm = async () => {
if (!csvFile) return;
await dispatch(uploadCsv(csvFile));
dispatch(setRefetch(true));
setCsvFile(null);
setIsModalActive(false);
};
const onModalCancel = () => {
setCsvFile(null);
setIsModalActive(false);
};
return (
<>
<Head>
<title>{getPageTitle('Redemption')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='Redemption'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
{hasCreatePermission && (
<BaseButton
className={'mr-3'}
href={'/redemption/redemption-new'}
color='info'
label='New Item'
/>
)}
<BaseButton
className={'mr-3'}
color='info'
label='Filter'
onClick={addFilter}
/>
<BaseButton
className={'mr-3'}
color='info'
label='Download CSV'
onClick={getRedemptionCSV}
/>
{hasCreatePermission && (
<BaseButton
color='info'
label='Upload CSV'
onClick={() => setIsModalActive(true)}
/>
)}
<div className='md:inline-flex items-center ms-auto'>
<div id='delete-rows-button'></div>
</div>
</CardBox>
<CardBox className='mb-6' hasTable>
<TableRedemption
filterItems={filterItems}
setFilterItems={setFilterItems}
filters={filters}
showGrid={false}
/>
</CardBox>
</SectionMain>
<CardBoxModal
title='Upload CSV'
buttonColor='info'
buttonLabel={'Confirm'}
// buttonLabel={false ? 'Deleting...' : 'Confirm'}
isActive={isModalActive}
onConfirm={onModalConfirm}
onCancel={onModalCancel}
>
<DragDropFilePicker
file={csvFile}
setFile={setCsvFile}
formats={'.csv'}
/>
</CardBoxModal>
</>
);
};
RedemptionTablesPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_REDEMPTION'}>
{page}
</LayoutAuthenticated>
);
};
export default RedemptionTablesPage;

View File

@ -0,0 +1,156 @@
import {
mdiAccount,
mdiChartTimelineVariant,
mdiMail,
mdiUpload,
} from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement } from 'react';
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 { SwitchField } from '../../components/SwitchField';
import { SelectField } from '../../components/SelectField';
import { SelectFieldMany } from '../../components/SelectFieldMany';
import { RichTextField } from '../../components/RichTextField';
import { create } from '../../stores/redemption/redemptionSlice';
import { useAppDispatch } from '../../stores/hooks';
import { useRouter } from 'next/router';
import moment from 'moment';
const initialValues = {
user: '',
pointsused: '',
redemptiontype: '',
discountvalue: '',
status: '',
booking: '',
};
const RedemptionNew = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const handleSubmit = async (data) => {
await dispatch(create(data));
await router.push('/redemption/redemption-list');
};
return (
<>
<Head>
<title>{getPageTitle('New Item')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='New Item'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='User' labelFor='user'>
<Field
name='user'
id='user'
component={SelectField}
options={[]}
itemRef={'users'}
></Field>
</FormField>
<FormField label='Pointsused'>
<Field
type='number'
name='pointsused'
placeholder='Pointsused'
/>
</FormField>
<FormField label='Redemptiontype'>
<FormCheckRadioGroup>
<FormCheckRadio type='radio' label='value'>
<Field type='radio' name='redemptiontype' value='value' />
</FormCheckRadio>
</FormCheckRadioGroup>
</FormField>
<FormField label='Discountvalue'>
<Field
type='number'
name='discountvalue'
placeholder='Discountvalue'
/>
</FormField>
<FormField label='Status'>
<FormCheckRadioGroup>
<FormCheckRadio type='radio' label='value'>
<Field type='radio' name='status' value='value' />
</FormCheckRadio>
</FormCheckRadioGroup>
</FormField>
<FormField label='Booking' labelFor='booking'>
<Field
name='booking'
id='booking'
component={SelectField}
options={[]}
itemRef={'bookings'}
></Field>
</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('/redemption/redemption-list')}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
RedemptionNew.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'CREATE_REDEMPTION'}>
{page}
</LayoutAuthenticated>
);
};
export default RedemptionNew;

View File

@ -0,0 +1,176 @@
import { mdiChartTimelineVariant } from '@mdi/js';
import Head from 'next/head';
import { uniqueId } from 'lodash';
import React, { ReactElement, useState } from 'react';
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 TableRedemption from '../../components/Redemption/TableRedemption';
import BaseButton from '../../components/BaseButton';
import axios from 'axios';
import Link from 'next/link';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import CardBoxModal from '../../components/CardBoxModal';
import DragDropFilePicker from '../../components/DragDropFilePicker';
import { setRefetch, uploadCsv } from '../../stores/redemption/redemptionSlice';
import { hasPermission } from '../../helpers/userPermissions';
const RedemptionTablesPage = () => {
const [filterItems, setFilterItems] = useState([]);
const [csvFile, setCsvFile] = useState<File | null>(null);
const [isModalActive, setIsModalActive] = useState(false);
const [showTableView, setShowTableView] = useState(false);
const { currentUser } = useAppSelector((state) => state.auth);
const dispatch = useAppDispatch();
const [filters] = useState([
{ label: 'Pointsused', title: 'pointsused', number: 'true' },
{ label: 'Discountvalue', title: 'discountvalue', number: 'true' },
{ label: 'User', title: 'user' },
{ label: 'Booking', title: 'booking' },
{
label: 'Redemptiontype',
title: 'redemptiontype',
type: 'enum',
options: ['value'],
},
{ label: 'Status', title: 'status', type: 'enum', options: ['value'] },
]);
const hasCreatePermission =
currentUser && hasPermission(currentUser, 'CREATE_REDEMPTION');
const addFilter = () => {
const newItem = {
id: uniqueId(),
fields: {
filterValue: '',
filterValueFrom: '',
filterValueTo: '',
selectedField: '',
},
};
newItem.fields.selectedField = filters[0].title;
setFilterItems([...filterItems, newItem]);
};
const getRedemptionCSV = async () => {
const response = await axios({
url: '/redemption?filetype=csv',
method: 'GET',
responseType: 'blob',
});
const type = response.headers['content-type'];
const blob = new Blob([response.data], { type: type });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'redemptionCSV.csv';
link.click();
};
const onModalConfirm = async () => {
if (!csvFile) return;
await dispatch(uploadCsv(csvFile));
dispatch(setRefetch(true));
setCsvFile(null);
setIsModalActive(false);
};
const onModalCancel = () => {
setCsvFile(null);
setIsModalActive(false);
};
return (
<>
<Head>
<title>{getPageTitle('Redemption')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='Redemption'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
{hasCreatePermission && (
<BaseButton
className={'mr-3'}
href={'/redemption/redemption-new'}
color='info'
label='New Item'
/>
)}
<BaseButton
className={'mr-3'}
color='info'
label='Filter'
onClick={addFilter}
/>
<BaseButton
className={'mr-3'}
color='info'
label='Download CSV'
onClick={getRedemptionCSV}
/>
{hasCreatePermission && (
<BaseButton
color='info'
label='Upload CSV'
onClick={() => setIsModalActive(true)}
/>
)}
<div className='md:inline-flex items-center ms-auto'>
<div id='delete-rows-button'></div>
</div>
</CardBox>
<CardBox className='mb-6' hasTable>
<TableRedemption
filterItems={filterItems}
setFilterItems={setFilterItems}
filters={filters}
showGrid={true}
/>
</CardBox>
</SectionMain>
<CardBoxModal
title='Upload CSV'
buttonColor='info'
buttonLabel={'Confirm'}
// buttonLabel={false ? 'Deleting...' : 'Confirm'}
isActive={isModalActive}
onConfirm={onModalConfirm}
onCancel={onModalCancel}
>
<DragDropFilePicker
file={csvFile}
setFile={setCsvFile}
formats={'.csv'}
/>
</CardBoxModal>
</>
);
};
RedemptionTablesPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_REDEMPTION'}>
{page}
</LayoutAuthenticated>
);
};
export default RedemptionTablesPage;

View File

@ -0,0 +1,110 @@
import React, { ReactElement, useEffect } from 'react';
import Head from 'next/head';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import dayjs from 'dayjs';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { fetch } from '../../stores/redemption/redemptionSlice';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from '../../components/ImageField';
import LayoutAuthenticated from '../../layouts/Authenticated';
import { getPageTitle } from '../../config';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import SectionMain from '../../components/SectionMain';
import CardBox from '../../components/CardBox';
import BaseButton from '../../components/BaseButton';
import BaseDivider from '../../components/BaseDivider';
import { mdiChartTimelineVariant } from '@mdi/js';
import { SwitchField } from '../../components/SwitchField';
import FormField from '../../components/FormField';
const RedemptionView = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const { redemption } = useAppSelector((state) => state.redemption);
const { id } = router.query;
function removeLastCharacter(str) {
console.log(str, `str`);
return str.slice(0, -1);
}
useEffect(() => {
dispatch(fetch({ id }));
}, [dispatch, id]);
return (
<>
<Head>
<title>{getPageTitle('View redemption')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={removeLastCharacter('View redemption')}
main
>
<BaseButton
color='info'
label='Edit'
href={`/redemption/redemption-edit/?id=${id}`}
/>
</SectionTitleLineWithButton>
<CardBox>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>User</p>
<p>{redemption?.user?.firstName ?? 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Pointsused</p>
<p>{redemption?.pointsused || 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Redemptiontype</p>
<p>{redemption?.redemptiontype ?? 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Discountvalue</p>
<p>{redemption?.discountvalue || 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Status</p>
<p>{redemption?.status ?? 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Booking</p>
<p>{redemption?.booking?.service_type ?? 'No data'}</p>
</div>
<BaseDivider />
<BaseButton
color='info'
label='Back'
onClick={() => router.push('/redemption/redemption-list')}
/>
</CardBox>
</SectionMain>
</>
);
};
RedemptionView.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_REDEMPTION'}>
{page}
</LayoutAuthenticated>
);
};
export default RedemptionView;

View File

@ -0,0 +1,147 @@
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/referral/referralSlice';
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 EditReferral = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const initVals = {
referrer: null,
referredemail: '',
status: '',
};
const [initialValues, setInitialValues] = useState(initVals);
const { referral } = useAppSelector((state) => state.referral);
const { referralId } = router.query;
useEffect(() => {
dispatch(fetch({ id: referralId }));
}, [referralId]);
useEffect(() => {
if (typeof referral === 'object') {
setInitialValues(referral);
}
}, [referral]);
useEffect(() => {
if (typeof referral === 'object') {
const newInitialVal = { ...initVals };
Object.keys(initVals).forEach((el) => (newInitialVal[el] = referral[el]));
setInitialValues(newInitialVal);
}
}, [referral]);
const handleSubmit = async (data) => {
await dispatch(update({ id: referralId, data }));
await router.push('/referral/referral-list');
};
return (
<>
<Head>
<title>{getPageTitle('Edit referral')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={'Edit referral'}
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
enableReinitialize
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='Referrer' labelFor='referrer'>
<Field
name='referrer'
id='referrer'
component={SelectField}
options={initialValues.referrer}
itemRef={'users'}
showField={'firstName'}
></Field>
</FormField>
<FormField label='Referredemail'>
<Field name='referredemail' placeholder='Referredemail' />
</FormField>
<FormField label='Status'>
<FormCheckRadioGroup>
<FormCheckRadio type='radio' label='value'>
<Field type='radio' name='status' value='value' />
</FormCheckRadio>
</FormCheckRadioGroup>
</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('/referral/referral-list')}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
EditReferral.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'UPDATE_REFERRAL'}>
{page}
</LayoutAuthenticated>
);
};
export default EditReferral;

View File

@ -0,0 +1,145 @@
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/referral/referralSlice';
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 EditReferralPage = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const initVals = {
referrer: null,
referredemail: '',
status: '',
};
const [initialValues, setInitialValues] = useState(initVals);
const { referral } = useAppSelector((state) => state.referral);
const { id } = router.query;
useEffect(() => {
dispatch(fetch({ id: id }));
}, [id]);
useEffect(() => {
if (typeof referral === 'object') {
setInitialValues(referral);
}
}, [referral]);
useEffect(() => {
if (typeof referral === 'object') {
const newInitialVal = { ...initVals };
Object.keys(initVals).forEach((el) => (newInitialVal[el] = referral[el]));
setInitialValues(newInitialVal);
}
}, [referral]);
const handleSubmit = async (data) => {
await dispatch(update({ id: id, data }));
await router.push('/referral/referral-list');
};
return (
<>
<Head>
<title>{getPageTitle('Edit referral')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={'Edit referral'}
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
enableReinitialize
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='Referrer' labelFor='referrer'>
<Field
name='referrer'
id='referrer'
component={SelectField}
options={initialValues.referrer}
itemRef={'users'}
showField={'firstName'}
></Field>
</FormField>
<FormField label='Referredemail'>
<Field name='referredemail' placeholder='Referredemail' />
</FormField>
<FormField label='Status'>
<FormCheckRadioGroup>
<FormCheckRadio type='radio' label='value'>
<Field type='radio' name='status' value='value' />
</FormCheckRadio>
</FormCheckRadioGroup>
</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('/referral/referral-list')}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
EditReferralPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'UPDATE_REFERRAL'}>
{page}
</LayoutAuthenticated>
);
};
export default EditReferralPage;

View File

@ -0,0 +1,168 @@
import { mdiChartTimelineVariant } from '@mdi/js';
import Head from 'next/head';
import { uniqueId } from 'lodash';
import React, { ReactElement, useState } from 'react';
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 TableReferral from '../../components/Referral/TableReferral';
import BaseButton from '../../components/BaseButton';
import axios from 'axios';
import Link from 'next/link';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import CardBoxModal from '../../components/CardBoxModal';
import DragDropFilePicker from '../../components/DragDropFilePicker';
import { setRefetch, uploadCsv } from '../../stores/referral/referralSlice';
import { hasPermission } from '../../helpers/userPermissions';
const ReferralTablesPage = () => {
const [filterItems, setFilterItems] = useState([]);
const [csvFile, setCsvFile] = useState<File | null>(null);
const [isModalActive, setIsModalActive] = useState(false);
const [showTableView, setShowTableView] = useState(false);
const { currentUser } = useAppSelector((state) => state.auth);
const dispatch = useAppDispatch();
const [filters] = useState([
{ label: 'Referredemail', title: 'referredemail' },
{ label: 'Referrer', title: 'referrer' },
{ label: 'Status', title: 'status', type: 'enum', options: ['value'] },
]);
const hasCreatePermission =
currentUser && hasPermission(currentUser, 'CREATE_REFERRAL');
const addFilter = () => {
const newItem = {
id: uniqueId(),
fields: {
filterValue: '',
filterValueFrom: '',
filterValueTo: '',
selectedField: '',
},
};
newItem.fields.selectedField = filters[0].title;
setFilterItems([...filterItems, newItem]);
};
const getReferralCSV = async () => {
const response = await axios({
url: '/referral?filetype=csv',
method: 'GET',
responseType: 'blob',
});
const type = response.headers['content-type'];
const blob = new Blob([response.data], { type: type });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'referralCSV.csv';
link.click();
};
const onModalConfirm = async () => {
if (!csvFile) return;
await dispatch(uploadCsv(csvFile));
dispatch(setRefetch(true));
setCsvFile(null);
setIsModalActive(false);
};
const onModalCancel = () => {
setCsvFile(null);
setIsModalActive(false);
};
return (
<>
<Head>
<title>{getPageTitle('Referral')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='Referral'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
{hasCreatePermission && (
<BaseButton
className={'mr-3'}
href={'/referral/referral-new'}
color='info'
label='New Item'
/>
)}
<BaseButton
className={'mr-3'}
color='info'
label='Filter'
onClick={addFilter}
/>
<BaseButton
className={'mr-3'}
color='info'
label='Download CSV'
onClick={getReferralCSV}
/>
{hasCreatePermission && (
<BaseButton
color='info'
label='Upload CSV'
onClick={() => setIsModalActive(true)}
/>
)}
<div className='md:inline-flex items-center ms-auto'>
<div id='delete-rows-button'></div>
</div>
</CardBox>
<CardBox className='mb-6' hasTable>
<TableReferral
filterItems={filterItems}
setFilterItems={setFilterItems}
filters={filters}
showGrid={false}
/>
</CardBox>
</SectionMain>
<CardBoxModal
title='Upload CSV'
buttonColor='info'
buttonLabel={'Confirm'}
// buttonLabel={false ? 'Deleting...' : 'Confirm'}
isActive={isModalActive}
onConfirm={onModalConfirm}
onCancel={onModalCancel}
>
<DragDropFilePicker
file={csvFile}
setFile={setCsvFile}
formats={'.csv'}
/>
</CardBoxModal>
</>
);
};
ReferralTablesPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_REFERRAL'}>
{page}
</LayoutAuthenticated>
);
};
export default ReferralTablesPage;

View File

@ -0,0 +1,120 @@
import {
mdiAccount,
mdiChartTimelineVariant,
mdiMail,
mdiUpload,
} from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement } from 'react';
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 { SwitchField } from '../../components/SwitchField';
import { SelectField } from '../../components/SelectField';
import { SelectFieldMany } from '../../components/SelectFieldMany';
import { RichTextField } from '../../components/RichTextField';
import { create } from '../../stores/referral/referralSlice';
import { useAppDispatch } from '../../stores/hooks';
import { useRouter } from 'next/router';
import moment from 'moment';
const initialValues = {
referrer: '',
referredemail: '',
status: '',
};
const ReferralNew = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const handleSubmit = async (data) => {
await dispatch(create(data));
await router.push('/referral/referral-list');
};
return (
<>
<Head>
<title>{getPageTitle('New Item')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='New Item'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='Referrer' labelFor='referrer'>
<Field
name='referrer'
id='referrer'
component={SelectField}
options={[]}
itemRef={'users'}
></Field>
</FormField>
<FormField label='Referredemail'>
<Field name='referredemail' placeholder='Referredemail' />
</FormField>
<FormField label='Status'>
<FormCheckRadioGroup>
<FormCheckRadio type='radio' label='value'>
<Field type='radio' name='status' value='value' />
</FormCheckRadio>
</FormCheckRadioGroup>
</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('/referral/referral-list')}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
ReferralNew.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'CREATE_REFERRAL'}>
{page}
</LayoutAuthenticated>
);
};
export default ReferralNew;

View File

@ -0,0 +1,167 @@
import { mdiChartTimelineVariant } from '@mdi/js';
import Head from 'next/head';
import { uniqueId } from 'lodash';
import React, { ReactElement, useState } from 'react';
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 TableReferral from '../../components/Referral/TableReferral';
import BaseButton from '../../components/BaseButton';
import axios from 'axios';
import Link from 'next/link';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import CardBoxModal from '../../components/CardBoxModal';
import DragDropFilePicker from '../../components/DragDropFilePicker';
import { setRefetch, uploadCsv } from '../../stores/referral/referralSlice';
import { hasPermission } from '../../helpers/userPermissions';
const ReferralTablesPage = () => {
const [filterItems, setFilterItems] = useState([]);
const [csvFile, setCsvFile] = useState<File | null>(null);
const [isModalActive, setIsModalActive] = useState(false);
const [showTableView, setShowTableView] = useState(false);
const { currentUser } = useAppSelector((state) => state.auth);
const dispatch = useAppDispatch();
const [filters] = useState([
{ label: 'Referredemail', title: 'referredemail' },
{ label: 'Referrer', title: 'referrer' },
{ label: 'Status', title: 'status', type: 'enum', options: ['value'] },
]);
const hasCreatePermission =
currentUser && hasPermission(currentUser, 'CREATE_REFERRAL');
const addFilter = () => {
const newItem = {
id: uniqueId(),
fields: {
filterValue: '',
filterValueFrom: '',
filterValueTo: '',
selectedField: '',
},
};
newItem.fields.selectedField = filters[0].title;
setFilterItems([...filterItems, newItem]);
};
const getReferralCSV = async () => {
const response = await axios({
url: '/referral?filetype=csv',
method: 'GET',
responseType: 'blob',
});
const type = response.headers['content-type'];
const blob = new Blob([response.data], { type: type });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'referralCSV.csv';
link.click();
};
const onModalConfirm = async () => {
if (!csvFile) return;
await dispatch(uploadCsv(csvFile));
dispatch(setRefetch(true));
setCsvFile(null);
setIsModalActive(false);
};
const onModalCancel = () => {
setCsvFile(null);
setIsModalActive(false);
};
return (
<>
<Head>
<title>{getPageTitle('Referral')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='Referral'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
{hasCreatePermission && (
<BaseButton
className={'mr-3'}
href={'/referral/referral-new'}
color='info'
label='New Item'
/>
)}
<BaseButton
className={'mr-3'}
color='info'
label='Filter'
onClick={addFilter}
/>
<BaseButton
className={'mr-3'}
color='info'
label='Download CSV'
onClick={getReferralCSV}
/>
{hasCreatePermission && (
<BaseButton
color='info'
label='Upload CSV'
onClick={() => setIsModalActive(true)}
/>
)}
<div className='md:inline-flex items-center ms-auto'>
<div id='delete-rows-button'></div>
</div>
</CardBox>
<CardBox className='mb-6' hasTable>
<TableReferral
filterItems={filterItems}
setFilterItems={setFilterItems}
filters={filters}
showGrid={true}
/>
</CardBox>
</SectionMain>
<CardBoxModal
title='Upload CSV'
buttonColor='info'
buttonLabel={'Confirm'}
// buttonLabel={false ? 'Deleting...' : 'Confirm'}
isActive={isModalActive}
onConfirm={onModalConfirm}
onCancel={onModalCancel}
>
<DragDropFilePicker
file={csvFile}
setFile={setCsvFile}
formats={'.csv'}
/>
</CardBoxModal>
</>
);
};
ReferralTablesPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_REFERRAL'}>
{page}
</LayoutAuthenticated>
);
};
export default ReferralTablesPage;

View File

@ -0,0 +1,94 @@
import React, { ReactElement, useEffect } from 'react';
import Head from 'next/head';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import dayjs from 'dayjs';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { fetch } from '../../stores/referral/referralSlice';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from '../../components/ImageField';
import LayoutAuthenticated from '../../layouts/Authenticated';
import { getPageTitle } from '../../config';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import SectionMain from '../../components/SectionMain';
import CardBox from '../../components/CardBox';
import BaseButton from '../../components/BaseButton';
import BaseDivider from '../../components/BaseDivider';
import { mdiChartTimelineVariant } from '@mdi/js';
import { SwitchField } from '../../components/SwitchField';
import FormField from '../../components/FormField';
const ReferralView = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const { referral } = useAppSelector((state) => state.referral);
const { id } = router.query;
function removeLastCharacter(str) {
console.log(str, `str`);
return str.slice(0, -1);
}
useEffect(() => {
dispatch(fetch({ id }));
}, [dispatch, id]);
return (
<>
<Head>
<title>{getPageTitle('View referral')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={removeLastCharacter('View referral')}
main
>
<BaseButton
color='info'
label='Edit'
href={`/referral/referral-edit/?id=${id}`}
/>
</SectionTitleLineWithButton>
<CardBox>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Referrer</p>
<p>{referral?.referrer?.firstName ?? 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Referredemail</p>
<p>{referral?.referredemail}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Status</p>
<p>{referral?.status ?? 'No data'}</p>
</div>
<BaseDivider />
<BaseButton
color='info'
label='Back'
onClick={() => router.push('/referral/referral-list')}
/>
</CardBox>
</SectionMain>
</>
);
};
ReferralView.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_REFERRAL'}>
{page}
</LayoutAuthenticated>
);
};
export default ReferralView;

View File

@ -115,6 +115,10 @@ const RolesView = () => {
<th>E-Mail</th> <th>E-Mail</th>
<th>Disabled</th> <th>Disabled</th>
<th>Pointsbalance</th>
<th>Referralcode</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@ -138,6 +142,12 @@ const RolesView = () => {
<td data-label='disabled'> <td data-label='disabled'>
{dataFormatter.booleanFormatter(item.disabled)} {dataFormatter.booleanFormatter(item.disabled)}
</td> </td>
<td data-label='pointsbalance'>
{item.pointsbalance}
</td>
<td data-label='referralcode'>{item.referralcode}</td>
</tr> </tr>
))} ))}
</tbody> </tbody>

View File

@ -52,6 +52,12 @@ const EditUsers = () => {
custom_permissions: [], custom_permissions: [],
loyaltytier: null,
pointsbalance: '',
referralcode: '',
password: '', password: '',
}; };
const [initialValues, setInitialValues] = useState(initVals); const [initialValues, setInitialValues] = useState(initVals);
@ -170,6 +176,29 @@ const EditUsers = () => {
></Field> ></Field>
</FormField> </FormField>
<FormField label='Loyaltytier' labelFor='loyaltytier'>
<Field
name='loyaltytier'
id='loyaltytier'
component={SelectField}
options={initialValues.loyaltytier}
itemRef={'loyaltytier'}
showField={'name'}
></Field>
</FormField>
<FormField label='Pointsbalance'>
<Field
type='number'
name='pointsbalance'
placeholder='Pointsbalance'
/>
</FormField>
<FormField label='Referralcode'>
<Field name='referralcode' placeholder='Referralcode' />
</FormField>
<FormField label='Password'> <FormField label='Password'>
<Field name='password' placeholder='password' /> <Field name='password' placeholder='password' />
</FormField> </FormField>

View File

@ -52,6 +52,12 @@ const EditUsersPage = () => {
custom_permissions: [], custom_permissions: [],
loyaltytier: null,
pointsbalance: '',
referralcode: '',
password: '', password: '',
}; };
const [initialValues, setInitialValues] = useState(initVals); const [initialValues, setInitialValues] = useState(initVals);
@ -168,6 +174,29 @@ const EditUsersPage = () => {
></Field> ></Field>
</FormField> </FormField>
<FormField label='Loyaltytier' labelFor='loyaltytier'>
<Field
name='loyaltytier'
id='loyaltytier'
component={SelectField}
options={initialValues.loyaltytier}
itemRef={'loyaltytier'}
showField={'name'}
></Field>
</FormField>
<FormField label='Pointsbalance'>
<Field
type='number'
name='pointsbalance'
placeholder='Pointsbalance'
/>
</FormField>
<FormField label='Referralcode'>
<Field name='referralcode' placeholder='Referralcode' />
</FormField>
<FormField label='Password'> <FormField label='Password'>
<Field name='password' placeholder='password' /> <Field name='password' placeholder='password' />
</FormField> </FormField>

View File

@ -33,9 +33,13 @@ const UsersTablesPage = () => {
{ label: 'Last Name', title: 'lastName' }, { label: 'Last Name', title: 'lastName' },
{ label: 'Phone Number', title: 'phoneNumber' }, { label: 'Phone Number', title: 'phoneNumber' },
{ label: 'E-Mail', title: 'email' }, { label: 'E-Mail', title: 'email' },
{ label: 'Referralcode', title: 'referralcode' },
{ label: 'Pointsbalance', title: 'pointsbalance', number: 'true' },
{ label: 'App Role', title: 'app_role' }, { label: 'App Role', title: 'app_role' },
{ label: 'Loyaltytier', title: 'loyaltytier' },
{ label: 'Custom Permissions', title: 'custom_permissions' }, { label: 'Custom Permissions', title: 'custom_permissions' },
]); ]);

View File

@ -48,6 +48,12 @@ const initialValues = {
app_role: '', app_role: '',
custom_permissions: [], custom_permissions: [],
loyaltytier: '',
pointsbalance: '',
referralcode: '',
}; };
const UsersNew = () => { const UsersNew = () => {
@ -140,6 +146,28 @@ const UsersNew = () => {
></Field> ></Field>
</FormField> </FormField>
<FormField label='Loyaltytier' labelFor='loyaltytier'>
<Field
name='loyaltytier'
id='loyaltytier'
component={SelectField}
options={[]}
itemRef={'loyaltytier'}
></Field>
</FormField>
<FormField label='Pointsbalance'>
<Field
type='number'
name='pointsbalance'
placeholder='Pointsbalance'
/>
</FormField>
<FormField label='Referralcode'>
<Field name='referralcode' placeholder='Referralcode' />
</FormField>
<BaseDivider /> <BaseDivider />
<BaseButtons> <BaseButtons>
<BaseButton type='submit' color='info' label='Submit' /> <BaseButton type='submit' color='info' label='Submit' />

View File

@ -33,9 +33,13 @@ const UsersTablesPage = () => {
{ label: 'Last Name', title: 'lastName' }, { label: 'Last Name', title: 'lastName' },
{ label: 'Phone Number', title: 'phoneNumber' }, { label: 'Phone Number', title: 'phoneNumber' },
{ label: 'E-Mail', title: 'email' }, { label: 'E-Mail', title: 'email' },
{ label: 'Referralcode', title: 'referralcode' },
{ label: 'Pointsbalance', title: 'pointsbalance', number: 'true' },
{ label: 'App Role', title: 'app_role' }, { label: 'App Role', title: 'app_role' },
{ label: 'Loyaltytier', title: 'loyaltytier' },
{ label: 'Custom Permissions', title: 'custom_permissions' }, { label: 'Custom Permissions', title: 'custom_permissions' },
]); ]);

View File

@ -138,6 +138,118 @@ const UsersView = () => {
</CardBox> </CardBox>
</> </>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Loyaltytier</p>
<p>{users?.loyaltytier?.name ?? 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Pointsbalance</p>
<p>{users?.pointsbalance || 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Referralcode</p>
<p>{users?.referralcode}</p>
</div>
<>
<p className={'block font-bold mb-2'}>Referral Referrer</p>
<CardBox
className='mb-6 border border-gray-300 rounded overflow-hidden'
hasTable
>
<div className='overflow-x-auto'>
<table>
<thead>
<tr>
<th>Referredemail</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{users.referral_referrer &&
Array.isArray(users.referral_referrer) &&
users.referral_referrer.map((item: any) => (
<tr
key={item.id}
onClick={() =>
router.push(
`/referral/referral-view/?id=${item.id}`,
)
}
>
<td data-label='referredemail'>
{item.referredemail}
</td>
<td data-label='status'>{item.status}</td>
</tr>
))}
</tbody>
</table>
</div>
{!users?.referral_referrer?.length && (
<div className={'text-center py-4'}>No data</div>
)}
</CardBox>
</>
<>
<p className={'block font-bold mb-2'}>Redemption User</p>
<CardBox
className='mb-6 border border-gray-300 rounded overflow-hidden'
hasTable
>
<div className='overflow-x-auto'>
<table>
<thead>
<tr>
<th>Pointsused</th>
<th>Redemptiontype</th>
<th>Discountvalue</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{users.redemption_user &&
Array.isArray(users.redemption_user) &&
users.redemption_user.map((item: any) => (
<tr
key={item.id}
onClick={() =>
router.push(
`/redemption/redemption-view/?id=${item.id}`,
)
}
>
<td data-label='pointsused'>{item.pointsused}</td>
<td data-label='redemptiontype'>
{item.redemptiontype}
</td>
<td data-label='discountvalue'>
{item.discountvalue}
</td>
<td data-label='status'>{item.status}</td>
</tr>
))}
</tbody>
</table>
</div>
{!users?.redemption_user?.length && (
<div className={'text-center py-4'}>No data</div>
)}
</CardBox>
</>
<BaseDivider /> <BaseDivider />
<BaseButton <BaseButton

View File

@ -113,7 +113,7 @@ export default function WebSite() {
<FeaturesSection <FeaturesSection
projectName={'FLYARU'} projectName={'FLYARU'}
image={['Travel essentials on a table']} image={['Travel essentials on a table']}
withBg={1} withBg={0}
features={features_points} features={features_points}
mainText={`Discover FlyAru's Exceptional Features`} mainText={`Discover FlyAru's Exceptional Features`}
subTitle={`Experience seamless travel planning with FlyAru's innovative features. Book, explore, and enjoy with ease.`} subTitle={`Experience seamless travel planning with FlyAru's innovative features. Book, explore, and enjoy with ease.`}

View File

@ -0,0 +1,236 @@
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axios from 'axios';
import {
fulfilledNotify,
rejectNotify,
resetNotify,
} from '../../helpers/notifyStateHandler';
interface MainState {
redemption: any;
loading: boolean;
count: number;
refetch: boolean;
rolesWidgets: any[];
notify: {
showNotification: boolean;
textNotification: string;
typeNotification: string;
};
}
const initialState: MainState = {
redemption: [],
loading: false,
count: 0,
refetch: false,
rolesWidgets: [],
notify: {
showNotification: false,
textNotification: '',
typeNotification: 'warn',
},
};
export const fetch = createAsyncThunk('redemption/fetch', async (data: any) => {
const { id, query } = data;
const result = await axios.get(`redemption${query || (id ? `/${id}` : '')}`);
return id
? result.data
: { rows: result.data.rows, count: result.data.count };
});
export const deleteItemsByIds = createAsyncThunk(
'redemption/deleteByIds',
async (data: any, { rejectWithValue }) => {
try {
await axios.post('redemption/deleteByIds', { data });
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const deleteItem = createAsyncThunk(
'redemption/deleteRedemption',
async (id: string, { rejectWithValue }) => {
try {
await axios.delete(`redemption/${id}`);
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const create = createAsyncThunk(
'redemption/createRedemption',
async (data: any, { rejectWithValue }) => {
try {
const result = await axios.post('redemption', { data });
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const uploadCsv = createAsyncThunk(
'redemption/uploadCsv',
async (file: File, { rejectWithValue }) => {
try {
const data = new FormData();
data.append('file', file);
data.append('filename', file.name);
const result = await axios.post('redemption/bulk-import', data, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const update = createAsyncThunk(
'redemption/updateRedemption',
async (payload: any, { rejectWithValue }) => {
try {
const result = await axios.put(`redemption/${payload.id}`, {
id: payload.id,
data: payload.data,
});
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const redemptionSlice = createSlice({
name: 'redemption',
initialState,
reducers: {
setRefetch: (state, action: PayloadAction<boolean>) => {
state.refetch = action.payload;
},
},
extraReducers: (builder) => {
builder.addCase(fetch.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(fetch.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(fetch.fulfilled, (state, action) => {
if (action.payload.rows && action.payload.count >= 0) {
state.redemption = action.payload.rows;
state.count = action.payload.count;
} else {
state.redemption = action.payload;
}
state.loading = false;
});
builder.addCase(deleteItemsByIds.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(deleteItemsByIds.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, 'Redemption has been deleted');
});
builder.addCase(deleteItemsByIds.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(deleteItem.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(deleteItem.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, `${'Redemption'.slice(0, -1)} has been deleted`);
});
builder.addCase(deleteItem.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(create.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(create.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(create.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, `${'Redemption'.slice(0, -1)} has been created`);
});
builder.addCase(update.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(update.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, `${'Redemption'.slice(0, -1)} has been updated`);
});
builder.addCase(update.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(uploadCsv.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(uploadCsv.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, 'Redemption has been uploaded');
});
builder.addCase(uploadCsv.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
},
});
// Action creators are generated for each case reducer function
export const { setRefetch } = redemptionSlice.actions;
export default redemptionSlice.reducer;

View File

@ -0,0 +1,236 @@
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axios from 'axios';
import {
fulfilledNotify,
rejectNotify,
resetNotify,
} from '../../helpers/notifyStateHandler';
interface MainState {
referral: any;
loading: boolean;
count: number;
refetch: boolean;
rolesWidgets: any[];
notify: {
showNotification: boolean;
textNotification: string;
typeNotification: string;
};
}
const initialState: MainState = {
referral: [],
loading: false,
count: 0,
refetch: false,
rolesWidgets: [],
notify: {
showNotification: false,
textNotification: '',
typeNotification: 'warn',
},
};
export const fetch = createAsyncThunk('referral/fetch', async (data: any) => {
const { id, query } = data;
const result = await axios.get(`referral${query || (id ? `/${id}` : '')}`);
return id
? result.data
: { rows: result.data.rows, count: result.data.count };
});
export const deleteItemsByIds = createAsyncThunk(
'referral/deleteByIds',
async (data: any, { rejectWithValue }) => {
try {
await axios.post('referral/deleteByIds', { data });
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const deleteItem = createAsyncThunk(
'referral/deleteReferral',
async (id: string, { rejectWithValue }) => {
try {
await axios.delete(`referral/${id}`);
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const create = createAsyncThunk(
'referral/createReferral',
async (data: any, { rejectWithValue }) => {
try {
const result = await axios.post('referral', { data });
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const uploadCsv = createAsyncThunk(
'referral/uploadCsv',
async (file: File, { rejectWithValue }) => {
try {
const data = new FormData();
data.append('file', file);
data.append('filename', file.name);
const result = await axios.post('referral/bulk-import', data, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const update = createAsyncThunk(
'referral/updateReferral',
async (payload: any, { rejectWithValue }) => {
try {
const result = await axios.put(`referral/${payload.id}`, {
id: payload.id,
data: payload.data,
});
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const referralSlice = createSlice({
name: 'referral',
initialState,
reducers: {
setRefetch: (state, action: PayloadAction<boolean>) => {
state.refetch = action.payload;
},
},
extraReducers: (builder) => {
builder.addCase(fetch.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(fetch.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(fetch.fulfilled, (state, action) => {
if (action.payload.rows && action.payload.count >= 0) {
state.referral = action.payload.rows;
state.count = action.payload.count;
} else {
state.referral = action.payload;
}
state.loading = false;
});
builder.addCase(deleteItemsByIds.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(deleteItemsByIds.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, 'Referral has been deleted');
});
builder.addCase(deleteItemsByIds.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(deleteItem.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(deleteItem.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, `${'Referral'.slice(0, -1)} has been deleted`);
});
builder.addCase(deleteItem.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(create.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(create.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(create.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, `${'Referral'.slice(0, -1)} has been created`);
});
builder.addCase(update.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(update.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, `${'Referral'.slice(0, -1)} has been updated`);
});
builder.addCase(update.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(uploadCsv.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(uploadCsv.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, 'Referral has been uploaded');
});
builder.addCase(uploadCsv.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
},
});
// Action creators are generated for each case reducer function
export const { setRefetch } = referralSlice.actions;
export default referralSlice.reducer;

View File

@ -13,6 +13,8 @@ import vouchersSlice from './vouchers/vouchersSlice';
import rolesSlice from './roles/rolesSlice'; import rolesSlice from './roles/rolesSlice';
import permissionsSlice from './permissions/permissionsSlice'; import permissionsSlice from './permissions/permissionsSlice';
import loyaltytierSlice from './loyaltytier/loyaltytierSlice'; import loyaltytierSlice from './loyaltytier/loyaltytierSlice';
import referralSlice from './referral/referralSlice';
import redemptionSlice from './redemption/redemptionSlice';
export const store = configureStore({ export const store = configureStore({
reducer: { reducer: {
@ -30,6 +32,8 @@ export const store = configureStore({
roles: rolesSlice, roles: rolesSlice,
permissions: permissionsSlice, permissions: permissionsSlice,
loyaltytier: loyaltytierSlice, loyaltytier: loyaltytierSlice,
referral: referralSlice,
redemption: redemptionSlice,
}, },
}); });