diff --git a/server/migrations/20240611010054-create-data-attributes.js b/server/migrations/20240611010054-create-data-attributes.js index c12b86ce52..7b01ffd647 100644 --- a/server/migrations/20240611010054-create-data-attributes.js +++ b/server/migrations/20240611010054-create-data-attributes.js @@ -19,6 +19,14 @@ module.exports = { model: "users", }, }, + teamId: { + type: Sequelize.UUID, + allowNull: false, + onDelete: "cascade", + references: { + model: "teams", + } + }, name: { type: Sequelize.STRING, allowNull: false, @@ -106,8 +114,8 @@ module.exports = { }, down: async (queryInterface, Sequelize) => { await queryInterface.sequelize.transaction(async (transaction) => { - await queryInterface.dropTable("data_attributes", { transaction }); await queryInterface.dropTable("document_data_attributes", { transaction }); + await queryInterface.dropTable("data_attributes", { transaction }); }); } }; diff --git a/server/models/DataAttribute.ts b/server/models/DataAttribute.ts new file mode 100644 index 0000000000..7d909bca9c --- /dev/null +++ b/server/models/DataAttribute.ts @@ -0,0 +1,88 @@ +import { InferAttributes, InferCreationAttributes } from "sequelize"; +import { + Column, + Table, + BelongsTo, + ForeignKey, + AllowNull, + IsIn, + DataType, + Default, +} from "sequelize-typescript"; +import { DataAttributeValidation } from "@shared/validations"; +import Team from "./Team"; +import User from "./User"; +import ParanoidModel from "./base/ParanoidModel"; +import Fix from "./decorators/Fix"; +import Length from "./validators/Length"; +import NotContainsUrl from "./validators/NotContainsUrl"; + +export enum DataAttributeDataType { + String = "string", + Integer = "integer", + Boolean = "boolean", + List = "list", +} + +export type DataAttributeOptions = { + options: string[]; +}; + +@Table({ tableName: "data_attributes", modelName: "data_attribute" }) +@Fix +class DataAttribute extends ParanoidModel< + InferAttributes, + Partial> +> { + @Length({ + min: DataAttributeValidation.minNameLength, + max: DataAttributeValidation.maxNameLength, + msg: `Name must be between ${DataAttributeValidation.minNameLength} and ${DataAttributeValidation.maxNameLength} characters`, + }) + @NotContainsUrl + @Column + name: string; + + @AllowNull + @Column + description: string; + + @IsIn([Object.values(DataAttributeDataType)]) + @Column(DataType.ENUM(...Object.values(DataAttributeDataType))) + dataType: DataAttributeDataType; + + @AllowNull + @Column(DataType.JSONB) + options: DataAttributeOptions; + + @Default(false) + @Column + pinned: boolean; + + @Column + index: string; + + @AllowNull + @Column + archivedAt: Date | null; + + // hooks + + // associations + + @BelongsTo(() => User, "createdById") + createdBy: User; + + @ForeignKey(() => User) + @Column + createdById: string; + + @BelongsTo(() => Team) + team: Team; + + @ForeignKey(() => Team) + @Column(DataType.UUID) + teamId: string; +} + +export default DataAttribute; diff --git a/server/models/index.ts b/server/models/index.ts index 6679ebe796..7a63c97058 100644 --- a/server/models/index.ts +++ b/server/models/index.ts @@ -8,6 +8,8 @@ export { default as Backlink } from "./Backlink"; export { default as Collection } from "./Collection"; +export { default as DataAttribute } from "./DataAttribute"; + export { default as GroupMembership } from "./GroupMembership"; export { default as UserMembership } from "./UserMembership"; diff --git a/server/policies/dataAttribute.ts b/server/policies/dataAttribute.ts new file mode 100644 index 0000000000..ad8ded0888 --- /dev/null +++ b/server/policies/dataAttribute.ts @@ -0,0 +1,18 @@ +import { User, Team, DataAttribute } from "@server/models"; +import { allow } from "./cancan"; +import { and, isTeamAdmin, isTeamModel, isTeamMutable } from "./utils"; + +allow(User, "createDataAttribute", Team, (actor, team) => + and( + // + isTeamAdmin(actor, team), + isTeamMutable(actor), + !actor.isSuspended + ) +); + +allow(User, "listDataAttribute", Team, isTeamModel); + +allow(User, "read", DataAttribute, isTeamModel); + +allow(User, ["update", "delete"], DataAttribute, isTeamAdmin); diff --git a/server/presenters/dataAttribute.ts b/server/presenters/dataAttribute.ts new file mode 100644 index 0000000000..aa5b7a2b2b --- /dev/null +++ b/server/presenters/dataAttribute.ts @@ -0,0 +1,12 @@ +import DataAttribute from "@server/models/DataAttribute"; + +export default function presentDataAttribute(dataAttribute: DataAttribute) { + return { + id: dataAttribute.id, + name: dataAttribute.name, + description: dataAttribute.description, + createdAt: dataAttribute.createdAt, + updatedAt: dataAttribute.updatedAt, + archivedAt: dataAttribute.archivedAt, + }; +} diff --git a/server/presenters/index.ts b/server/presenters/index.ts index 7834353b1f..1cbb657157 100644 --- a/server/presenters/index.ts +++ b/server/presenters/index.ts @@ -4,6 +4,7 @@ import presentAuthenticationProvider from "./authenticationProvider"; import presentAvailableTeam from "./availableTeam"; import presentCollection from "./collection"; import presentComment from "./comment"; +import presentDataAttribute from "./dataAttribute"; import presentDocument from "./document"; import presentEvent from "./event"; import presentFileOperation from "./fileOperation"; @@ -32,6 +33,7 @@ export { presentAvailableTeam, presentCollection, presentComment, + presentDataAttribute, presentDocument, presentEvent, presentFileOperation, diff --git a/server/routes/api/dataAttributes/dataAttributes.ts b/server/routes/api/dataAttributes/dataAttributes.ts new file mode 100644 index 0000000000..e08ec59abc --- /dev/null +++ b/server/routes/api/dataAttributes/dataAttributes.ts @@ -0,0 +1,85 @@ +import Router from "koa-router"; +import { UserRole } from "@shared/types"; +import auth from "@server/middlewares/authentication"; +import { transaction } from "@server/middlewares/transaction"; +import validate from "@server/middlewares/validate"; +import { DataAttribute } from "@server/models"; +import { authorize } from "@server/policies"; +import { presentDataAttribute, presentPolicies } from "@server/presenters"; +import { APIContext } from "@server/types"; +import pagination from "../middlewares/pagination"; +import * as T from "./schema"; + +const router = new Router(); + +router.post( + "dataAttributes.info", + auth(), + validate(T.DataAttributesInfoSchema), + async (ctx: APIContext) => { + const { id } = ctx.input.body; + const { user } = ctx.state.auth; + + const dataAttribute = await DataAttribute.findByPk(id, { + rejectOnEmpty: true, + }); + + authorize(user, "read", dataAttribute); + + ctx.body = { + data: presentDataAttribute(dataAttribute), + }; + } +); + +router.post( + "dataAttributes.list", + auth(), + validate(T.DataAttributesListSchema), + pagination(), + async (ctx: APIContext) => { + const { sort, direction } = ctx.input.body; + const { user } = ctx.state.auth; + + const dataAttributes = await DataAttribute.findAll({ + where: { teamId: user.teamId }, + order: [[sort, direction]], + offset: ctx.state.pagination.offset, + limit: ctx.state.pagination.limit, + }); + + ctx.body = { + data: dataAttributes.map(presentDataAttribute), + }; + } +); + +router.post( + "dataAttributes.create", + auth({ role: UserRole.Admin }), + validate(T.DataAttributesCreateSchema), + transaction(), + async (ctx: APIContext) => { + const { name, description, dataType, options, pinned } = ctx.input.body; + const { user } = ctx.state.auth; + const { transaction } = ctx.state; + + const dataAttribute = await DataAttribute.create( + { + name, + description, + createdById: user.id, + teamId: user.teamId, + dataType, + options, + pinned, + }, + { transaction } + ); + + ctx.body = { + data: presentDataAttribute(dataAttribute), + policies: presentPolicies(user, [dataAttribute]), + }; + } +); diff --git a/server/routes/api/dataAttributes/index.ts b/server/routes/api/dataAttributes/index.ts new file mode 100644 index 0000000000..c4f87eba98 --- /dev/null +++ b/server/routes/api/dataAttributes/index.ts @@ -0,0 +1 @@ +export { default } from "./dataAttributes"; diff --git a/server/routes/api/dataAttributes/schema.ts b/server/routes/api/dataAttributes/schema.ts new file mode 100644 index 0000000000..0cc5c3f569 --- /dev/null +++ b/server/routes/api/dataAttributes/schema.ts @@ -0,0 +1,59 @@ +import z from "zod"; +import { DataAttributeDataType } from "@server/models/DataAttribute"; +import { BaseSchema } from "../schema"; + +const BaseIdSchema = z.object({ + /** Id of the data attribute */ + id: z.string().uuid(), +}); + +const DataAttributesSortParamsSchema = z.object({ + /** Specifies the attributes by which data attributes will be sorted in the list */ + sort: z + .string() + .refine((val) => ["createdAt", "updatedAt"].includes(val)) + .default("createdAt"), + + /** Specifies the sort order with respect to sort field */ + direction: z + .string() + .optional() + .transform((val) => (val !== "ASC" ? "DESC" : val)), +}); + +export const DataAttributesInfoSchema = BaseSchema.extend({ + body: BaseIdSchema, +}); + +export type DataAttributesInfoReq = z.infer; + +export const DataAttributesListSchema = BaseSchema.extend({ + body: DataAttributesSortParamsSchema, +}); + +export type DataAttributesListReq = z.infer; + +export const DataAttributesCreateSchema = BaseSchema.extend({ + body: z.object({ + /** Name of the data attribute */ + name: z.string(), + + /** Description of the data attribute */ + description: z.string().optional(), + + /** Type of the data attribute */ + dataType: z.nativeEnum(DataAttributeDataType), + + /** Options for the data attribute (if list type) */ + options: z.object({ + options: z.array(z.string()), + }), + + /** Whether the data attribute is pinned to the top of document */ + pinned: z.boolean().optional(), + }), +}); + +export type DataAttributesCreateReq = z.infer< + typeof DataAttributesCreateSchema +>; diff --git a/shared/validations.ts b/shared/validations.ts index 2110bddc4b..51b4bc928c 100644 --- a/shared/validations.ts +++ b/shared/validations.ts @@ -26,6 +26,13 @@ export const ApiKeyValidation = { maxNameLength: 255, }; +export const DataAttributeValidation = { + /** The minimum length of the name */ + minNameLength: 3, + /** The maximum length of the name */ + maxNameLength: 255, +}; + export const CollectionValidation = { /** The maximum length of the collection description */ maxDescriptionLength: 10 * 1000,