Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(document): add copy button #1109

Merged
merged 1 commit into from
Feb 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions addon/components/documents-side-panel.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
{{else}}
<MultiDocumentDetails
@selectedDocuments={{@selectedDocuments}}
@refreshDocumentList={{@refreshDocumentList}}
data-test-multi-doc-details
/>
{{/if}}
Expand Down
34 changes: 24 additions & 10 deletions addon/components/multi-document-details.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,35 @@
{{#if @selectedDocuments.length}}
<MarkManager @documents={{@selectedDocuments}} class="uk-margin" />

<div class="uk-margin">
<DocumentDeleteButton
@docsToDelete={{@selectedDocuments}}
as |showDialog|
>
<div class="uk-grid uk-grid-small uk-child-width-1-2" uk-grid>
<div>
<UkButton
data-test-delete
@size="small"
@color="danger"
@onClick={{this.copyDocuments.perform}}
@loading={{this.copyDocuments.isLoading}}
class="uk-width-1"
{{on "click" showDialog}}
data-test-copy
>
{{t "alexandria.delete"}}
{{t "alexandria.copy"}}
</UkButton>
</DocumentDeleteButton>
</div>

<div>
<DocumentDeleteButton
@docsToDelete={{@selectedDocuments}}
as |showDialog|
>
<UkButton
data-test-delete
@size="small"
@color="danger"
class="uk-width-1"
{{on "click" showDialog}}
>
{{t "alexandria.delete"}}
</UkButton>
</DocumentDeleteButton>
</div>
</div>

<hr>
Expand Down
26 changes: 26 additions & 0 deletions addon/components/multi-document-details.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { inject as service } from "@ember/service";
import Component from "@glimmer/component";
import { task } from "ember-concurrency";

import { ErrorHandler } from "ember-alexandria/utils/error-handler";

export default class MultiDocumentDetailsComponent extends Component {
@service("alexandria-side-panel") sidePanel;
@service("alexandria-documents") documents;
@service notification;
@service intl;

get mergedTags() {
const tags = [];
Expand All @@ -23,4 +30,23 @@ export default class MultiDocumentDetailsComponent extends Component {

return tags;
}

copyDocuments = task({ drop: true }, async (event) => {
event?.preventDefault();
try {
await this.documents.copy(
this.args.selectedDocuments.map((doc) => doc.id),
);
await this.args.refreshDocumentList();
this.notification.success(
this.intl.t("alexandria.success.copy-document", {
count: this.args.selectedDocuments.length,
}),
);
} catch (error) {
new ErrorHandler(this, error).notify("alexandria.errors.copy-document", {
count: this.args.selectedDocuments.length,
});
}
});
}
14 changes: 13 additions & 1 deletion addon/components/single-document-details.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,18 @@
</div>
{{/if}}

<div>
<UkButton
@size="small"
@onClick={{this.copyDocument.perform}}
@loading={{this.copyDocument.isRunning}}
class="uk-width-1"
data-test-copy
>
{{t "alexandria.copy"}}
</UkButton>
</div>

<div uk-form-custom>
<input
data-test-replace
Expand All @@ -241,7 +253,7 @@
</button>
</div>

<div>
<div class="uk-width-1-1">
<DocumentDeleteButton @docsToDelete={{@document}} as |showDialog|>
<UkButton
data-test-delete
Expand Down
15 changes: 15 additions & 0 deletions addon/components/single-document-details.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,4 +146,19 @@ export default class SingleDocumentDetailsComponent extends Component {
new ErrorHandler(this, error).notify("alexandria.errors.open-webdav");
}
});

copyDocument = task({ drop: true }, async (event) => {
event?.preventDefault();
try {
await this.documents.copy([this.args.document.id]);
await this.args.refreshDocumentList();
this.notification.success(
this.intl.t("alexandria.success.copy-document", { count: 1 }),
);
} catch (error) {
new ErrorHandler(this, error).notify("alexandria.errors.copy-document", {
count: 1,
});
}
});
}
70 changes: 70 additions & 0 deletions addon/services/alexandria-documents.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,76 @@ export default class AlexandriaDocumentsService extends Service {
return states;
}

/**
* Copies one or multiple files.
*
* @param {Array<Number>} documentIds.
* @param {Object} category category instance.
*/
async copy(documentIds, category = null) {
const INVALID_FILE_TYPE = "invalid-file-type";

const states = await Promise.all(
documentIds.map(async (id) => {
const originalDocument = this.store.peekRecord("document", id);
if (!originalDocument) {
return true;
}

const files = (await originalDocument.files) ?? [];
if (
category &&
files
.filter((f) => f.variant === "original")
.some((file) => !fileHasValidMimeType(file, category))
) {
return "invalid-file-type";
}

const adapter = this.store.adapterFor("document");
let url = adapter.buildURL("document", originalDocument.id);
url += "/copy";

const data = {
type: "documents",
id: originalDocument.id,
relationships: {},
};

if (category) {
data.relationships.category = {
data: {
id: category.id,
type: "categories",
},
};
}

try {
const res = await this.fetch.fetch(url, {
method: "POST",
body: JSON.stringify({ data }),
});

return (await res.json()).data.id;
} catch (error) {
new ErrorHandler(this, error).notify();

return false;
}
}),
);

if (states.includes(INVALID_FILE_TYPE)) {
this.mimeTypeErrorNotification(category);
return states.map((state) =>
state === INVALID_FILE_TYPE ? false : state,
);
}

return states;
}

/**
* Clears the document selection
*/
Expand Down
50 changes: 50 additions & 0 deletions tests/acceptance/documents-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,56 @@ module("Acceptance | documents", function (hooks) {
assert.dom("[data-test-document]").doesNotExist();
});

test("copy single document", async function (assert) {
const document = this.server.create("document");

await visit(`/`);

assert.dom("[data-test-document-list-item]").exists({ count: 1 });
await click("[data-test-document-list-item]:nth-of-type(1)");

this.assertRequest("POST", "/api/v1/documents/:id/copy", (request) => {
assert.strictEqual(
request.params.id,
document.id,
"copying the correct document",
);
});

await click("[data-test-single-doc-details] [data-test-copy]");
assert.dom("[data-test-document-list-item]").exists({ count: 2 });
});

test("copy multiple documents", async function (assert) {
const documents = this.server.createList("document", 2);

await visit(`/`);

assert.dom("[data-test-document-list-item]").exists({ count: 2 });

await click("[data-test-document-list-item]:nth-of-type(1)");
await click("[data-test-document-list-item]:nth-of-type(2)", {
shiftKey: true,
});

const assertFn = (document) => (request) => {
assert.strictEqual(
request.params.id,
document.id,
"copying the correct document",
);
};

this.assertRequests(
"POST",
"/api/v1/documents/:id/copy",
documents.map(assertFn),
);

await click("[data-test-multi-doc-details] [data-test-copy]");
assert.dom("[data-test-document-list-item]").exists({ count: 4 });
});

test("upload file", async function (assert) {
this.server.create("category");

Expand Down
19 changes: 19 additions & 0 deletions tests/dummy/mirage/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,25 @@ export default function makeServer(config) {
this.post("/documents", function (schema) {
return schema.documents.create();
});
this.post("/documents/:id/copy", function (schema, request) {
const originalDocument = schema.documents.find(request.params.id);
const payload = JSON.parse(request.requestBody || "{}");
const payloadCategoryId =
payload?.data?.relationships?.category?.data?.id;
const category = payloadCategoryId
? schema.categories.find(payloadCategoryId)
: originalDocument.category;

const input = {
...originalDocument.attrs,
};
delete input.id;

return schema.documents.create({
...input,
category,
});
});
this.resource("tags", { except: ["delete"] });
this.resource("marks", { only: ["index", "show"] });

Expand Down
3 changes: 3 additions & 0 deletions translations/de.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ alexandria:
upload-file: "Datei hochladen"
download: "Download"
move-document: "{count} {count, plural, one {Dokument} other {Dokumente}} verschieben"
copy: "Kopieren"

errors:
save-file: "Beim Herunterladen der Datei ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut."
Expand All @@ -21,6 +22,7 @@ alexandria:
update: "Änderungen konnten nicht gespeichert werden. Versuchen Sie es erneut."
no-permission: "Sie haben keine Berechtigung, diese Aktion auszuführen."
move-document: "Beim Verschieben {count, plural, one {des Dokumentes} other {von # Dokumenten}} ist ein Fehler aufgetreten"
copy-document: "Beim Kopieren {count, plural, one {des Dokumentes} other {von # Dokumenten}} ist ein Fehler aufgetreten"
convert-pdf: "Während dem Umwandeln ist ein Fehler aufgetreten."
invalid-file-type: 'In der Kategorie "{category}" können nur {types} hochgeladen werden.'
file-too-large: "Die hochgeladene Datei ist zu gross."
Expand All @@ -35,6 +37,7 @@ alexandria:
} erfolgreich hochgeladen.
update: "Änderungen wurden gespeichert."
move-document: "{count, plural, one {Das Dokument wurde} other {# Dokumente wurden}} erfolgreich verschoben"
copy-document: "{count, plural, one {Das Dokument wurde} other {# Dokumente wurden}} erfolgreich kopiert"
convert-pdf: "Dokument wurde erfolgreich umgewandelt."

category-nav:
Expand Down
3 changes: 3 additions & 0 deletions translations/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ alexandria:
upload-file: "Upload file"
download: "Download"
move-document: "Move {count} {count, plural, one {document} other {documents}}"
copy: "Copy"

errors:
save-file: "While downloading the document, an error occured. Please try again."
Expand All @@ -21,6 +22,7 @@ alexandria:
update: "Your changes could not be saved. Please try again."
no-permission: "You don't have permission to perform this action."
move-document: "While moving {count, plural, one {the document} other {# documents}}, an error occured. Please try again."
copy-document: "While copying {count, plural, one {the document} other {# documents}}, an error occured. Please try again."
convert-pdf: "While converting, an error occured. Please try again."
invalid-file-type: 'In category "{category}" only {types} can be uploaded.'
file-too-large: "The uploaded file is too large."
Expand All @@ -35,6 +37,7 @@ alexandria:
} uploaded successfully.
update: "Changes saved."
move-document: "{count, plural, one {Document} other {# documents}} moved successfully"
copy-document: "{count, plural, one {Document} other {# documents}} copied successfully"
convert-pdf: "Document converted successfully."

category-nav:
Expand Down
5 changes: 4 additions & 1 deletion translations/it.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,21 @@ alexandria:
upload-file: "Carica file"
download: "Download"
move-document: "Sposta {count} {count, plural, one {documento} other {documenti}}"
copy: "Copia"

errors:
save-file: "Errore nel tentativo di scaricare il file. Riprova"
delete-document: "Errore nel tentativo di eliminare il documento. Riprova"
fetch-categories: "Errore nel tentativo di caricare le categorie."
replace-document: "Errore nel tentativo di sostituire il documento."
upload-document: |-
Errore nel tentativo di caricare
Errore nel tentativo di caricare
{count, plural, one {il documento}
other {i documenti}}.
update: "Non è stato possibile salvare le modifiche. Riprova"
no-permission: "Non dispone dei diritti per eseguire questa operazione."
move-document: "Errore nel tentativo di spostare {count, plural, one {il documento} other {i documenti}}"
copy-document: "Errore nel tentativo di copiare {count, plural, one {il documento} other {i documenti}}"
convert-pdf: "Errore nel tentativo di convertire il documento."
invalid-file-type: 'Nella categoria "{category}" è possibile caricare solo {types}.'
file-too-large: "Il file caricato è troppo grande."
Expand All @@ -34,6 +36,7 @@ alexandria:
} con successo.
update: "Le modifiche sono state salvate."
move-document: "{count, plural, one {Il documento è stato spostato} other {# I documenti sono stati spostati}} con successo"
copy-document: "{count, plural, one {Il documento è stato copiato} other {# I documenti sono stati copiati}} con successo"
convert-pdf: "Il documento è stato convertito con successo."

category-nav:
Expand Down