profit-planet-frontend/src/app/admin/contract-management/components/contractEditor.tsx
2025-12-13 12:00:30 +01:00

264 lines
9.3 KiB
TypeScript

'use client';
import React, { useEffect, useRef, useState } from 'react';
import useContractManagement from '../hooks/useContractManagement';
type Props = {
onSaved?: () => void;
};
export default function ContractEditor({ onSaved }: Props) {
const [name, setName] = useState('');
const [htmlCode, setHtmlCode] = useState('');
const [isPreview, setIsPreview] = useState(false);
const [saving, setSaving] = useState(false);
const [statusMsg, setStatusMsg] = useState<string | null>(null);
const [lang, setLang] = useState<'en' | 'de'>('en');
const [type, setType] = useState<'contract' | 'bill' | 'other'>('contract');
const [userType, setUserType] = useState<'personal' | 'company' | 'both'>('personal');
const [description, setDescription] = useState<string>('');
const iframeRef = useRef<HTMLIFrameElement | null>(null);
const { uploadTemplate, updateTemplateState } = useContractManagement();
// Build a full HTML doc if user pasted only a snippet
const wrapIfNeeded = (src: string) => {
const hasDoc = /<!DOCTYPE|<html[\s>]/i.test(src);
if (hasDoc) return src;
// Minimal A4 skeleton so snippets render and print correctly
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Preview</title>
<style>
@page { size: A4; margin: 0; }
html, body { margin:0; padding:0; background:#eee; }
body { display:flex; justify-content:center; }
.a4 { width:210mm; min-height:297mm; background:#fff; box-shadow:0 0 5mm rgba(0,0,0,0.1); box-sizing:border-box; padding:20mm; }
@media print {
html, body { background:#fff; }
.a4 { box-shadow:none; margin:0; }
}
</style>
</head>
<body>
<div class="a4">${src}</div>
</body>
</html>`;
};
// Write/refresh iframe preview
useEffect(() => {
if (!isPreview) return;
const iframe = iframeRef.current;
if (!iframe) return;
const doc = iframe.contentDocument || iframe.contentWindow?.document;
if (!doc) return;
const html = wrapIfNeeded(htmlCode);
doc.open();
doc.write(html);
doc.close();
const resize = () => {
// Allow time for layout/styles
requestAnimationFrame(() => {
const h = doc.body ? Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight) : 1200;
iframe.style.height = Math.min(Math.max(h, 1123), 2000) + 'px'; // clamp for UX
});
};
// Initial resize and after load
resize();
const onLoad = () => resize();
iframe.addEventListener('load', onLoad);
// Also observe mutations to adjust height if content changes
const mo = new MutationObserver(resize);
mo.observe(doc.documentElement, { childList: true, subtree: true, attributes: true, characterData: true });
return () => {
iframe.removeEventListener('load', onLoad);
mo.disconnect();
};
}, [isPreview, htmlCode]);
const printPreview = () => {
const w = iframeRef.current?.contentWindow;
w?.focus();
w?.print();
};
const slug = (s: string) =>
s.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'template';
// NEW: all-fields-required guard
const canSave = Boolean(
name.trim() &&
htmlCode.trim() &&
description.trim() &&
type &&
userType &&
lang
)
const save = async (publish: boolean) => {
const html = htmlCode.trim();
// NEW: validate all fields
if (!canSave) {
setStatusMsg('Please fill all required fields (name, HTML, type, user type, language, description).');
return;
}
setSaving(true);
setStatusMsg(null);
try {
// Build a file from HTML code
const file = new File([html], `${slug(name)}.html`, { type: 'text/html' });
const created = await uploadTemplate({
file,
name,
type,
lang,
description: description || undefined,
user_type: userType,
});
if (publish && created?.id) {
await updateTemplateState(created.id, 'active');
}
setStatusMsg(publish ? 'Template created and activated.' : 'Template created.');
if (onSaved) onSaved();
// Optionally clear fields
// setName(''); setHtmlCode(''); setDescription(''); setType('contract'); setLang('en');
} catch (e: any) {
setStatusMsg(e?.message || 'Save failed.');
} finally {
setSaving(false);
}
};
return (
<div className="space-y-6">
<div className="flex flex-col gap-4">
<div className="flex flex-col sm:flex-row gap-4">
<input
type="text"
placeholder="Template name"
value={name}
onChange={(e) => setName(e.target.value)}
required
className="w-full sm:w-1/2 rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm text-gray-900 outline-none focus:ring-2 focus:ring-indigo-500/50 shadow"
/>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => setIsPreview((v) => !v)}
className="inline-flex items-center rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-900 px-4 py-2 text-sm font-medium shadow transition"
>
{isPreview ? 'Switch to Code' : 'Preview HTML'}
</button>
{isPreview && (
<button
type="button"
onClick={printPreview}
className="inline-flex items-center rounded-lg bg-indigo-50 hover:bg-indigo-100 text-indigo-700 px-4 py-2 text-sm font-medium shadow transition"
>
Print
</button>
)}
</div>
</div>
{/* New metadata inputs */}
<div className="flex flex-col sm:flex-row gap-4">
<select
value={type}
onChange={(e) => setType(e.target.value as 'contract' | 'bill' | 'other')}
required
className="w-full sm:w-1/3 rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm text-gray-900 outline-none focus:ring-2 focus:ring-indigo-500/50 shadow"
>
<option value="contract">Contract</option>
<option value="bill">Bill</option>
<option value="other">Other</option>
</select>
<select
value={userType}
onChange={(e) => setUserType(e.target.value as 'personal' | 'company' | 'both')}
required
className="w-full sm:w-40 rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm text-gray-900 outline-none focus:ring-2 focus:ring-indigo-500/50 shadow"
>
<option value="personal">Personal</option>
<option value="company">Company</option>
<option value="both">Both</option>
</select>
<select
value={lang}
onChange={(e) => setLang(e.target.value as 'en' | 'de')}
required
className="w-full sm:w-32 rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm text-gray-900 outline-none focus:ring-2 focus:ring-indigo-500/50 shadow"
>
<option value="en">English (en)</option>
<option value="de">Deutsch (de)</option>
</select>
<input
type="text"
placeholder="Description (optional)"
value={description}
onChange={(e) => setDescription(e.target.value)}
required
className="w-full rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm text-gray-900 outline-none focus:ring-2 focus:ring-indigo-500/50 shadow"
/>
</div>
</div>
{!isPreview && (
<textarea
value={htmlCode}
onChange={(e) => setHtmlCode(e.target.value)}
placeholder="Paste your full HTML (or snippet) here…"
required
className="min-h-[320px] w-full rounded-lg border border-gray-300 bg-white px-4 py-3 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 font-mono shadow"
/>
)}
{isPreview && (
<div className="rounded-lg border border-gray-300 bg-white shadow">
<iframe
ref={iframeRef}
title="Contract Preview"
className="w-full rounded-lg"
style={{ height: 1200, background: 'transparent' }}
/>
</div>
)}
<div className="flex items-center gap-4">
<button
onClick={() => save(false)}
disabled={saving || !canSave}
className="inline-flex items-center rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-900 px-4 py-2 text-sm font-medium shadow disabled:opacity-60 transition"
>
Create (inactive)
</button>
<button
onClick={() => save(true)}
disabled={saving || !canSave}
className="inline-flex items-center rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white px-4 py-2 text-sm font-medium shadow disabled:opacity-60 transition"
>
Create & Activate
</button>
{/* NEW: helper text */}
{!canSave && <span className="text-xs text-red-600">Fill all fields to proceed.</span>}
{saving && <span className="text-xs text-gray-500">Saving</span>}
{statusMsg && <span className="text-xs text-gray-600">{statusMsg}</span>}
</div>
</div>
);
}