add tag assign to documents batch

This commit is contained in:
team 1
2026-02-25 15:37:29 +01:00
parent 4b5ad9b338
commit 3e264cbff4
4 changed files with 269 additions and 3 deletions

View File

@@ -4,9 +4,12 @@ declare(strict_types=1);
namespace App\Controller\Admin; namespace App\Controller\Admin;
use App\Entity\Document;
use App\Entity\DocumentTag;
use App\Entity\Tag; use App\Entity\Tag;
use App\Entity\TagRebuildJob; use App\Entity\TagRebuildJob;
use App\Tag\TagService; use App\Tag\TagService;
use App\Service\TagRebuildJobService;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\RedirectResponse;
@@ -20,10 +23,10 @@ final class TagController extends AbstractController
#[Route('', name: 'admin_tags_index', methods: ['GET'])] #[Route('', name: 'admin_tags_index', methods: ['GET'])]
public function index( public function index(
EntityManagerInterface $em, EntityManagerInterface $em,
\App\Service\TagRebuildJobService $jobs TagRebuildJobService $jobs
): Response { ): Response {
$tags = $em->getRepository(\App\Entity\Tag::class) $tags = $em->getRepository(Tag::class)
->findBy([], ['label' => 'ASC']); ->findBy([], ['label' => 'ASC']);
return $this->render('admin/tag/index.html.twig', [ return $this->render('admin/tag/index.html.twig', [
@@ -89,5 +92,71 @@ final class TagController extends AbstractController
return $this->redirectToRoute('admin_tags_index'); return $this->redirectToRoute('admin_tags_index');
} }
#[Route('/{id}/assign', name: 'admin_tags_assign', methods: ['GET', 'POST'])]
public function assign(
string $id,
EntityManagerInterface $em,
Request $request,
TagService $tagService,
TagRebuildJobService $jobs
): Response {
$tag = $em->getRepository(Tag::class)->find($id);
if (!$tag instanceof Tag) {
throw $this->createNotFoundException('Tag nicht gefunden.');
}
// Alle Dokumente laden
$documents = $em->getRepository(Document::class)->findAll();
$documentsData = array_map(
fn(Document $d) => [
'id' => (string) $d->getId(),
'title' => $d->getTitle(),
],
$documents
);
// Aktuell zugewiesene Dokumente ermitteln
$existingRelations = $em
->getRepository(DocumentTag::class)
->findBy(['tag' => $tag]);
$assignedDocIds = array_map(
fn(DocumentTag $dt) => (string) $dt->getDocument()->getId(),
$existingRelations
);
if ($request->isMethod('POST')) {
if (!$this->isCsrfTokenValid(
'assign_tag_' . $tag->getId(),
$request->request->get('_token')
)) {
throw $this->createAccessDeniedException();
}
$selectedIds = $request->request->all('documents') ?? [];
$tagService->syncTagDocuments($tag, $selectedIds);
$this->addFlash('success', 'Zuweisungen aktualisiert.');
return $this->redirectToRoute('admin_tags_assign', [
'id' => $tag->getId()
]);
}
return $this->render('admin/tag/assign.html.twig', [
'tag' => $tag,
'documents' => $documentsData,
'assignedDocIds' => $assignedDocIds,
'latestJob' => $jobs->getLatestJob(),
'hasActiveJob' => $jobs->hasActiveJob(),
'statusRunning' => TagRebuildJob::STATUS_RUNNING,
'statusQueued' => TagRebuildJob::STATUS_QUEUED,
'statusCompleted' => TagRebuildJob::STATUS_COMPLETED,
'statusFailed' => TagRebuildJob::STATUS_FAILED,
]);
}
} }

View File

@@ -110,6 +110,49 @@ final class TagService
} }
} }
// =========================================================
// TAG → DOCUMENT SYNC (Bulk Assign)
// =========================================================
/**
* Synchronisiert alle Dokumente eines Tags.
* Löst einen Rebuild aus, da document_ids Teil des NDJSON sind.
*/
public function syncTagDocuments(Tag $tag, array $newDocumentIds): void
{
$newDocumentIds = array_unique($newDocumentIds);
$currentRelations = $this->em
->getRepository(DocumentTag::class)
->findBy(['tag' => $tag]);
$currentDocumentIds = array_map(
fn(DocumentTag $dt) => (string) $dt->getDocument()->getId(),
$currentRelations
);
$toAdd = array_diff($newDocumentIds, $currentDocumentIds);
$toRemove = array_diff($currentDocumentIds, $newDocumentIds);
foreach ($toAdd as $documentId) {
$document = $this->em->getRepository(Document::class)->find($documentId);
if ($document instanceof Document) {
$this->em->persist(new DocumentTag($document, $tag));
}
}
foreach ($currentRelations as $relation) {
if (in_array((string) $relation->getDocument()->getId(), $toRemove, true)) {
$this->em->remove($relation);
}
}
if ($toAdd || $toRemove) {
$this->em->flush();
$this->triggerRebuildIfIdle();
}
}
// ========================================================= // =========================================================
// INTERNAL HELPERS // INTERNAL HELPERS
// ========================================================= // =========================================================

View File

@@ -0,0 +1,144 @@
{% extends 'admin/base.html.twig' %}
{% block title %}Tag zuweisen{% endblock %}
{% block body %}
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="h3 mb-0">
Tag: {{ tag.label }}
</h1>
<a href="{{ path('admin_tags_index') }}"
class="btn btn-sm btn-outline-secondary">
Zurück
</a>
</div>
{# ========================================================= #}
{# LIVE REBUILD STATUS (SSE) #}
{# ========================================================= #}
<div id="rebuild-status">
<div class="alert alert-secondary shadow-sm">
Status wird geladen…
</div>
</div>
<script>
const statusBox = document.getElementById('rebuild-status');
const source = new EventSource("{{ path('admin_tags_rebuild_stream') }}");
source.onmessage = function (event) {
const data = JSON.parse(event.data);
let html = '';
if (data.status === '{{ statusRunning }}') {
html = `
<div class="alert alert-info shadow-sm d-flex justify-content-between align-items-center">
<div>
<strong>Tag-Rebuild läuft</strong><br>
${data.startedAt ? 'Gestartet: ' + new Date(data.startedAt).toLocaleString() : ''}
</div>
<div class="spinner-border spinner-border-sm"></div>
</div>
`;
} else if (data.status === '{{ statusQueued }}') {
html = `
<div class="alert alert-secondary shadow-sm">
<strong>Tag-Rebuild in Warteschlange</strong>
</div>
`;
} else if (data.status === '{{ statusCompleted }}') {
html = `
<div class="alert alert-success shadow-sm">
<strong>Tag-Rebuild erfolgreich abgeschlossen</strong>
</div>
`;
} else if (data.status === '{{ statusFailed }}') {
html = `
<div class="alert alert-danger shadow-sm">
<strong>Tag-Rebuild fehlgeschlagen</strong><br>
${data.error ? '<code>' + data.error + '</code>' : ''}
</div>
`;
}
statusBox.innerHTML = html;
};
source.onerror = function () {
console.warn('SSE Verbindung verloren');
};
</script>
{# ============================= #}
{# Flash Messages #}
{# ============================= #}
{% for message in app.flashes('success') %}
<div class="alert alert-success">
{{ message }}
</div>
{% endfor %}
{% for message in app.flashes('danger') %}
<div class="alert alert-danger">
{{ message }}
</div>
{% endfor %}
{# ============================= #}
{# Tag → Dokumente #}
{# ============================= #}
<form method="post">
<input type="hidden"
name="_token"
value="{{ csrf_token('assign_tag_' ~ tag.id) }}">
<div class="card bg-black border-secondary">
<div class="card-body p-0">
<table class="table table-dark table-striped table-hover mb-0 align-middle">
<thead class="table-secondary text-dark">
<tr>
<th style="width:60px;"></th>
<th>Dokument</th>
</tr>
</thead>
<tbody>
{% for doc in documents %}
<tr>
<td>
<input type="checkbox"
name="documents[]"
value="{{ doc.id }}"
{% if doc.id in assignedDocIds %}checked{% endif %}>
</td>
<td>
{{ doc.title }}
</td>
</tr>
{% else %}
<tr>
<td colspan="2" class="text-center text-muted">
Keine Dokumente vorhanden.
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<button class="btn btn-primary mt-3">
Speichern
</button>
</form>
{% endblock %}

View File

@@ -158,16 +158,26 @@
<td><code>{{ tag.slug }}</code></td> <td><code>{{ tag.slug }}</code></td>
<td>{{ tag.description ?: '-' }}</td> <td>{{ tag.description ?: '-' }}</td>
<td class="text-end"> <td class="text-end">
<a href="{{ path('admin_tags_assign', { id: tag.id }) }}"
class="btn btn-sm btn-outline-info me-2">
Zuweisen
</a>
<form method="post" <form method="post"
action="{{ path('admin_tags_delete', {id: tag.id}) }}"> action="{{ path('admin_tags_delete', {id: tag.id}) }}"
style="display:inline-block;">
<input type="hidden" <input type="hidden"
name="_token" name="_token"
value="{{ csrf_token('admin_tag_delete_' ~ tag.id) }}"/> value="{{ csrf_token('admin_tag_delete_' ~ tag.id) }}"/>
<button class="btn btn-sm btn-outline-danger" <button class="btn btn-sm btn-outline-danger"
onclick="return confirm('Tag wirklich löschen? Zuweisungen werden entfernt.')"> onclick="return confirm('Tag wirklich löschen? Zuweisungen werden entfernt.')">
Löschen Löschen
</button> </button>
</form> </form>
</td> </td>
</tr> </tr>
{% else %} {% else %}