feat: implement template update functionality with file handling and validation
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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>
|
||||
|
||||
143
src/components/TemplateEditForm.js
Normal file
143
src/components/TemplateEditForm.js
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -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,6 +105,18 @@ 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"
|
||||
>
|
||||
{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">
|
||||
@@ -128,6 +155,13 @@ export default function TemplateList({ templates, onTemplateDeleted }) {
|
||||
>
|
||||
Pobierz
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => handleEdit(template.template_id)}
|
||||
>
|
||||
Edytuj
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
@@ -138,6 +172,7 @@ export default function TemplateList({ templates, onTemplateDeleted }) {
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user