Decision now support auto mailing

This commit is contained in:
Simon Pocrnjič
2025-10-12 00:20:03 +02:00
parent 1b615163be
commit 3ab1c05fcc
33 changed files with 1862 additions and 548 deletions
+264 -217
View File
@@ -4,12 +4,7 @@ import { Head, Link, useForm, router, usePage } from "@inertiajs/vue3";
import { ref, watch, computed, onMounted, nextTick } from "vue";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { faArrowLeft, faEye } from "@fortawesome/free-solid-svg-icons";
// Ensure Quill is available before importing the wrapper component
import Quill from "quill";
if (typeof window !== "undefined" && !window.Quill) {
// @ts-ignore
window.Quill = Quill;
}
// Keep Quill CSS for nicer preview styling, but remove the Quill editor itself
import "quill/dist/quill.snow.css";
const props = defineProps({
@@ -44,9 +39,8 @@ const previewHtml = computed(() => {
return containsDocScaffold(html) ? extractBody(html) : html;
}
// Fallback to local content if server preview didn't provide HTML
return sourceMode.value
? extractBody(form.html_template || "")
: stripDocScaffold(form.html_template || "");
// We only use the advanced editor now, so just show the <body> content when available
return extractBody(form.html_template || "");
});
const docsRaw = ref(props.template?.documents ? [...props.template.documents] : []);
const docs = computed(() =>
@@ -66,6 +60,12 @@ function updateLocalDoc(documentId, path, name = null, size = null) {
docsRaw.value.splice(idx, 1, next);
}
}
async function removeLocalDoc(documentId) {
const idx = docsRaw.value.findIndex((d) => d.id === documentId);
if (idx !== -1) {
docsRaw.value.splice(idx, 1);
}
}
function formatSize(bytes) {
if (!bytes && bytes !== 0) return "";
const kb = bytes / 1024;
@@ -97,6 +97,7 @@ const fetchPreview = () => {
// Always send full HTML so head/styles can be respected and inlined server-side
html: form.html_template,
text: form.text_template,
activity_id: sample.value.activity_id || undefined,
client_id: sample.value.client_id || undefined,
case_id: sample.value.case_id || undefined,
contract_id: sample.value.contract_id || undefined,
@@ -130,6 +131,7 @@ async function fetchFinalHtml() {
subject: form.subject_template,
html: form.html_template,
text: form.text_template,
activity_id: sample.value.activity_id || undefined,
client_id: sample.value.client_id || undefined,
case_id: sample.value.case_id || undefined,
contract_id: sample.value.contract_id || undefined,
@@ -186,62 +188,25 @@ onMounted(() => {
// Populate cascading selects immediately so the Client dropdown isn't empty
loadClients();
fetchPreview();
// Mount Quill editor directly
try {
if (quillContainer.value) {
// instantiate lazily to ensure DOM is ready
const editor = new Quill(quillContainer.value, {
theme: "snow",
modules: quillModules.value,
});
quill.value = editor;
if (form.html_template) {
const bodyOnly = stripDocScaffold(form.html_template);
if (bodyOnly) {
// Ensure Quill properly converts HTML to Delta
editor.clipboard.dangerouslyPasteHTML(0, bodyOnly, "api");
} else {
editor.setText(
"(Body is empty. Switch to Source HTML to edit full document.)",
"api"
);
}
}
editor.on("text-change", (_delta, _old, source) => {
// Ignore programmatic changes; only persist user edits
if (source !== "user") {
return;
}
if (!sourceMode.value) {
const bodyHtml = editor.root.innerHTML;
form.html_template = containsDocScaffold(form.html_template)
? replaceBody(form.html_template, bodyHtml)
: bodyHtml;
}
});
}
} catch (e) {
console.error("Failed to mount Quill", e);
}
// Initialize iframe editor if advanced mode is on
if (advancedMode.value) {
initIframeEditor();
}
// Advanced editor is the only mode
activeField.value = "html";
initIframeEditor();
});
// --- Variable insertion and sample entity selection ---
const subjectRef = ref(null);
const quillContainer = ref(null);
const htmlSourceRef = ref(null);
const textRef = ref(null);
const activeField = ref(null); // 'subject' | 'html' | 'text'
const quill = ref(null);
const sourceMode = ref(false); // toggle for HTML source editing
const activeField = ref("html"); // default to HTML for variable inserts
// Raw HTML editor toggle (full-document source)
const rawMode = ref(false);
// Advanced full-document editor that renders styles from <head>
const advancedMode = ref(false);
const advancedMode = ref(true);
const iframeRef = ref(null);
let iframeSyncing = false;
const selectedImageSrc = ref("");
// Preview iframe ref (to render preview HTML with <head> styles applied)
const previewIframeRef = ref(null);
// Detect and handle full-document HTML so Quill doesn't wipe content
function containsDocScaffold(html) {
@@ -261,20 +226,9 @@ function extractBody(html) {
return m ? m[1] : html;
}
// Retained for compatibility, but no longer used actively
function stripDocScaffold(html) {
if (!html) return "";
let out = html;
// Prefer body content when present
out = extractBody(out);
// Remove comments, doctype, html/head blocks, meta/title, and styles (Quill can't keep these)
out = out
.replace(/<!DOCTYPE[\s\S]*?>/gi, "")
.replace(/<\/?html[^>]*>/gi, "")
.replace(/<head[\s\S]*?>[\s\S]*?<\/head>/gi, "")
.replace(/<\/?meta[^>]*>/gi, "")
.replace(/<title[\s\S]*?>[\s\S]*?<\/title>/gi, "")
.replace(/<style[\s\S]*?>[\s\S]*?<\/style>/gi, "");
return out.trim();
return extractBody(html || "");
}
// Replace only the inner content of <body>...</body> in a full document
@@ -287,82 +241,31 @@ function replaceBody(htmlDoc, newBody) {
return htmlDoc.replace(/(<body[^>]*>)[\s\S]*?(<\/body>)/i, `$1${newBody || ""}$2`);
}
// Keep Quill and textarea in sync when toggling source mode
watch(
() => sourceMode.value,
(on) => {
if (on) {
// Switching to source view: if current model is NOT a full document,
// sync from Quill. Otherwise, keep the full source untouched.
if (quill.value && !containsDocScaffold(form.html_template)) {
form.html_template = quill.value.root.innerHTML;
}
} else {
// switching back to WYSIWYG: update editor html from model
if (quill.value) {
const bodyOnly = stripDocScaffold(form.html_template || "");
if (bodyOnly) {
quill.value.clipboard.dangerouslyPasteHTML(0, bodyOnly, "api");
} else {
quill.value.setText(
"(Body is empty. Switch to Source HTML to edit full document.)",
"api"
);
}
} else if (quillContainer.value) {
// if the instance doesn't exist for any reason, re-create it
const editor = new Quill(quillContainer.value, {
theme: "snow",
modules: quillModules.value,
});
quill.value = editor;
const bodyOnly = stripDocScaffold(form.html_template || "");
if (bodyOnly) {
editor.clipboard.dangerouslyPasteHTML(0, bodyOnly, "api");
} else {
editor.setText(
"(Body is empty. Switch to Source HTML to edit full document.)",
"api"
);
}
editor.on("text-change", (_d, _o, source) => {
if (source !== "user") {
return;
}
if (!sourceMode.value) {
const bodyHtml = editor.root.innerHTML;
form.html_template = containsDocScaffold(form.html_template)
? replaceBody(form.html_template, bodyHtml)
: bodyHtml;
}
});
}
}
}
);
// Quill/source mode removed
// Keep advanced editor in a stable state with source/quill
watch(
() => advancedMode.value,
async (on) => {
if (on) {
sourceMode.value = false;
await nextTick();
initIframeEditor();
}
}
);
// Advanced mode is always on
// When HTML changes externally, reflect it into iframe (unless we're the ones syncing)
watch(
() => form.html_template,
async () => {
if (!advancedMode.value || iframeSyncing) return;
if (iframeSyncing) return;
await nextTick();
writeIframeDocument();
}
);
// Re-initialize iframe editor when switching back from Raw HTML
watch(
() => rawMode.value,
async (on) => {
if (!on) {
await nextTick();
initIframeEditor();
}
}
);
function ensureFullDoc(html) {
if (!html)
return '<!doctype html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /></head><body></body></html>';
@@ -401,6 +304,8 @@ function initIframeEditor() {
} else {
selectedImageSrc.value = "";
}
// Ensure variable buttons target HTML editor
activeField.value = "html";
});
const handler = debounce(() => {
if (!advancedMode.value) return;
@@ -416,6 +321,17 @@ function initIframeEditor() {
doc.addEventListener("keyup", handler);
}
function writePreviewDocument() {
const iframe = previewIframeRef.value;
if (!iframe) return;
const doc = iframe.contentDocument;
if (!doc) return;
const html = ensureFullDoc(preview.value?.html || form.html_template || "");
doc.open();
doc.write(html);
doc.close();
}
function iframeExec(command, value = null) {
const iframe = iframeRef.value;
if (!iframe) return;
@@ -522,6 +438,128 @@ function setActive(field) {
activeField.value = field;
}
async function deleteAttachedImage(doc) {
if (!props.template?.id) return;
if (!doc?.id) return;
const confirmed = window.confirm(
"Odstranim to sliko iz predloge? Datoteka bo izbrisana."
);
if (!confirmed) return;
try {
await window.axios.delete(
route("admin.email-templates.images.delete", {
emailTemplate: props.template.id,
document: doc.id,
})
);
await removeLocalDoc(doc.id);
// After deletion, scrub or replace references in current HTML
tryReplaceOrRemoveDeletedImageReferences(doc);
} catch (e) {
console.error("Delete image failed", e);
alert("Brisanje slike ni uspelo.");
}
}
function tryReplaceOrRemoveDeletedImageReferences(deletedDoc) {
const deletedPath = deletedDoc?.path || "";
if (!deletedPath) return;
const targetRel = "/storage/" + deletedPath.replace(/^\/+/, "");
// Helper: does an <img> src match the deleted doc path (relative or absolute)?
const srcMatches = (src) => {
if (!src) return false;
try {
// Absolute URL: compare its pathname
const u = new URL(src, window.location.origin);
return u.pathname === targetRel;
} catch {
// Relative path string
if (src === targetRel) return true;
// Also accept raw disk path variant (unlikely in HTML)
if (src.replace(/^\/+/, "") === targetRel.replace(/^\/+/, "")) return true;
return false;
}
};
// Choose a replacement doc based on <img alt> when possible; else, if only one image remains, use that.
const pickReplacement = (altText) => {
const remaining = (docsRaw.value || []).slice();
if (!remaining.length) return null;
const norm = (s) => (s || "").toString().toLowerCase();
const stem = (name) =>
(name || "")
.toString()
.toLowerCase()
.replace(/\.[^.]+$/, "");
const simplify = (s) => norm(s).replace(/[^a-z0-9]+/g, "");
if (altText) {
const altKey = simplify(altText);
// exact name stem match (name, file_name, original_name)
const exact = remaining.find((d) => {
const candidates = [d.name, d.file_name, d.original_name].map(stem);
return candidates.some(
(c) => simplify(c) === altKey || norm(c) === norm(altText)
);
});
if (exact) return exact;
// relaxed contains on simplified stems
const relaxed = remaining.find((d) => {
const candidates = [d.name, d.file_name, d.original_name].map(stem).map(simplify);
return candidates.some((c) => c && altKey && c.includes(altKey));
});
if (relaxed) return relaxed;
}
if (remaining.length === 1) return remaining[0];
return null;
};
const replaceInDocument = (docEl) => {
if (!docEl) return false;
let changed = false;
const imgs = Array.from(docEl.querySelectorAll("img"));
imgs.forEach((img) => {
const src = img.getAttribute("src");
if (!srcMatches(src)) return;
const alt = img.getAttribute("alt") || "";
const replacement = pickReplacement(alt);
if (replacement && replacement.path) {
img.setAttribute("src", "/storage/" + replacement.path.replace(/^\/+/, ""));
} else {
// No replacement remove the image tag entirely
img.parentNode && img.parentNode.removeChild(img);
}
changed = true;
});
return changed;
};
if (!rawMode.value) {
// Advanced iframe editor
const iframe = iframeRef.value;
const doc = iframe?.contentDocument;
if (doc && doc.documentElement) {
const changed = replaceInDocument(doc);
if (changed) {
iframeSyncing = true;
form.html_template = doc.documentElement.outerHTML;
iframeSyncing = false;
}
}
} else {
// Raw mode: parse and mutate via DOMParser
const html = form.html_template || "";
const full = ensureFullDoc(html);
const parser = new DOMParser();
const parsed = parser.parseFromString(full, "text/html");
const changed = replaceInDocument(parsed);
if (changed) {
form.html_template = parsed.documentElement.outerHTML;
}
}
}
function insertAtCursor(el, value, modelGetter, modelSetter) {
if (!el) return;
const start = el.selectionStart ?? 0;
@@ -549,8 +587,8 @@ function insertPlaceholder(token) {
(v) => (form.subject_template = v)
);
} else if (activeField.value === "html") {
// If in source mode, treat HTML as textarea
if (sourceMode.value && htmlSourceRef.value) {
// If editing raw source, insert at caret into textarea
if (rawMode.value && htmlSourceRef.value) {
insertAtCursor(
htmlSourceRef.value,
content,
@@ -559,16 +597,31 @@ function insertPlaceholder(token) {
);
return;
}
// Insert into Quill editor at current selection
if (quill.value) {
let range = quill.value.getSelection(true);
const index = range ? range.index : quill.value.getLength() - 1;
quill.value.insertText(index, content, "user");
quill.value.setSelection(index + content.length, 0, "user");
// Sync back to form model as HTML
form.html_template = quill.value.root.innerHTML;
// Otherwise, insert into the iframe at caret position
// Insert into the iframe at caret position without rewriting the document
const iframe = iframeRef.value;
const doc = iframe?.contentDocument;
if (doc) {
const sel = doc.getSelection();
if (sel && sel.rangeCount > 0) {
const range = sel.getRangeAt(0);
range.deleteContents();
const node = doc.createTextNode(content);
range.insertNode(node);
// place caret after inserted node
range.setStartAfter(node);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
} else {
doc.body.appendChild(doc.createTextNode(content));
}
// Sync back to model
iframeSyncing = true;
form.html_template = doc.documentElement.outerHTML;
iframeSyncing = false;
} else {
// Fallback: append to the end of the model
// last resort
form.html_template = (form.html_template || "") + content;
}
} else if (activeField.value === "text" && textRef.value) {
@@ -581,53 +634,7 @@ function insertPlaceholder(token) {
}
}
// Quill toolbar & image upload handler
const quillModules = computed(() => ({
toolbar: {
container: [
["bold", "italic", "underline", "strike"],
[{ header: [1, 2, 3, false] }],
[{ list: "ordered" }, { list: "bullet" }],
["link", "image"],
[{ align: [] }],
["clean"],
],
handlers: {
image: () => onQuillImageUpload(),
},
},
}));
function onQuillImageUpload() {
const input = document.createElement("input");
input.type = "file";
input.accept = "image/*";
input.onchange = async () => {
const file = input.files?.[0];
if (!file) return;
const data = new FormData();
data.append("file", file);
try {
const { data: res } = await window.axios.post(
route("admin.email-templates.upload-image"),
data,
{ headers: { "Content-Type": "multipart/form-data" } }
);
const url = res?.url;
if (url && quill.value) {
const range = quill.value.getSelection(true);
const index = range ? range.index : quill.value.getLength();
quill.value.insertEmbed(index, "image", url, "user");
quill.value.setSelection(index + 1, 0, "user");
form.html_template = quill.value.root.innerHTML;
}
} catch (e) {
// optional: show toast
console.error("Image upload failed", e);
}
};
input.click();
}
// Quill handlers removed; image actions handled by iframe toolbar
const placeholderGroups = computed(() => {
const groups = [];
@@ -643,10 +650,15 @@ const placeholderGroups = computed(() => {
]);
}
if (want.has("client")) {
add("client", "Client", ["client.id", "client.uuid"]);
add("client", "Client", ["client.id", "client.uuid", "client.person.full_name"]);
}
if (want.has("client_case")) {
add("case", "Case", ["case.id", "case.uuid", "case.reference"]);
add("case", "Case", [
"case.id",
"case.uuid",
"case.reference",
"case.person.full_name",
]);
}
if (want.has("contract")) {
add("contract", "Contract", [
@@ -657,13 +669,28 @@ const placeholderGroups = computed(() => {
"contract.meta.some_key",
]);
}
// Activity placeholders (always useful if template references workflow actions/decisions)
add("activity", "Activity", [
"activity.id",
"activity.note",
"activity.due_date",
"activity.amount",
"activity.action.name",
"activity.decision.name",
]);
// Extra is always useful for ad-hoc data
add("extra", "Extra", ["extra.some_key"]);
return groups;
});
// Sample entity selection for preview
const sample = ref({ client_id: "", case_id: "", contract_id: "", extra: "" });
const sample = ref({
client_id: "",
case_id: "",
contract_id: "",
activity_id: "",
extra: "",
});
// Cascading select options
const clients = ref([]);
@@ -716,6 +743,10 @@ watch(
() => sample.value.contract_id,
() => doPreview()
);
watch(
() => sample.value.activity_id,
() => doPreview()
);
function applySample() {
fetchPreview();
@@ -745,6 +776,7 @@ function sendTest() {
subject: form.subject_template,
html: form.html_template,
text: form.text_template,
activity_id: sample.value.activity_id || undefined,
client_id: sample.value.client_id || undefined,
person_id: sample.value.person_id || undefined,
case_id: sample.value.case_id || undefined,
@@ -780,6 +812,8 @@ function sendTest() {
}
} catch {}
notify("Testni e-poštni naslov je bil poslan.", "success");
// Slight UX tweak: controller now queues the email
// (flash success message from backend reflects 'queued')
},
onError: () => {
// Validation errors trigger onError; controller may also set flash('error') on redirect
@@ -798,6 +832,15 @@ function sendTest() {
},
});
}
// Keep preview iframe in sync with server-rendered preview
watch(
() => preview.value?.html,
async () => {
await nextTick();
writePreviewDocument();
}
);
</script>
<template>
@@ -887,35 +930,22 @@ function sendTest() {
<label class="label">HTML vsebina</label>
<div class="flex items-center gap-4 text-xs text-gray-600">
<label class="inline-flex items-center gap-2">
<input type="checkbox" v-model="advancedMode" /> Napredni (poln
dokument)
</label>
<label class="inline-flex items-center gap-2">
<input type="checkbox" v-model="sourceMode" :disabled="advancedMode" />
Source HTML
<input type="checkbox" v-model="rawMode" /> Raw HTML
</label>
</div>
</div>
<!-- Quill body editor (hidden when advanced editor is active) -->
<div v-show="!sourceMode && !advancedMode">
<div
ref="quillContainer"
class="bg-white border rounded-lg min-h-[260px] p-2 focus-within:ring-2 ring-indigo-500/40"
@focusin="setActive('html')"
></div>
</div>
<!-- Source HTML textarea -->
<div v-show="sourceMode && !advancedMode">
<!-- Raw HTML textarea -->
<div v-show="rawMode">
<textarea
v-model="form.html_template"
rows="12"
rows="16"
class="input font-mono"
ref="htmlSourceRef"
@focus="setActive('html')"
></textarea>
</div>
<!-- Advanced full-document editor (iframe) -->
<div v-show="advancedMode" class="space-y-2">
<div v-show="!rawMode" class="space-y-2">
<div class="flex flex-wrap gap-2">
<button
type="button"
@@ -1057,6 +1087,15 @@ function sendTest() {
<div>
<div class="label">Sample entities</div>
<div class="grid grid-cols-2 gap-2">
<label class="text-xs text-gray-600">
Activity ID
<input
v-model="sample.activity_id"
type="number"
class="input h-9"
placeholder="npr. 123"
/>
</label>
<label class="text-xs text-gray-600">
Client
<select v-model="sample.client_id" class="input h-9">
@@ -1121,10 +1160,10 @@ function sendTest() {
</div>
<div>
<div class="label">HTML</div>
<div
class="p-3 rounded-lg bg-gray-50 border ql-editor max-h-[480px] overflow-auto"
v-html="previewHtml"
></div>
<iframe
ref="previewIframeRef"
class="w-full h-[480px] border rounded bg-white"
></iframe>
</div>
<div>
<div class="label">Text</div>
@@ -1134,7 +1173,8 @@ function sendTest() {
</div>
<div class="text-xs text-gray-500" v-pre>
Available placeholders example: {{ person.full_name }}, {{ client.uuid }},
{{ case.reference }}, {{ contract.reference }}, {{ contract.meta.some_key }}
{{ case.reference }}, {{ contract.reference }}, {{ contract.meta.some_key }},
{{ activity.note }}, {{ activity.action.name }}, {{ activity.decision.name }}
</div>
<div class="mt-4 flex flex-col sm:flex-row sm:items-end gap-2">
<div class="w-full sm:w-auto">
@@ -1214,6 +1254,13 @@ function sendTest() {
class="text-xs px-2 py-1 rounded border bg-gray-50 hover:bg-gray-100"
>Odpri</a
>
<button
type="button"
class="text-xs px-2 py-1 rounded border bg-red-50 text-red-700 hover:bg-red-100"
@click="deleteAttachedImage(d)"
>
Odstrani
</button>
</div>
</div>
</div>