feat: Add document template management functionality
- Created migration script to add `docx_templates` table with necessary fields and indexes. - Implemented API routes for uploading, fetching, and deleting document templates. - Developed document generation feature using selected templates and project data. - Added UI components for template upload and listing, including a modal for document generation. - Integrated document generation into the project view page, allowing users to generate documents based on selected templates. - Enhanced error handling and user feedback for template operations.
This commit is contained in:
248
src/components/DocumentGenerator.js
Normal file
248
src/components/DocumentGenerator.js
Normal file
@@ -0,0 +1,248 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Button from "@/components/ui/Button";
|
||||
import Card from "@/components/ui/Card";
|
||||
|
||||
export default function DocumentGenerator({ projectId }) {
|
||||
const [templates, setTemplates] = useState([]);
|
||||
const [selectedTemplate, setSelectedTemplate] = useState("");
|
||||
const [generating, setGenerating] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [customFields, setCustomFields] = useState([{ key: "", value: "" }]);
|
||||
const [showCustomFields, setShowCustomFields] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetchTemplates();
|
||||
}, []);
|
||||
|
||||
const fetchTemplates = async () => {
|
||||
try {
|
||||
const response = await fetch("/api/templates");
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setTemplates(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching templates:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCustomFieldChange = (index, field, value) => {
|
||||
const updatedFields = [...customFields];
|
||||
updatedFields[index][field] = value;
|
||||
setCustomFields(updatedFields);
|
||||
};
|
||||
|
||||
const addCustomField = () => {
|
||||
setCustomFields([...customFields, { key: "", value: "" }]);
|
||||
};
|
||||
|
||||
const removeCustomField = (index) => {
|
||||
if (customFields.length > 1) {
|
||||
setCustomFields(customFields.filter((_, i) => i !== index));
|
||||
}
|
||||
};
|
||||
|
||||
const getCustomData = () => {
|
||||
const customData = {};
|
||||
customFields.forEach(field => {
|
||||
if (field.key.trim()) {
|
||||
customData[field.key.trim()] = field.value;
|
||||
}
|
||||
});
|
||||
return customData;
|
||||
};
|
||||
|
||||
const handleGenerate = async () => {
|
||||
if (!selectedTemplate) {
|
||||
alert("Proszę wybrać szablon");
|
||||
return;
|
||||
}
|
||||
|
||||
setGenerating(true);
|
||||
|
||||
try {
|
||||
const customData = getCustomData();
|
||||
const response = await fetch("/api/templates/generate", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
templateId: selectedTemplate,
|
||||
projectId: projectId,
|
||||
customData: customData,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
// Create a blob from the response and download it
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
|
||||
// Get filename from response headers
|
||||
const contentDisposition = response.headers.get("Content-Disposition");
|
||||
let filename = "generated_document.docx";
|
||||
if (contentDisposition) {
|
||||
const filenameMatch = contentDisposition.match(/filename="(.+)"/);
|
||||
if (filenameMatch) {
|
||||
filename = filenameMatch[1];
|
||||
}
|
||||
}
|
||||
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
document.body.removeChild(a);
|
||||
} else {
|
||||
const error = await response.json();
|
||||
let errorMessage = error.error;
|
||||
|
||||
// Provide more helpful error messages
|
||||
if (error.details) {
|
||||
errorMessage += `\n\nSzczegóły: ${error.details}`;
|
||||
}
|
||||
|
||||
if (error.error.includes("duplicate")) {
|
||||
errorMessage += "\n\nRozwiązanie: Użyj unikalnych nazw dla każdego wystąpienia tej samej informacji, np. {{project_name_1}} i {{project_name_2}}.";
|
||||
}
|
||||
|
||||
alert(`Błąd podczas generowania dokumentu:\n\n${errorMessage}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Generation error:", error);
|
||||
alert("Błąd podczas generowania dokumentu");
|
||||
} finally {
|
||||
setGenerating(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="text-sm text-gray-500">Ładowanie szablonów...</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (templates.length === 0) {
|
||||
return (
|
||||
<div className="text-sm text-gray-500">
|
||||
Brak dostępnych szablonów.{" "}
|
||||
<a
|
||||
href="/templates"
|
||||
className="text-blue-600 hover:text-blue-800 underline"
|
||||
target="_blank"
|
||||
>
|
||||
Dodaj szablon
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Wybierz szablon
|
||||
</label>
|
||||
<select
|
||||
value={selectedTemplate}
|
||||
onChange={(e) => setSelectedTemplate(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
<option value="">-- Wybierz szablon --</option>
|
||||
{templates.map((template) => (
|
||||
<option key={template.template_id} value={template.template_id}>
|
||||
{template.template_name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Custom Fields Section */}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Dodatkowe dane (opcjonalne)
|
||||
</label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowCustomFields(!showCustomFields)}
|
||||
className="text-xs"
|
||||
>
|
||||
{showCustomFields ? "Ukryj" : "Pokaż"} dodatkowe pola
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showCustomFields && (
|
||||
<div className="space-y-2 border border-gray-200 rounded-md p-3 bg-gray-50">
|
||||
{customFields.map((field, index) => (
|
||||
<div key={index} className="flex gap-2 items-center">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Nazwa pola (np. custom_note)"
|
||||
value={field.key}
|
||||
onChange={(e) => handleCustomFieldChange(index, 'key', e.target.value)}
|
||||
className="flex-1 px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-transparent"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Wartość"
|
||||
value={field.value}
|
||||
onChange={(e) => handleCustomFieldChange(index, 'value', e.target.value)}
|
||||
className="flex-1 px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-transparent"
|
||||
/>
|
||||
{customFields.length > 1 && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => removeCustomField(index)}
|
||||
className="text-red-600 hover:text-red-800 p-1"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addCustomField}
|
||||
className="w-full text-xs"
|
||||
>
|
||||
+ Dodaj pole
|
||||
</Button>
|
||||
<div className="text-xs text-gray-500 mt-2">
|
||||
Wprowadź dodatkowe dane, które będą dostępne w szablonie jako {"{custom_note}"}, {"{additional_info}"} itp.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleGenerate}
|
||||
disabled={!selectedTemplate || generating}
|
||||
variant="primary"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
>
|
||||
{generating ? "Generowanie..." : "Generuj dokument"}
|
||||
</Button>
|
||||
|
||||
<div className="text-xs text-gray-500">
|
||||
Dokument zostanie wygenerowany na podstawie danych projektu i pobrany automatycznie.
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
146
src/components/TemplateList.js
Normal file
146
src/components/TemplateList.js
Normal file
@@ -0,0 +1,146 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Button from "@/components/ui/Button";
|
||||
import Badge from "@/components/ui/Badge";
|
||||
|
||||
export default function TemplateList({ templates, onTemplateDeleted }) {
|
||||
const [deletingId, setDeletingId] = useState(null);
|
||||
|
||||
const handleDelete = async (templateId) => {
|
||||
if (!confirm("Czy na pewno chcesz usunąć ten szablon?")) {
|
||||
return;
|
||||
}
|
||||
|
||||
setDeletingId(templateId);
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/templates/${templateId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
onTemplateDeleted(templateId);
|
||||
} else {
|
||||
alert("Błąd podczas usuwania szablonu");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Delete error:", error);
|
||||
alert("Błąd podczas usuwania szablonu");
|
||||
} finally {
|
||||
setDeletingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const formatFileSize = (bytes) => {
|
||||
if (bytes === 0) return "0 Bytes";
|
||||
const k = 1024;
|
||||
const sizes = ["Bytes", "KB", "MB", "GB"];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
|
||||
};
|
||||
|
||||
const formatDate = (dateString) => {
|
||||
return new Date(dateString).toLocaleDateString("pl-PL", {
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
};
|
||||
|
||||
if (templates.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-12">
|
||||
<div className="text-gray-400 mb-4">
|
||||
<svg
|
||||
className="w-12 h-12 mx-auto"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.5}
|
||||
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="text-lg font-medium text-gray-900 mb-2">
|
||||
Brak szablonów
|
||||
</h3>
|
||||
<p className="text-gray-500">
|
||||
Dodaj swój pierwszy szablon dokumentów DOCX.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-lg font-medium text-gray-900">
|
||||
Dostępne szablony ({templates.length})
|
||||
</h3>
|
||||
|
||||
<div className="space-y-3">
|
||||
{templates.map((template) => (
|
||||
<div
|
||||
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>
|
||||
</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>
|
||||
|
||||
<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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
134
src/components/TemplateUploadForm.js
Normal file
134
src/components/TemplateUploadForm.js
Normal file
@@ -0,0 +1,134 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef } from "react";
|
||||
import Button from "@/components/ui/Button";
|
||||
|
||||
export default function TemplateUploadForm({ onTemplateUploaded, onCancel }) {
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [formData, setFormData] = useState({
|
||||
templateName: "",
|
||||
description: "",
|
||||
});
|
||||
const fileInputRef = useRef(null);
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
const file = fileInputRef.current?.files[0];
|
||||
if (!file) {
|
||||
alert("Proszę wybrać plik DOCX");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!formData.templateName.trim()) {
|
||||
alert("Proszę podać nazwę szablonu");
|
||||
return;
|
||||
}
|
||||
|
||||
setUploading(true);
|
||||
|
||||
try {
|
||||
const uploadData = new FormData();
|
||||
uploadData.append("file", file);
|
||||
uploadData.append("templateName", formData.templateName);
|
||||
uploadData.append("description", formData.description);
|
||||
|
||||
const response = await fetch("/api/templates", {
|
||||
method: "POST",
|
||||
body: uploadData,
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const newTemplate = await response.json();
|
||||
onTemplateUploaded(newTemplate);
|
||||
setFormData({ templateName: "", description: "" });
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = "";
|
||||
}
|
||||
} else {
|
||||
const error = await response.json();
|
||||
alert(`Błąd podczas przesyłania: ${error.error}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Upload error:", error);
|
||||
alert("Błąd podczas przesyłania szablonu");
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleInputChange = (e) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[name]: value
|
||||
}));
|
||||
};
|
||||
|
||||
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">
|
||||
Plik DOCX *
|
||||
</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"
|
||||
required
|
||||
/>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
Wybierz plik szablonu DOCX (max 10MB)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={uploading}
|
||||
>
|
||||
{uploading ? "Przesyłanie..." : "Prześlij szablon"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onCancel}
|
||||
disabled={uploading}
|
||||
>
|
||||
Anuluj
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user