This commit is contained in:
Tom Moor committed 2024-07-24 21:48:52 -04:00
1 parent c23b5d1ef4
commit c636c4e5df
21 files changed
+364 -24

No files matched your search

@@ -0,0 +1,24 @@
import { PlusIcon } from "outline-icons";
import * as React from "react";
import stores from "~/stores";
import { createAction } from "..";
import { SettingsSection } from "../sections";
export const createDataAttribute = createAction({
name: ({ t }) => t("New attribute"),
analyticsName: "New attribute",
section: SettingsSection,
icon: <PlusIcon />,
keywords: "create",
visible: () =>
stores.policies.abilities(stores.auth.team?.id || "").createDataAttribute,
perform: ({ t, event }) => {
event?.preventDefault();
event?.stopPropagation();
stores.dialogs.openModal({
title: t("New attribute"),
// content: TODO
});
},
});
+10
View File
@@ -14,6 +14,7 @@ import {
ImportIcon,
ShapesIcon,
Icon,
DatabaseIcon,
} from "outline-icons";
import React, { ComponentProps } from "react";
import { useTranslation } from "react-i18next";
@@ -29,6 +30,7 @@ import useCurrentUser from "./useCurrentUser";
import usePolicy from "./usePolicy";
const ApiKeys = lazy(() => import("~/scenes/Settings/ApiKeys"));
const DataAttributes = lazy(() => import("~/scenes/Settings/DataAttributes"));
const Details = lazy(() => import("~/scenes/Settings/Details"));
const Export = lazy(() => import("~/scenes/Settings/Export"));
const Features = lazy(() => import("~/scenes/Settings/Features"));
@@ -119,6 +121,14 @@ const useSettingsConfig = () => {
group: t("Workspace"),
icon: BeakerIcon,
},
{
name: t("Attributes"),
path: settingsPath("attributes"),
component: DataAttributes,
enabled: can.createDataAttribute,
group: t("Workspace"),
icon: DatabaseIcon,
},
{
name: t("Members"),
path: settingsPath("members"),
+52
View File
@@ -0,0 +1,52 @@
import { observable } from "mobx";
import {
DataAttributeDataType,
type DataAttributeOptions,
} from "@shared/models/types";
import User from "./User";
import ParanoidModel from "./base/ParanoidModel";
import Field from "./decorators/Field";
import Relation from "./decorators/Relation";
class DataAttribute extends ParanoidModel {
static modelName = "DataAttribute";
/** The name of this data attribute. */
@Field
@observable
name: string;
/** A user-facing description for the data attribute. */
@Field
@observable
description: string | null;
/** The data type of this data attribute. Cannot be changed after creation. */
@Field
@observable
dataType: DataAttributeDataType;
/** Options for `list` data type. */
@Field
@observable
options: DataAttributeOptions | null;
/** Whether this data attribute is pinned to the top of the document. */
@Field
@observable
pinned: boolean;
/** The sort index of this data attribute. */
@Field
@observable
index: number;
/** The user that created this data attribute. */
@Relation(() => User, { onDelete: "cascade" })
createdBy?: User;
/** The user ID that created this data attribute. */
createdById: string;
}
export default DataAttribute;
View File
Whitespace-only changes.
+63
View File
@@ -0,0 +1,63 @@
import { observer } from "mobx-react";
import { DatabaseIcon } from "outline-icons";
import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import DataAttribute from "~/models/DataAttribute";
import { Action } from "~/components/Actions";
import Button from "~/components/Button";
import Heading from "~/components/Heading";
import PaginatedList from "~/components/PaginatedList";
import Scene from "~/components/Scene";
import Text from "~/components/Text";
import { createDataAttribute } from "~/actions/definitions/dataAttributes";
import useActionContext from "~/hooks/useActionContext";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
function DataAttributes() {
const team = useCurrentTeam();
const { t } = useTranslation();
const { dataAttributes } = useStores();
const can = usePolicy(team);
const context = useActionContext();
return (
<Scene
title={t("Attributes")}
icon={<DatabaseIcon />}
actions={
<>
{can.createDataAttribute && (
<Action>
<Button
type="submit"
value={`${t("New Attribute")}…`}
action={createDataAttribute}
context={context}
/>
</Action>
)}
</>
}
>
<Heading>{t("Attributes")}</Heading>
<Text as="p" type="secondary">
<Trans>
Attributes allow you to define data to be stored with your documents.
They can be used to store metadata, tags, or any other structured
data.
</Trans>
</Text>
<PaginatedList
fetch={dataAttributes.fetchPage}
items={dataAttributes.orderedData}
renderItem={(dataAttribute: DataAttribute) => (
<span>{JSON.stringify(dataAttribute)}</span>
)}
/>
</Scene>
);
}
export default observer(DataAttributes);
+30
View File
@@ -0,0 +1,30 @@
import orderBy from "lodash/orderBy";
import { computed } from "mobx";
import DataAttribute from "~/models/DataAttribute";
import RootStore from "./RootStore";
import Store, { RPCAction } from "./base/Store";
export default class DataAttributesStore extends Store<DataAttribute> {
actions = [
RPCAction.List,
RPCAction.Create,
RPCAction.Update,
RPCAction.Delete,
];
constructor(rootStore: RootStore) {
super(rootStore, DataAttribute);
}
@computed
get active(): DataAttribute[] {
return this.orderedData.filter((d) => !d.deletedAt);
}
@computed
get deleted(): DataAttribute[] {
return orderBy(this.orderedData, "deletedAt", "desc").filter(
(d) => d.deletedAt
);
}
}
+3
View File
@@ -6,6 +6,7 @@ import AuthStore from "./AuthStore";
import AuthenticationProvidersStore from "./AuthenticationProvidersStore";
import CollectionsStore from "./CollectionsStore";
import CommentsStore from "./CommentsStore";
import DataAttributesStore from "./DataAttributesStore";
import DialogsStore from "./DialogsStore";
import DocumentPresenceStore from "./DocumentPresenceStore";
import DocumentsStore from "./DocumentsStore";
@@ -39,6 +40,7 @@ export default class RootStore {
groupMemberships: GroupMembershipsStore;
comments: CommentsStore;
dialogs: DialogsStore;
dataAttributes: DataAttributesStore;
documents: DocumentsStore;
events: EventsStore;
groups: GroupsStore;
@@ -68,6 +70,7 @@ export default class RootStore {
this.registerStore(CollectionsStore);
this.registerStore(GroupMembershipsStore);
this.registerStore(CommentsStore);
this.registerStore(DataAttributesStore);
this.registerStore(DocumentsStore);
this.registerStore(EventsStore);
this.registerStore(GroupsStore);
+29 -1
View File
@@ -1,5 +1,5 @@
import { Transaction } from "sequelize";
import { Event, Document, User } from "@server/models";
import { Event, Document, User, DocumentDataAttribute } from "@server/models";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
type Props = {
@@ -7,6 +7,8 @@ type Props = {
user: User;
/** The existing document */
document: Document;
/** Data attributes to apply to the document */
attributes?: Pick<DocumentDataAttribute, "value" | "dataAttributeId">[];
/** The new title */
title?: string;
/** The document icon */
@@ -47,6 +49,7 @@ type Props = {
export default async function documentUpdater({
user,
document,
attributes,
title,
icon,
color,
@@ -65,6 +68,10 @@ export default async function documentUpdater({
const previousTitle = document.title;
const cId = collectionId || document.collectionId;
if (attributes !== undefined) {
await updateDataAttributes(user, document, attributes, { transaction });
}
if (title !== undefined) {
document.title = title.trim();
}
@@ -150,3 +157,24 @@ export default async function documentUpdater({
transaction,
});
}
async function updateDataAttributes(
user: User,
document: Document,
attributes: Pick<DocumentDataAttribute, "value" | "dataAttributeId">[],
{ transaction }: { transaction: Transaction }
) {
await DocumentDataAttribute.destroy({
where: { documentId: document.id },
transaction,
});
await DocumentDataAttribute.bulkCreate(
attributes.map((attribute) => ({
...attribute,
userId: user.id,
documentId: document.id,
})),
{ transaction }
);
}
@@ -25,7 +25,7 @@ module.exports = {
onDelete: "cascade",
references: {
model: "teams",
}
}
},
name: {
type: Sequelize.STRING,
@@ -60,7 +60,7 @@ module.exports = {
type: Sequelize.DATE,
allowNull: false,
},
archivedAt: {
deletedAt: {
type: Sequelize.DATE,
allowNull: true,
},
@@ -68,6 +68,12 @@ module.exports = {
{ transaction }
);
await queryInterface.addIndex(
"data_attributes",
["teamId"],
{ transaction }
);
await queryInterface.createTable(
"document_data_attributes",
{
@@ -76,6 +82,14 @@ module.exports = {
allowNull: false,
primaryKey: true,
},
userId: {
type: Sequelize.UUID,
allowNull: false,
onDelete: "cascade",
references: {
model: "users",
}
},
documentId: {
type: Sequelize.UUID,
allowNull: false,
+28 -16
View File
@@ -8,7 +8,12 @@ import {
IsIn,
DataType,
Default,
BeforeCreate,
} from "sequelize-typescript";
import {
DataAttributeDataType,
type DataAttributeOptions,
} from "@shared/models/types";
import { DataAttributeValidation } from "@shared/validations";
import Team from "./Team";
import User from "./User";
@@ -17,23 +22,17 @@ 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" })
@Table({
tableName: "data_attributes",
modelName: "data_attribute",
paranoid: true,
})
@Fix
class DataAttribute extends ParanoidModel<
InferAttributes<DataAttribute>,
Partial<InferCreationAttributes<DataAttribute>>
> {
/** The name of this data attribute. */
@Length({
min: DataAttributeValidation.minNameLength,
max: DataAttributeValidation.maxNameLength,
@@ -43,30 +42,43 @@ class DataAttribute extends ParanoidModel<
@Column
name: string;
/** A user-facing description for the data attribute. */
@AllowNull
@Column
description: string;
/** The data type of this data attribute. Cannot be changed after creation. */
@IsIn([Object.values(DataAttributeDataType)])
@Column(DataType.ENUM(...Object.values(DataAttributeDataType)))
dataType: DataAttributeDataType;
/** Options for `list` data type. */
@AllowNull
@Column(DataType.JSONB)
options: DataAttributeOptions;
/** Whether this data attribute is pinned to the top of the document. */
@Default(false)
@Column
pinned: boolean;
/** The sort index of this data attribute. */
@Column
index: string;
@AllowNull
@Column
archivedAt: Date | null;
// hooks
@BeforeCreate
static async checkMaximumAttributes(model: DataAttribute) {
const count = await DataAttribute.count({
where: {
teamId: model.teamId,
},
});
if (count >= DataAttributeValidation.max) {
throw new Error("Maximum number of attributes reached");
}
}
// associations
+8
View File
@@ -54,6 +54,7 @@ import { ValidationError } from "@server/errors";
import { generateUrlId } from "@server/utils/url";
import Backlink from "./Backlink";
import Collection from "./Collection";
import DocumentDataAttribute from "./DocumentDataAttribute";
import FileOperation from "./FileOperation";
import Revision from "./Revision";
import Star from "./Star";
@@ -87,6 +88,10 @@ type AdditionalFindOptions = {
as: "updatedBy",
paranoid: false,
},
{
model: DocumentDataAttribute,
as: "dataAttributes",
},
],
where: {
publishedAt: {
@@ -554,6 +559,9 @@ class Document extends ParanoidModel<
@Column(DataType.UUID)
collectionId?: string | null;
@HasMany(() => DocumentDataAttribute)
dataAttributes: DocumentDataAttribute[];
@HasMany(() => UserMembership)
memberships: UserMembership[];
+51
View File
@@ -0,0 +1,51 @@
import { InferAttributes, InferCreationAttributes } from "sequelize";
import {
BelongsTo,
ForeignKey,
Column,
Table,
DataType,
} from "sequelize-typescript";
import DataAttribute from "./DataAttribute";
import Document from "./Document";
import User from "./User";
import Model from "./base/Model";
import Fix from "./decorators/Fix";
@Table({
tableName: "document_data_attributes",
modelName: "document_data_attribute",
})
@Fix
class DocumentDataAttribute extends Model<
InferAttributes<DocumentDataAttribute>,
Partial<InferCreationAttributes<DocumentDataAttribute>>
> {
@Column
value: string;
// associations
@BelongsTo(() => DataAttribute, "dataAttributeId")
dataAttribute: DataAttribute;
@ForeignKey(() => DataAttribute)
@Column(DataType.UUID)
dataAttributeId: string;
@BelongsTo(() => Document, "documentId")
document: Document;
@ForeignKey(() => Document)
@Column(DataType.UUID)
documentId: string;
@BelongsTo(() => User, "userId")
user: User;
@ForeignKey(() => User)
@Column(DataType.UUID)
userId: string;
}
export default DocumentDataAttribute;
+2
View File
@@ -10,6 +10,8 @@ export { default as Collection } from "./Collection";
export { default as DataAttribute } from "./DataAttribute";
export { default as DocumentDataAttribute } from "./DocumentDataAttribute";
export { default as GroupMembership } from "./GroupMembership";
export { default as UserMembership } from "./UserMembership";
+3
View File
@@ -9,6 +9,7 @@ import {
Group,
Notification,
UserMembership,
DataAttribute,
} from "@server/models";
import { _abilities, _can, _cannot, _authorize } from "./cancan";
import "./apiKey";
@@ -16,6 +17,7 @@ import "./attachment";
import "./authenticationProvider";
import "./collection";
import "./comment";
import "./dataAttribute";
import "./document";
import "./fileOperation";
import "./integration";
@@ -54,6 +56,7 @@ export function serialize(
| Attachment
| Collection
| Comment
| DataAttribute
| FileOperation
| Team
| Document
+7 -5
View File
@@ -1,12 +1,14 @@
import DataAttribute from "@server/models/DataAttribute";
import DocumentDataAttribute from "@server/models/DocumentDataAttribute";
export default function presentDataAttribute(dataAttribute: DataAttribute) {
export default function presentDocumentDataAttribute(
dataAttribute: DocumentDataAttribute
) {
return {
id: dataAttribute.id,
name: dataAttribute.name,
description: dataAttribute.description,
value: dataAttribute.value,
dataAttributeId: dataAttribute.dataAttributeId,
documentId: dataAttribute.documentId,
createdAt: dataAttribute.createdAt,
updatedAt: dataAttribute.updatedAt,
archivedAt: dataAttribute.archivedAt,
};
}
+4
View File
@@ -3,6 +3,7 @@ import { Document } from "@server/models";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
import { TextHelper } from "@server/models/helpers/TextHelper";
import { APIContext } from "@server/types";
import presentDocumentDataAttribute from "./dataAttribute";
import presentUser from "./user";
type Options = {
@@ -76,6 +77,9 @@ async function presentDocument(
if (!options.isPublic) {
const source = await document.$get("import");
data.dataAttributes = document.dataAttributes?.map(
presentDocumentDataAttribute(dataAttribute)
) ?? [];
data.isCollectionDeleted = await document.isCollectionDeleted();
data.collectionId = document.collectionId;
data.parentDocumentId = document.parentDocumentId;
@@ -0,0 +1,15 @@
import DataAttribute from "@server/models/DataAttribute";
export default function presentDataAttribute(dataAttribute: DataAttribute) {
return {
id: dataAttribute.id,
name: dataAttribute.name,
description: dataAttribute.description,
dataType: dataAttribute.dataType,
options: dataAttribute.options,
pinned: dataAttribute.pinned,
createdAt: dataAttribute.createdAt,
updatedAt: dataAttribute.updatedAt,
deletedAt: dataAttribute.deletedAt,
};
}
@@ -83,3 +83,5 @@ router.post(
};
}
);
export default router;
+2
View File
@@ -14,6 +14,7 @@ import authenticationProviders from "./authenticationProviders";
import collections from "./collections";
import comments from "./comments/comments";
import cron from "./cron";
import dataAttributes from "./dataAttributes";
import developer from "./developer";
import documents from "./documents";
import events from "./events";
@@ -70,6 +71,7 @@ router.use("/", events.routes());
router.use("/", users.routes());
router.use("/", collections.routes());
router.use("/", comments.routes());
router.use("/", dataAttributes.routes());
router.use("/", documents.routes());
router.use("/", pins.routes());
router.use("/", revisions.routes());
+10
View File
@@ -0,0 +1,10 @@
export enum DataAttributeDataType {
String = "string",
Integer = "integer",
Boolean = "boolean",
List = "list",
}
export type DataAttributeOptions = {
options: string[];
};
+5
View File
@@ -22,6 +22,7 @@ export const AttachmentValidation = {
export const ApiKeyValidation = {
/** The minimum length of the API key name */
minNameLength: 3,
/** The maximum length of the API key name */
maxNameLength: 255,
};
@@ -29,8 +30,12 @@ export const ApiKeyValidation = {
export const DataAttributeValidation = {
/** The minimum length of the name */
minNameLength: 3,
/** The maximum length of the name */
maxNameLength: 255,
/** The maximum number of data attributes */
max: 25,
};
export const CollectionValidation = {