From 220628574d09204eb90a803b6e6aa2ddd41f0a8f Mon Sep 17 00:00:00 2001 From: Flatlogic Bot Date: Tue, 1 Apr 2025 13:06:27 +0000 Subject: [PATCH] like's entity --- .gitignore | 5 + backend/src/db/api/likes.js | 344 ++++++++++++ backend/src/db/api/organizations.js | 4 + backend/src/db/api/users.js | 4 + backend/src/db/migrations/1743512382417.js | 90 ++++ backend/src/db/migrations/1743512407704.js | 47 ++ backend/src/db/migrations/1743512703885.js | 52 ++ backend/src/db/models/likes.js | 65 +++ backend/src/db/models/organizations.js | 8 + backend/src/db/models/users.js | 8 + .../db/seeders/20200430130760-user-roles.js | 51 ++ .../db/seeders/20231127130745-sample-data.js | 510 ++++-------------- backend/src/db/seeders/20250401125942.js | 87 +++ backend/src/index.js | 8 + backend/src/routes/likes.js | 447 +++++++++++++++ backend/src/services/likes.js | 114 ++++ backend/src/services/search.js | 2 + frontend/json/runtimeError.json | 1 + frontend/src/components/Likes/CardLikes.tsx | 118 ++++ frontend/src/components/Likes/ListLikes.tsx | 99 ++++ frontend/src/components/Likes/TableLikes.tsx | 484 +++++++++++++++++ .../components/Likes/configureLikesCols.tsx | 93 ++++ .../components/WebPageComponents/Header.tsx | 2 +- frontend/src/menuAside.ts | 8 + frontend/src/pages/dashboard.tsx | 35 ++ frontend/src/pages/index.tsx | 2 +- frontend/src/pages/likes/[likesId].tsx | 154 ++++++ frontend/src/pages/likes/likes-edit.tsx | 152 ++++++ frontend/src/pages/likes/likes-list.tsx | 164 ++++++ frontend/src/pages/likes/likes-new.tsx | 122 +++++ frontend/src/pages/likes/likes-table.tsx | 163 ++++++ frontend/src/pages/likes/likes-view.tsx | 97 ++++ .../organizations/organizations-view.tsx | 35 ++ frontend/src/pages/users/users-view.tsx | 35 ++ frontend/src/stores/likes/likesSlice.ts | 236 ++++++++ frontend/src/stores/store.ts | 2 + 36 files changed, 3427 insertions(+), 421 deletions(-) create mode 100644 backend/src/db/api/likes.js create mode 100644 backend/src/db/migrations/1743512382417.js create mode 100644 backend/src/db/migrations/1743512407704.js create mode 100644 backend/src/db/migrations/1743512703885.js create mode 100644 backend/src/db/models/likes.js create mode 100644 backend/src/db/seeders/20250401125942.js create mode 100644 backend/src/routes/likes.js create mode 100644 backend/src/services/likes.js create mode 100644 frontend/json/runtimeError.json create mode 100644 frontend/src/components/Likes/CardLikes.tsx create mode 100644 frontend/src/components/Likes/ListLikes.tsx create mode 100644 frontend/src/components/Likes/TableLikes.tsx create mode 100644 frontend/src/components/Likes/configureLikesCols.tsx create mode 100644 frontend/src/pages/likes/[likesId].tsx create mode 100644 frontend/src/pages/likes/likes-edit.tsx create mode 100644 frontend/src/pages/likes/likes-list.tsx create mode 100644 frontend/src/pages/likes/likes-new.tsx create mode 100644 frontend/src/pages/likes/likes-table.tsx create mode 100644 frontend/src/pages/likes/likes-view.tsx create mode 100644 frontend/src/stores/likes/likesSlice.ts diff --git a/.gitignore b/.gitignore index e427ff3..d0eb167 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,8 @@ node_modules/ */node_modules/ */build/ + +**/node_modules/ +**/build/ +.DS_Store +.env \ No newline at end of file diff --git a/backend/src/db/api/likes.js b/backend/src/db/api/likes.js new file mode 100644 index 0000000..6b04cff --- /dev/null +++ b/backend/src/db/api/likes.js @@ -0,0 +1,344 @@ +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 LikesDBApi { + static async create(data, options) { + const currentUser = (options && options.currentUser) || { id: null }; + const transaction = (options && options.transaction) || undefined; + + const likes = await db.likes.create( + { + id: data.id || undefined, + + amount: data.amount || null, + importHash: data.importHash || null, + createdById: currentUser.id, + updatedById: currentUser.id, + }, + { transaction }, + ); + + await likes.setOrganizations(data.organizations || null, { + transaction, + }); + + await likes.setUser(data.user || null, { + transaction, + }); + + return likes; + } + + 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 likesData = data.map((item, index) => ({ + id: item.id || undefined, + + amount: item.amount || null, + importHash: item.importHash || null, + createdById: currentUser.id, + updatedById: currentUser.id, + createdAt: new Date(Date.now() + index * 1000), + })); + + // Bulk create items + const likes = await db.likes.bulkCreate(likesData, { transaction }); + + // For each item created, replace relation files + + return likes; + } + + static async update(id, data, options) { + const currentUser = (options && options.currentUser) || { id: null }; + const transaction = (options && options.transaction) || undefined; + const globalAccess = currentUser.app_role?.globalAccess; + + const likes = await db.likes.findByPk(id, {}, { transaction }); + + const updatePayload = {}; + + if (data.amount !== undefined) updatePayload.amount = data.amount; + + updatePayload.updatedById = currentUser.id; + + await likes.update(updatePayload, { transaction }); + + if (data.organizations !== undefined) { + await likes.setOrganizations( + data.organizations, + + { transaction }, + ); + } + + if (data.user !== undefined) { + await likes.setUser( + data.user, + + { transaction }, + ); + } + + return likes; + } + + static async deleteByIds(ids, options) { + const currentUser = (options && options.currentUser) || { id: null }; + const transaction = (options && options.transaction) || undefined; + + const likes = await db.likes.findAll({ + where: { + id: { + [Op.in]: ids, + }, + }, + transaction, + }); + + await db.sequelize.transaction(async (transaction) => { + for (const record of likes) { + await record.update({ deletedBy: currentUser.id }, { transaction }); + } + for (const record of likes) { + await record.destroy({ transaction }); + } + }); + + return likes; + } + + static async remove(id, options) { + const currentUser = (options && options.currentUser) || { id: null }; + const transaction = (options && options.transaction) || undefined; + + const likes = await db.likes.findByPk(id, options); + + await likes.update( + { + deletedBy: currentUser.id, + }, + { + transaction, + }, + ); + + await likes.destroy({ + transaction, + }); + + return likes; + } + + static async findBy(where, options) { + const transaction = (options && options.transaction) || undefined; + + const likes = await db.likes.findOne({ where }, { transaction }); + + if (!likes) { + return likes; + } + + const output = likes.get({ plain: true }); + + output.organizations = await likes.getOrganizations({ + transaction, + }); + + output.user = await likes.getUser({ + transaction, + }); + + return output; + } + + static async findAll(filter, globalAccess, options) { + const limit = filter.limit || 0; + let offset = 0; + let where = {}; + const currentPage = +filter.page; + + const user = (options && options.currentUser) || null; + const userOrganizations = (user && user.organizations?.id) || null; + + if (userOrganizations) { + if (options?.currentUser?.organizationsId) { + where.organizationsId = options.currentUser.organizationsId; + } + } + + offset = currentPage * limit; + + const orderBy = null; + + const transaction = (options && options.transaction) || undefined; + + let include = [ + { + model: db.organizations, + as: 'organizations', + }, + + { + 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}%` })), + }, + }, + ], + } + : {}, + }, + ]; + + if (filter) { + if (filter.id) { + where = { + ...where, + ['id']: Utils.uuid(filter.id), + }; + } + + if (filter.amount) { + where = { + ...where, + [Op.and]: Utils.ilike('likes', 'amount', filter.amount), + }; + } + + if (filter.active !== undefined) { + where = { + ...where, + active: filter.active === true || filter.active === 'true', + }; + } + + if (filter.organizations) { + const listItems = filter.organizations.split('|').map((item) => { + return Utils.uuid(item); + }); + + where = { + ...where, + organizationsId: { [Op.or]: listItems }, + }; + } + + 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, + }, + }; + } + } + } + + if (globalAccess) { + delete where.organizationsId; + } + + 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.likes.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, + globalAccess, + organizationId, + ) { + let where = {}; + + if (!globalAccess && organizationId) { + where.organizationId = organizationId; + } + + if (query) { + where = { + [Op.or]: [ + { ['id']: Utils.uuid(query) }, + Utils.ilike('likes', 'amount', query), + ], + }; + } + + const records = await db.likes.findAll({ + attributes: ['id', 'amount'], + where, + limit: limit ? Number(limit) : undefined, + offset: offset ? Number(offset) : undefined, + orderBy: [['amount', 'ASC']], + }); + + return records.map((record) => ({ + id: record.id, + label: record.amount, + })); + } +}; diff --git a/backend/src/db/api/organizations.js b/backend/src/db/api/organizations.js index 53df73a..7bf245b 100644 --- a/backend/src/db/api/organizations.js +++ b/backend/src/db/api/organizations.js @@ -169,6 +169,10 @@ module.exports = class OrganizationsDBApi { transaction, }); + output.likes_organizations = await organizations.getLikes_organizations({ + transaction, + }); + return output; } diff --git a/backend/src/db/api/users.js b/backend/src/db/api/users.js index e0193b0..aa802af 100644 --- a/backend/src/db/api/users.js +++ b/backend/src/db/api/users.js @@ -287,6 +287,10 @@ module.exports = class UsersDBApi { transaction, }); + output.likes_user = await users.getLikes_user({ + transaction, + }); + output.avatar = await users.getAvatar({ transaction, }); diff --git a/backend/src/db/migrations/1743512382417.js b/backend/src/db/migrations/1743512382417.js new file mode 100644 index 0000000..78d4914 --- /dev/null +++ b/backend/src/db/migrations/1743512382417.js @@ -0,0 +1,90 @@ +module.exports = { + /** + * @param {QueryInterface} queryInterface + * @param {Sequelize} Sequelize + * @returns {Promise} + */ + async up(queryInterface, Sequelize) { + /** + * @type {Transaction} + */ + const transaction = await queryInterface.sequelize.transaction(); + try { + await queryInterface.createTable( + 'likes', + { + 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 queryInterface.addColumn( + 'likes', + 'organizationsId', + { + type: Sequelize.DataTypes.UUID, + + references: { + model: 'organizations', + key: 'id', + }, + }, + { transaction }, + ); + + await transaction.commit(); + } catch (err) { + await transaction.rollback(); + throw err; + } + }, + /** + * @param {QueryInterface} queryInterface + * @param {Sequelize} Sequelize + * @returns {Promise} + */ + async down(queryInterface, Sequelize) { + /** + * @type {Transaction} + */ + const transaction = await queryInterface.sequelize.transaction(); + try { + await queryInterface.removeColumn('likes', 'organizationsId', { + transaction, + }); + + await queryInterface.dropTable('likes', { transaction }); + + await transaction.commit(); + } catch (err) { + await transaction.rollback(); + throw err; + } + }, +}; diff --git a/backend/src/db/migrations/1743512407704.js b/backend/src/db/migrations/1743512407704.js new file mode 100644 index 0000000..628c42f --- /dev/null +++ b/backend/src/db/migrations/1743512407704.js @@ -0,0 +1,47 @@ +module.exports = { + /** + * @param {QueryInterface} queryInterface + * @param {Sequelize} Sequelize + * @returns {Promise} + */ + async up(queryInterface, Sequelize) { + /** + * @type {Transaction} + */ + const transaction = await queryInterface.sequelize.transaction(); + try { + await queryInterface.addColumn( + 'likes', + 'amount', + { + type: Sequelize.DataTypes.TEXT, + }, + { transaction }, + ); + + await transaction.commit(); + } catch (err) { + await transaction.rollback(); + throw err; + } + }, + /** + * @param {QueryInterface} queryInterface + * @param {Sequelize} Sequelize + * @returns {Promise} + */ + async down(queryInterface, Sequelize) { + /** + * @type {Transaction} + */ + const transaction = await queryInterface.sequelize.transaction(); + try { + await queryInterface.removeColumn('likes', 'amount', { transaction }); + + await transaction.commit(); + } catch (err) { + await transaction.rollback(); + throw err; + } + }, +}; diff --git a/backend/src/db/migrations/1743512703885.js b/backend/src/db/migrations/1743512703885.js new file mode 100644 index 0000000..1741f3b --- /dev/null +++ b/backend/src/db/migrations/1743512703885.js @@ -0,0 +1,52 @@ +module.exports = { + /** + * @param {QueryInterface} queryInterface + * @param {Sequelize} Sequelize + * @returns {Promise} + */ + async up(queryInterface, Sequelize) { + /** + * @type {Transaction} + */ + const transaction = await queryInterface.sequelize.transaction(); + try { + await queryInterface.addColumn( + 'likes', + '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} + */ + async down(queryInterface, Sequelize) { + /** + * @type {Transaction} + */ + const transaction = await queryInterface.sequelize.transaction(); + try { + await queryInterface.removeColumn('likes', 'userId', { transaction }); + + await transaction.commit(); + } catch (err) { + await transaction.rollback(); + throw err; + } + }, +}; diff --git a/backend/src/db/models/likes.js b/backend/src/db/models/likes.js new file mode 100644 index 0000000..59e7ab6 --- /dev/null +++ b/backend/src/db/models/likes.js @@ -0,0 +1,65 @@ +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 likes = sequelize.define( + 'likes', + { + id: { + type: DataTypes.UUID, + defaultValue: DataTypes.UUIDV4, + primaryKey: true, + }, + + amount: { + type: DataTypes.TEXT, + }, + + importHash: { + type: DataTypes.STRING(255), + allowNull: true, + unique: true, + }, + }, + { + timestamps: true, + paranoid: true, + freezeTableName: true, + }, + ); + + likes.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.likes.belongsTo(db.organizations, { + as: 'organizations', + foreignKey: { + name: 'organizationsId', + }, + constraints: false, + }); + + db.likes.belongsTo(db.users, { + as: 'user', + foreignKey: { + name: 'userId', + }, + constraints: false, + }); + + db.likes.belongsTo(db.users, { + as: 'createdBy', + }); + + db.likes.belongsTo(db.users, { + as: 'updatedBy', + }); + }; + + return likes; +}; diff --git a/backend/src/db/models/organizations.js b/backend/src/db/models/organizations.js index 7bff04d..f290dba 100644 --- a/backend/src/db/models/organizations.js +++ b/backend/src/db/models/organizations.js @@ -90,6 +90,14 @@ module.exports = function (sequelize, DataTypes) { constraints: false, }); + db.organizations.hasMany(db.likes, { + as: 'likes_organizations', + foreignKey: { + name: 'organizationsId', + }, + constraints: false, + }); + //end loop db.organizations.belongsTo(db.users, { diff --git a/backend/src/db/models/users.js b/backend/src/db/models/users.js index 18b5d14..d83a112 100644 --- a/backend/src/db/models/users.js +++ b/backend/src/db/models/users.js @@ -118,6 +118,14 @@ module.exports = function (sequelize, DataTypes) { constraints: false, }); + db.users.hasMany(db.likes, { + as: 'likes_user', + foreignKey: { + name: 'userId', + }, + constraints: false, + }); + //end loop db.users.belongsTo(db.roles, { diff --git a/backend/src/db/seeders/20200430130760-user-roles.js b/backend/src/db/seeders/20200430130760-user-roles.js index 9fe5c63..671686d 100644 --- a/backend/src/db/seeders/20200430130760-user-roles.js +++ b/backend/src/db/seeders/20200430130760-user-roles.js @@ -119,6 +119,7 @@ module.exports = { 'roles', 'permissions', 'organizations', + 'likes', , ]; await queryInterface.bulkInsert( @@ -1069,6 +1070,31 @@ primary key ("roles_permissionsId", "permissionId") permissionId: getId('DELETE_STUDENTS'), }, + { + createdAt, + updatedAt, + roles_permissionsId: getId('Administrator'), + permissionId: getId('CREATE_LIKES'), + }, + { + createdAt, + updatedAt, + roles_permissionsId: getId('Administrator'), + permissionId: getId('READ_LIKES'), + }, + { + createdAt, + updatedAt, + roles_permissionsId: getId('Administrator'), + permissionId: getId('UPDATE_LIKES'), + }, + { + createdAt, + updatedAt, + roles_permissionsId: getId('Administrator'), + permissionId: getId('DELETE_LIKES'), + }, + { createdAt, updatedAt, @@ -1319,6 +1345,31 @@ primary key ("roles_permissionsId", "permissionId") permissionId: getId('DELETE_ORGANIZATIONS'), }, + { + createdAt, + updatedAt, + roles_permissionsId: getId('SuperAdmin'), + permissionId: getId('CREATE_LIKES'), + }, + { + createdAt, + updatedAt, + roles_permissionsId: getId('SuperAdmin'), + permissionId: getId('READ_LIKES'), + }, + { + createdAt, + updatedAt, + roles_permissionsId: getId('SuperAdmin'), + permissionId: getId('UPDATE_LIKES'), + }, + { + createdAt, + updatedAt, + roles_permissionsId: getId('SuperAdmin'), + permissionId: getId('DELETE_LIKES'), + }, + { createdAt, updatedAt, diff --git a/backend/src/db/seeders/20231127130745-sample-data.js b/backend/src/db/seeders/20231127130745-sample-data.js index f80085a..bbf640a 100644 --- a/backend/src/db/seeders/20231127130745-sample-data.js +++ b/backend/src/db/seeders/20231127130745-sample-data.js @@ -15,6 +15,8 @@ const Students = db.students; const Organizations = db.organizations; +const Likes = db.likes; + const AnalyticsData = [ { // type code here for "relation_one" field @@ -51,30 +53,6 @@ const AnalyticsData = [ // type code here for "relation_one" field }, - - { - // type code here for "relation_one" field - - engagement_rate: 80, - - completion_rate: 85, - - instructor_performance: 85, - - // type code here for "relation_one" field - }, - - { - // type code here for "relation_one" field - - engagement_rate: 90, - - completion_rate: 90, - - instructor_performance: 95, - - // type code here for "relation_one" field - }, ]; const CoursesData = [ @@ -126,38 +104,6 @@ const CoursesData = [ // type code here for "relation_one" field }, - - { - title: 'Graphic Design Basics', - - description: 'An introduction to graphic design principles and tools.', - - // type code here for "relation_many" field - - // type code here for "relation_many" field - - // type code here for "files" field - - // type code here for "relation_many" field - - // type code here for "relation_one" field - }, - - { - title: 'Data Science Essentials', - - description: 'Learn data science techniques and tools for data analysis.', - - // type code here for "relation_many" field - - // type code here for "relation_many" field - - // type code here for "files" field - - // type code here for "relation_many" field - - // type code here for "relation_one" field - }, ]; const DiscussionBoardsData = [ @@ -190,26 +136,6 @@ const DiscussionBoardsData = [ // type code here for "relation_one" field }, - - { - // type code here for "relation_one" field - - topic: 'Design Tips', - - // type code here for "relation_many" field - - // type code here for "relation_one" field - }, - - { - // type code here for "relation_one" field - - topic: 'Data Science Q&A', - - // type code here for "relation_many" field - - // type code here for "relation_one" field - }, ]; const EnrollmentsData = [ @@ -223,16 +149,6 @@ const EnrollmentsData = [ // type code here for "relation_one" field }, - { - // type code here for "relation_one" field - - // type code here for "relation_one" field - - payment_status: 'pending', - - // type code here for "relation_one" field - }, - { // type code here for "relation_one" field @@ -252,16 +168,6 @@ const EnrollmentsData = [ // type code here for "relation_one" field }, - - { - // type code here for "relation_one" field - - // type code here for "relation_one" field - - payment_status: 'overdue', - - // type code here for "relation_one" field - }, ]; const InstructorsData = [ @@ -294,26 +200,6 @@ const InstructorsData = [ // type code here for "relation_one" field }, - - { - // type code here for "relation_one" field - - // type code here for "relation_many" field - - qualifications: 'BA in Graphic Design', - - // type code here for "relation_one" field - }, - - { - // type code here for "relation_one" field - - // type code here for "relation_many" field - - qualifications: 'MSc in Data Science', - - // type code here for "relation_one" field - }, ]; const StudentsData = [ @@ -352,51 +238,45 @@ const StudentsData = [ // type code here for "relation_one" field }, - - { - // type code here for "relation_one" field - - // type code here for "relation_many" field - - // type code here for "relation_many" field - - progress: 90, - - // type code here for "relation_one" field - }, - - { - // type code here for "relation_one" field - - // type code here for "relation_many" field - - // type code here for "relation_many" field - - progress: 50, - - // type code here for "relation_one" field - }, ]; const OrganizationsData = [ { - name: 'Antoine Laurent Lavoisier', + name: 'Marcello Malpighi', }, { - name: 'Konrad Lorenz', + name: 'Rudolf Virchow', }, { - name: 'Antoine Laurent Lavoisier', + name: 'Francis Crick', + }, +]; + +const LikesData = [ + { + // type code here for "relation_one" field + + amount: 'Albert Einstein', + + // type code here for "relation_one" field }, { - name: 'Hans Bethe', + // type code here for "relation_one" field + + amount: 'Max Delbruck', + + // type code here for "relation_one" field }, { - name: 'Hans Selye', + // type code here for "relation_one" field + + amount: 'Edward Teller', + + // type code here for "relation_one" field }, ]; @@ -435,28 +315,6 @@ async function associateUserWithOrganization() { if (User2?.setOrganization) { await User2.setOrganization(relatedOrganization2); } - - const relatedOrganization3 = await Organizations.findOne({ - offset: Math.floor(Math.random() * (await Organizations.count())), - }); - const User3 = await Users.findOne({ - order: [['id', 'ASC']], - offset: 3, - }); - if (User3?.setOrganization) { - await User3.setOrganization(relatedOrganization3); - } - - const relatedOrganization4 = await Organizations.findOne({ - offset: Math.floor(Math.random() * (await Organizations.count())), - }); - const User4 = await Users.findOne({ - order: [['id', 'ASC']], - offset: 4, - }); - if (User4?.setOrganization) { - await User4.setOrganization(relatedOrganization4); - } } async function associateAnalyticWithCourse() { @@ -492,28 +350,6 @@ async function associateAnalyticWithCourse() { if (Analytic2?.setCourse) { await Analytic2.setCourse(relatedCourse2); } - - const relatedCourse3 = await Courses.findOne({ - offset: Math.floor(Math.random() * (await Courses.count())), - }); - const Analytic3 = await Analytics.findOne({ - order: [['id', 'ASC']], - offset: 3, - }); - if (Analytic3?.setCourse) { - await Analytic3.setCourse(relatedCourse3); - } - - const relatedCourse4 = await Courses.findOne({ - offset: Math.floor(Math.random() * (await Courses.count())), - }); - const Analytic4 = await Analytics.findOne({ - order: [['id', 'ASC']], - offset: 4, - }); - if (Analytic4?.setCourse) { - await Analytic4.setCourse(relatedCourse4); - } } async function associateAnalyticWithOrganization() { @@ -549,28 +385,6 @@ async function associateAnalyticWithOrganization() { if (Analytic2?.setOrganization) { await Analytic2.setOrganization(relatedOrganization2); } - - const relatedOrganization3 = await Organizations.findOne({ - offset: Math.floor(Math.random() * (await Organizations.count())), - }); - const Analytic3 = await Analytics.findOne({ - order: [['id', 'ASC']], - offset: 3, - }); - if (Analytic3?.setOrganization) { - await Analytic3.setOrganization(relatedOrganization3); - } - - const relatedOrganization4 = await Organizations.findOne({ - offset: Math.floor(Math.random() * (await Organizations.count())), - }); - const Analytic4 = await Analytics.findOne({ - order: [['id', 'ASC']], - offset: 4, - }); - if (Analytic4?.setOrganization) { - await Analytic4.setOrganization(relatedOrganization4); - } } // Similar logic for "relation_many" @@ -612,28 +426,6 @@ async function associateCourseWithOrganization() { if (Course2?.setOrganization) { await Course2.setOrganization(relatedOrganization2); } - - const relatedOrganization3 = await Organizations.findOne({ - offset: Math.floor(Math.random() * (await Organizations.count())), - }); - const Course3 = await Courses.findOne({ - order: [['id', 'ASC']], - offset: 3, - }); - if (Course3?.setOrganization) { - await Course3.setOrganization(relatedOrganization3); - } - - const relatedOrganization4 = await Organizations.findOne({ - offset: Math.floor(Math.random() * (await Organizations.count())), - }); - const Course4 = await Courses.findOne({ - order: [['id', 'ASC']], - offset: 4, - }); - if (Course4?.setOrganization) { - await Course4.setOrganization(relatedOrganization4); - } } async function associateDiscussionBoardWithCourse() { @@ -669,28 +461,6 @@ async function associateDiscussionBoardWithCourse() { if (DiscussionBoard2?.setCourse) { await DiscussionBoard2.setCourse(relatedCourse2); } - - const relatedCourse3 = await Courses.findOne({ - offset: Math.floor(Math.random() * (await Courses.count())), - }); - const DiscussionBoard3 = await DiscussionBoards.findOne({ - order: [['id', 'ASC']], - offset: 3, - }); - if (DiscussionBoard3?.setCourse) { - await DiscussionBoard3.setCourse(relatedCourse3); - } - - const relatedCourse4 = await Courses.findOne({ - offset: Math.floor(Math.random() * (await Courses.count())), - }); - const DiscussionBoard4 = await DiscussionBoards.findOne({ - order: [['id', 'ASC']], - offset: 4, - }); - if (DiscussionBoard4?.setCourse) { - await DiscussionBoard4.setCourse(relatedCourse4); - } } // Similar logic for "relation_many" @@ -728,28 +498,6 @@ async function associateDiscussionBoardWithOrganization() { if (DiscussionBoard2?.setOrganization) { await DiscussionBoard2.setOrganization(relatedOrganization2); } - - const relatedOrganization3 = await Organizations.findOne({ - offset: Math.floor(Math.random() * (await Organizations.count())), - }); - const DiscussionBoard3 = await DiscussionBoards.findOne({ - order: [['id', 'ASC']], - offset: 3, - }); - if (DiscussionBoard3?.setOrganization) { - await DiscussionBoard3.setOrganization(relatedOrganization3); - } - - const relatedOrganization4 = await Organizations.findOne({ - offset: Math.floor(Math.random() * (await Organizations.count())), - }); - const DiscussionBoard4 = await DiscussionBoards.findOne({ - order: [['id', 'ASC']], - offset: 4, - }); - if (DiscussionBoard4?.setOrganization) { - await DiscussionBoard4.setOrganization(relatedOrganization4); - } } async function associateEnrollmentWithStudent() { @@ -785,28 +533,6 @@ async function associateEnrollmentWithStudent() { if (Enrollment2?.setStudent) { await Enrollment2.setStudent(relatedStudent2); } - - const relatedStudent3 = await Students.findOne({ - offset: Math.floor(Math.random() * (await Students.count())), - }); - const Enrollment3 = await Enrollments.findOne({ - order: [['id', 'ASC']], - offset: 3, - }); - if (Enrollment3?.setStudent) { - await Enrollment3.setStudent(relatedStudent3); - } - - const relatedStudent4 = await Students.findOne({ - offset: Math.floor(Math.random() * (await Students.count())), - }); - const Enrollment4 = await Enrollments.findOne({ - order: [['id', 'ASC']], - offset: 4, - }); - if (Enrollment4?.setStudent) { - await Enrollment4.setStudent(relatedStudent4); - } } async function associateEnrollmentWithCourse() { @@ -842,28 +568,6 @@ async function associateEnrollmentWithCourse() { if (Enrollment2?.setCourse) { await Enrollment2.setCourse(relatedCourse2); } - - const relatedCourse3 = await Courses.findOne({ - offset: Math.floor(Math.random() * (await Courses.count())), - }); - const Enrollment3 = await Enrollments.findOne({ - order: [['id', 'ASC']], - offset: 3, - }); - if (Enrollment3?.setCourse) { - await Enrollment3.setCourse(relatedCourse3); - } - - const relatedCourse4 = await Courses.findOne({ - offset: Math.floor(Math.random() * (await Courses.count())), - }); - const Enrollment4 = await Enrollments.findOne({ - order: [['id', 'ASC']], - offset: 4, - }); - if (Enrollment4?.setCourse) { - await Enrollment4.setCourse(relatedCourse4); - } } async function associateEnrollmentWithOrganization() { @@ -899,28 +603,6 @@ async function associateEnrollmentWithOrganization() { if (Enrollment2?.setOrganization) { await Enrollment2.setOrganization(relatedOrganization2); } - - const relatedOrganization3 = await Organizations.findOne({ - offset: Math.floor(Math.random() * (await Organizations.count())), - }); - const Enrollment3 = await Enrollments.findOne({ - order: [['id', 'ASC']], - offset: 3, - }); - if (Enrollment3?.setOrganization) { - await Enrollment3.setOrganization(relatedOrganization3); - } - - const relatedOrganization4 = await Organizations.findOne({ - offset: Math.floor(Math.random() * (await Organizations.count())), - }); - const Enrollment4 = await Enrollments.findOne({ - order: [['id', 'ASC']], - offset: 4, - }); - if (Enrollment4?.setOrganization) { - await Enrollment4.setOrganization(relatedOrganization4); - } } async function associateInstructorWithUser() { @@ -956,28 +638,6 @@ async function associateInstructorWithUser() { if (Instructor2?.setUser) { await Instructor2.setUser(relatedUser2); } - - const relatedUser3 = await Users.findOne({ - offset: Math.floor(Math.random() * (await Users.count())), - }); - const Instructor3 = await Instructors.findOne({ - order: [['id', 'ASC']], - offset: 3, - }); - if (Instructor3?.setUser) { - await Instructor3.setUser(relatedUser3); - } - - const relatedUser4 = await Users.findOne({ - offset: Math.floor(Math.random() * (await Users.count())), - }); - const Instructor4 = await Instructors.findOne({ - order: [['id', 'ASC']], - offset: 4, - }); - if (Instructor4?.setUser) { - await Instructor4.setUser(relatedUser4); - } } // Similar logic for "relation_many" @@ -1015,28 +675,6 @@ async function associateInstructorWithOrganization() { if (Instructor2?.setOrganization) { await Instructor2.setOrganization(relatedOrganization2); } - - const relatedOrganization3 = await Organizations.findOne({ - offset: Math.floor(Math.random() * (await Organizations.count())), - }); - const Instructor3 = await Instructors.findOne({ - order: [['id', 'ASC']], - offset: 3, - }); - if (Instructor3?.setOrganization) { - await Instructor3.setOrganization(relatedOrganization3); - } - - const relatedOrganization4 = await Organizations.findOne({ - offset: Math.floor(Math.random() * (await Organizations.count())), - }); - const Instructor4 = await Instructors.findOne({ - order: [['id', 'ASC']], - offset: 4, - }); - if (Instructor4?.setOrganization) { - await Instructor4.setOrganization(relatedOrganization4); - } } async function associateStudentWithUser() { @@ -1072,28 +710,6 @@ async function associateStudentWithUser() { if (Student2?.setUser) { await Student2.setUser(relatedUser2); } - - const relatedUser3 = await Users.findOne({ - offset: Math.floor(Math.random() * (await Users.count())), - }); - const Student3 = await Students.findOne({ - order: [['id', 'ASC']], - offset: 3, - }); - if (Student3?.setUser) { - await Student3.setUser(relatedUser3); - } - - const relatedUser4 = await Users.findOne({ - offset: Math.floor(Math.random() * (await Users.count())), - }); - const Student4 = await Students.findOne({ - order: [['id', 'ASC']], - offset: 4, - }); - if (Student4?.setUser) { - await Student4.setUser(relatedUser4); - } } // Similar logic for "relation_many" @@ -1133,27 +749,75 @@ async function associateStudentWithOrganization() { if (Student2?.setOrganization) { await Student2.setOrganization(relatedOrganization2); } +} - const relatedOrganization3 = await Organizations.findOne({ +async function associateLikeWithOrganization() { + const relatedOrganization0 = await Organizations.findOne({ offset: Math.floor(Math.random() * (await Organizations.count())), }); - const Student3 = await Students.findOne({ + const Like0 = await Likes.findOne({ order: [['id', 'ASC']], - offset: 3, + offset: 0, }); - if (Student3?.setOrganization) { - await Student3.setOrganization(relatedOrganization3); + if (Like0?.setOrganization) { + await Like0.setOrganization(relatedOrganization0); } - const relatedOrganization4 = await Organizations.findOne({ + const relatedOrganization1 = await Organizations.findOne({ offset: Math.floor(Math.random() * (await Organizations.count())), }); - const Student4 = await Students.findOne({ + const Like1 = await Likes.findOne({ order: [['id', 'ASC']], - offset: 4, + offset: 1, }); - if (Student4?.setOrganization) { - await Student4.setOrganization(relatedOrganization4); + if (Like1?.setOrganization) { + await Like1.setOrganization(relatedOrganization1); + } + + const relatedOrganization2 = await Organizations.findOne({ + offset: Math.floor(Math.random() * (await Organizations.count())), + }); + const Like2 = await Likes.findOne({ + order: [['id', 'ASC']], + offset: 2, + }); + if (Like2?.setOrganization) { + await Like2.setOrganization(relatedOrganization2); + } +} + +async function associateLikeWithUser() { + const relatedUser0 = await Users.findOne({ + offset: Math.floor(Math.random() * (await Users.count())), + }); + const Like0 = await Likes.findOne({ + order: [['id', 'ASC']], + offset: 0, + }); + if (Like0?.setUser) { + await Like0.setUser(relatedUser0); + } + + const relatedUser1 = await Users.findOne({ + offset: Math.floor(Math.random() * (await Users.count())), + }); + const Like1 = await Likes.findOne({ + order: [['id', 'ASC']], + offset: 1, + }); + if (Like1?.setUser) { + await Like1.setUser(relatedUser1); + } + + const relatedUser2 = await Users.findOne({ + offset: Math.floor(Math.random() * (await Users.count())), + }); + const Like2 = await Likes.findOne({ + order: [['id', 'ASC']], + offset: 2, + }); + if (Like2?.setUser) { + await Like2.setUser(relatedUser2); } } @@ -1173,6 +837,8 @@ module.exports = { await Organizations.bulkCreate(OrganizationsData); + await Likes.bulkCreate(LikesData); + await Promise.all([ // Similar logic for "relation_many" @@ -1215,6 +881,10 @@ module.exports = { // Similar logic for "relation_many" await associateStudentWithOrganization(), + + await associateLikeWithOrganization(), + + await associateLikeWithUser(), ]); }, @@ -1232,5 +902,7 @@ module.exports = { await queryInterface.bulkDelete('students', null, {}); await queryInterface.bulkDelete('organizations', null, {}); + + await queryInterface.bulkDelete('likes', null, {}); }, }; diff --git a/backend/src/db/seeders/20250401125942.js b/backend/src/db/seeders/20250401125942.js new file mode 100644 index 0000000..2e6f63b --- /dev/null +++ b/backend/src/db/seeders/20250401125942.js @@ -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} + */ + async up(queryInterface) { + const createdAt = new Date(); + const updatedAt = new Date(); + + /** @type {Map} */ + 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 = ['likes']; + + 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.super_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), + ); + }, +}; diff --git a/backend/src/index.js b/backend/src/index.js index f6c9c5d..4026fc9 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -41,6 +41,8 @@ const permissionsRoutes = require('./routes/permissions'); const organizationsRoutes = require('./routes/organizations'); +const likesRoutes = require('./routes/likes'); + const getBaseUrl = (url) => { if (!url) return ''; return url.endsWith('/api') ? url.slice(0, -4) : url; @@ -166,6 +168,12 @@ app.use( organizationsRoutes, ); +app.use( + '/api/likes', + passport.authenticate('jwt', { session: false }), + likesRoutes, +); + app.use( '/api/openai', passport.authenticate('jwt', { session: false }), diff --git a/backend/src/routes/likes.js b/backend/src/routes/likes.js new file mode 100644 index 0000000..2b1478f --- /dev/null +++ b/backend/src/routes/likes.js @@ -0,0 +1,447 @@ +const express = require('express'); + +const LikesService = require('../services/likes'); +const LikesDBApi = require('../db/api/likes'); +const wrapAsync = require('../helpers').wrapAsync; + +const config = require('../config'); + +const router = express.Router(); + +const { parse } = require('json2csv'); + +const { checkCrudPermissions } = require('../middlewares/check-permissions'); + +router.use(checkCrudPermissions('likes')); + +/** + * @swagger + * components: + * schemas: + * Likes: + * type: object + * properties: + + * amount: + * type: string + * default: amount + + */ + +/** + * @swagger + * tags: + * name: Likes + * description: The Likes managing API + */ + +/** + * @swagger + * /api/likes: + * post: + * security: + * - bearerAuth: [] + * tags: [Likes] + * 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/Likes" + * responses: + * 200: + * description: The item was successfully added + * content: + * application/json: + * schema: + * $ref: "#/components/schemas/Likes" + * 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 LikesService.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: [Likes] + * 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/Likes" + * responses: + * 200: + * description: The items were successfully imported + * content: + * application/json: + * schema: + * $ref: "#/components/schemas/Likes" + * 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 LikesService.bulkImport(req, res, true, link.host); + const payload = true; + res.status(200).send(payload); + }), +); + +/** + * @swagger + * /api/likes/{id}: + * put: + * security: + * - bearerAuth: [] + * tags: [Likes] + * 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/Likes" + * required: + * - id + * responses: + * 200: + * description: The item data was successfully updated + * content: + * application/json: + * schema: + * $ref: "#/components/schemas/Likes" + * 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 LikesService.update(req.body.data, req.body.id, req.currentUser); + const payload = true; + res.status(200).send(payload); + }), +); + +/** + * @swagger + * /api/likes/{id}: + * delete: + * security: + * - bearerAuth: [] + * tags: [Likes] + * 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/Likes" + * 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 LikesService.remove(req.params.id, req.currentUser); + const payload = true; + res.status(200).send(payload); + }), +); + +/** + * @swagger + * /api/likes/deleteByIds: + * post: + * security: + * - bearerAuth: [] + * tags: [Likes] + * 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/Likes" + * 401: + * $ref: "#/components/responses/UnauthorizedError" + * 404: + * description: Items not found + * 500: + * description: Some server error + */ +router.post( + '/deleteByIds', + wrapAsync(async (req, res) => { + await LikesService.deleteByIds(req.body.data, req.currentUser); + const payload = true; + res.status(200).send(payload); + }), +); + +/** + * @swagger + * /api/likes: + * get: + * security: + * - bearerAuth: [] + * tags: [Likes] + * summary: Get all likes + * description: Get all likes + * responses: + * 200: + * description: Likes list successfully received + * content: + * application/json: + * schema: + * type: array + * items: + * $ref: "#/components/schemas/Likes" + * 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 globalAccess = req.currentUser.app_role.globalAccess; + + const currentUser = req.currentUser; + const payload = await LikesDBApi.findAll(req.query, globalAccess, { + currentUser, + }); + if (filetype && filetype === 'csv') { + const fields = ['id', 'amount']; + 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/likes/count: + * get: + * security: + * - bearerAuth: [] + * tags: [Likes] + * summary: Count all likes + * description: Count all likes + * responses: + * 200: + * description: Likes count successfully received + * content: + * application/json: + * schema: + * type: array + * items: + * $ref: "#/components/schemas/Likes" + * 401: + * $ref: "#/components/responses/UnauthorizedError" + * 404: + * description: Data not found + * 500: + * description: Some server error + */ +router.get( + '/count', + wrapAsync(async (req, res) => { + const globalAccess = req.currentUser.app_role.globalAccess; + + const currentUser = req.currentUser; + const payload = await LikesDBApi.findAll(req.query, globalAccess, { + countOnly: true, + currentUser, + }); + + res.status(200).send(payload); + }), +); + +/** + * @swagger + * /api/likes/autocomplete: + * get: + * security: + * - bearerAuth: [] + * tags: [Likes] + * summary: Find all likes that match search criteria + * description: Find all likes that match search criteria + * responses: + * 200: + * description: Likes list successfully received + * content: + * application/json: + * schema: + * type: array + * items: + * $ref: "#/components/schemas/Likes" + * 401: + * $ref: "#/components/responses/UnauthorizedError" + * 404: + * description: Data not found + * 500: + * description: Some server error + */ +router.get('/autocomplete', async (req, res) => { + const globalAccess = req.currentUser.app_role.globalAccess; + + const organizationId = req.currentUser.organization?.id; + + const payload = await LikesDBApi.findAllAutocomplete( + req.query.query, + req.query.limit, + req.query.offset, + globalAccess, + organizationId, + ); + + res.status(200).send(payload); +}); + +/** + * @swagger + * /api/likes/{id}: + * get: + * security: + * - bearerAuth: [] + * tags: [Likes] + * 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/Likes" + * 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 LikesDBApi.findBy({ id: req.params.id }); + + res.status(200).send(payload); + }), +); + +router.use('/', require('../helpers').commonErrorHandler); + +module.exports = router; diff --git a/backend/src/services/likes.js b/backend/src/services/likes.js new file mode 100644 index 0000000..d8f6f3e --- /dev/null +++ b/backend/src/services/likes.js @@ -0,0 +1,114 @@ +const db = require('../db/models'); +const LikesDBApi = require('../db/api/likes'); +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 LikesService { + static async create(data, currentUser) { + const transaction = await db.sequelize.transaction(); + try { + await LikesDBApi.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 LikesDBApi.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 likes = await LikesDBApi.findBy({ id }, { transaction }); + + if (!likes) { + throw new ValidationError('likesNotFound'); + } + + const updatedLikes = await LikesDBApi.update(id, data, { + currentUser, + transaction, + }); + + await transaction.commit(); + return updatedLikes; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + static async deleteByIds(ids, currentUser) { + const transaction = await db.sequelize.transaction(); + + try { + await LikesDBApi.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 LikesDBApi.remove(id, { + currentUser, + transaction, + }); + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + } +}; diff --git a/backend/src/services/search.js b/backend/src/services/search.js index 0d8919b..aa089df 100644 --- a/backend/src/services/search.js +++ b/backend/src/services/search.js @@ -50,6 +50,8 @@ module.exports = class SearchService { instructors: ['qualifications'], organizations: ['name'], + + likes: ['amount'], }; const columnsInt = { analytics: [ diff --git a/frontend/json/runtimeError.json b/frontend/json/runtimeError.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/frontend/json/runtimeError.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/frontend/src/components/Likes/CardLikes.tsx b/frontend/src/components/Likes/CardLikes.tsx new file mode 100644 index 0000000..c72eebb --- /dev/null +++ b/frontend/src/components/Likes/CardLikes.tsx @@ -0,0 +1,118 @@ +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 = { + likes: any[]; + loading: boolean; + onDelete: (id: string) => void; + currentPage: number; + numPages: number; + onPageChange: (page: number) => void; +}; + +const CardLikes = ({ + likes, + 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_LIKES'); + + return ( +
+ {loading && } +
    + {!loading && + likes.map((item, index) => ( +
  • +
    + + {item.amount} + + +
    + +
    +
    +
    +
    +
    + Amount +
    +
    +
    + {item.amount} +
    +
    +
    + +
    +
    User
    +
    +
    + {dataFormatter.usersOneListFormatter(item.user)} +
    +
    +
    +
    +
  • + ))} + {!loading && likes.length === 0 && ( +
    +

    No data to display

    +
    + )} +
+
+ +
+
+ ); +}; + +export default CardLikes; diff --git a/frontend/src/components/Likes/ListLikes.tsx b/frontend/src/components/Likes/ListLikes.tsx new file mode 100644 index 0000000..a24e8e8 --- /dev/null +++ b/frontend/src/components/Likes/ListLikes.tsx @@ -0,0 +1,99 @@ +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 = { + likes: any[]; + loading: boolean; + onDelete: (id: string) => void; + currentPage: number; + numPages: number; + onPageChange: (page: number) => void; +}; + +const ListLikes = ({ + likes, + loading, + onDelete, + currentPage, + numPages, + onPageChange, +}: Props) => { + const currentUser = useAppSelector((state) => state.auth.currentUser); + const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_LIKES'); + + const corners = useAppSelector((state) => state.style.corners); + const bgColor = useAppSelector((state) => state.style.cardsColor); + + return ( + <> +
+ {loading && } + {!loading && + likes.map((item) => ( + +
+ dark:divide-dark-700 overflow-x-auto' + } + > +
+

Amount

+

{item.amount}

+
+ +
+

User

+

+ {dataFormatter.usersOneListFormatter(item.user)} +

+
+ + +
+
+ ))} + {!loading && likes.length === 0 && ( +
+

No data to display

+
+ )} +
+
+ +
+ + ); +}; + +export default ListLikes; diff --git a/frontend/src/components/Likes/TableLikes.tsx b/frontend/src/components/Likes/TableLikes.tsx new file mode 100644 index 0000000..1328a91 --- /dev/null +++ b/frontend/src/components/Likes/TableLikes.tsx @@ -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/likes/likesSlice'; +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 './configureLikesCols'; +import _ from 'lodash'; +import dataFormatter from '../../helpers/dataFormatter'; +import { dataGridStyles } from '../../styles'; + +const perPage = 10; + +const TableSampleLikes = ({ + 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([]); + const [selectedRows, setSelectedRows] = useState([]); + const [sortModel, setSortModel] = useState([ + { + field: '', + sort: 'desc', + }, + ]); + + const { + likes, + loading, + count, + notify: likesNotify, + refetch, + } = useAppSelector((state) => state.likes); + 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 (likesNotify.showNotification) { + notify(likesNotify.typeNotification, likesNotify.textNotification); + } + }, [likesNotify.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, `likes`, 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 = ( +
+ `datagrid--row`} + rows={likes ?? []} + 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); + }} + /> +
+ ); + + return ( + <> + {filterItems && Array.isArray(filterItems) && filterItems.length ? ( + + null} + > +
+ <> + {filterItems && + filterItems.map((filterItem) => { + return ( +
+
+
+ Filter +
+ + {filters.map((selectOption) => ( + + ))} + +
+ {filters.find( + (filter) => + filter.title === filterItem?.fields?.selectedField, + )?.type === 'enum' ? ( +
+
Value
+ + + {filters + .find( + (filter) => + filter.title === + filterItem?.fields?.selectedField, + ) + ?.options?.map((option) => ( + + ))} + +
+ ) : filters.find( + (filter) => + filter.title === + filterItem?.fields?.selectedField, + )?.number ? ( +
+
+
+ From +
+ +
+
+
+ To +
+ +
+
+ ) : filters.find( + (filter) => + filter.title === + filterItem?.fields?.selectedField, + )?.date ? ( +
+
+
+ From +
+ +
+
+
+ To +
+ +
+
+ ) : ( +
+
+ Contains +
+ +
+ )} +
+
+ Action +
+ { + deleteFilter(filterItem.id); + }} + /> +
+
+ ); + })} +
+ + +
+ +
+
+
+ ) : null} + +

Are you sure you want to delete this item?

+
+ + {dataGrid} + + {selectedRows.length > 0 && + createPortal( + onDeleteRows(selectedRows)} + />, + document.getElementById('delete-rows-button'), + )} + + + ); +}; + +export default TableSampleLikes; diff --git a/frontend/src/components/Likes/configureLikesCols.tsx b/frontend/src/components/Likes/configureLikesCols.tsx new file mode 100644 index 0000000..ad1de06 --- /dev/null +++ b/frontend/src/components/Likes/configureLikesCols.tsx @@ -0,0 +1,93 @@ +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_LIKES'); + + return [ + { + field: 'amount', + headerName: 'Amount', + flex: 1, + minWidth: 120, + filterable: false, + headerClassName: 'datagrid--header', + cellClassName: 'datagrid--cell', + + editable: hasUpdatePermission, + }, + + { + 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: 'actions', + type: 'actions', + minWidth: 30, + headerClassName: 'datagrid--header', + cellClassName: 'datagrid--cell', + getActions: (params: GridRowParams) => { + return [ + , + ]; + }, + }, + ]; +}; diff --git a/frontend/src/components/WebPageComponents/Header.tsx b/frontend/src/components/WebPageComponents/Header.tsx index 3d58f24..729ecbe 100644 --- a/frontend/src/components/WebPageComponents/Header.tsx +++ b/frontend/src/components/WebPageComponents/Header.tsx @@ -21,7 +21,7 @@ export default function WebSiteHeader({ const style = HeaderStyle.PAGES_RIGHT; - const design = HeaderDesigns.DEFAULT_DESIGN; + const design = HeaderDesigns.DESIGN_DIVERSITY; return (
{ const [roles, setRoles] = React.useState('Loading...'); const [permissions, setPermissions] = React.useState('Loading...'); const [organizations, setOrganizations] = React.useState('Loading...'); + const [likes, setLikes] = React.useState('Loading...'); const [widgetsRole, setWidgetsRole] = React.useState({ role: { value: '', label: '' }, @@ -56,6 +57,7 @@ const Dashboard = () => { 'roles', 'permissions', 'organizations', + 'likes', ]; const fns = [ setUsers, @@ -68,6 +70,7 @@ const Dashboard = () => { setRoles, setPermissions, setOrganizations, + setLikes, ]; const requests = entities.map((entity, index) => { @@ -497,6 +500,38 @@ const Dashboard = () => {
)} + + {hasPermission(currentUser, 'READ_LIKES') && ( + +
+
+
+
+ Likes +
+
+ {likes} +
+
+
+ +
+
+
+ + )} diff --git a/frontend/src/pages/index.tsx b/frontend/src/pages/index.tsx index 89afeec..e4b1c2f 100644 --- a/frontend/src/pages/index.tsx +++ b/frontend/src/pages/index.tsx @@ -139,7 +139,7 @@ export default function WebSite() { { + const router = useRouter(); + const dispatch = useAppDispatch(); + const initVals = { + organizations: null, + + amount: '', + + user: null, + }; + const [initialValues, setInitialValues] = useState(initVals); + + const { likes } = useAppSelector((state) => state.likes); + + const { currentUser } = useAppSelector((state) => state.auth); + + const { likesId } = router.query; + + useEffect(() => { + dispatch(fetch({ id: likesId })); + }, [likesId]); + + useEffect(() => { + if (typeof likes === 'object') { + setInitialValues(likes); + } + }, [likes]); + + useEffect(() => { + if (typeof likes === 'object') { + const newInitialVal = { ...initVals }; + + Object.keys(initVals).forEach((el) => (newInitialVal[el] = likes[el])); + + setInitialValues(newInitialVal); + } + }, [likes]); + + const handleSubmit = async (data) => { + await dispatch(update({ id: likesId, data })); + await router.push('/likes/likes-list'); + }; + + return ( + <> + + {getPageTitle('Edit likes')} + + + + {''} + + + handleSubmit(values)} + > +
+ + + + + + + + + + + + + + + + + router.push('/likes/likes-list')} + /> + + +
+
+
+ + ); +}; + +EditLikes.getLayout = function getLayout(page: ReactElement) { + return ( + + {page} + + ); +}; + +export default EditLikes; diff --git a/frontend/src/pages/likes/likes-edit.tsx b/frontend/src/pages/likes/likes-edit.tsx new file mode 100644 index 0000000..dc781f1 --- /dev/null +++ b/frontend/src/pages/likes/likes-edit.tsx @@ -0,0 +1,152 @@ +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/likes/likesSlice'; +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'; + +import { hasPermission } from '../../helpers/userPermissions'; + +const EditLikesPage = () => { + const router = useRouter(); + const dispatch = useAppDispatch(); + const initVals = { + organizations: null, + + amount: '', + + user: null, + }; + const [initialValues, setInitialValues] = useState(initVals); + + const { likes } = useAppSelector((state) => state.likes); + + const { currentUser } = useAppSelector((state) => state.auth); + + const { id } = router.query; + + useEffect(() => { + dispatch(fetch({ id: id })); + }, [id]); + + useEffect(() => { + if (typeof likes === 'object') { + setInitialValues(likes); + } + }, [likes]); + + useEffect(() => { + if (typeof likes === 'object') { + const newInitialVal = { ...initVals }; + Object.keys(initVals).forEach((el) => (newInitialVal[el] = likes[el])); + setInitialValues(newInitialVal); + } + }, [likes]); + + const handleSubmit = async (data) => { + await dispatch(update({ id: id, data })); + await router.push('/likes/likes-list'); + }; + + return ( + <> + + {getPageTitle('Edit likes')} + + + + {''} + + + handleSubmit(values)} + > +
+ + + + + + + + + + + + + + + + + router.push('/likes/likes-list')} + /> + + +
+
+
+ + ); +}; + +EditLikesPage.getLayout = function getLayout(page: ReactElement) { + return ( + + {page} + + ); +}; + +export default EditLikesPage; diff --git a/frontend/src/pages/likes/likes-list.tsx b/frontend/src/pages/likes/likes-list.tsx new file mode 100644 index 0000000..c211da1 --- /dev/null +++ b/frontend/src/pages/likes/likes-list.tsx @@ -0,0 +1,164 @@ +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 TableLikes from '../../components/Likes/TableLikes'; +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/likes/likesSlice'; + +import { hasPermission } from '../../helpers/userPermissions'; + +const LikesTablesPage = () => { + const [filterItems, setFilterItems] = useState([]); + const [csvFile, setCsvFile] = useState(null); + const [isModalActive, setIsModalActive] = useState(false); + const [showTableView, setShowTableView] = useState(false); + + const { currentUser } = useAppSelector((state) => state.auth); + + const dispatch = useAppDispatch(); + + const [filters] = useState([ + { label: 'Amount', title: 'amount' }, + + { label: 'User', title: 'user' }, + ]); + + const hasCreatePermission = + currentUser && hasPermission(currentUser, 'CREATE_LIKES'); + + const addFilter = () => { + const newItem = { + id: uniqueId(), + fields: { + filterValue: '', + filterValueFrom: '', + filterValueTo: '', + selectedField: '', + }, + }; + newItem.fields.selectedField = filters[0].title; + setFilterItems([...filterItems, newItem]); + }; + + const getLikesCSV = async () => { + const response = await axios({ + url: '/likes?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 = 'likesCSV.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 ( + <> + + {getPageTitle('Likes')} + + + + {''} + + + {hasCreatePermission && ( + + )} + + + + + {hasCreatePermission && ( + setIsModalActive(true)} + /> + )} + +
+
+
+
+ + + + +
+ + + + + ); +}; + +LikesTablesPage.getLayout = function getLayout(page: ReactElement) { + return ( + {page} + ); +}; + +export default LikesTablesPage; diff --git a/frontend/src/pages/likes/likes-new.tsx b/frontend/src/pages/likes/likes-new.tsx new file mode 100644 index 0000000..80f28f8 --- /dev/null +++ b/frontend/src/pages/likes/likes-new.tsx @@ -0,0 +1,122 @@ +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/likes/likesSlice'; +import { useAppDispatch } from '../../stores/hooks'; +import { useRouter } from 'next/router'; +import moment from 'moment'; + +const initialValues = { + organizations: '', + + amount: '', + + user: '', +}; + +const LikesNew = () => { + const router = useRouter(); + const dispatch = useAppDispatch(); + + const handleSubmit = async (data) => { + await dispatch(create(data)); + await router.push('/likes/likes-list'); + }; + return ( + <> + + {getPageTitle('New Item')} + + + + {''} + + + handleSubmit(values)} + > +
+ + + + + + + + + + + + + + + + + router.push('/likes/likes-list')} + /> + + +
+
+
+ + ); +}; + +LikesNew.getLayout = function getLayout(page: ReactElement) { + return ( + + {page} + + ); +}; + +export default LikesNew; diff --git a/frontend/src/pages/likes/likes-table.tsx b/frontend/src/pages/likes/likes-table.tsx new file mode 100644 index 0000000..8cd1fa4 --- /dev/null +++ b/frontend/src/pages/likes/likes-table.tsx @@ -0,0 +1,163 @@ +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 TableLikes from '../../components/Likes/TableLikes'; +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/likes/likesSlice'; + +import { hasPermission } from '../../helpers/userPermissions'; + +const LikesTablesPage = () => { + const [filterItems, setFilterItems] = useState([]); + const [csvFile, setCsvFile] = useState(null); + const [isModalActive, setIsModalActive] = useState(false); + const [showTableView, setShowTableView] = useState(false); + + const { currentUser } = useAppSelector((state) => state.auth); + + const dispatch = useAppDispatch(); + + const [filters] = useState([ + { label: 'Amount', title: 'amount' }, + + { label: 'User', title: 'user' }, + ]); + + const hasCreatePermission = + currentUser && hasPermission(currentUser, 'CREATE_LIKES'); + + const addFilter = () => { + const newItem = { + id: uniqueId(), + fields: { + filterValue: '', + filterValueFrom: '', + filterValueTo: '', + selectedField: '', + }, + }; + newItem.fields.selectedField = filters[0].title; + setFilterItems([...filterItems, newItem]); + }; + + const getLikesCSV = async () => { + const response = await axios({ + url: '/likes?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 = 'likesCSV.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 ( + <> + + {getPageTitle('Likes')} + + + + {''} + + + {hasCreatePermission && ( + + )} + + + + + {hasCreatePermission && ( + setIsModalActive(true)} + /> + )} + +
+
+
+
+ + + +
+ + + + + ); +}; + +LikesTablesPage.getLayout = function getLayout(page: ReactElement) { + return ( + {page} + ); +}; + +export default LikesTablesPage; diff --git a/frontend/src/pages/likes/likes-view.tsx b/frontend/src/pages/likes/likes-view.tsx new file mode 100644 index 0000000..0ea548e --- /dev/null +++ b/frontend/src/pages/likes/likes-view.tsx @@ -0,0 +1,97 @@ +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/likes/likesSlice'; +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'; + +import { hasPermission } from '../../helpers/userPermissions'; + +const LikesView = () => { + const router = useRouter(); + const dispatch = useAppDispatch(); + const { likes } = useAppSelector((state) => state.likes); + + const { currentUser } = useAppSelector((state) => state.auth); + + const { id } = router.query; + + function removeLastCharacter(str) { + console.log(str, `str`); + return str.slice(0, -1); + } + + useEffect(() => { + dispatch(fetch({ id })); + }, [dispatch, id]); + + return ( + <> + + {getPageTitle('View likes')} + + + + + + +
+

organizations

+ +

{likes?.organizations?.name ?? 'No data'}

+
+ +
+

Amount

+

{likes?.amount}

+
+ +
+

User

+ +

{likes?.user?.firstName ?? 'No data'}

+
+ + + + router.push('/likes/likes-list')} + /> +
+
+ + ); +}; + +LikesView.getLayout = function getLayout(page: ReactElement) { + return ( + {page} + ); +}; + +export default LikesView; diff --git a/frontend/src/pages/organizations/organizations-view.tsx b/frontend/src/pages/organizations/organizations-view.tsx index 4d16788..2161e5a 100644 --- a/frontend/src/pages/organizations/organizations-view.tsx +++ b/frontend/src/pages/organizations/organizations-view.tsx @@ -364,6 +364,41 @@ const OrganizationsView = () => { + <> +

Likes organizations

+ +
+ + + + + + + + {organizations.likes_organizations && + Array.isArray(organizations.likes_organizations) && + organizations.likes_organizations.map((item: any) => ( + + router.push(`/likes/likes-view/?id=${item.id}`) + } + > + + + ))} + +
Amount
{item.amount}
+
+ {!organizations?.likes_organizations?.length && ( +
No data
+ )} +
+ + { + <> +

Likes User

+ +
+ + + + + + + + {users.likes_user && + Array.isArray(users.likes_user) && + users.likes_user.map((item: any) => ( + + router.push(`/likes/likes-view/?id=${item.id}`) + } + > + + + ))} + +
Amount
{item.amount}
+
+ {!users?.likes_user?.length && ( +
No data
+ )} +
+ + { + const { id, query } = data; + const result = await axios.get(`likes${query || (id ? `/${id}` : '')}`); + return id + ? result.data + : { rows: result.data.rows, count: result.data.count }; +}); + +export const deleteItemsByIds = createAsyncThunk( + 'likes/deleteByIds', + async (data: any, { rejectWithValue }) => { + try { + await axios.post('likes/deleteByIds', { data }); + } catch (error) { + if (!error.response) { + throw error; + } + + return rejectWithValue(error.response.data); + } + }, +); + +export const deleteItem = createAsyncThunk( + 'likes/deleteLikes', + async (id: string, { rejectWithValue }) => { + try { + await axios.delete(`likes/${id}`); + } catch (error) { + if (!error.response) { + throw error; + } + + return rejectWithValue(error.response.data); + } + }, +); + +export const create = createAsyncThunk( + 'likes/createLikes', + async (data: any, { rejectWithValue }) => { + try { + const result = await axios.post('likes', { data }); + return result.data; + } catch (error) { + if (!error.response) { + throw error; + } + + return rejectWithValue(error.response.data); + } + }, +); + +export const uploadCsv = createAsyncThunk( + 'likes/uploadCsv', + async (file: File, { rejectWithValue }) => { + try { + const data = new FormData(); + data.append('file', file); + data.append('filename', file.name); + + const result = await axios.post('likes/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( + 'likes/updateLikes', + async (payload: any, { rejectWithValue }) => { + try { + const result = await axios.put(`likes/${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 likesSlice = createSlice({ + name: 'likes', + initialState, + reducers: { + setRefetch: (state, action: PayloadAction) => { + 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.likes = action.payload.rows; + state.count = action.payload.count; + } else { + state.likes = 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, 'Likes 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, `${'Likes'.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, `${'Likes'.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, `${'Likes'.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, 'Likes 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 } = likesSlice.actions; + +export default likesSlice.reducer; diff --git a/frontend/src/stores/store.ts b/frontend/src/stores/store.ts index 5586de5..5b4eda6 100644 --- a/frontend/src/stores/store.ts +++ b/frontend/src/stores/store.ts @@ -14,6 +14,7 @@ import studentsSlice from './students/studentsSlice'; import rolesSlice from './roles/rolesSlice'; import permissionsSlice from './permissions/permissionsSlice'; import organizationsSlice from './organizations/organizationsSlice'; +import likesSlice from './likes/likesSlice'; export const store = configureStore({ reducer: { @@ -32,6 +33,7 @@ export const store = configureStore({ roles: rolesSlice, permissions: permissionsSlice, organizations: organizationsSlice, + likes: likesSlice, }, });