From fe50488c97aa6ca5977e2ddb257c83c14c5e0a8b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 6 Nov 2026 08:05:31 -0500 Subject: [PATCH] feat: Allow selecting a destination when importing (#14486) * feat: allow selecting import destination * fix: address import destination review findings * feat: multi-step import dialog with workspace root location - Import dialog is now upload then location, the same height as the move dialog - Document explorer lists the workspace as the root and marks the selected row - A document export with a sibling folder merges into one document, or becomes the collection overview when creating new collections - Destination document checks now rely on the createChildDocument policy * fix: delete archived imported documents and read legacy task inputs - Deleting an import now removes the children of archived imported documents - Tasks queued before the rename to rootExternalId are still assigned correctly --- .../DocumentExplorer/DocumentExplorer.tsx | 5 + .../DocumentExplorer/DocumentExplorerNode.tsx | 6 + .../DocumentExplorerSearchResult.tsx | 3 +- app/models/Import.ts | 6 + .../Settings/components/DropToImport.tsx | 127 +++-- .../Settings/components/ImportJSONDialog.tsx | 40 +- .../components/ImportMarkdownDialog.tsx | 38 +- .../Settings/components/ImportOKFDialog.tsx | 34 +- .../Settings/components/ImportRootPicker.tsx | 163 ++++++ .../Settings/components/ImportSteps.tsx | 147 +++++ .../notion/client/components/ImportDialog.tsx | 91 +-- .../server/tasks/NotionAPIImportTask.ts | 13 +- .../client/components/ImportSlabDialog.tsx | 36 +- .../20260724145212-add-imports-destination.js | 49 ++ server/models/Import.ts | 18 + server/presenters/import.ts | 2 + server/queues/processors/ImportsProcessor.ts | 522 ++++++++++++++---- server/queues/tasks/JSONAPIImportTask.test.ts | 276 ++++++++- server/queues/tasks/JSONAPIImportTask.ts | 6 +- .../tasks/MarkdownAPIImportTask.test.ts | 372 +++++++++++++ server/queues/tasks/MarkdownAPIImportTask.ts | 239 +++++--- server/routes/api/imports/imports.test.ts | 234 +++++++- server/routes/api/imports/imports.ts | 47 +- server/routes/api/imports/schema.ts | 53 +- shared/i18n/locales/en_US/translation.json | 4 +- shared/schema.ts | 13 + 26 files changed, 2137 insertions(+), 407 deletions(-) create mode 100644 app/scenes/Settings/components/ImportRootPicker.tsx create mode 100644 app/scenes/Settings/components/ImportSteps.tsx create mode 100644 server/migrations/20260724145212-add-imports-destination.js diff --git a/app/components/DocumentExplorer/DocumentExplorer.tsx b/app/components/DocumentExplorer/DocumentExplorer.tsx index 44d3cbc0c8..454c23eb01 100644 --- a/app/components/DocumentExplorer/DocumentExplorer.tsx +++ b/app/components/DocumentExplorer/DocumentExplorer.tsx @@ -40,6 +40,8 @@ type Props = { defaultValue?: string; /** Whether to show child documents */ showDocuments?: boolean; + /** Overrides the icon of a node, return undefined to keep the default. */ + renderIcon?: (node: NavigationNode) => React.ReactNode; }; const VERTICAL_PADDING = 6; @@ -62,6 +64,7 @@ function DocumentExplorer({ items, defaultValue, showDocuments, + renderIcon, }: Props) { const isMobile = useMobile(); const { collections, documents } = useStores(); @@ -313,6 +316,8 @@ function DocumentExplorer({ .join(" / "); } + renderedIcon = renderIcon?.(node) ?? renderedIcon; + return deferredSearchTerm ? ( {icon} {title || t("Untitled")} + {selected && } ); } +export const SelectedIcon = styled(CheckmarkIcon)` + margin-left: auto; +`; + const Title = styled(Text)` ${ellipsis()} margin: 0 4px 0 4px; diff --git a/app/components/DocumentExplorer/DocumentExplorerSearchResult.tsx b/app/components/DocumentExplorer/DocumentExplorerSearchResult.tsx index 38d5449080..ad751487b1 100644 --- a/app/components/DocumentExplorer/DocumentExplorerSearchResult.tsx +++ b/app/components/DocumentExplorer/DocumentExplorerSearchResult.tsx @@ -3,7 +3,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import { ellipsis } from "@shared/styles"; -import { Node as SearchResult } from "./DocumentExplorerNode"; +import { Node as SearchResult, SelectedIcon } from "./DocumentExplorerNode"; import Flex from "~/components/Flex"; import Text from "~/components/Text"; @@ -51,6 +51,7 @@ function DocumentExplorerSearchResult({ {path} + {selected && } ); } diff --git a/app/models/Import.ts b/app/models/Import.ts index 3a62283ba4..26d100466a 100644 --- a/app/models/Import.ts +++ b/app/models/Import.ts @@ -35,6 +35,12 @@ class Import extends Model { @observable documentCount: number; + /** The existing collection to import into, if any. */ + collectionId: string | null; + + /** The existing document to import under, if any. */ + documentId: string | null; + /** The user who created the import. */ @Relation(() => User, {}) createdBy: User; diff --git a/app/scenes/Settings/components/DropToImport.tsx b/app/scenes/Settings/components/DropToImport.tsx index ac95799450..06dbe92ab8 100644 --- a/app/scenes/Settings/components/DropToImport.tsx +++ b/app/scenes/Settings/components/DropToImport.tsx @@ -12,21 +12,22 @@ import { type ImportableIntegrationService, } from "@shared/types"; import { bytesToHumanReadable } from "@shared/utils/files"; -import Button from "~/components/Button"; import { DropzoneContainer, dropzoneIcon, } from "~/components/DropzoneContainer"; import Flex from "~/components/Flex"; -import { InputSelectPermission } from "~/components/InputSelectPermission"; import LoadingIndicator from "~/components/LoadingIndicator"; import Text from "~/components/Text"; import useStores from "~/hooks/useStores"; -import { EmptySelectValue } from "~/types"; import { uploadFile } from "~/utils/files"; +import type { ImportOptions } from "./ImportSteps"; +import { ImportSteps } from "./ImportSteps"; type Props = { children: React.JSX.Element; + /** Explains what the file should contain, shown above the dropzone. */ + description?: React.ReactNode; /** The importable service to create an import for. */ service: ImportableIntegrationService; disabled?: boolean; @@ -34,15 +35,18 @@ type Props = { onSubmit: () => void; }; -function DropToImport({ disabled, onSubmit, children, service }: Props) { +function DropToImport({ + disabled, + onSubmit, + children, + description, + service, +}: Props) { const { t } = useTranslation(); const { imports } = useStores(); const [file, setFile] = useState(null); const [isImporting, setImporting] = useState(false); const [uploadProgress, setUploadProgress] = useState(0); - const [permission, setPermission] = useState( - CollectionPermission.ReadWrite - ); const handleFiles = (files: File[]) => { if (files.length > 1) { @@ -52,7 +56,10 @@ function DropToImport({ disabled, onSubmit, children, service }: Props) { setFile(files[0]); }; - const handleStartImport = async () => { + const handleStartImport = async ({ + destination, + permission, + }: ImportOptions) => { if (!file) { return; } @@ -70,7 +77,8 @@ function DropToImport({ disabled, onSubmit, children, service }: Props) { { service }, { attachmentId: attachment.id, - permission: permission ?? undefined, + permission, + ...destination, } ); @@ -97,57 +105,48 @@ function DropToImport({ disabled, onSubmit, children, service }: Props) { } return ( - + <> {isImporting && } - - - {({ getRootProps, getInputProps, isDragActive }) => ( - - - - - {file - ? t(`${file.name} (${bytesToHumanReadable(file.size)})`) - : children} - - - )} - - -
- { - setPermission(value === EmptySelectValue ? null : value); - }} - /> - - {t( - "Set the default permission level for collections created from the import" - )} - . - -
- - - -
+ + {description} + + + {({ getRootProps, getInputProps, isDragActive }) => ( + + + + + {file + ? t(`${file.name} (${bytesToHumanReadable(file.size)})`) + : children} + + + )} + + + + } + canContinue={!!file} + defaultPermission={CollectionPermission.ReadWrite} + isSubmitting={isImporting} + submittingLabel={t("Uploading {{progress}}%", { + progress: Math.min(99, Math.floor(uploadProgress * 100)), + })} + onStart={handleStartImport} + /> + ); } @@ -160,7 +159,17 @@ const Icon = styled(NewDocumentIcon)` ${dropzoneIcon} `; +const DropzoneText = styled(Text)` + display: flex; + flex: 1; + margin-bottom: 12px; +`; + const Container = styled(DropzoneContainer)` + display: flex; + flex: 1; + align-items: center; + justify-content: center; padding: 52px; `; diff --git a/app/scenes/Settings/components/ImportJSONDialog.tsx b/app/scenes/Settings/components/ImportJSONDialog.tsx index 5aee6e8749..f2a95b75fd 100644 --- a/app/scenes/Settings/components/ImportJSONDialog.tsx +++ b/app/scenes/Settings/components/ImportJSONDialog.tsx @@ -10,26 +10,26 @@ function ImportJSONDialog() { const appName = env.APP_NAME; return ( - <> - - , - }} - /> - - - - Drag and drop the zip file from the JSON export option in{" "} - {{ appName }}, or click to upload - - - + + , + }} + /> + + } + onSubmit={dialogs.closeAllModals} + service={IntegrationService.JSON} + > + + Drag and drop the zip file from the JSON export option in {{ appName }}, + or click to upload + + ); } diff --git a/app/scenes/Settings/components/ImportMarkdownDialog.tsx b/app/scenes/Settings/components/ImportMarkdownDialog.tsx index a11ddaddec..7aba1f0b5e 100644 --- a/app/scenes/Settings/components/ImportMarkdownDialog.tsx +++ b/app/scenes/Settings/components/ImportMarkdownDialog.tsx @@ -10,25 +10,25 @@ function ImportMarkdownDialog() { const appName = env.APP_NAME; return ( - <> - - , - }} - /> - - - - Drag and drop the zip file from the Markdown export option in{" "} - {{ appName }}, or click to upload - - - + + , + }} + /> + + } + onSubmit={dialogs.closeAllModals} + service={IntegrationService.Markdown} + > + + Drag and drop the zip file from the Markdown export option in{" "} + {{ appName }}, or click to upload + + ); } diff --git a/app/scenes/Settings/components/ImportOKFDialog.tsx b/app/scenes/Settings/components/ImportOKFDialog.tsx index c3648e6297..1d81dc22b9 100644 --- a/app/scenes/Settings/components/ImportOKFDialog.tsx +++ b/app/scenes/Settings/components/ImportOKFDialog.tsx @@ -8,23 +8,23 @@ function ImportOKFDialog() { const { dialogs } = useStores(); return ( - <> - - - You can import a zip file of an Open Knowledge Format (OKF) bundle – - folders become collections and documents, and document titles are read - from YAML frontmatter. - - - - - Drag and drop a zip file of the OKF bundle, or click to upload - - - + + + You can import a zip file of an Open Knowledge Format (OKF) bundle – + folders become collections and documents, and document titles are + read from YAML frontmatter. + + + } + onSubmit={dialogs.closeAllModals} + service={IntegrationService.OKF} + > + + Drag and drop a zip file of the OKF bundle, or click to upload + + ); } diff --git a/app/scenes/Settings/components/ImportRootPicker.tsx b/app/scenes/Settings/components/ImportRootPicker.tsx new file mode 100644 index 0000000000..fe84422791 --- /dev/null +++ b/app/scenes/Settings/components/ImportRootPicker.tsx @@ -0,0 +1,163 @@ +import { observer } from "mobx-react"; +import { useCallback, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import styled from "styled-components"; +import type { NavigationNode } from "@shared/types"; +import { NavigationNodeType } from "@shared/types"; +import { AvatarSize } from "~/components/Avatar"; +import DocumentExplorer from "~/components/DocumentExplorer"; +import Text from "~/components/Text"; +import Flex from "~/components/Flex"; +import TeamLogo from "~/components/TeamLogo"; +import useCollectionTrees from "~/hooks/useCollectionTrees"; +import useCurrentTeam from "~/hooks/useCurrentTeam"; +import useStores from "~/hooks/useStores"; + +/** The chosen import destination — a collection or a document, never both. */ +export type ImportDestination = + | { collectionId: string; documentId?: undefined } + | { documentId: string; collectionId?: undefined }; + +/** The location that creates new collections for the import. */ +export const NewCollections = "new-collections"; + +/** The chosen import location. */ +export type ImportLocation = typeof NewCollections | ImportDestination; + +type Props = { + /** The location that is initially selected. */ + defaultValue: ImportLocation | null; + /** Called whenever the location changes, `null` means nothing is selected. */ + onChange: (location: ImportLocation | null) => void; +}; + +/** + * Lets the user pick the location for a workspace import: the workspace itself, + * which creates new collections, or an existing collection or document. Shared + * by every import dialog. + */ +function ImportRootPicker({ defaultValue, onChange }: Props) { + const { t } = useTranslation(); + const { policies } = useStores(); + const team = useCurrentTeam(); + const collectionTrees = useCollectionTrees(); + // The explorer scrolls to its default value whenever it changes, so it is + // only read on mount. + const [initialId] = useState(() => + defaultValue === NewCollections + ? NewCollections + : (defaultValue?.collectionId ?? defaultValue?.documentId) + ); + + // Only offer collections the user can create documents in; documents nested + // within them inherit selectability and the server enforces the rest. + const options = useMemo(() => { + const newCollections: NavigationNode = { + id: NewCollections, + title: team.name, + url: "", + type: NavigationNodeType.Document, + // A depth of zero places this row one level left of the collections. + depth: 0, + parent: null, + children: [], + }; + + return [ + newCollections, + ...collectionTrees.filter((node) => + node.collectionId + ? policies.get(node.collectionId)?.abilities.createDocument + : true + ), + ]; + }, [team.name, policies, collectionTrees]); + + const handleSelect = useCallback( + (node: NavigationNode | null) => { + if (!node) { + onChange(null); + return; + } + if (node.id === NewCollections) { + onChange(NewCollections); + return; + } + onChange( + node.type === NavigationNodeType.Collection + ? { collectionId: node.id } + : { documentId: node.id } + ); + }, + [onChange] + ); + + const renderIcon = useCallback( + (node: NavigationNode) => + node.id === NewCollections ? ( + + + + ) : undefined, + [team] + ); + + return ( + + + {t( + "Choose an existing location to import into, or new collections will be created." + )} + + + + + + ); +} + +// Matches the size of the other icons in the explorer. +const LogoContainer = styled(Flex)` + width: 24px; + height: 24px; + flex-shrink: 0; +`; + +const Container = styled(Flex)` + flex: 1; + min-height: 0; +`; + +const ExplorerContainer = styled.div` + display: flex; + flex: 1; + min-height: 0; + margin-left: -24px; + margin-right: -24px; + + // The explorer sizes its list to the viewport, here it fills the space left. + > div { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; + } + + > div > :first-child { + flex: none; + } + + > div > div:last-child { + flex: 1; + height: auto; + min-height: 0; + } +`; + +export default observer(ImportRootPicker); diff --git a/app/scenes/Settings/components/ImportSteps.tsx b/app/scenes/Settings/components/ImportSteps.tsx new file mode 100644 index 0000000000..9d97a21555 --- /dev/null +++ b/app/scenes/Settings/components/ImportSteps.tsx @@ -0,0 +1,147 @@ +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import styled from "styled-components"; +import { breakpoint } from "@shared/styles/breakpoint"; +import type { CollectionPermission } from "@shared/types"; +import Button from "~/components/Button"; +import Flex from "~/components/Flex"; +import { InputSelectPermission } from "~/components/InputSelectPermission"; +import { EmptySelectValue } from "~/types"; +import type { ImportDestination, ImportLocation } from "./ImportRootPicker"; +import ImportRootPicker, { NewCollections } from "./ImportRootPicker"; + +/** The options chosen by the user in the import steps. */ +export interface ImportOptions { + /** The chosen destination, or null to create new collections. */ + destination: ImportDestination | null; + /** The permission for new collections, always unset with a destination. */ + permission?: CollectionPermission; +} + +enum Step { + Upload = "upload", + Location = "location", +} + +interface Props { + /** The content of the first step, omit when the import has no upload. */ + upload?: React.ReactNode; + /** Whether the upload step is complete. */ + canContinue?: boolean; + /** The permission that is initially selected. */ + defaultPermission?: CollectionPermission; + /** Whether the import is being started. */ + isSubmitting: boolean; + /** The button label to show while the import is being started. */ + submittingLabel: string; + /** Called when the user starts the import. */ + onStart: (options: ImportOptions) => void; +} + +/** + * Walks the user through the steps to start an import within a single dialog: + * the upload (when there is one), then the location. The location is either new + * collections, which also need a default permission, or an existing collection + * or document. + * + * @param props The component props. + * @returns The rendered steps. + */ +export function ImportSteps({ + upload, + canContinue = true, + defaultPermission, + isSubmitting, + submittingLabel, + onStart, +}: Props) { + const { t } = useTranslation(); + const [step, setStep] = useState(upload ? Step.Upload : Step.Location); + const [location, setLocation] = useState( + NewCollections + ); + const [permission, setPermission] = useState(defaultPermission); + + const isNewCollections = location === NewCollections; + const canSubmit = step === Step.Upload ? canContinue : !!location; + + const handleBack = () => { + setStep(Step.Upload); + }; + + const handleContinue = () => { + if (step === Step.Upload) { + setStep(Step.Location); + return; + } + if (!location) { + return; + } + onStart( + location === NewCollections + ? { destination: null, permission } + : { destination: location } + ); + }; + + const handlePermissionChange = ( + value: CollectionPermission | typeof EmptySelectValue + ) => { + setPermission(value === EmptySelectValue ? undefined : value); + }; + + return ( + + {step === Step.Upload && upload} + {step === Step.Location && ( + <> + +
+ {isNewCollections ? ( + + ) : null} +
+ + )} +
+ {upload && step === Step.Location && ( + + )} + +
+
+ ); +} + +// Matches the content height of the document move dialog, which is the height +// of the explorer list plus its search input and footer. +const Container = styled(Flex)<{ $fixedHeight: boolean }>` + --import-steps-height: calc(65vh + 76px); + min-height: var(--import-steps-height); + height: ${(props) => + props.$fixedHeight ? "var(--import-steps-height)" : "auto"}; + + ${breakpoint("tablet")` + --import-steps-height: max(calc(40vh + 76px), 340px); + `} +`; + +const Footer = styled(Flex)` + flex-shrink: 0; + margin-top: auto; +`; diff --git a/plugins/notion/client/components/ImportDialog.tsx b/plugins/notion/client/components/ImportDialog.tsx index 5c36edb442..969677ebf6 100644 --- a/plugins/notion/client/components/ImportDialog.tsx +++ b/plugins/notion/client/components/ImportDialog.tsx @@ -3,15 +3,11 @@ import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import { errToString } from "@shared/utils/error"; import type { ImportInput } from "@shared/schema"; -import type { CollectionPermission } from "@shared/types"; import { IntegrationService } from "@shared/types"; -import Button from "~/components/Button"; -import Flex from "~/components/Flex"; -import { InputSelectPermission } from "~/components/InputSelectPermission"; -import Text from "~/components/Text"; import useBoolean from "~/hooks/useBoolean"; import useStores from "~/hooks/useStores"; -import { EmptySelectValue } from "~/types"; +import type { ImportOptions } from "~/scenes/Settings/components/ImportSteps"; +import { ImportSteps } from "~/scenes/Settings/components/ImportSteps"; type Props = { /** The integrationId associated with this import flow. */ @@ -24,65 +20,38 @@ export function ImportDialog({ integrationId, onSubmit }: Props) { const { t } = useTranslation(); const { imports } = useStores(); const [submitting, setSubmitting, resetSubmitting] = useBoolean(); - const [permission, setPermission] = React.useState(); - const handlePermissionChange = React.useCallback( - (value: CollectionPermission | typeof EmptySelectValue) => { - setPermission(value === EmptySelectValue ? undefined : value); + const handleStartImport = React.useCallback( + async ({ destination, permission }: ImportOptions) => { + setSubmitting(); + + // Root pages are fetched on the server to avoid Notion search timeouts. + const input: ImportInput = [{ permission }]; + + try { + await imports.create( + { service: IntegrationService.Notion }, + { integrationId, input, ...destination } + ); + + toast.success( + t("Your import is being processed, you can safely leave this page") + ); + + onSubmit(); + } catch (err) { + toast.error(errToString(err)); + resetSubmitting(); + } }, - [] + [onSubmit, integrationId, t, imports, resetSubmitting, setSubmitting] ); - const handleStartImport = React.useCallback(async () => { - setSubmitting(); - - // Root pages are fetched on the server to avoid Notion search timeouts. - const input: ImportInput = [{ permission }]; - - try { - await imports.create( - { service: IntegrationService.Notion }, - { integrationId, input } - ); - - toast.success( - t("Your import is being processed, you can safely leave this page") - ); - - onSubmit(); - } catch (err) { - toast.error(errToString(err)); - resetSubmitting(); - } - }, [ - permission, - onSubmit, - integrationId, - t, - imports, - resetSubmitting, - setSubmitting, - ]); - return ( - -
- - - {t( - "Set the default permission level for collections created from the import" - )} - . - -
- - - -
+ ); } diff --git a/plugins/notion/server/tasks/NotionAPIImportTask.ts b/plugins/notion/server/tasks/NotionAPIImportTask.ts index 6ab2dc554f..e97845ec0b 100644 --- a/plugins/notion/server/tasks/NotionAPIImportTask.ts +++ b/plugins/notion/server/tasks/NotionAPIImportTask.ts @@ -18,7 +18,7 @@ import { NotionConverter } from "../utils/NotionConverter"; type ChildPage = { type: PageType; externalId: string }; type ParsePageOutput = ImportTaskOutput[number] & { - collectionExternalId?: string; + rootExternalId?: string; children: ChildPage[]; }; @@ -95,7 +95,7 @@ export default class NotionAPIImportTask extends APIImportTask[number]; client: NotionClient; }): Promise { - const collectionExternalId = item.collectionExternalId ?? item.externalId; + const rootExternalId = + item.rootExternalId ?? item.collectionExternalId ?? item.externalId; const titleMaxLength = - item.externalId === collectionExternalId // This means it's a root page which will be imported as a collection + item.externalId === rootExternalId // This means it's a root page (materialized as a collection or root document) ? CollectionValidation.maxNameLength : DocumentValidation.maxTitleLength; @@ -149,7 +150,7 @@ export default class NotionAPIImportTask extends APIImportTask ({ type: page.type, externalId: page.id, @@ -167,7 +168,7 @@ export default class NotionAPIImportTask extends APIImportTask - - - Import a zip file of Markdown documents exported from Slab – - collections, posts, images, and attachments will be imported. In Slab, - open the admin settings and use the Export option to download - an archive of your content. - - - - - Drag and drop the zip file exported from Slab, or click to upload - - - + + + Import a zip file of Markdown documents exported from Slab – + collections, posts, images, and attachments will be imported. In + Slab, open the admin settings and use the Export option to + download an archive of your content. + + + } + onSubmit={dialogs.closeAllModals} + service={IntegrationService.Slab} + > + + Drag and drop the zip file exported from Slab, or click to upload + + ); } diff --git a/server/migrations/20260724145212-add-imports-destination.js b/server/migrations/20260724145212-add-imports-destination.js new file mode 100644 index 0000000000..da32c0e6a3 --- /dev/null +++ b/server/migrations/20260724145212-add-imports-destination.js @@ -0,0 +1,49 @@ +"use strict"; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface, Sequelize) { + return queryInterface.sequelize.transaction(async (transaction) => { + await queryInterface.addColumn( + "imports", + "collectionId", + { + type: Sequelize.UUID, + allowNull: true, + references: { + model: "collections", + key: "id", + }, + onDelete: "SET NULL", + }, + { transaction } + ); + + await queryInterface.addColumn( + "imports", + "documentId", + { + type: Sequelize.UUID, + allowNull: true, + references: { + model: "documents", + key: "id", + }, + onDelete: "SET NULL", + }, + { transaction } + ); + }); + }, + + async down(queryInterface) { + return queryInterface.sequelize.transaction(async (transaction) => { + await queryInterface.removeColumn("imports", "collectionId", { + transaction, + }); + await queryInterface.removeColumn("imports", "documentId", { + transaction, + }); + }); + }, +}; diff --git a/server/models/Import.ts b/server/models/Import.ts index b53ea2e0bf..ddab94b8ae 100644 --- a/server/models/Import.ts +++ b/server/models/Import.ts @@ -21,6 +21,8 @@ import { ImportableIntegrationService, ImportState } from "@shared/types"; import { ImportValidation } from "@shared/validations"; import { UnprocessableEntityError } from "@server/errors"; import { LockHelper } from "@server/storage/LockHelper"; +import Collection from "./Collection"; +import Document from "./Document"; import Integration from "./Integration"; import Team from "./Team"; import User from "./User"; @@ -97,6 +99,22 @@ class Import extends ParanoidModel< @Column(DataType.UUID) teamId: string; + @BelongsTo(() => Collection, "collectionId") + collection: Collection | null; + + @AllowNull + @ForeignKey(() => Collection) + @Column(DataType.UUID) + collectionId: string | null; + + @BelongsTo(() => Document, "documentId") + document: Document | null; + + @AllowNull + @ForeignKey(() => Document) + @Column(DataType.UUID) + documentId: string | null; + /** * Serializes imports per team — blocks creation while another import is * already in flight. Centralizing the check here lets every code path that diff --git a/server/presenters/import.ts b/server/presenters/import.ts index 4a91e3e47d..46195edca9 100644 --- a/server/presenters/import.ts +++ b/server/presenters/import.ts @@ -11,6 +11,8 @@ export default function presentImport( service: importModel.service, state: importModel.state, documentCount: importModel.documentCount, + collectionId: importModel.collectionId, + documentId: importModel.documentId, error: importModel.error, createdBy: presentUser(importModel.createdBy), createdById: importModel.createdById, diff --git a/server/queues/processors/ImportsProcessor.ts b/server/queues/processors/ImportsProcessor.ts index 629a0a1f65..285c939c67 100644 --- a/server/queues/processors/ImportsProcessor.ts +++ b/server/queues/processors/ImportsProcessor.ts @@ -2,7 +2,7 @@ import fractionalIndex from "fractional-index"; import { chunk, keyBy, truncate } from "es-toolkit/compat"; import { Fragment, Node } from "prosemirror-model"; import type { CreateOptions, CreationAttributes, Transaction } from "sequelize"; -import { UniqueConstraintError } from "sequelize"; +import { Op, UniqueConstraintError } from "sequelize"; import { randomUUID } from "node:crypto"; import { randomElement } from "@shared/random"; import type { @@ -27,10 +27,19 @@ import { colorPalette } from "@shared/constants"; import { UrlHelper } from "@shared/utils/UrlHelper"; import { errToString } from "@shared/utils/error"; import { CollectionValidation } from "@shared/validations"; +import documentMover from "@server/commands/documentMover"; import { createContext } from "@server/context"; import { schema } from "@server/editor"; import Logger from "@server/logging/Logger"; -import { Attachment, Collection, Document, Import, User } from "@server/models"; +import { + Attachment, + Collection, + Document, + GroupMembership, + Import, + User, + UserMembership, +} from "@server/models"; import type { ImportTaskAttributes, ImportTaskCreationAttributes, @@ -46,6 +55,16 @@ import BaseProcessor from "./BaseProcessor"; export const PagePerImportTask = 3; +/** + * Resolved import destination. When present, root nodes are materialized as + * documents under `collection` (at its root, or nested beneath `document`) + * rather than as new collections. + */ +type ImportDestination = { + collection: Collection; + document?: Document; +}; + export default abstract class ImportsProcessor< T extends ImportableIntegrationService, > extends BaseProcessor { @@ -197,36 +216,81 @@ export default abstract class ImportsProcessor< transaction: Transaction ): Promise { try { - const { collections } = await this.createCollectionsAndDocuments({ - importModel, - transaction, - }); + const { collections, destination } = + await this.createCollectionsAndDocuments({ + importModel, + transaction, + }); - // Once all collections and documents are created, update collection's document structure. - // This ensures the root documents have the whole subtree available in the structure. - for (const collection of collections) { + if (destination) { + // Import targeted an existing destination — no collections were + // created. Append each top-of-import document (parented to the + // destination document, or the collection root) into the destination + // collection's structure. addDocumentToStructure pulls the whole + // subtree, so only the top-level rows need iterating. await Document.unscoped().findAllInBatches( { - where: { parentDocumentId: null, collectionId: collection.id }, + where: { + apiImportId: importModel.id, + collectionId: destination.collection.id, + parentDocumentId: destination.document?.id ?? null, + }, order: [ - ["createdAt", "DESC"], + ["createdAt", "ASC"], ["id", "ASC"], ], transaction, }, async (documents) => { for (const document of documents) { - await collection.addDocumentToStructure(document, undefined, { - save: false, - silent: true, - transaction, - insertOrder: "append", - }); + await destination.collection.addDocumentToStructure( + document, + undefined, + { + save: false, + transaction, + insertOrder: "append", + } + ); } } ); - await collection.save({ silent: true, transaction }); + // Save with a ctx event (not silent) so WebsocketsProcessor pushes the + // refreshed structure to clients — a pre-existing collection receives + // no `collections.create` event. + await destination.collection.saveWithCtx( + createContext({ user: importModel.createdBy, transaction }), + undefined, + { name: "update" } + ); + } else { + // Once all collections and documents are created, update collection's document structure. + // This ensures the root documents have the whole subtree available in the structure. + for (const collection of collections) { + await Document.unscoped().findAllInBatches( + { + where: { parentDocumentId: null, collectionId: collection.id }, + order: [ + ["createdAt", "DESC"], + ["id", "ASC"], + ], + transaction, + }, + async (documents) => { + for (const document of documents) { + await collection.addDocumentToStructure(document, undefined, { + save: false, + silent: true, + transaction, + insertOrder: "append", + }); + } + } + ); + + await collection.save({ silent: true, transaction }); + } } const storageKey = importModel.scratch?.storageKey; @@ -290,6 +354,10 @@ export default abstract class ImportsProcessor< transaction, }); + const ctx = createContext({ user, ip: event.ip, transaction }); + + // Collections created by this import (destination mode creates none — a + // pre-existing destination collection has no apiImportId, so it's skipped). const collections = await Collection.findAll({ transaction, lock: transaction.LOCK.NO_KEY_UPDATE, @@ -303,18 +371,110 @@ export default abstract class ImportsProcessor< Logger.debug("processor", "Destroying collection created from import", { collectionId: collection.id, }); - await collection.destroyWithCtx( - createContext({ user, ip: event.ip, transaction }) - ); + await collection.destroyWithCtx(ctx); + } + + // Documents created by this import that live in a pre-existing destination + // (the destination itself has no apiImportId, so it survives). + const created = await Document.unscoped().findAll({ + attributes: ["id", "collectionId", "parentDocumentId"], + transaction, + where: { + teamId: importModel.teamId, + apiImportId: importModel.id, + }, + }); + + if (created.length === 0) { + return; + } + + const importedIds = new Set(created.map((doc) => doc.id)); + const importedById = new Map( + created.map((document) => [document.id, document]) + ); + + // Lock every affected collection before inspecting descendants. This + // prevents a concurrent move or publish from changing the document tree + // while unrelated subtrees are moved away from documents being deleted. + const collectionIds = [ + ...new Set( + created.flatMap((document) => + document.collectionId ? [document.collectionId] : [] + ) + ), + ].sort(); + for (const collectionId of collectionIds) { + await Collection.findByPk(collectionId, { + includeDocumentStructure: true, + lock: transaction.LOCK.NO_KEY_UPDATE, + paranoid: false, + transaction, + }); + } + + // A document added below imported content after the import completed must + // survive deletion of the import. Move each such subtree to the nearest + // parent that was not created by this import before deleting imported rows. + const children = await Document.unscoped().findAll({ + transaction, + lock: transaction.LOCK.NO_KEY_UPDATE, + where: { + parentDocumentId: { [Op.in]: [...importedIds] }, + }, + }); + const unrelatedChildren = children.filter( + (document) => document.apiImportId !== importModel.id + ); + + for (const document of unrelatedChildren) { + let parentDocumentId = document.parentDocumentId; + while (parentDocumentId && importedIds.has(parentDocumentId)) { + const importedParent = importedById.get(parentDocumentId); + if (!importedParent) { + break; + } + parentDocumentId = importedParent.parentDocumentId; + } + + await documentMover(ctx, { + document, + collectionId: document.collectionId ?? null, + parentDocumentId, + }); + } + + const topLevelIds = created + .filter( + (doc) => !doc.parentDocumentId || !importedIds.has(doc.parentDocumentId) + ) + .map((doc) => doc.id); + + // Deleting an archived document does not cascade, so every imported id is + // visited. Top-level ids go first, and cascaded documents are skipped below. + for (const id of new Set([...topLevelIds, ...importedIds])) { + const document = await Document.findByPk(id, { + userId: user.id, + transaction, + }); + if (!document) { + continue; + } + Logger.debug("processor", "Destroying document created from import", { + documentId: document.id, + }); + await document.destroyWithCtx(ctx); } } /** - * Create collections and documents associated with the import. + * Create the collections and documents associated with the import. Root + * nodes materialize as new collections by default, or as documents under an + * existing destination when the import specifies one. * * @param importModel Import model associated with the event. * @param transaction Sequelize transaction. - * @returns Promise of collection models that are created. + * @returns Promise of the created collections and the resolved destination. */ private async createCollectionsAndDocuments({ importModel, @@ -322,7 +482,10 @@ export default abstract class ImportsProcessor< }: { importModel: Import; transaction: Transaction; - }): Promise<{ collections: Collection[] }> { + }): Promise<{ + collections: Collection[]; + destination: ImportDestination | null; + }> { const now = new Date(); const createdCollections: Collection[] = []; // External id to internal model id. @@ -330,30 +493,52 @@ export default abstract class ImportsProcessor< // Cache of resolved external author → internal user id (or undefined when // no match). Reused across every output in the import. const userIdCache = new Map(); - // These will be imported as collections. Widened to the base input shape - // because the abstract class has no narrowed view of T. - const importInput = keyBy( + // The import's root nodes. Widened to the base input shape because the + // abstract class has no narrowed view of T. + const rootNodesByExternalId = keyBy( importModel.input as BaseImportInput, "externalId" ); const ctx = createContext({ user: importModel.createdBy, transaction }); - const firstCollection = await Collection.findFirstCollectionForUser( - importModel.createdBy, - { - attributes: ["index"], - transaction, - } - ); + const destination = await this.resolveDestination(importModel, transaction); - let collectionIdx = firstCollection?.index ?? null; + // When a synthetic root node collapses in destination mode, its loose + // child documents parent directly to the destination. `null` means the + // destination collection root; a string means the destination document. + const rootParentOverride: Record = {}; + + // Destination-mode documents are created unpublished (see below) and then + // published in a second pass that doesn't trigger the collection-structure + // hook. Collected here as (id, publishedAt) so original dates are kept. + const pendingPublish: { id: string; publishedAt: Date }[] = []; + + // Only compute a fractional index for new collections; skip the query + // entirely when importing into a destination. + let collectionIdx: string | null = null; + if (!destination) { + const firstCollection = await Collection.findFirstCollectionForUser( + importModel.createdBy, + { + attributes: ["index"], + transaction, + } + ); + collectionIdx = firstCollection?.index ?? null; + } // Pre-pass: allocate new urlIds for every collection and document in this // import so internal link hrefs in document content can be rewritten to // point at the new paths during persistence. The map is keyed by the old // urlId from the export, which is what appears in `/doc/-` - // and `/collection/-` link hrefs. - const urlIdMap: Record = {}; + // and `/collection/-` link hrefs. `kind` records whether the + // node materialized as a collection or a document so the rewrite picks the + // right path builder — a root node is only a collection when there's no + // destination. + const urlIdMap: Record< + string, + { urlId: string; title: string; kind: "collection" | "document" } + > = {}; await ImportTask.findAllInBatches>( { @@ -371,13 +556,15 @@ export default abstract class ImportsProcessor< if (!output.urlId || urlIdMap[output.urlId]) { continue; } - const isCollection = !!importInput[output.externalId]; + const isCollection = + !destination && !!rootNodesByExternalId[output.externalId]; const allocated = isCollection ? await this.preserveCollectionUrlId(output.urlId, transaction) : await this.preserveDocumentUrlId(output.urlId, transaction); urlIdMap[output.urlId] = { urlId: allocated, title: output.title, + kind: isCollection ? "collection" : "document", }; } } @@ -390,7 +577,7 @@ export default abstract class ImportsProcessor< order: [ ["createdAt", "ASC"], ["id", "ASC"], // for stable order when multiple tasks have same "createdAt" value. - ], // ordering ensures collections are created first. + ], // ordering ensures root nodes are created first. batchLimit: 5, // output data per task could be huge, keep a low batch size to prevent OOM. transaction, }, @@ -406,11 +593,6 @@ export default abstract class ImportsProcessor< ? await this.getInternalId(parentExternalId, idMap) : undefined; - const collectionExternalId = input.collectionExternalId; - const collectionInternalId = collectionExternalId - ? await this.getInternalId(collectionExternalId, idMap) - : undefined; - const output = outputMap[externalId]; // Skip this item if it has no output (likely due to an error during processing) @@ -422,18 +604,19 @@ export default abstract class ImportsProcessor< continue; } - const collectionItem = importInput[externalId]; + const rootNode = rootNodesByExternalId[externalId]; const attachments = await Attachment.findAll({ attributes: ["id", "size"], - where: { documentId: externalId }, // This will be set for root pages too (which will be imported as collection) + where: { documentId: externalId }, // This will be set for root pages too transaction, }); const transformedContent = await this.rewriteReferences({ content: output.content, attachments, - importInput, + rootNodesByExternalId, + hasDestination: !!destination, idMap, urlIdMap, actorId: importModel.createdById, @@ -448,7 +631,12 @@ export default abstract class ImportsProcessor< transaction )) ?? importModel.createdById; - if (collectionItem) { + const urlId = output.urlId + ? urlIdMap[output.urlId]?.urlId + : undefined; + + // Root node without a destination → materialize a Collection. + if (rootNode && !destination) { // imported collection will be placed in the beginning. collectionIdx = fractionalIndex(null, collectionIdx); @@ -466,10 +654,6 @@ export default abstract class ImportsProcessor< createdByName: output.author, }; - const urlId = output.urlId - ? urlIdMap[output.urlId]?.urlId - : undefined; - const collection = Collection.build({ id: internalId, urlId, @@ -487,7 +671,7 @@ export default abstract class ImportsProcessor< apiImportId: importModel.id, index: collectionIdx, sort: Collection.DEFAULT_SORT, - permission: collectionItem.permission, + permission: rootNode.permission, sourceMetadata, createdAt: output.createdAt ?? now, updatedAt: output.updatedAt ?? now, @@ -512,13 +696,55 @@ export default abstract class ImportsProcessor< continue; } - // Document at the root of a collection when there's no parent (or) the parent is the collection. - const isRootDocument = - !parentExternalId || !!importInput[parentExternalId]; + // Synthetic root node in destination mode → materialize nothing; + // its loose child documents parent directly to the destination. + if (rootNode && destination && rootNode.synthetic) { + rootParentOverride[externalId] = destination.document?.id ?? null; + continue; + } - const urlId = output.urlId - ? urlIdMap[output.urlId]?.urlId - : undefined; + // Resolve the collection and parent for a document. In destination + // mode every document lives in the destination collection; root + // nodes and root-level documents parent to the destination + // document (or the collection root), everything else to its parent. + const isRootDocument = + !parentExternalId || !!rootNodesByExternalId[parentExternalId]; + + let collectionId: string | undefined; + let parentDocumentId: string | undefined; + const inputRootExternalId = + input.rootExternalId ?? input.collectionExternalId; + + if (destination) { + collectionId = destination.collection.id; + + if (rootNode) { + // A materialized root document parents to the destination. + parentDocumentId = destination.document?.id; + } else if (isRootDocument) { + const rootExternalId = parentExternalId ?? inputRootExternalId; + if (rootExternalId && rootExternalId in rootParentOverride) { + // Synthetic-root child → parent directly to the destination. + parentDocumentId = + rootParentOverride[rootExternalId] ?? undefined; + } else { + // Non-synthetic root → parent to the materialized root doc. + parentDocumentId = rootExternalId + ? await this.getInternalId(rootExternalId, idMap) + : destination.document?.id; + } + } else { + parentDocumentId = parentInternalId; + } + } else { + collectionId = inputRootExternalId + ? await this.getInternalId(inputRootExternalId, idMap) + : undefined; + parentDocumentId = isRootDocument ? undefined : parentInternalId; + } + + const publishedAt = + output.publishedAt ?? output.updatedAt ?? output.createdAt ?? now; const defaults = { title: output.title, @@ -529,8 +755,8 @@ export default abstract class ImportsProcessor< text: await DocumentHelper.toMarkdown(transformedContent, { includeTitle: false, }), - collectionId: collectionInternalId, - parentDocumentId: isRootDocument ? undefined : parentInternalId, + collectionId, + parentDocumentId, createdById: resolvedCreatedById, lastModifiedById: resolvedCreatedById, teamId: importModel.createdBy.teamId, @@ -542,15 +768,18 @@ export default abstract class ImportsProcessor< }, createdAt: output.createdAt ?? now, updatedAt: output.updatedAt ?? now, - publishedAt: - output.publishedAt ?? - output.updatedAt ?? - output.createdAt ?? - now, + // In destination mode the document is created unpublished so + // Document's AfterCreate structure hook (which opens its own + // transaction and locks the pre-existing collection) is a no-op — + // it would otherwise deadlock against this transaction's FK lock. + // publishedAt is applied below and the structure is built in + // onProcessed, mirroring how a new collection is invisible to that + // hook in the default path. + publishedAt: destination ? null : publishedAt, }; try { - await Document.findOrCreateWithCtx( + const [document, created] = await Document.findOrCreateWithCtx( ctx, { where: { @@ -564,6 +793,21 @@ export default abstract class ImportsProcessor< data: { title: output.title, source: "import" }, } ); + + if (destination && created && parentDocumentId) { + await Promise.all([ + GroupMembership.copy( + { documentId: parentDocumentId }, + document, + { transaction } + ), + UserMembership.copy( + { documentId: parentDocumentId }, + document, + { transaction } + ), + ]); + } } catch (err) { if (err instanceof UniqueConstraintError) { Logger.error( @@ -581,6 +825,10 @@ export default abstract class ImportsProcessor< throw err; } + if (destination) { + pendingPublish.push({ id: internalId, publishedAt }); + } + // Update document id for attachments in document content. await Attachment.update( { documentId: internalId }, @@ -591,7 +839,82 @@ export default abstract class ImportsProcessor< } ); - return { collections: createdCollections }; + // Publish destination-mode documents now that every row exists. hooks are + // disabled so the AfterCreate structure hook never runs — onProcessed + // builds the destination collection's structure instead. + for (const { id, publishedAt } of pendingPublish) { + await Document.unscoped().update( + { publishedAt }, + { where: { id }, transaction, hooks: false, silent: true } + ); + } + + return { collections: createdCollections, destination }; + } + + /** + * Resolve the optional destination for the import. A document destination is + * re-resolved at persistence time so a mid-import move is reflected. + * + * @param importModel Import model associated with the event. + * @param transaction Sequelize transaction. + * @returns The resolved destination, or null when none is set. + * @throws Error when a document destination is missing, soft-deleted, or + * archived — `onFailed` then flips the import to Errored. + */ + private async resolveDestination( + importModel: Import, + transaction: Transaction + ): Promise { + if (importModel.documentId) { + // Lock the collection before the document to match documentMover's lock + // order. If the document moved between the initial read and the lock, + // retry against its current collection. + for (let attempt = 0; attempt < 3; attempt++) { + const document = await Document.unscoped().findOne({ + where: { id: importModel.documentId }, + transaction, + }); + if (!document || document.archivedAt || !document.collectionId) { + break; + } + + const collection = await Collection.findByPk(document.collectionId, { + includeDocumentStructure: true, + lock: transaction.LOCK.NO_KEY_UPDATE, + transaction, + rejectOnEmpty: true, + }); + const lockedDocument = await Document.unscoped().findOne({ + where: { id: importModel.documentId }, + lock: transaction.LOCK.NO_KEY_UPDATE, + transaction, + }); + if ( + lockedDocument && + !lockedDocument.archivedAt && + lockedDocument.collectionId === collection.id + ) { + return { collection, document: lockedDocument }; + } + } + + throw new Error( + `Import destination document ${importModel.documentId} is no longer available` + ); + } + + if (importModel.collectionId) { + const collection = await Collection.findByPk(importModel.collectionId, { + includeDocumentStructure: true, + lock: transaction.LOCK.NO_KEY_UPDATE, + transaction, + rejectOnEmpty: true, + }); + return { collection }; + } + + return null; } /** @@ -602,10 +925,12 @@ export default abstract class ImportsProcessor< * @param content ProseMirrorDoc that represents collection (or) document content. * @param attachments Array of attachment models created for the import. * @param idMap Map of internalId to externalId. - * @param urlIdMap Map of old urlId to the newly allocated urlId and title, - * used to rewrite `/doc/-` and `/collection/-` - * link hrefs. - * @param importInput Contains the root externalId and associated info which were used to create the import. + * @param urlIdMap Map of old urlId to the newly allocated urlId, title, and + * materialized kind, used to rewrite `/doc/-` and + * `/collection/-` link hrefs to the correct new path. + * @param rootNodesByExternalId The import's root nodes keyed by externalId. + * @param hasDestination Whether the import targets an existing destination — + * when true root-node references become document mentions/links. * @param actorId ID of the user who created the import. * @returns Updated ProseMirrorDoc. */ @@ -614,16 +939,21 @@ export default abstract class ImportsProcessor< attachments, idMap, urlIdMap, - importInput, + rootNodesByExternalId, + hasDestination, actorId, teamId, }: { content: ProsemirrorDoc; attachments: Attachment[]; idMap: Record; - urlIdMap: Record; + urlIdMap: Record< + string, + { urlId: string; title: string; kind: "collection" | "document" } + >; // oxlint-disable-next-line @typescript-eslint/no-explicit-any - importInput: Record[number]>; + rootNodesByExternalId: Record[number]>; + hasDestination: boolean; actorId: string; teamId: string; }): Promise { @@ -646,7 +976,10 @@ export default abstract class ImportsProcessor< const externalId = attrs.modelId as string; attrs.modelId = await this.getInternalId(externalId, idMap, teamId); - const isCollectionMention = !!importInput[externalId]; // the referenced externalId is a root page. + // A root-node reference is a collection mention only when the import + // materializes collections; in destination mode it becomes a document. + const isCollectionMention = + !hasDestination && !!rootNodesByExternalId[externalId]; attrs.type = isCollectionMention ? MentionType.Collection : MentionType.Document; @@ -666,29 +999,24 @@ export default abstract class ImportsProcessor< }; const rewriteInternalLinkHref = (href: string): string => { - const docMatch = /^\/doc\/([^/?#]+)(.*)$/.exec(href); - if (docMatch) { - const slugMatch = UrlHelper.SLUG_URL_REGEX.exec(docMatch[1]); - const mapped = slugMatch ? urlIdMap[slugMatch[1]] : undefined; - if (mapped) { - return ( - Document.getPath({ title: mapped.title, urlId: mapped.urlId }) + - docMatch[2] - ); - } + // Match either a `/doc/` or `/collection/` href; the destination path is + // chosen by the mapped node's materialized kind, not the source path, so + // a `/collection/` link whose node became a document (destination mode) + // rewrites to a `/doc/` path rather than a non-existent collection path. + const match = /^\/(?:doc|collection)\/([^/?#]+)(.*)$/.exec(href); + if (!match) { + return href; } - const collectionMatch = /^\/collection\/([^/?#]+)(.*)$/.exec(href); - if (collectionMatch) { - const slugMatch = UrlHelper.SLUG_URL_REGEX.exec(collectionMatch[1]); - const mapped = slugMatch ? urlIdMap[slugMatch[1]] : undefined; - if (mapped) { - return ( - Collection.getPath({ name: mapped.title, urlId: mapped.urlId }) + - collectionMatch[2] - ); - } + const slugMatch = UrlHelper.SLUG_URL_REGEX.exec(match[1]); + const mapped = slugMatch ? urlIdMap[slugMatch[1]] : undefined; + if (!mapped) { + return href; } - return href; + const path = + mapped.kind === "collection" + ? Collection.getPath({ name: mapped.title, urlId: mapped.urlId }) + : Document.getPath({ title: mapped.title, urlId: mapped.urlId }); + return path + match[2]; }; const transformLinkMarks = (node: Node): Node => { diff --git a/server/queues/tasks/JSONAPIImportTask.test.ts b/server/queues/tasks/JSONAPIImportTask.test.ts index 2ce5af0699..6f1c42badf 100644 --- a/server/queues/tasks/JSONAPIImportTask.test.ts +++ b/server/queues/tasks/JSONAPIImportTask.test.ts @@ -10,11 +10,13 @@ import { Import, ImportTask, User, + UserMembership, } from "@server/models"; import FileStorage from "@server/storage/files"; import { CollectionPermission, ImportState, + DocumentPermission, ImportTaskPhase, ImportTaskState, IntegrationService, @@ -22,6 +24,7 @@ import { import { buildAdmin, buildAttachment, + buildCollection, buildDocument, buildImport, buildTeam, @@ -232,19 +235,28 @@ async function runImport(opts: { createdById: string; zipPath: string; storageKey?: string; + collectionId?: string | null; + documentId?: string | null; }): Promise<{ importId: string }> { vi.spyOn(FileStorage, "getFileHandle").mockResolvedValue({ path: opts.zipPath, cleanup: async () => {}, }); + const hasDestination = !!(opts.collectionId || opts.documentId); + const importModel = await buildImport({ teamId: opts.teamId, createdById: opts.createdById, service: IntegrationService.JSON, integrationId: null, + collectionId: opts.collectionId ?? null, + documentId: opts.documentId ?? null, input: [ - { externalId: randomUUID(), permission: CollectionPermission.Read }, + { + externalId: randomUUID(), + permission: hasDestination ? undefined : CollectionPermission.Read, + }, ], scratch: { storageKey: opts.storageKey ?? "fixture-key" }, }); @@ -535,6 +547,268 @@ describe("JSONAPIImportTask", () => { } }); }); + + describe("import into an existing collection", () => { + it("materializes root nodes as root documents without creating collections", async () => { + const admin = await buildAdmin(); + const destination = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + }); + + const { importId } = await runImport({ + teamId: admin.teamId, + createdById: admin.id, + zipPath: zip.filePath, + collectionId: destination.id, + }); + + const createdCollections = await Collection.findAll({ + where: { apiImportId: importId }, + }); + expect(createdCollections.length).toBe(0); + + const documents = await Document.findAll({ + where: { apiImportId: importId }, + }); + // The exported collection becomes a root document + its two documents. + expect(documents.length).toBe(3); + for (const document of documents) { + expect(document.collectionId).toBe(destination.id); + } + + const rootDoc = documents.find((d) => d.title === "Test JSON"); + const docOne = documents.find((d) => d.title === "Document 1"); + const docTwo = documents.find((d) => d.title === "Document 2"); + expect(rootDoc).toBeDefined(); + expect(rootDoc!.parentDocumentId).toBeNull(); + expect(docOne!.parentDocumentId).toBe(rootDoc!.id); + expect(docTwo!.parentDocumentId).toBe(rootDoc!.id); + + // The destination collection's structure now includes the root document. + const refreshed = await Collection.findByPk(destination.id, { + includeDocumentStructure: true, + rejectOnEmpty: true, + }); + expect( + refreshed.documentStructure?.some((node) => node.id === rootDoc!.id) + ).toBe(true); + }); + + it("rewrites collection links to the materialized document path", async () => { + const admin = await buildAdmin(); + const destination = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + }); + + const { importId } = await runImport({ + teamId: admin.teamId, + createdById: admin.id, + zipPath: zip.filePath, + collectionId: destination.id, + }); + + const rootDoc = await Document.findOne({ + where: { apiImportId: importId, title: "Test JSON" }, + rejectOnEmpty: true, + }); + const docOne = await Document.findOne({ + where: { apiImportId: importId, title: "Document 1" }, + rejectOnEmpty: true, + }); + + // The `/collection/...` link now resolves to the root node's document + // path rather than a non-existent collection path. + const linkParagraph = docOne.content?.content?.[2]; + const linkText = linkParagraph?.content?.[0]; + const linkMark = linkText?.marks?.find((m) => m.type === "link"); + expect(linkMark?.attrs?.href).toBe(rootDoc.path); + expect(linkMark?.attrs?.href).toContain("/doc/"); + }); + }); + + describe("import into an existing document", () => { + it("nests the imported subtree under the destination document", async () => { + const admin = await buildAdmin(); + const destination = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + }); + const destinationDoc = await buildDocument({ + teamId: admin.teamId, + userId: admin.id, + collectionId: destination.id, + }); + + const { importId } = await runImport({ + teamId: admin.teamId, + createdById: admin.id, + zipPath: zip.filePath, + documentId: destinationDoc.id, + }); + + const createdCollections = await Collection.findAll({ + where: { apiImportId: importId }, + }); + expect(createdCollections.length).toBe(0); + + const documents = await Document.findAll({ + where: { apiImportId: importId }, + }); + expect(documents.length).toBe(3); + + const rootDoc = documents.find((d) => d.title === "Test JSON"); + expect(rootDoc).toBeDefined(); + // Root node parents to the destination document, collection inherited. + expect(rootDoc!.parentDocumentId).toBe(destinationDoc.id); + for (const document of documents) { + expect(document.collectionId).toBe(destination.id); + } + }); + + it("copies parent document memberships to every imported document", async () => { + const admin = await buildAdmin(); + const member = await buildUser({ teamId: admin.teamId }); + const destination = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + permission: null, + }); + const destinationDoc = await buildDocument({ + teamId: admin.teamId, + userId: admin.id, + collectionId: destination.id, + }); + const sourceMembership = await UserMembership.create({ + documentId: destinationDoc.id, + userId: member.id, + permission: DocumentPermission.Read, + createdById: admin.id, + }); + + const { importId } = await runImport({ + teamId: admin.teamId, + createdById: admin.id, + zipPath: zip.filePath, + documentId: destinationDoc.id, + }); + + const documents = await Document.findAll({ + where: { apiImportId: importId }, + }); + expect(documents.length).toBe(3); + + const memberships = await UserMembership.findAll({ + where: { + documentId: documents.map((document) => document.id), + userId: member.id, + }, + }); + expect(memberships.length).toBe(documents.length); + expect( + memberships.every( + (membership) => membership.sourceId === sourceMembership.id + ) + ).toBe(true); + }); + }); + + describe("deleting an import into an existing collection", () => { + it("removes only the created documents, leaving the destination intact", async () => { + const admin = await buildAdmin(); + const destination = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + }); + const existingDoc = await buildDocument({ + teamId: admin.teamId, + userId: admin.id, + collectionId: destination.id, + }); + + const { importId } = await runImport({ + teamId: admin.teamId, + createdById: admin.id, + zipPath: zip.filePath, + collectionId: destination.id, + }); + + expect( + (await Document.findAll({ where: { apiImportId: importId } })).length + ).toBe(3); + + await new JSONImportsProcessor().perform({ + name: "imports.delete", + modelId: importId, + teamId: admin.teamId, + actorId: admin.id, + ip: "127.0.0.1", + changes: { attributes: {}, previous: {} }, + }); + + // All created documents are gone. + expect( + (await Document.findAll({ where: { apiImportId: importId } })).length + ).toBe(0); + + // The destination collection and its pre-existing document survive. + expect(await Collection.findByPk(destination.id)).not.toBeNull(); + expect( + await Document.findByPk(existingDoc.id, { userId: admin.id }) + ).not.toBeNull(); + }); + + it("keeps documents added below imported content", async () => { + const admin = await buildAdmin(); + const destination = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + }); + + const { importId } = await runImport({ + teamId: admin.teamId, + createdById: admin.id, + zipPath: zip.filePath, + collectionId: destination.id, + }); + const importedRoot = await Document.findOne({ + where: { apiImportId: importId, parentDocumentId: null }, + rejectOnEmpty: true, + }); + const existingChild = await buildDocument({ + teamId: admin.teamId, + userId: admin.id, + collectionId: destination.id, + parentDocumentId: importedRoot.id, + }); + + await new JSONImportsProcessor().perform({ + name: "imports.delete", + modelId: importId, + teamId: admin.teamId, + actorId: admin.id, + ip: "127.0.0.1", + changes: { attributes: {}, previous: {} }, + }); + + const preserved = await Document.findByPk(existingChild.id, { + userId: admin.id, + rejectOnEmpty: true, + }); + expect(preserved.parentDocumentId).toBeNull(); + + const refreshed = await Collection.findByPk(destination.id, { + includeDocumentStructure: true, + rejectOnEmpty: true, + }); + expect( + refreshed.documentStructure?.some( + (document) => document.id === existingChild.id + ) + ).toBe(true); + }); + }); }); describe("rewriteAttachmentReferences", () => { diff --git a/server/queues/tasks/JSONAPIImportTask.ts b/server/queues/tasks/JSONAPIImportTask.ts index 145a05a212..7fd1223a1b 100644 --- a/server/queues/tasks/JSONAPIImportTask.ts +++ b/server/queues/tasks/JSONAPIImportTask.ts @@ -44,7 +44,7 @@ const ATTACHMENT_NODE_TYPES = ["attachment", "image", "video"]; interface DiscoveredDocument { externalId: string; parentExternalId?: string; - collectionExternalId: string; + rootExternalId: string; export: DocumentJSONExport; children: DiscoveredDocument[]; } @@ -418,7 +418,7 @@ export default class JSONAPIImportTask extends APIImportTask { ): DiscoveredDocument => ({ externalId: doc.id, parentExternalId: parentExternalId ?? doc.parentDocumentId ?? undefined, - collectionExternalId: externalId, + rootExternalId: externalId, export: doc, children: [], }); @@ -524,7 +524,7 @@ export default class JSONAPIImportTask extends APIImportTask { return { externalId: doc.externalId, parentExternalId: doc.parentExternalId, - collectionExternalId: doc.collectionExternalId, + rootExternalId: doc.rootExternalId, title: exported.title, urlId: exported.urlId, icon: exported.icon ?? exported.emoji, diff --git a/server/queues/tasks/MarkdownAPIImportTask.test.ts b/server/queues/tasks/MarkdownAPIImportTask.test.ts index a57fa6c8ae..1d5592988f 100644 --- a/server/queues/tasks/MarkdownAPIImportTask.test.ts +++ b/server/queues/tasks/MarkdownAPIImportTask.test.ts @@ -1,4 +1,25 @@ +import { randomUUID } from "node:crypto"; +import fs from "fs-extra"; +import JSZip from "jszip"; +import tmp from "tmp"; +import type { ProsemirrorDoc } from "@shared/types"; +import { Collection, Document, ImportTask } from "@server/models"; +import FileStorage from "@server/storage/files"; import { + ImportState, + ImportTaskPhase, + ImportTaskState, + IntegrationService, +} from "@shared/types"; +import { + buildAdmin, + buildCollection, + buildDocument, + buildImport, +} from "@server/test/factories"; +import { withAPIContext } from "@server/test/support"; +import MarkdownImportsProcessor from "../processors/MarkdownImportsProcessor"; +import MarkdownAPIImportTask, { rewriteAttachmentPaths, rewriteInternalLinks, } from "./MarkdownAPIImportTask"; @@ -144,3 +165,354 @@ describe("rewriteInternalLinks", () => { expect(out).toBe('see [other](<> "The other one")'); }); }); + +describe("MarkdownImportsProcessor destination", () => { + const emptyDoc: ProsemirrorDoc = { + type: "doc", + content: [{ type: "paragraph" }], + }; + + it("collapses a synthetic root node so loose files land under the destination collection", async () => { + const admin = await buildAdmin(); + const destination = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + }); + + const rootId = randomUUID(); + const docAId = randomUUID(); + const docBId = randomUUID(); + + const importModel = await buildImport({ + teamId: admin.teamId, + createdById: admin.id, + service: IntegrationService.Markdown, + integrationId: null, + collectionId: destination.id, + // The synthetic "Documents" fallback root node holding loose files. + input: [{ externalId: rootId, synthetic: true }], + scratch: { storageKey: "fixture-key" }, + state: ImportState.Processed, + }); + + await ImportTask.create>({ + state: ImportTaskState.Completed, + phase: ImportTaskPhase.Page, + importId: importModel.id, + input: [ + { externalId: rootId }, + { externalId: docAId, rootExternalId: rootId }, + { externalId: docBId, rootExternalId: rootId }, + ], + output: [ + { externalId: rootId, title: "Documents", content: emptyDoc }, + { externalId: docAId, title: "Loose A", content: emptyDoc }, + { externalId: docBId, title: "Loose B", content: emptyDoc }, + ], + } as Parameters[0]); + + await new MarkdownImportsProcessor().perform({ + name: "imports.processed", + modelId: importModel.id, + teamId: admin.teamId, + actorId: admin.id, + ip: "127.0.0.1", + changes: { attributes: {}, previous: {} }, + }); + + // No collections created — the synthetic root materializes nothing. + const collections = await Collection.findAll({ + where: { apiImportId: importModel.id }, + }); + expect(collections.length).toBe(0); + + const documents = await Document.findAll({ + where: { apiImportId: importModel.id }, + }); + expect(documents.length).toBe(2); + for (const document of documents) { + expect(document.collectionId).toBe(destination.id); + // Loose files parent directly to the destination collection root. + expect(document.parentDocumentId).toBeNull(); + } + expect(documents.map((d) => d.title).sort()).toEqual([ + "Loose A", + "Loose B", + ]); + }); +}); + +describe("MarkdownImportsProcessor legacy task input", () => { + it("assigns documents using collectionExternalId from tasks queued before the rename", async () => { + const admin = await buildAdmin(); + const emptyDoc: ProsemirrorDoc = { + type: "doc", + content: [{ type: "paragraph" }], + }; + const rootId = randomUUID(); + const docId = randomUUID(); + + const importModel = await buildImport({ + teamId: admin.teamId, + createdById: admin.id, + service: IntegrationService.Markdown, + integrationId: null, + input: [{ externalId: rootId }], + scratch: { storageKey: "fixture-key" }, + state: ImportState.Processed, + }); + + await ImportTask.create>({ + state: ImportTaskState.Completed, + phase: ImportTaskPhase.Page, + importId: importModel.id, + input: [ + { externalId: rootId }, + { externalId: docId, collectionExternalId: rootId }, + ], + output: [ + { externalId: rootId, title: "Legacy", content: emptyDoc }, + { externalId: docId, title: "Legacy doc", content: emptyDoc }, + ], + } as Parameters[0]); + + await new MarkdownImportsProcessor().perform({ + name: "imports.processed", + modelId: importModel.id, + teamId: admin.teamId, + actorId: admin.id, + ip: "127.0.0.1", + changes: { attributes: {}, previous: {} }, + }); + + const collection = await Collection.findOne({ + where: { apiImportId: importModel.id }, + }); + const document = await Document.findOne({ + where: { apiImportId: importModel.id }, + }); + expect(document?.collectionId).toBe(collection?.id); + }); +}); + +describe("MarkdownAPIImportTask document export archives", () => { + /** An archive with the layout of a document export. */ + const documentExport = { + "Parent.md": + "# Parent\n\nParent body\n\n![pic](Parent/attachments/pic.png)\n", + "Parent/Child.md": "# Child\n\n[up](../Parent.md)", + "Parent/attachments/pic.png": "pixels", + }; + + /** + * Imports an archive with the given files. + * + * @param admin The user that creates the import. + * @param files The contents of the archive, keyed by path. + * @param destination The destination of the import, if any. + * @returns The documents and collections created by the import. + */ + async function importArchive( + admin: Awaited>, + files: Record, + destination: { collectionId?: string; documentId?: string } = {} + ) { + const zip = new JSZip(); + for (const [name, content] of Object.entries(files)) { + zip.file(name, content); + } + const filePath: string = await new Promise((resolve, reject) => { + tmp.file({ postfix: ".zip" }, (err, p) => + err ? reject(err) : resolve(p) + ); + }); + await fs.writeFile( + filePath, + await zip.generateAsync({ type: "nodebuffer" }) + ); + + vi.spyOn(FileStorage, "getFileHandle").mockResolvedValue({ + path: filePath, + cleanup: async () => {}, + }); + vi.spyOn(MarkdownAPIImportTask.prototype, "schedule").mockResolvedValue( + undefined as never + ); + + const externalId = randomUUID(); + const importModel = await buildImport({ + teamId: admin.teamId, + createdById: admin.id, + service: IntegrationService.Markdown, + integrationId: null, + ...destination, + input: [{ externalId }], + scratch: { storageKey: "fixture-key" }, + }); + const bootstrapTask = await ImportTask.create< + ImportTask + >({ + state: ImportTaskState.Created, + phase: ImportTaskPhase.Bootstrap, + input: [{ externalId }], + importId: importModel.id, + } as Parameters[0]); + + await new MarkdownAPIImportTask().perform({ + importTaskId: bootstrapTask.id, + }); + const findNext = () => + ImportTask.findOne>({ + where: { state: ImportTaskState.Created, importId: importModel.id }, + order: [["createdAt", "ASC"]], + }); + for (let task = await findNext(); task; task = await findNext()) { + await new MarkdownAPIImportTask().perform({ importTaskId: task.id }); + } + await new MarkdownAPIImportTask().perform({ + importTaskId: bootstrapTask.id, + }); + + await new MarkdownImportsProcessor().perform({ + name: "imports.processed", + modelId: importModel.id, + teamId: admin.teamId, + actorId: admin.id, + ip: "127.0.0.1", + changes: { attributes: {}, previous: {} }, + }); + await fs.rm(filePath, { force: true }); + + return { + documents: await Document.findAll({ + where: { apiImportId: importModel.id }, + }), + collections: await Collection.findAll({ + where: { apiImportId: importModel.id }, + }), + }; + } + + it("merges a document with its folder when importing into a collection", async () => { + const admin = await buildAdmin(); + const destination = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + }); + + const { documents, collections } = await importArchive( + admin, + documentExport, + { collectionId: destination.id } + ); + + expect(collections).toHaveLength(0); + expect(documents.map((d) => d.title).sort()).toEqual(["Child", "Parent"]); + + const parent = documents.find((d) => d.title === "Parent"); + const child = documents.find((d) => d.title === "Child"); + expect(parent?.parentDocumentId).toBeNull(); + expect(parent?.text).toContain("Parent body"); + expect(child?.parentDocumentId).toBe(parent?.id); + expect(child?.text).toContain(`/doc/${parent?.id}`); + }); + + it("merges a document with its folder when importing under a document", async () => { + const admin = await buildAdmin(); + const collection = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + }); + const destination = await buildDocument({ + teamId: admin.teamId, + userId: admin.id, + collectionId: collection.id, + }); + + const { documents } = await importArchive(admin, documentExport, { + documentId: destination.id, + }); + + expect(documents.map((d) => d.title).sort()).toEqual(["Child", "Parent"]); + const parent = documents.find((d) => d.title === "Parent"); + const child = documents.find((d) => d.title === "Child"); + expect(parent?.parentDocumentId).toBe(destination.id); + expect(child?.parentDocumentId).toBe(parent?.id); + }); + + it("uses the file as the collection overview when creating new collections", async () => { + const admin = await buildAdmin(); + + const { documents, collections } = await importArchive( + admin, + documentExport + ); + + expect(collections.map((c) => c.name)).toEqual(["Parent"]); + const [collection] = collections; + expect(collection.description).toContain("Parent body"); + expect(collection.description).not.toContain("# Parent"); + expect(collection.description).toContain("/api/attachments.redirect"); + + expect(documents.map((d) => d.title)).toEqual(["Child"]); + const [child] = documents; + expect(child.collectionId).toBe(collection.id); + expect(child.parentDocumentId).toBeNull(); + expect(child.text).toContain(collection.id); + }); + + it("keeps a file without a matching folder in the fallback collection", async () => { + const admin = await buildAdmin(); + + const { documents, collections } = await importArchive(admin, { + "Loose.md": "# Loose\n\nLoose body", + "Parent/Child.md": "# Child\n\nChild body", + }); + + expect(collections.map((c) => c.name).sort()).toEqual([ + "Documents", + "Parent", + ]); + expect(documents.map((d) => d.title).sort()).toEqual(["Child", "Loose"]); + expect( + collections.find((c) => c.name === "Parent")?.description + ).toBeFalsy(); + }); + + it("deletes the children of an archived document when the import is deleted", async () => { + const admin = await buildAdmin(); + const destination = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + }); + + const { documents } = await importArchive(admin, documentExport, { + collectionId: destination.id, + }); + const importId = documents[0].apiImportId; + if (!importId) { + throw new Error("Expected the document to belong to the import"); + } + const parent = documents.find((d) => d.title === "Parent"); + if (!parent) { + throw new Error("Expected the parent document to be imported"); + } + const archivable = await Document.findByPk(parent.id, { + userId: admin.id, + rejectOnEmpty: true, + }); + await withAPIContext(admin, (ctx) => archivable.archiveWithCtx(ctx)); + + await new MarkdownImportsProcessor().perform({ + name: "imports.delete", + modelId: importId, + teamId: admin.teamId, + actorId: admin.id, + ip: "127.0.0.1", + changes: { attributes: {}, previous: {} }, + }); + + expect(await Document.count({ where: { apiImportId: importId } })).toBe(0); + expect(await Collection.findByPk(destination.id)).not.toBeNull(); + }); +}); diff --git a/server/queues/tasks/MarkdownAPIImportTask.ts b/server/queues/tasks/MarkdownAPIImportTask.ts index acd5cdf76a..a05f8c2d4a 100644 --- a/server/queues/tasks/MarkdownAPIImportTask.ts +++ b/server/queues/tasks/MarkdownAPIImportTask.ts @@ -39,15 +39,18 @@ interface DiscoveredDocument { id: string; title: string; pathInZip: string; - collectionId: string; + rootId: string; parentDocumentId?: string; markdownText: string; children: DiscoveredDocument[]; } -interface DiscoveredCollection { +interface DiscoveredRootNode { id: string; title: string; + synthetic?: boolean; + /** The markdown file that holds the content of this root node, if any. */ + contentFile?: ZipTreeNode; children: DiscoveredDocument[]; } @@ -288,22 +291,30 @@ export default class MarkdownAPIImportTask extends APIImportTask { } ); - const rootNodes = this.resolveCollectionRootNodes(tree.children); + const topLevelNodes = this.resolveCollectionRootNodes(tree.children); - if (rootNodes.length === 0) { + if (topLevelNodes.length === 0) { throw FileImportError("Could not find valid content in zip file"); } - const collections: DiscoveredCollection[] = []; + const rootNodes: DiscoveredRootNode[] = []; const manifest: MarkdownAttachmentManifestItem[] = []; // Loose markdown files that sit at the archive root rather than inside a - // collection folder are gathered into a fallback collection below. + // root folder are gathered into a synthetic fallback root node below. const looseDocuments: ZipTreeNode[] = []; + // Folders that hold the children of a loose markdown file of the same name. + const looseDocumentFolders: ZipTreeNode[] = []; + const hasDestination = + !!importTask.import.collectionId || !!importTask.import.documentId; + const looseFilesByTitle = new Map( + topLevelNodes + .filter((node) => this.isMarkdownFile(node)) + .map((node) => [node.title, node]) + ); - for (const node of rootNodes) { + for (const node of topLevelNodes) { if (node.children.length === 0) { - const ext = path.extname(node.name).toLowerCase(); - if (ext === ".md" || ext === ".markdown") { + if (this.isMarkdownFile(node)) { looseDocuments.push(node); } else { manifest.push({ @@ -321,34 +332,51 @@ export default class MarkdownAPIImportTask extends APIImportTask { continue; } - const collection: DiscoveredCollection = { + // A document export writes "name.md" beside "name/". In a destination + // they form one document, otherwise the file is the collection overview. + const contentFile = looseFilesByTitle.get(node.title); + if (contentFile && hasDestination) { + looseDocumentFolders.push(node); + continue; + } + + const rootNode: DiscoveredRootNode = { id: randomUUID(), title: node.title, + contentFile, children: [], }; - collections.push(collection); + rootNodes.push(rootNode); this.collectDocumentsAndAttachments({ children: node.children, - collectionId: collection.id, - out: collection.children, + rootId: rootNode.id, + out: rootNode.children, manifest, markdownByNode, }); } - if (looseDocuments.length > 0) { - const collection: DiscoveredCollection = { + const contentFiles = new Set(rootNodes.map((c) => c.contentFile)); + // Folders follow the files so that merged documents keep the file's path. + const syntheticChildren = [ + ...looseDocuments.filter((node) => !contentFiles.has(node)), + ...looseDocumentFolders, + ]; + + if (syntheticChildren.length > 0) { + const rootNode: DiscoveredRootNode = { id: randomUUID(), - title: this.fallbackCollectionTitle(), + title: this.fallbackRootNodeTitle(), + synthetic: true, children: [], }; - collections.push(collection); + rootNodes.push(rootNode); this.collectDocumentsAndAttachments({ - children: looseDocuments, - collectionId: collection.id, - out: collection.children, + children: syntheticChildren, + rootId: rootNode.id, + out: rootNode.children, manifest, markdownByNode, }); @@ -364,61 +392,69 @@ export default class MarkdownAPIImportTask extends APIImportTask { collectDocMap(d.children); } }; - for (const c of collections) { + for (const c of rootNodes) { + if (c.contentFile) { + docMap[c.contentFile.pathInZip] = c.id; + } collectDocMap(c.children); } // Replace (not append) anything past the create-time placeholder with - // the freshly discovered collections so a retried bootstrap doesn't + // the freshly discovered root nodes so a retried bootstrap doesn't // accumulate duplicate entries with fresh UUIDs from a previous - // partial run. ImportsProcessor's persistence pass treats these as - // collections. + // partial run. ImportsProcessor's persistence pass materializes these + // as collections (default) or root documents (destination mode). const associatedImport = importTask.import; const placeholder = associatedImport.input[0]; associatedImport.input = [ placeholder, - ...collections.map((c) => ({ + ...rootNodes.map((c) => ({ externalId: c.id, permission: placeholder.permission, + synthetic: c.synthetic, })), ]; associatedImport.scratch = { storageKey, manifest, docMap }; await associatedImport.save(); - // Append collection placeholder items so ImportsProcessor iterates + // Append root-node placeholder items so ImportsProcessor iterates // them during the bootstrap row (the earliest createdAt) — that - // guarantees collections land in the DB before any per-page document + // guarantees root nodes land in the DB before any per-page document // references them. - const collectionInputItems: MarkdownPageImportTaskInputItem[] = - collections.map((c) => ({ - externalId: c.id, - title: c.title, - path: c.title, - markdownText: "", - attachmentMap: [], - })); + const rootInputItems: MarkdownPageImportTaskInputItem[] = rootNodes.map( + (c) => { + const markdownText = c.contentFile + ? (markdownByNode.get(c.contentFile) ?? "") + : ""; + return { + externalId: c.id, + title: c.title, + path: c.contentFile?.pathInZip ?? c.title, + markdownText, + attachmentMap: this.attachmentsReferencedBy(markdownText, manifest), + }; + } + ); - importTask.input = [importTask.input[0], ...collectionInputItems]; + importTask.input = [importTask.input[0], ...rootInputItems]; - const collectionOutputs: ImportTaskOutput = collections.map((c) => ({ - externalId: c.id, - title: truncate(c.title, { - length: CollectionValidation.maxNameLength, - }), - content: ProsemirrorDataHelper.getEmpty() as ProsemirrorDoc, - })); + const rootOutputs: ImportTaskOutput = await Promise.all( + rootInputItems.map((item) => + this.convertPage(item, docMap, CollectionValidation.maxNameLength) + ) + ); - // First wave of document tasks: only top-level docs in each collection. + // First wave of document tasks: only top-level docs in each root node. // Each carries its descendants in `children` and the per-page handler // re-emits them as the next wave of childTasksInput, producing a strict // depth-ordered cascade of ImportTask rows so parent FKs are always // satisfied at child-doc creation time. - const childTasksInput: ImportTaskInput = collections.flatMap( + const childTasksInput: ImportTaskInput = rootNodes.flatMap( (c) => c.children.map((d) => this.toPageInput(d, manifest)) ); - return { taskOutput: collectionOutputs, childTasksInput }; + return { taskOutput: rootOutputs, childTasksInput }; } finally { await handle.cleanup().catch(() => {}); } @@ -440,7 +476,7 @@ export default class MarkdownAPIImportTask extends APIImportTask { return { externalId: doc.id, parentExternalId: doc.parentDocumentId, - collectionExternalId: doc.collectionId, + rootExternalId: doc.rootId, title: doc.title, path: doc.pathInZip, markdownText: doc.markdownText, @@ -463,39 +499,9 @@ export default class MarkdownAPIImportTask extends APIImportTask { const items = importTask.input as MarkdownPageImportTaskInputItem[]; for (const item of items) { - // Empty markdown short-circuits — used by collection placeholders so - // ImportsProcessor sees their externalId paired with empty content and - // builds a Collection rather than a Document. (Currently collections - // are persisted via the bootstrap task itself, so this branch is only - // a defensive fallback.) - if (!item.markdownText) { - taskOutput.push({ - externalId: item.externalId, - title: truncate(item.title, { - length: DocumentValidation.maxTitleLength, - }), - content: ProsemirrorDataHelper.getEmpty() as ProsemirrorDoc, - }); - } else { - const transformedMarkdown = this.rewriteMarkdown(item, docMap); - const converted = await DocumentConverter.convert( - transformedMarkdown, - path.basename(item.path), - "text/markdown", - { extractTitle: this.shouldExtractTitleFromHeading() } - ); - const { title, icon } = converted; - const doc = this.transformDocument(converted.doc); - - taskOutput.push({ - externalId: item.externalId, - title: truncate(title || item.title, { - length: DocumentValidation.maxTitleLength, - }), - icon, - content: doc.toJSON() as ProsemirrorDoc, - }); - } + taskOutput.push( + await this.convertPage(item, docMap, DocumentValidation.maxTitleLength) + ); // Cascade this doc's direct descendants as the next task wave. Their // ImportTask rows will be created after the current one returns, so @@ -509,6 +515,46 @@ export default class MarkdownAPIImportTask extends APIImportTask { return { taskOutput, childTasksInput }; } + /** + * Converts a page's markdown text into task output. + * + * @param item The per-page task input. + * @param docMap Path → externalId map for internal link rewriting. + * @param maxTitleLength The maximum length of the title in the output. + * @returns The task output for the page. + */ + private async convertPage( + item: MarkdownPageImportTaskInputItem, + docMap: Record, + maxTitleLength: number + ): Promise { + // Empty markdown short-circuits, as a root node without a content file has + // no text to convert. + if (!item.markdownText) { + return { + externalId: item.externalId, + title: truncate(item.title, { length: maxTitleLength }), + content: ProsemirrorDataHelper.getEmpty() as ProsemirrorDoc, + }; + } + + const converted = await DocumentConverter.convert( + this.rewriteMarkdown(item, docMap), + path.basename(item.path), + "text/markdown", + { extractTitle: this.shouldExtractTitleFromHeading() } + ); + + return { + externalId: item.externalId, + title: truncate(converted.title || item.title, { + length: maxTitleLength, + }), + icon: converted.icon, + content: this.transformDocument(converted.doc).toJSON() as ProsemirrorDoc, + }; + } + /** * Pre-rewrites a page's markdown text. Internal `.md` links become mention * markdown so the editor parses them as Document mentions. Attachment paths @@ -623,16 +669,27 @@ export default class MarkdownAPIImportTask extends APIImportTask { } /** - * Title for the fallback collection that holds markdown files found loose at - * the archive root (outside any collection folder). Subclasses can override - * to give the collection a source-appropriate name. + * Title for the fallback root node that holds markdown files found loose at + * the archive root (outside any folder). Subclasses can override to give it + * a source-appropriate name. * - * @returns The fallback collection title. + * @returns The fallback root node title. */ - protected fallbackCollectionTitle(): string { + protected fallbackRootNodeTitle(): string { return "Documents"; } + /** + * Detects files in the archive that hold a markdown document. + * + * @param node ZipTreeNode to inspect. + * @returns true when the node is a markdown file. + */ + private isMarkdownFile(node: ZipTreeNode): boolean { + const ext = path.extname(node.name).toLowerCase(); + return node.children.length === 0 && (ext === ".md" || ext === ".markdown"); + } + /** * Detects folders containing only attachments (no markdown documents). * Recursively considers nested folders; mirrors the legacy heuristic. @@ -692,7 +749,7 @@ export default class MarkdownAPIImportTask extends APIImportTask { * per-page task cascade consumes. * * @param children ZipTreeNode children of the current folder. - * @param collectionId Pre-assigned id of the enclosing collection. + * @param rootId Pre-assigned id of the enclosing root node. * @param parentDocumentId Optional parent document id when nested. * @param out Sibling accumulator to push discovered documents into. * @param manifest Attachment manifest accumulator. @@ -700,14 +757,14 @@ export default class MarkdownAPIImportTask extends APIImportTask { */ private collectDocumentsAndAttachments({ children, - collectionId, + rootId, parentDocumentId, out, manifest, markdownByNode, }: { children: ZipTreeNode[]; - collectionId: string; + rootId: string; parentDocumentId?: string; out: DiscoveredDocument[]; manifest: MarkdownAttachmentManifestItem[]; @@ -758,7 +815,7 @@ export default class MarkdownAPIImportTask extends APIImportTask { if (isFolder) { this.collectDocumentsAndAttachments({ children: child.children, - collectionId, + rootId, parentDocumentId: sibling.id, out: sibling.children, manifest, @@ -772,7 +829,7 @@ export default class MarkdownAPIImportTask extends APIImportTask { id, title: child.title, pathInZip: child.pathInZip, - collectionId, + rootId, parentDocumentId, markdownText, children: [], @@ -783,7 +840,7 @@ export default class MarkdownAPIImportTask extends APIImportTask { if (isFolder) { this.collectDocumentsAndAttachments({ children: child.children, - collectionId, + rootId, parentDocumentId: id, out: node.children, manifest, diff --git a/server/routes/api/imports/imports.test.ts b/server/routes/api/imports/imports.test.ts index 0a244baa72..0c4b57ff69 100644 --- a/server/routes/api/imports/imports.test.ts +++ b/server/routes/api/imports/imports.test.ts @@ -1,8 +1,15 @@ -import { ImportState, IntegrationService } from "@shared/types"; +import { + CollectionPermission, + ImportState, + IntegrationService, +} from "@shared/types"; import type { Import } from "@server/models"; import { buildAdmin, buildAttachment, + buildCollection, + buildDocument, + buildDraftDocument, buildImport, buildUser, } from "@server/test/factories"; @@ -61,6 +68,231 @@ describe("#imports.create", () => { expect(res.status).toEqual(403); }); + + describe("destination", () => { + it("persists collectionId when importing into an existing collection", async () => { + const admin = await buildAdmin(); + const attachment = await buildAttachment({ + teamId: admin.teamId, + userId: admin.id, + }); + const collection = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + permission: CollectionPermission.ReadWrite, + }); + + const res = await server.post("/api/imports.create", admin, { + body: { + service: IntegrationService.JSON, + attachmentId: attachment.id, + collectionId: collection.id, + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.collectionId).toEqual(collection.id); + expect(body.data.documentId).toBeNull(); + }); + + it("persists documentId when importing into an existing document", async () => { + const admin = await buildAdmin(); + const attachment = await buildAttachment({ + teamId: admin.teamId, + userId: admin.id, + }); + const collection = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + permission: CollectionPermission.ReadWrite, + }); + const document = await buildDocument({ + teamId: admin.teamId, + userId: admin.id, + collectionId: collection.id, + }); + + const res = await server.post("/api/imports.create", admin, { + body: { + service: IntegrationService.JSON, + attachmentId: attachment.id, + documentId: document.id, + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.documentId).toEqual(document.id); + expect(body.data.collectionId).toBeNull(); + }); + + it("rejects when both collectionId and documentId are set", async () => { + const admin = await buildAdmin(); + const attachment = await buildAttachment({ + teamId: admin.teamId, + userId: admin.id, + }); + const collection = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + permission: CollectionPermission.ReadWrite, + }); + const document = await buildDocument({ + teamId: admin.teamId, + userId: admin.id, + collectionId: collection.id, + }); + + const res = await server.post("/api/imports.create", admin, { + body: { + service: IntegrationService.JSON, + attachmentId: attachment.id, + collectionId: collection.id, + documentId: document.id, + }, + }); + + expect(res.status).toEqual(400); + }); + + it("rejects permission together with a destination", async () => { + const admin = await buildAdmin(); + const attachment = await buildAttachment({ + teamId: admin.teamId, + userId: admin.id, + }); + const collection = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + permission: CollectionPermission.ReadWrite, + }); + + const res = await server.post("/api/imports.create", admin, { + body: { + service: IntegrationService.JSON, + attachmentId: attachment.id, + collectionId: collection.id, + permission: CollectionPermission.Read, + }, + }); + + expect(res.status).toEqual(400); + }); + + it("rejects a collection the user cannot create documents in", async () => { + const admin = await buildAdmin(); + const attachment = await buildAttachment({ + teamId: admin.teamId, + userId: admin.id, + }); + // A private collection (no ReadWrite permission) the admin has no + // membership in — createDocument is denied. + const other = await buildUser({ teamId: admin.teamId }); + const collection = await buildCollection({ + teamId: admin.teamId, + userId: other.id, + permission: null, + }); + + const res = await server.post("/api/imports.create", admin, { + body: { + service: IntegrationService.JSON, + attachmentId: attachment.id, + collectionId: collection.id, + }, + }); + + expect(res.status).toEqual(403); + }); + + it("rejects an archived document destination", async () => { + const admin = await buildAdmin(); + const attachment = await buildAttachment({ + teamId: admin.teamId, + userId: admin.id, + }); + const document = await buildDocument({ + teamId: admin.teamId, + userId: admin.id, + archivedAt: new Date(), + }); + + const res = await server.post("/api/imports.create", admin, { + body: { + service: IntegrationService.Markdown, + attachmentId: attachment.id, + documentId: document.id, + }, + }); + + expect(res.status).toEqual(403); + }); + + it("rejects a template document destination", async () => { + const admin = await buildAdmin(); + const attachment = await buildAttachment({ + teamId: admin.teamId, + userId: admin.id, + }); + const document = await buildDocument({ + teamId: admin.teamId, + userId: admin.id, + template: true, + }); + + const res = await server.post("/api/imports.create", admin, { + body: { + service: IntegrationService.Markdown, + attachmentId: attachment.id, + documentId: document.id, + }, + }); + + expect(res.status).toEqual(404); + }); + + it("rejects a document destination in another team", async () => { + const admin = await buildAdmin(); + const attachment = await buildAttachment({ + teamId: admin.teamId, + userId: admin.id, + }); + const document = await buildDocument(); + + const res = await server.post("/api/imports.create", admin, { + body: { + service: IntegrationService.Markdown, + attachmentId: attachment.id, + documentId: document.id, + }, + }); + + expect(res.status).toEqual(403); + }); + + it("rejects a draft document destination", async () => { + const admin = await buildAdmin(); + const attachment = await buildAttachment({ + teamId: admin.teamId, + userId: admin.id, + }); + const draft = await buildDraftDocument({ + teamId: admin.teamId, + userId: admin.id, + }); + + const res = await server.post("/api/imports.create", admin, { + body: { + service: IntegrationService.JSON, + attachmentId: attachment.id, + documentId: draft.id, + }, + }); + + expect(res.status).toEqual(403); + }); + }); }); describe("#imports.list", () => { diff --git a/server/routes/api/imports/imports.ts b/server/routes/api/imports/imports.ts index 4d4fbd1742..809c5e8bbb 100644 --- a/server/routes/api/imports/imports.ts +++ b/server/routes/api/imports/imports.ts @@ -9,7 +9,7 @@ import auth from "@server/middlewares/authentication"; import { rateLimiter } from "@server/middlewares/rateLimiter"; import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; -import { Attachment, Integration } from "@server/models"; +import { Attachment, Collection, Document, Integration } from "@server/models"; import Import from "@server/models/Import"; import { authorize } from "@server/policies"; import { presentImport, presentPolicies } from "@server/presenters"; @@ -20,6 +20,45 @@ import * as T from "./schema"; const router = new Router(); +/** + * Resolves and authorizes the optional import destination. When a collection + * is chosen the user must be able to create documents in it; when a document + * is chosen the user must be able to add children to it. + * + * @param ctx The API context for the create request. + * @returns The resolved destination ids (both null when no destination set). + */ +async function resolveImportDestination( + ctx: APIContext +): Promise<{ collectionId: string | null; documentId: string | null }> { + const { user } = ctx.state.auth; + const { transaction } = ctx.state; + const { collectionId, documentId } = ctx.input.body; + + if (collectionId) { + const collection = await Collection.findByPk(collectionId, { + userId: user.id, + transaction, + rejectOnEmpty: true, + }); + authorize(user, "createDocument", collection); + return { collectionId, documentId: null }; + } + + if (documentId) { + const document = await Document.findByPk(documentId, { + userId: user.id, + transaction, + rejectOnEmpty: true, + }); + authorize(user, "createChildDocument", document); + + return { collectionId: null, documentId }; + } + + return { collectionId: null, documentId: null }; +} + router.post( "imports.create", rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), @@ -32,6 +71,8 @@ router.post( authorize(user, "createImport", user.team); + const { collectionId, documentId } = await resolveImportDestination(ctx); + if ("attachmentId" in body) { const attachment = await Attachment.findByPk(body.attachmentId, { rejectOnEmpty: true, @@ -52,6 +93,8 @@ router.post( ], scratch: { storageKey: attachment.key }, integrationId: null, + collectionId, + documentId, createdById: user.id, teamId: user.teamId, }); @@ -79,6 +122,8 @@ router.post( state: ImportState.Created, input: body.input, integrationId: body.integrationId, + collectionId, + documentId, createdById: user.id, teamId: user.teamId, }); diff --git a/server/routes/api/imports/schema.ts b/server/routes/api/imports/schema.ts index 0e8c6fc98a..dedd7fdf5b 100644 --- a/server/routes/api/imports/schema.ts +++ b/server/routes/api/imports/schema.ts @@ -8,11 +8,24 @@ import { import { Hook, PluginManager } from "@server/utils/PluginManager"; import { BaseSchema } from "../schema"; +/** + * Optional destination for the import. When either is set, root nodes are + * materialized as documents under the destination rather than as new + * collections. + */ +const DestinationShape = { + /** Existing collection to import root nodes into as root documents. */ + collectionId: z.uuid().optional(), + /** Existing document to import root nodes under as child documents. */ + documentId: z.uuid().optional(), +}; + /** The body to import an uploaded file. */ export const AttachmentImportBodySchema = z.object({ service: z.enum(ImportableIntegrationService), attachmentId: z.uuid(), permission: z.enum(CollectionPermission).optional(), + ...DestinationShape, }); /** The body to import from a connected integration. */ @@ -20,6 +33,7 @@ export const IntegrationImportBodySchema = z.object({ service: z.enum(ImportableIntegrationService), integrationId: z.uuid(), input: z.array(BaseImportInputItemSchema), + ...DestinationShape, }); /** A body that an import plugin accepts in imports.create. */ @@ -57,16 +71,35 @@ const ImportsSortParamsSchema = z.object({ }); export const ImportsCreateSchema = BaseSchema.extend({ - body: z.union([ - AttachmentImportBodySchema.extend({ - service: z.enum([ - IntegrationService.Markdown, - IntegrationService.OKF, - IntegrationService.JSON, - ]), - }), - pluginBodies, - ]), + body: z + .union([ + AttachmentImportBodySchema.extend({ + service: z.enum([ + IntegrationService.Markdown, + IntegrationService.OKF, + IntegrationService.JSON, + ]), + }), + pluginBodies, + ]) + .refine((body) => !(body.collectionId && body.documentId), { + error: "Only one of collectionId or documentId may be set", + }) + .refine( + (body) => { + if (!body.collectionId && !body.documentId) { + return true; + } + if ("input" in body) { + return !body.input.some((item) => item.permission); + } + return body.permission === undefined; + }, + { + error: + "permission cannot be set when importing into an existing destination", + } + ), }); export type ImportsCreateReq = z.infer; diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 0e98697fab..cd1108f631 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -1332,9 +1332,7 @@ "Please choose a single file to import": "Please choose a single file to import", "Your import is being processed, you can safely leave this page": "Your import is being processed, you can safely leave this page", "File not supported – please upload a valid ZIP file": "File not supported – please upload a valid ZIP file", - "Set the default permission level for collections created from the import": "Set the default permission level for collections created from the import", "Uploading {{progress}}%": "Uploading {{progress}}%", - "Start import": "Start import", "Added by": "Added by", "Date added": "Date added", "Users exported successfully": "Users exported successfully", @@ -1395,6 +1393,8 @@ "Drag and drop the zip file from the Markdown export option in {{appName}}, or click to upload": "Drag and drop the zip file from the Markdown export option in {{appName}}, or click to upload", "You can import a zip file of an Open Knowledge Format (OKF) bundle – folders become collections and documents, and document titles are read from YAML frontmatter.": "You can import a zip file of an Open Knowledge Format (OKF) bundle – folders become collections and documents, and document titles are read from YAML frontmatter.", "Drag and drop a zip file of the OKF bundle, or click to upload": "Drag and drop a zip file of the OKF bundle, or click to upload", + "Choose an existing location to import into, or new collections will be created.": "Choose an existing location to import into, or new collections will be created.", + "Set the default permission level for collections created from the import": "Set the default permission level for collections created from the import", "Configure": "Configure", "Never used": "Never used", "Are you sure you want to revoke access?": "Are you sure you want to revoke access?", diff --git a/shared/schema.ts b/shared/schema.ts index 4667f4bb2a..6ceb348f0e 100644 --- a/shared/schema.ts +++ b/shared/schema.ts @@ -8,6 +8,12 @@ import { export const BaseImportInputItemSchema = z.object({ permission: z.enum(CollectionPermission).optional(), + /** + * Marks a synthetic root node (e.g. Markdown's fallback "Documents" node) + * so it can collapse when importing into an existing destination — its loose + * child files then parent directly to the destination. + */ + synthetic: z.boolean().optional(), }); export type BaseImportInput = z.infer[]; @@ -39,6 +45,9 @@ export type ImportInput = export const BaseImportTaskInputItemSchema = z.object({ externalId: z.string(), parentExternalId: z.string().optional(), + /** External id of the root node this item descends from. */ + rootExternalId: z.string().optional(), + /** @deprecated Only present on tasks queued before rootExternalId existed. */ collectionExternalId: z.string().optional(), }); @@ -134,6 +143,8 @@ export type ImportScratch = export interface MarkdownPageImportTaskInputItem { externalId: string; parentExternalId?: string; + rootExternalId?: string; + /** @deprecated Only present on tasks queued before rootExternalId existed. */ collectionExternalId?: string; title: string; path: string; @@ -165,6 +176,8 @@ export type MarkdownImportTaskInput = ( export interface JSONPageImportTaskInputItem { externalId: string; parentExternalId?: string; + rootExternalId?: string; + /** @deprecated Only present on tasks queued before rootExternalId existed. */ collectionExternalId?: string; title: string; urlId?: string;