feat: implement template update functionality with file handling and validation

This commit is contained in:
2025-12-18 11:00:01 +01:00
parent 75b8bfd84f
commit 8b11dc5083
4 changed files with 338 additions and 45 deletions

View File

@@ -1,8 +1,116 @@
import { NextRequest, NextResponse } from "next/server";
import { unlink } from "fs/promises";
import fs from "fs";
import path from "path";
import db from "@/lib/db";
export async function PUT(request, { params }) {
try {
const { templateId } = params;
const formData = await request.formData();
const templateName = formData.get("templateName")?.toString().trim();
const description = formData.get("description")?.toString().trim();
const file = formData.get("file");
if (!templateName) {
return NextResponse.json(
{ error: "Template name is required" },
{ status: 400 }
);
}
// Check if template exists
const existingTemplate = db.prepare(`
SELECT * FROM docx_templates WHERE template_id = ? AND is_active = 1
`).get(templateId);
if (!existingTemplate) {
return NextResponse.json(
{ error: "Template not found" },
{ status: 404 }
);
}
let updateData = {
template_name: templateName,
description: description || null,
updated_at: new Date().toISOString()
};
// If a new file is provided, handle file replacement
if (file && file.size > 0) {
// Validate file type
if (!file.name.toLowerCase().endsWith('.docx')) {
return NextResponse.json(
{ error: "Only .docx files are allowed" },
{ status: 400 }
);
}
// Validate file size (10MB limit)
if (file.size > 10 * 1024 * 1024) {
return NextResponse.json(
{ error: "File size must be less than 10MB" },
{ status: 400 }
);
}
// Delete old file
try {
const oldFilePath = path.join(process.cwd(), "public", existingTemplate.file_path);
await unlink(oldFilePath);
} catch (fileError) {
console.warn("Could not delete old template file:", fileError);
}
// Save new file
const fileExtension = path.extname(file.name);
const fileName = `${Date.now()}-${Math.random().toString(36).substring(2)}${fileExtension}`;
const filePath = path.join(process.cwd(), "public", "templates", fileName);
// Ensure templates directory exists
const templatesDir = path.join(process.cwd(), "public", "templates");
try {
await fs.promises.access(templatesDir);
} catch {
await fs.promises.mkdir(templatesDir, { recursive: true });
}
const buffer = Buffer.from(await file.arrayBuffer());
await fs.promises.writeFile(filePath, buffer);
updateData.file_path = `/templates/${fileName}`;
updateData.original_filename = file.name;
updateData.file_size = file.size;
}
// Update database
const updateFields = Object.keys(updateData).map(key => `${key} = ?`).join(', ');
const updateValues = Object.values(updateData);
db.prepare(`
UPDATE docx_templates
SET ${updateFields}
WHERE template_id = ?
`).run([...updateValues, templateId]);
// Get updated template
const updatedTemplate = db.prepare(`
SELECT * FROM docx_templates WHERE template_id = ?
`).get(templateId);
return NextResponse.json(updatedTemplate);
} catch (error) {
console.error("Template update error:", error);
return NextResponse.json(
{ error: "Failed to update template" },
{ status: 500 }
);
}
}
export async function DELETE(request, { params }) {
try {
const { templateId } = params;

View File

@@ -40,6 +40,12 @@ export default function TemplatesPage() {
setTemplates(prev => prev.filter(t => t.template_id !== templateId));
};
const handleTemplateUpdated = (updatedTemplate) => {
setTemplates(prev => prev.map(t =>
t.template_id === updatedTemplate.template_id ? updatedTemplate : t
));
};
if (loading) {
return (
<PageContainer>
@@ -83,6 +89,7 @@ export default function TemplatesPage() {
<TemplateList
templates={templates}
onTemplateDeleted={handleTemplateDeleted}
onTemplateUpdated={handleTemplateUpdated}
/>
</div>
</Card>

View File

@@ -0,0 +1,143 @@
"use client";
import { useState, useRef, useEffect } from "react";
import Button from "@/components/ui/Button";
export default function TemplateEditForm({ template, onTemplateUpdated, onCancel }) {
const [updating, setUpdating] = useState(false);
const [formData, setFormData] = useState({
templateName: "",
description: "",
});
const fileInputRef = useRef(null);
useEffect(() => {
if (template) {
setFormData({
templateName: template.template_name || "",
description: template.description || "",
});
}
}, [template]);
const handleSubmit = async (e) => {
e.preventDefault();
if (!formData.templateName.trim()) {
alert("Proszę podać nazwę szablonu");
return;
}
setUpdating(true);
try {
const updateData = new FormData();
updateData.append("templateName", formData.templateName);
updateData.append("description", formData.description);
const file = fileInputRef.current?.files[0];
if (file) {
updateData.append("file", file);
}
const response = await fetch(`/api/templates/${template.template_id}`, {
method: "PUT",
body: updateData,
});
if (response.ok) {
const updatedTemplate = await response.json();
onTemplateUpdated(updatedTemplate);
} else {
const error = await response.json();
alert(`Błąd podczas aktualizacji: ${error.error}`);
}
} catch (error) {
console.error("Update error:", error);
alert("Błąd podczas aktualizacji szablonu");
} finally {
setUpdating(false);
}
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value
}));
};
if (!template) {
return null;
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Nazwa szablonu *
</label>
<input
type="text"
name="templateName"
value={formData.templateName}
onChange={handleInputChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="np. Umowa projektowa"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Opis
</label>
<textarea
name="description"
value={formData.description}
onChange={handleInputChange}
rows={3}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="Opcjonalny opis szablonu"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Nowy plik DOCX (opcjonalnie)
</label>
<input
type="file"
ref={fileInputRef}
accept=".docx"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
<p className="text-sm text-gray-500 mt-1">
Zostaw puste, aby zachować obecny plik. Max 10MB.
</p>
<p className="text-sm text-gray-600 mt-1">
Obecny plik: {template.original_filename}
</p>
</div>
<div className="flex gap-3">
<Button
type="submit"
variant="primary"
disabled={updating}
>
{updating ? "Aktualizowanie..." : "Aktualizuj szablon"}
</Button>
<Button
type="button"
variant="outline"
onClick={onCancel}
disabled={updating}
>
Anuluj
</Button>
</div>
</form>
);
}

View File

@@ -3,9 +3,11 @@
import { useState } from "react";
import Button from "@/components/ui/Button";
import Badge from "@/components/ui/Badge";
import TemplateEditForm from "./TemplateEditForm";
export default function TemplateList({ templates, onTemplateDeleted }) {
export default function TemplateList({ templates, onTemplateDeleted, onTemplateUpdated }) {
const [deletingId, setDeletingId] = useState(null);
const [editingId, setEditingId] = useState(null);
const handleDelete = async (templateId) => {
if (!confirm("Czy na pewno chcesz usunąć ten szablon?")) {
@@ -32,6 +34,19 @@ export default function TemplateList({ templates, onTemplateDeleted }) {
}
};
const handleEdit = (templateId) => {
setEditingId(templateId);
};
const handleEditCancel = () => {
setEditingId(null);
};
const handleTemplateUpdated = (updatedTemplate) => {
onTemplateUpdated(updatedTemplate);
setEditingId(null);
};
const formatFileSize = (bytes) => {
if (bytes === 0) return "0 Bytes";
const k = 1024;
@@ -90,54 +105,74 @@ export default function TemplateList({ templates, onTemplateDeleted }) {
key={template.template_id}
className="border border-gray-200 rounded-lg p-4 hover:bg-gray-50 transition-colors"
>
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<h4 className="font-medium text-gray-900">
{template.template_name}
</h4>
<Badge variant="success" size="xs">
Aktywny
</Badge>
{editingId === template.template_id ? (
<div>
<h4 className="font-medium text-gray-900 mb-4">
Edytuj szablon: {template.template_name}
</h4>
<TemplateEditForm
template={template}
onTemplateUpdated={handleTemplateUpdated}
onCancel={handleEditCancel}
/>
</div>
) : (
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<h4 className="font-medium text-gray-900">
{template.template_name}
</h4>
<Badge variant="success" size="xs">
Aktywny
</Badge>
</div>
{template.description && (
<p className="text-sm text-gray-600 mb-2">
{template.description}
</p>
)}
<div className="flex items-center gap-4 text-sm text-gray-500">
<span>
Plik: {template.original_filename}
</span>
<span>
Rozmiar: {formatFileSize(template.file_size)}
</span>
<span>
Dodano: {formatDate(template.created_at)}
</span>
</div>
</div>
{template.description && (
<p className="text-sm text-gray-600 mb-2">
{template.description}
</p>
)}
<div className="flex items-center gap-4 text-sm text-gray-500">
<span>
Plik: {template.original_filename}
</span>
<span>
Rozmiar: {formatFileSize(template.file_size)}
</span>
<span>
Dodano: {formatDate(template.created_at)}
</span>
<div className="flex gap-2 ml-4">
<Button
variant="outline"
size="sm"
onClick={() => window.open(template.file_path, "_blank")}
>
Pobierz
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => handleEdit(template.template_id)}
>
Edytuj
</Button>
<Button
variant="danger"
size="sm"
onClick={() => handleDelete(template.template_id)}
disabled={deletingId === template.template_id}
>
{deletingId === template.template_id ? "Usuwanie..." : "Usuń"}
</Button>
</div>
</div>
<div className="flex gap-2 ml-4">
<Button
variant="outline"
size="sm"
onClick={() => window.open(template.file_path, "_blank")}
>
Pobierz
</Button>
<Button
variant="danger"
size="sm"
onClick={() => handleDelete(template.template_id)}
disabled={deletingId === template.template_id}
>
{deletingId === template.template_id ? "Usuwanie..." : "Usuń"}
</Button>
</div>
</div>
)}
</div>
))}
</div>