From 5f83e06e9998e8ce01b457da64457b12e2ce702d Mon Sep 17 00:00:00 2001 From: Flatlogic Bot Date: Tue, 18 Mar 2025 13:44:22 +0000 Subject: [PATCH] adding category entity --- backend/src/db/api/categories.js | 248 +++++++++ backend/src/db/migrations/1742305074257.js | 72 +++ backend/src/db/migrations/1742305103246.js | 47 ++ backend/src/db/models/categories.js | 49 ++ .../db/seeders/20200430130760-user-roles.js | 26 + .../db/seeders/20231127130745-sample-data.js | 80 ++- backend/src/db/seeders/20250318133754.js | 87 ++++ backend/src/index.js | 18 +- backend/src/routes/categories.js | 438 ++++++++++++++++ backend/src/routes/tags.js | 5 +- backend/src/services/categories.js | 114 +++++ backend/src/services/search.js | 4 +- frontend/json/runtimeError.json | 1 + frontend/src/components/BigCalendar.tsx | 2 +- .../components/Categories/CardCategories.tsx | 105 ++++ .../components/Categories/ListCategories.tsx | 90 ++++ .../components/Categories/TableCategories.tsx | 484 ++++++++++++++++++ .../Categories/configureCategoriesCols.tsx | 73 +++ frontend/src/components/Tags/CardTags.tsx | 101 ++-- frontend/src/components/Tags/ListTags.tsx | 5 + .../src/components/Tags/configureTagsCols.tsx | 12 + .../WidgetCreator/WidgetCreator.tsx | 2 +- frontend/src/menuAside.ts | 8 + .../src/pages/categories/[categoriesId].tsx | 126 +++++ .../src/pages/categories/categories-edit.tsx | 124 +++++ .../src/pages/categories/categories-list.tsx | 162 ++++++ .../src/pages/categories/categories-new.tsx | 98 ++++ .../src/pages/categories/categories-table.tsx | 161 ++++++ .../src/pages/categories/categories-view.tsx | 83 +++ frontend/src/pages/courses/[coursesId].tsx | 2 +- frontend/src/pages/courses/courses-edit.tsx | 2 +- frontend/src/pages/courses/courses-view.tsx | 4 + frontend/src/pages/dashboard.tsx | 35 ++ frontend/src/pages/index.tsx | 2 +- frontend/src/pages/tags/[tagsId].tsx | 6 + frontend/src/pages/tags/tags-edit.tsx | 6 + frontend/src/pages/tags/tags-list.tsx | 5 +- frontend/src/pages/tags/tags-new.tsx | 6 + frontend/src/pages/tags/tags-table.tsx | 5 +- frontend/src/pages/tags/tags-view.tsx | 5 + .../src/stores/categories/categoriesSlice.ts | 236 +++++++++ frontend/src/stores/store.ts | 2 + 42 files changed, 3060 insertions(+), 81 deletions(-) create mode 100644 backend/src/db/api/categories.js create mode 100644 backend/src/db/migrations/1742305074257.js create mode 100644 backend/src/db/migrations/1742305103246.js create mode 100644 backend/src/db/models/categories.js create mode 100644 backend/src/db/seeders/20250318133754.js create mode 100644 backend/src/routes/categories.js create mode 100644 backend/src/services/categories.js create mode 100644 frontend/json/runtimeError.json create mode 100644 frontend/src/components/Categories/CardCategories.tsx create mode 100644 frontend/src/components/Categories/ListCategories.tsx create mode 100644 frontend/src/components/Categories/TableCategories.tsx create mode 100644 frontend/src/components/Categories/configureCategoriesCols.tsx create mode 100644 frontend/src/pages/categories/[categoriesId].tsx create mode 100644 frontend/src/pages/categories/categories-edit.tsx create mode 100644 frontend/src/pages/categories/categories-list.tsx create mode 100644 frontend/src/pages/categories/categories-new.tsx create mode 100644 frontend/src/pages/categories/categories-table.tsx create mode 100644 frontend/src/pages/categories/categories-view.tsx create mode 100644 frontend/src/stores/categories/categoriesSlice.ts diff --git a/backend/src/db/api/categories.js b/backend/src/db/api/categories.js new file mode 100644 index 0000000..2c750d9 --- /dev/null +++ b/backend/src/db/api/categories.js @@ -0,0 +1,248 @@ +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 CategoriesDBApi { + static async create(data, options) { + const currentUser = (options && options.currentUser) || { id: null }; + const transaction = (options && options.transaction) || undefined; + + const categories = await db.categories.create( + { + id: data.id || undefined, + + name: data.name || null, + importHash: data.importHash || null, + createdById: currentUser.id, + updatedById: currentUser.id, + }, + { transaction }, + ); + + return categories; + } + + 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 categoriesData = data.map((item, index) => ({ + id: item.id || undefined, + + name: item.name || null, + importHash: item.importHash || null, + createdById: currentUser.id, + updatedById: currentUser.id, + createdAt: new Date(Date.now() + index * 1000), + })); + + // Bulk create items + const categories = await db.categories.bulkCreate(categoriesData, { + transaction, + }); + + // For each item created, replace relation files + + return categories; + } + + static async update(id, data, options) { + const currentUser = (options && options.currentUser) || { id: null }; + const transaction = (options && options.transaction) || undefined; + + const categories = await db.categories.findByPk(id, {}, { transaction }); + + const updatePayload = {}; + + if (data.name !== undefined) updatePayload.name = data.name; + + updatePayload.updatedById = currentUser.id; + + await categories.update(updatePayload, { transaction }); + + return categories; + } + + static async deleteByIds(ids, options) { + const currentUser = (options && options.currentUser) || { id: null }; + const transaction = (options && options.transaction) || undefined; + + const categories = await db.categories.findAll({ + where: { + id: { + [Op.in]: ids, + }, + }, + transaction, + }); + + await db.sequelize.transaction(async (transaction) => { + for (const record of categories) { + await record.update({ deletedBy: currentUser.id }, { transaction }); + } + for (const record of categories) { + await record.destroy({ transaction }); + } + }); + + return categories; + } + + static async remove(id, options) { + const currentUser = (options && options.currentUser) || { id: null }; + const transaction = (options && options.transaction) || undefined; + + const categories = await db.categories.findByPk(id, options); + + await categories.update( + { + deletedBy: currentUser.id, + }, + { + transaction, + }, + ); + + await categories.destroy({ + transaction, + }); + + return categories; + } + + static async findBy(where, options) { + const transaction = (options && options.transaction) || undefined; + + const categories = await db.categories.findOne({ where }, { transaction }); + + if (!categories) { + return categories; + } + + const output = categories.get({ plain: true }); + + 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 = []; + + if (filter) { + if (filter.id) { + where = { + ...where, + ['id']: Utils.uuid(filter.id), + }; + } + + if (filter.name) { + where = { + ...where, + [Op.and]: Utils.ilike('categories', 'name', filter.name), + }; + } + + if (filter.active !== undefined) { + where = { + ...where, + active: filter.active === true || filter.active === 'true', + }; + } + + 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.categories.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('categories', 'name', query), + ], + }; + } + + const records = await db.categories.findAll({ + attributes: ['id', 'name'], + where, + limit: limit ? Number(limit) : undefined, + offset: offset ? Number(offset) : undefined, + orderBy: [['name', 'ASC']], + }); + + return records.map((record) => ({ + id: record.id, + label: record.name, + })); + } +}; diff --git a/backend/src/db/migrations/1742305074257.js b/backend/src/db/migrations/1742305074257.js new file mode 100644 index 0000000..6bedca1 --- /dev/null +++ b/backend/src/db/migrations/1742305074257.js @@ -0,0 +1,72 @@ +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( + 'categories', + { + 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} + */ + async down(queryInterface, Sequelize) { + /** + * @type {Transaction} + */ + const transaction = await queryInterface.sequelize.transaction(); + try { + await queryInterface.dropTable('categories', { transaction }); + + await transaction.commit(); + } catch (err) { + await transaction.rollback(); + throw err; + } + }, +}; diff --git a/backend/src/db/migrations/1742305103246.js b/backend/src/db/migrations/1742305103246.js new file mode 100644 index 0000000..bd2d80a --- /dev/null +++ b/backend/src/db/migrations/1742305103246.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( + 'categories', + 'name', + { + 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('categories', 'name', { transaction }); + + await transaction.commit(); + } catch (err) { + await transaction.rollback(); + throw err; + } + }, +}; diff --git a/backend/src/db/models/categories.js b/backend/src/db/models/categories.js new file mode 100644 index 0000000..d0fb8ae --- /dev/null +++ b/backend/src/db/models/categories.js @@ -0,0 +1,49 @@ +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 categories = sequelize.define( + 'categories', + { + id: { + type: DataTypes.UUID, + defaultValue: DataTypes.UUIDV4, + primaryKey: true, + }, + + name: { + type: DataTypes.TEXT, + }, + + importHash: { + type: DataTypes.STRING(255), + allowNull: true, + unique: true, + }, + }, + { + timestamps: true, + paranoid: true, + freezeTableName: true, + }, + ); + + categories.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.categories.belongsTo(db.users, { + as: 'createdBy', + }); + + db.categories.belongsTo(db.users, { + as: 'updatedBy', + }); + }; + + return categories; +}; diff --git a/backend/src/db/seeders/20200430130760-user-roles.js b/backend/src/db/seeders/20200430130760-user-roles.js index 8616096..3fef19c 100644 --- a/backend/src/db/seeders/20200430130760-user-roles.js +++ b/backend/src/db/seeders/20200430130760-user-roles.js @@ -108,6 +108,7 @@ module.exports = { 'tags', 'roles', 'permissions', + 'categories', , ]; await queryInterface.bulkInsert( @@ -921,6 +922,31 @@ primary key ("roles_permissionsId", "permissionId") permissionId: getId('DELETE_PERMISSIONS'), }, + { + createdAt, + updatedAt, + roles_permissionsId: getId('Administrator'), + permissionId: getId('CREATE_CATEGORIES'), + }, + { + createdAt, + updatedAt, + roles_permissionsId: getId('Administrator'), + permissionId: getId('READ_CATEGORIES'), + }, + { + createdAt, + updatedAt, + roles_permissionsId: getId('Administrator'), + permissionId: getId('UPDATE_CATEGORIES'), + }, + { + createdAt, + updatedAt, + roles_permissionsId: getId('Administrator'), + permissionId: getId('DELETE_CATEGORIES'), + }, + { createdAt, updatedAt, diff --git a/backend/src/db/seeders/20231127130745-sample-data.js b/backend/src/db/seeders/20231127130745-sample-data.js index b152f22..bed9bea 100644 --- a/backend/src/db/seeders/20231127130745-sample-data.js +++ b/backend/src/db/seeders/20231127130745-sample-data.js @@ -17,45 +17,47 @@ const Students = db.students; const Tags = db.tags; +const Categories = db.categories; + const AnalyticsData = [ { // type code here for "relation_one" field - student_engagement: 8, + student_engagement: 3, - completion_rate: 6, + completion_rate: 9, - instructor_performance: 7, + instructor_performance: 3, }, { // type code here for "relation_one" field - student_engagement: 1, + student_engagement: 5, completion_rate: 8, - instructor_performance: 7, + instructor_performance: 6, }, { // type code here for "relation_one" field - student_engagement: 1, + student_engagement: 5, - completion_rate: 1, + completion_rate: 2, - instructor_performance: 7, + instructor_performance: 5, }, { // type code here for "relation_one" field - student_engagement: 7, + student_engagement: 6, - completion_rate: 3, + completion_rate: 9, - instructor_performance: 1, + instructor_performance: 4, }, ]; @@ -153,6 +155,14 @@ const DiscussionBoardsData = [ ]; const EnrollmentsData = [ + { + // type code here for "relation_one" field + + // type code here for "relation_one" field + + payment_status: 'Pending', + }, + { // type code here for "relation_one" field @@ -174,15 +184,7 @@ const EnrollmentsData = [ // type code here for "relation_one" field - payment_status: 'Failed', - }, - - { - // type code here for "relation_one" field - - // type code here for "relation_one" field - - payment_status: 'Failed', + payment_status: 'Pending', }, ]; @@ -306,19 +308,45 @@ const StudentsData = [ const TagsData = [ { - name: 'Hans Bethe', + name: 'Marie Curie', + + description: 'Ernst Mayr', }, { - name: 'Charles Darwin', + name: 'Galileo Galilei', + + description: 'B. F. Skinner', }, { - name: 'Jean Baptiste Lamarck', + name: 'Franz Boas', + + description: 'Jonas Salk', }, { - name: 'Max von Laue', + name: 'Alexander Fleming', + + description: 'Archimedes', + }, +]; + +const CategoriesData = [ + { + name: 'Edward O. Wilson', + }, + + { + name: 'Emil Kraepelin', + }, + + { + name: 'Ludwig Boltzmann', + }, + + { + name: 'Werner Heisenberg', }, ]; @@ -632,6 +660,8 @@ module.exports = { await Tags.bulkCreate(TagsData); + await Categories.bulkCreate(CategoriesData); + await Promise.all([ // Similar logic for "relation_many" @@ -679,5 +709,7 @@ module.exports = { await queryInterface.bulkDelete('students', null, {}); await queryInterface.bulkDelete('tags', null, {}); + + await queryInterface.bulkDelete('categories', null, {}); }, }; diff --git a/backend/src/db/seeders/20250318133754.js b/backend/src/db/seeders/20250318133754.js new file mode 100644 index 0000000..17f6705 --- /dev/null +++ b/backend/src/db/seeders/20250318133754.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 = ['categories']; + + 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), + ); + }, +}; diff --git a/backend/src/index.js b/backend/src/index.js index 9dac143..6dc32bf 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -41,6 +41,13 @@ const rolesRoutes = require('./routes/roles'); const permissionsRoutes = require('./routes/permissions'); +const categoriesRoutes = require('./routes/categories'); + +const getBaseUrl = (url) => { + if (!url) return ''; + return url.endsWith('/api') ? url.slice(0, -4) : url; +}; + const options = { definition: { openapi: '3.0.0', @@ -52,7 +59,7 @@ const options = { }, servers: [ { - url: config.swaggerUrl, + url: getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || config.swaggerUrl, description: 'Development server', }, ], @@ -83,7 +90,8 @@ const specs = swaggerJsDoc(options); app.use( '/api-docs', function (req, res, next) { - swaggerUI.host = req.get('host'); + swaggerUI.host = + getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || req.get('host'); next(); }, swaggerUI.serve, @@ -166,6 +174,12 @@ app.use( permissionsRoutes, ); +app.use( + '/api/categories', + passport.authenticate('jwt', { session: false }), + categoriesRoutes, +); + app.use( '/api/openai', passport.authenticate('jwt', { session: false }), diff --git a/backend/src/routes/categories.js b/backend/src/routes/categories.js new file mode 100644 index 0000000..1b5ad7a --- /dev/null +++ b/backend/src/routes/categories.js @@ -0,0 +1,438 @@ +const express = require('express'); + +const CategoriesService = require('../services/categories'); +const CategoriesDBApi = require('../db/api/categories'); +const wrapAsync = require('../helpers').wrapAsync; + +const router = express.Router(); + +const { parse } = require('json2csv'); + +const { checkCrudPermissions } = require('../middlewares/check-permissions'); + +router.use(checkCrudPermissions('categories')); + +/** + * @swagger + * components: + * schemas: + * Categories: + * type: object + * properties: + + * name: + * type: string + * default: name + + */ + +/** + * @swagger + * tags: + * name: Categories + * description: The Categories managing API + */ + +/** + * @swagger + * /api/categories: + * post: + * security: + * - bearerAuth: [] + * tags: [Categories] + * 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/Categories" + * responses: + * 200: + * description: The item was successfully added + * content: + * application/json: + * schema: + * $ref: "#/components/schemas/Categories" + * 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 CategoriesService.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: [Categories] + * 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/Categories" + * responses: + * 200: + * description: The items were successfully imported + * content: + * application/json: + * schema: + * $ref: "#/components/schemas/Categories" + * 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 CategoriesService.bulkImport(req, res, true, link.host); + const payload = true; + res.status(200).send(payload); + }), +); + +/** + * @swagger + * /api/categories/{id}: + * put: + * security: + * - bearerAuth: [] + * tags: [Categories] + * 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/Categories" + * required: + * - id + * responses: + * 200: + * description: The item data was successfully updated + * content: + * application/json: + * schema: + * $ref: "#/components/schemas/Categories" + * 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 CategoriesService.update(req.body.data, req.body.id, req.currentUser); + const payload = true; + res.status(200).send(payload); + }), +); + +/** + * @swagger + * /api/categories/{id}: + * delete: + * security: + * - bearerAuth: [] + * tags: [Categories] + * 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/Categories" + * 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 CategoriesService.remove(req.params.id, req.currentUser); + const payload = true; + res.status(200).send(payload); + }), +); + +/** + * @swagger + * /api/categories/deleteByIds: + * post: + * security: + * - bearerAuth: [] + * tags: [Categories] + * 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/Categories" + * 401: + * $ref: "#/components/responses/UnauthorizedError" + * 404: + * description: Items not found + * 500: + * description: Some server error + */ +router.post( + '/deleteByIds', + wrapAsync(async (req, res) => { + await CategoriesService.deleteByIds(req.body.data, req.currentUser); + const payload = true; + res.status(200).send(payload); + }), +); + +/** + * @swagger + * /api/categories: + * get: + * security: + * - bearerAuth: [] + * tags: [Categories] + * summary: Get all categories + * description: Get all categories + * responses: + * 200: + * description: Categories list successfully received + * content: + * application/json: + * schema: + * type: array + * items: + * $ref: "#/components/schemas/Categories" + * 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 CategoriesDBApi.findAll(req.query, { currentUser }); + if (filetype && filetype === 'csv') { + const fields = ['id', 'name']; + 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/categories/count: + * get: + * security: + * - bearerAuth: [] + * tags: [Categories] + * summary: Count all categories + * description: Count all categories + * responses: + * 200: + * description: Categories count successfully received + * content: + * application/json: + * schema: + * type: array + * items: + * $ref: "#/components/schemas/Categories" + * 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 CategoriesDBApi.findAll(req.query, null, { + countOnly: true, + currentUser, + }); + + res.status(200).send(payload); + }), +); + +/** + * @swagger + * /api/categories/autocomplete: + * get: + * security: + * - bearerAuth: [] + * tags: [Categories] + * summary: Find all categories that match search criteria + * description: Find all categories that match search criteria + * responses: + * 200: + * description: Categories list successfully received + * content: + * application/json: + * schema: + * type: array + * items: + * $ref: "#/components/schemas/Categories" + * 401: + * $ref: "#/components/responses/UnauthorizedError" + * 404: + * description: Data not found + * 500: + * description: Some server error + */ +router.get('/autocomplete', async (req, res) => { + const payload = await CategoriesDBApi.findAllAutocomplete( + req.query.query, + req.query.limit, + req.query.offset, + ); + + res.status(200).send(payload); +}); + +/** + * @swagger + * /api/categories/{id}: + * get: + * security: + * - bearerAuth: [] + * tags: [Categories] + * 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/Categories" + * 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 CategoriesDBApi.findBy({ id: req.params.id }); + + res.status(200).send(payload); + }), +); + +router.use('/', require('../helpers').commonErrorHandler); + +module.exports = router; diff --git a/backend/src/routes/tags.js b/backend/src/routes/tags.js index 3055204..e3a41de 100644 --- a/backend/src/routes/tags.js +++ b/backend/src/routes/tags.js @@ -23,6 +23,9 @@ router.use(checkCrudPermissions('tags')); * name: * type: string * default: name + * description: + * type: string + * default: description */ @@ -299,7 +302,7 @@ router.get( const currentUser = req.currentUser; const payload = await TagsDBApi.findAll(req.query, { currentUser }); if (filetype && filetype === 'csv') { - const fields = ['id', 'name']; + const fields = ['id', 'name', 'description']; const opts = { fields }; try { const csv = parse(payload.rows, opts); diff --git a/backend/src/services/categories.js b/backend/src/services/categories.js new file mode 100644 index 0000000..a30fcd4 --- /dev/null +++ b/backend/src/services/categories.js @@ -0,0 +1,114 @@ +const db = require('../db/models'); +const CategoriesDBApi = require('../db/api/categories'); +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 CategoriesService { + static async create(data, currentUser) { + const transaction = await db.sequelize.transaction(); + try { + await CategoriesDBApi.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 CategoriesDBApi.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 categories = await CategoriesDBApi.findBy({ id }, { transaction }); + + if (!categories) { + throw new ValidationError('categoriesNotFound'); + } + + const updatedCategories = await CategoriesDBApi.update(id, data, { + currentUser, + transaction, + }); + + await transaction.commit(); + return updatedCategories; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + static async deleteByIds(ids, currentUser) { + const transaction = await db.sequelize.transaction(); + + try { + await CategoriesDBApi.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 CategoriesDBApi.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 1275240..7877ce8 100644 --- a/backend/src/services/search.js +++ b/backend/src/services/search.js @@ -53,7 +53,9 @@ module.exports = class SearchService { students: ['first_name', 'last_name'], - tags: ['name'], + tags: ['name', 'description'], + + categories: ['name'], }; 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/BigCalendar.tsx b/frontend/src/components/BigCalendar.tsx index 5d3c01c..0b26ffe 100644 --- a/frontend/src/components/BigCalendar.tsx +++ b/frontend/src/components/BigCalendar.tsx @@ -49,7 +49,7 @@ const BigCalendar = ({ 'end-data-key': endDataKey, }: Props) => { const [myEvents, setMyEvents] = useState([]); - const prevRange = useRef<{ start: string; end: string }>(); + const prevRange = useRef<{ start: string; end: string } | null>(null); const currentUser = useAppSelector((state) => state.auth.currentUser); const hasUpdatePermission = diff --git a/frontend/src/components/Categories/CardCategories.tsx b/frontend/src/components/Categories/CardCategories.tsx new file mode 100644 index 0000000..c2a6a19 --- /dev/null +++ b/frontend/src/components/Categories/CardCategories.tsx @@ -0,0 +1,105 @@ +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 = { + categories: any[]; + loading: boolean; + onDelete: (id: string) => void; + currentPage: number; + numPages: number; + onPageChange: (page: number) => void; +}; + +const CardCategories = ({ + categories, + 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_CATEGORIES'); + + return ( +
+ {loading && } +
    + {!loading && + categories.map((item, index) => ( +
  • +
    + + {item.name} + + +
    + +
    +
    +
    +
    +
    Name
    +
    +
    {item.name}
    +
    +
    +
    +
  • + ))} + {!loading && categories.length === 0 && ( +
    +

    No data to display

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

Name

+

{item.name}

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

No data to display

+
+ )} +
+
+ +
+ + ); +}; + +export default ListCategories; diff --git a/frontend/src/components/Categories/TableCategories.tsx b/frontend/src/components/Categories/TableCategories.tsx new file mode 100644 index 0000000..166198d --- /dev/null +++ b/frontend/src/components/Categories/TableCategories.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/categories/categoriesSlice'; +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 './configureCategoriesCols'; +import _ from 'lodash'; +import dataFormatter from '../../helpers/dataFormatter'; +import { dataGridStyles } from '../../styles'; + +const perPage = 10; + +const TableSampleCategories = ({ + 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 { + categories, + loading, + count, + notify: categoriesNotify, + refetch, + } = useAppSelector((state) => state.categories); + 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 (categoriesNotify.showNotification) { + notify( + categoriesNotify.typeNotification, + categoriesNotify.textNotification, + ); + } + }, [categoriesNotify.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, `categories`, 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={categories ?? []} + 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 TableSampleCategories; diff --git a/frontend/src/components/Categories/configureCategoriesCols.tsx b/frontend/src/components/Categories/configureCategoriesCols.tsx new file mode 100644 index 0000000..a0ff001 --- /dev/null +++ b/frontend/src/components/Categories/configureCategoriesCols.tsx @@ -0,0 +1,73 @@ +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_CATEGORIES'); + + return [ + { + field: 'name', + headerName: 'Name', + flex: 1, + minWidth: 120, + filterable: false, + headerClassName: 'datagrid--header', + cellClassName: 'datagrid--cell', + + editable: hasUpdatePermission, + }, + + { + field: 'actions', + type: 'actions', + minWidth: 30, + headerClassName: 'datagrid--header', + cellClassName: 'datagrid--cell', + getActions: (params: GridRowParams) => { + return [ + , + ]; + }, + }, + ]; +}; diff --git a/frontend/src/components/Tags/CardTags.tsx b/frontend/src/components/Tags/CardTags.tsx index 890e046..4eb2555 100644 --- a/frontend/src/components/Tags/CardTags.tsx +++ b/frontend/src/components/Tags/CardTags.tsx @@ -4,11 +4,11 @@ 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 {saveFile} from "../../helpers/fileSaver"; +import LoadingSpinner from "../LoadingSpinner"; import Link from 'next/link'; -import { hasPermission } from '../../helpers/userPermissions'; +import {hasPermission} from "../../helpers/userPermissions"; type Props = { tags: any[]; @@ -27,16 +27,16 @@ const CardTags = ({ 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 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_TAGS'); + const currentUser = useAppSelector((state) => state.auth.currentUser); + const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_TAGS') return (
@@ -45,46 +45,55 @@ const CardTags = ({ 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 && - tags.map((item, index) => ( -
  • ( +
  • -
    - - {item.name} + }`} + > + +
    + + + {item.} -
    - -
    +
    +
    -
    +
    +
    +
    -
    Name
    -
    -
    {item.name}
    -
    +
    Name
    +
    +
    + { item.name } +
    +
    -
    -
  • - ))} + +
    +
    Description
    +
    +
    + { item.description } +
    +
    +
    + + + + ))} {!loading && tags.length === 0 && (

    No data to display

    diff --git a/frontend/src/components/Tags/ListTags.tsx b/frontend/src/components/Tags/ListTags.tsx index 3bcc8c5..cc19b24 100644 --- a/frontend/src/components/Tags/ListTags.tsx +++ b/frontend/src/components/Tags/ListTags.tsx @@ -59,6 +59,11 @@ const ListTags = ({

    Name

    {item.name}

    + +
    +

    Description

    +

    {item.description}

    +
    { const description = values.description; - const projectId = '29799'; + const projectId = ''; const payload = { roleId: widgetsRole?.role?.value, diff --git a/frontend/src/menuAside.ts b/frontend/src/menuAside.ts index 3f716b1..5698969 100644 --- a/frontend/src/menuAside.ts +++ b/frontend/src/menuAside.ts @@ -104,6 +104,14 @@ const menuAside: MenuAsideItem[] = [ : icon.mdiTable, permissions: 'READ_PERMISSIONS', }, + { + href: '/categories/categories-list', + label: 'Categories', + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + icon: icon.mdiTable ? icon.mdiTable : icon.mdiTable, + permissions: 'READ_CATEGORIES', + }, { href: '/profile', label: 'Profile', diff --git a/frontend/src/pages/categories/[categoriesId].tsx b/frontend/src/pages/categories/[categoriesId].tsx new file mode 100644 index 0000000..3e6238e --- /dev/null +++ b/frontend/src/pages/categories/[categoriesId].tsx @@ -0,0 +1,126 @@ +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/categories/categoriesSlice'; +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 EditCategories = () => { + const router = useRouter(); + const dispatch = useAppDispatch(); + const initVals = { + name: '', + }; + const [initialValues, setInitialValues] = useState(initVals); + + const { categories } = useAppSelector((state) => state.categories); + + const { categoriesId } = router.query; + + useEffect(() => { + dispatch(fetch({ id: categoriesId })); + }, [categoriesId]); + + useEffect(() => { + if (typeof categories === 'object') { + setInitialValues(categories); + } + }, [categories]); + + useEffect(() => { + if (typeof categories === 'object') { + const newInitialVal = { ...initVals }; + + Object.keys(initVals).forEach( + (el) => (newInitialVal[el] = categories[el]), + ); + + setInitialValues(newInitialVal); + } + }, [categories]); + + const handleSubmit = async (data) => { + await dispatch(update({ id: categoriesId, data })); + await router.push('/categories/categories-list'); + }; + + return ( + <> + + {getPageTitle('Edit categories')} + + + + {''} + + + handleSubmit(values)} + > +
    + + + + + + + + + router.push('/categories/categories-list')} + /> + + +
    +
    +
    + + ); +}; + +EditCategories.getLayout = function getLayout(page: ReactElement) { + return ( + + {page} + + ); +}; + +export default EditCategories; diff --git a/frontend/src/pages/categories/categories-edit.tsx b/frontend/src/pages/categories/categories-edit.tsx new file mode 100644 index 0000000..d311e63 --- /dev/null +++ b/frontend/src/pages/categories/categories-edit.tsx @@ -0,0 +1,124 @@ +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/categories/categoriesSlice'; +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 EditCategoriesPage = () => { + const router = useRouter(); + const dispatch = useAppDispatch(); + const initVals = { + name: '', + }; + const [initialValues, setInitialValues] = useState(initVals); + + const { categories } = useAppSelector((state) => state.categories); + + const { id } = router.query; + + useEffect(() => { + dispatch(fetch({ id: id })); + }, [id]); + + useEffect(() => { + if (typeof categories === 'object') { + setInitialValues(categories); + } + }, [categories]); + + useEffect(() => { + if (typeof categories === 'object') { + const newInitialVal = { ...initVals }; + Object.keys(initVals).forEach( + (el) => (newInitialVal[el] = categories[el]), + ); + setInitialValues(newInitialVal); + } + }, [categories]); + + const handleSubmit = async (data) => { + await dispatch(update({ id: id, data })); + await router.push('/categories/categories-list'); + }; + + return ( + <> + + {getPageTitle('Edit categories')} + + + + {''} + + + handleSubmit(values)} + > +
    + + + + + + + + + router.push('/categories/categories-list')} + /> + + +
    +
    +
    + + ); +}; + +EditCategoriesPage.getLayout = function getLayout(page: ReactElement) { + return ( + + {page} + + ); +}; + +export default EditCategoriesPage; diff --git a/frontend/src/pages/categories/categories-list.tsx b/frontend/src/pages/categories/categories-list.tsx new file mode 100644 index 0000000..31d2c0b --- /dev/null +++ b/frontend/src/pages/categories/categories-list.tsx @@ -0,0 +1,162 @@ +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 TableCategories from '../../components/Categories/TableCategories'; +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/categories/categoriesSlice'; + +import { hasPermission } from '../../helpers/userPermissions'; + +const CategoriesTablesPage = () => { + 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: 'Name', title: 'name' }]); + + const hasCreatePermission = + currentUser && hasPermission(currentUser, 'CREATE_CATEGORIES'); + + const addFilter = () => { + const newItem = { + id: uniqueId(), + fields: { + filterValue: '', + filterValueFrom: '', + filterValueTo: '', + selectedField: '', + }, + }; + newItem.fields.selectedField = filters[0].title; + setFilterItems([...filterItems, newItem]); + }; + + const getCategoriesCSV = async () => { + const response = await axios({ + url: '/categories?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 = 'categoriesCSV.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('Categories')} + + + + {''} + + + {hasCreatePermission && ( + + )} + + + + + {hasCreatePermission && ( + setIsModalActive(true)} + /> + )} + +
    +
    +
    +
    + + + + +
    + + + + + ); +}; + +CategoriesTablesPage.getLayout = function getLayout(page: ReactElement) { + return ( + + {page} + + ); +}; + +export default CategoriesTablesPage; diff --git a/frontend/src/pages/categories/categories-new.tsx b/frontend/src/pages/categories/categories-new.tsx new file mode 100644 index 0000000..591deb2 --- /dev/null +++ b/frontend/src/pages/categories/categories-new.tsx @@ -0,0 +1,98 @@ +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/categories/categoriesSlice'; +import { useAppDispatch } from '../../stores/hooks'; +import { useRouter } from 'next/router'; +import moment from 'moment'; + +const initialValues = { + name: '', +}; + +const CategoriesNew = () => { + const router = useRouter(); + const dispatch = useAppDispatch(); + + const handleSubmit = async (data) => { + await dispatch(create(data)); + await router.push('/categories/categories-list'); + }; + return ( + <> + + {getPageTitle('New Item')} + + + + {''} + + + handleSubmit(values)} + > +
    + + + + + + + + + router.push('/categories/categories-list')} + /> + + +
    +
    +
    + + ); +}; + +CategoriesNew.getLayout = function getLayout(page: ReactElement) { + return ( + + {page} + + ); +}; + +export default CategoriesNew; diff --git a/frontend/src/pages/categories/categories-table.tsx b/frontend/src/pages/categories/categories-table.tsx new file mode 100644 index 0000000..772a0fd --- /dev/null +++ b/frontend/src/pages/categories/categories-table.tsx @@ -0,0 +1,161 @@ +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 TableCategories from '../../components/Categories/TableCategories'; +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/categories/categoriesSlice'; + +import { hasPermission } from '../../helpers/userPermissions'; + +const CategoriesTablesPage = () => { + 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: 'Name', title: 'name' }]); + + const hasCreatePermission = + currentUser && hasPermission(currentUser, 'CREATE_CATEGORIES'); + + const addFilter = () => { + const newItem = { + id: uniqueId(), + fields: { + filterValue: '', + filterValueFrom: '', + filterValueTo: '', + selectedField: '', + }, + }; + newItem.fields.selectedField = filters[0].title; + setFilterItems([...filterItems, newItem]); + }; + + const getCategoriesCSV = async () => { + const response = await axios({ + url: '/categories?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 = 'categoriesCSV.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('Categories')} + + + + {''} + + + {hasCreatePermission && ( + + )} + + + + + {hasCreatePermission && ( + setIsModalActive(true)} + /> + )} + +
    +
    +
    +
    + + + +
    + + + + + ); +}; + +CategoriesTablesPage.getLayout = function getLayout(page: ReactElement) { + return ( + + {page} + + ); +}; + +export default CategoriesTablesPage; diff --git a/frontend/src/pages/categories/categories-view.tsx b/frontend/src/pages/categories/categories-view.tsx new file mode 100644 index 0000000..ad4bb7e --- /dev/null +++ b/frontend/src/pages/categories/categories-view.tsx @@ -0,0 +1,83 @@ +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/categories/categoriesSlice'; +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 CategoriesView = () => { + const router = useRouter(); + const dispatch = useAppDispatch(); + const { categories } = useAppSelector((state) => state.categories); + + 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 categories')} + + + + + + +
    +

    Name

    +

    {categories?.name}

    +
    + + + + router.push('/categories/categories-list')} + /> +
    +
    + + ); +}; + +CategoriesView.getLayout = function getLayout(page: ReactElement) { + return ( + + {page} + + ); +}; + +export default CategoriesView; diff --git a/frontend/src/pages/courses/[coursesId].tsx b/frontend/src/pages/courses/[coursesId].tsx index f82e366..17e2021 100644 --- a/frontend/src/pages/courses/[coursesId].tsx +++ b/frontend/src/pages/courses/[coursesId].tsx @@ -151,7 +151,7 @@ const EditCourses = () => { component={SelectFieldMany} options={initialValues.tags} itemRef={'tags'} - showField={'name'} + showField={''} > diff --git a/frontend/src/pages/courses/courses-edit.tsx b/frontend/src/pages/courses/courses-edit.tsx index b5e142e..55c8838 100644 --- a/frontend/src/pages/courses/courses-edit.tsx +++ b/frontend/src/pages/courses/courses-edit.tsx @@ -149,7 +149,7 @@ const EditCoursesPage = () => { component={SelectFieldMany} options={initialValues.tags} itemRef={'tags'} - showField={'name'} + showField={''} > diff --git a/frontend/src/pages/courses/courses-view.tsx b/frontend/src/pages/courses/courses-view.tsx index 94f5430..fb205f5 100644 --- a/frontend/src/pages/courses/courses-view.tsx +++ b/frontend/src/pages/courses/courses-view.tsx @@ -244,6 +244,8 @@ const CoursesView = () => { Name + + Description @@ -257,6 +259,8 @@ const CoursesView = () => { } > {item.name} + + {item.description} ))} diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsx index f16d410..8c425bb 100644 --- a/frontend/src/pages/dashboard.tsx +++ b/frontend/src/pages/dashboard.tsx @@ -34,6 +34,7 @@ const Dashboard = () => { const [tags, setTags] = React.useState('Loading...'); const [roles, setRoles] = React.useState('Loading...'); const [permissions, setPermissions] = React.useState('Loading...'); + const [categories, setCategories] = React.useState('Loading...'); const [widgetsRole, setWidgetsRole] = React.useState({ role: { value: '', label: '' }, @@ -56,6 +57,7 @@ const Dashboard = () => { 'tags', 'roles', 'permissions', + 'categories', ]; const fns = [ setUsers, @@ -69,6 +71,7 @@ const Dashboard = () => { setTags, setRoles, setPermissions, + setCategories, ]; const requests = entities.map((entity, index) => { @@ -528,6 +531,38 @@ const Dashboard = () => {
    )} + + {hasPermission(currentUser, 'READ_CATEGORIES') && ( + +
    +
    +
    +
    + Categories +
    +
    + {categories} +
    +
    +
    + +
    +
    +
    + + )} diff --git a/frontend/src/pages/index.tsx b/frontend/src/pages/index.tsx index fbfb62d..090b5df 100644 --- a/frontend/src/pages/index.tsx +++ b/frontend/src/pages/index.tsx @@ -148,7 +148,7 @@ export default function WebSite() { { const dispatch = useAppDispatch(); const initVals = { name: '', + + description: '', }; const [initialValues, setInitialValues] = useState(initVals); @@ -93,6 +95,10 @@ const EditTags = () => { + + + + diff --git a/frontend/src/pages/tags/tags-edit.tsx b/frontend/src/pages/tags/tags-edit.tsx index 9c21a04..6583021 100644 --- a/frontend/src/pages/tags/tags-edit.tsx +++ b/frontend/src/pages/tags/tags-edit.tsx @@ -37,6 +37,8 @@ const EditTagsPage = () => { const dispatch = useAppDispatch(); const initVals = { name: '', + + description: '', }; const [initialValues, setInitialValues] = useState(initVals); @@ -91,6 +93,10 @@ const EditTagsPage = () => { + + + + diff --git a/frontend/src/pages/tags/tags-list.tsx b/frontend/src/pages/tags/tags-list.tsx index 118a6af..183a870 100644 --- a/frontend/src/pages/tags/tags-list.tsx +++ b/frontend/src/pages/tags/tags-list.tsx @@ -28,7 +28,10 @@ const TagsTablesPage = () => { const dispatch = useAppDispatch(); - const [filters] = useState([{ label: 'Name', title: 'name' }]); + const [filters] = useState([ + { label: 'Name', title: 'name' }, + { label: 'Description', title: 'description' }, + ]); const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_TAGS'); diff --git a/frontend/src/pages/tags/tags-new.tsx b/frontend/src/pages/tags/tags-new.tsx index 0b67649..ce9c841 100644 --- a/frontend/src/pages/tags/tags-new.tsx +++ b/frontend/src/pages/tags/tags-new.tsx @@ -34,6 +34,8 @@ import moment from 'moment'; const initialValues = { name: '', + + description: '', }; const TagsNew = () => { @@ -67,6 +69,10 @@ const TagsNew = () => { + + + + diff --git a/frontend/src/pages/tags/tags-table.tsx b/frontend/src/pages/tags/tags-table.tsx index e9f02c6..08d8d7c 100644 --- a/frontend/src/pages/tags/tags-table.tsx +++ b/frontend/src/pages/tags/tags-table.tsx @@ -28,7 +28,10 @@ const TagsTablesPage = () => { const dispatch = useAppDispatch(); - const [filters] = useState([{ label: 'Name', title: 'name' }]); + const [filters] = useState([ + { label: 'Name', title: 'name' }, + { label: 'Description', title: 'description' }, + ]); const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_TAGS'); diff --git a/frontend/src/pages/tags/tags-view.tsx b/frontend/src/pages/tags/tags-view.tsx index 81b4d80..f3d1d54 100644 --- a/frontend/src/pages/tags/tags-view.tsx +++ b/frontend/src/pages/tags/tags-view.tsx @@ -59,6 +59,11 @@ const TagsView = () => {

    {tags?.name}

    +
    +

    Description

    +

    {tags?.description}

    +
    + { + const { id, query } = data; + const result = await axios.get(`categories${query || (id ? `/${id}` : '')}`); + return id + ? result.data + : { rows: result.data.rows, count: result.data.count }; +}); + +export const deleteItemsByIds = createAsyncThunk( + 'categories/deleteByIds', + async (data: any, { rejectWithValue }) => { + try { + await axios.post('categories/deleteByIds', { data }); + } catch (error) { + if (!error.response) { + throw error; + } + + return rejectWithValue(error.response.data); + } + }, +); + +export const deleteItem = createAsyncThunk( + 'categories/deleteCategories', + async (id: string, { rejectWithValue }) => { + try { + await axios.delete(`categories/${id}`); + } catch (error) { + if (!error.response) { + throw error; + } + + return rejectWithValue(error.response.data); + } + }, +); + +export const create = createAsyncThunk( + 'categories/createCategories', + async (data: any, { rejectWithValue }) => { + try { + const result = await axios.post('categories', { data }); + return result.data; + } catch (error) { + if (!error.response) { + throw error; + } + + return rejectWithValue(error.response.data); + } + }, +); + +export const uploadCsv = createAsyncThunk( + 'categories/uploadCsv', + async (file: File, { rejectWithValue }) => { + try { + const data = new FormData(); + data.append('file', file); + data.append('filename', file.name); + + const result = await axios.post('categories/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( + 'categories/updateCategories', + async (payload: any, { rejectWithValue }) => { + try { + const result = await axios.put(`categories/${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 categoriesSlice = createSlice({ + name: 'categories', + 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.categories = action.payload.rows; + state.count = action.payload.count; + } else { + state.categories = 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, 'Categories 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, `${'Categories'.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, `${'Categories'.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, `${'Categories'.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, 'Categories 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 } = categoriesSlice.actions; + +export default categoriesSlice.reducer; diff --git a/frontend/src/stores/store.ts b/frontend/src/stores/store.ts index 8af0195..d34a21c 100644 --- a/frontend/src/stores/store.ts +++ b/frontend/src/stores/store.ts @@ -15,6 +15,7 @@ import studentsSlice from './students/studentsSlice'; import tagsSlice from './tags/tagsSlice'; import rolesSlice from './roles/rolesSlice'; import permissionsSlice from './permissions/permissionsSlice'; +import categoriesSlice from './categories/categoriesSlice'; export const store = configureStore({ reducer: { @@ -34,6 +35,7 @@ export const store = configureStore({ tags: tagsSlice, roles: rolesSlice, permissions: permissionsSlice, + categories: categoriesSlice, }, });