unclean SPARC

This commit is contained in:
STEINNI
2025-08-27 07:03:09 +00:00
commit f308460931
430 changed files with 54426 additions and 0 deletions
@@ -0,0 +1,13 @@
<article eiccard eiccard collapsable collapsed hidden class="pub-decision">
<section>
<div class="forms decision-dialog">
<div class="eicui-input-container decision">
<label>You're about to request a review for this template.</label>
<label>Remarks or comments for the reviewer:</label>
<textarea eictextarea hint="Please don't be gross." name="decision" eicinput value="" class="tpl-decision"></textarea>
</div>
</div>
</section>
</article>
@@ -0,0 +1,51 @@
class TemplatesDecisionDialog extends EICDialogContent {
actions = [
{
label: 'Cancel',
onclick: this.cancel.bind(this),
severity: 'secondary',
role: 'cancel'
},
{
label: 'Validate',
onclick: this.validate.bind(this),
severity: 'primary',
role: 'validate',
disabled: true
}
]
constructor() {
super()
Object.assign(this, app.helpers.validators)
}
DOMContentLoaded(options) {
this.form = new Form(this.find('.decision-dialog'));
this.decisionTextarea = this.find('.tpl-decision');
this.decisionTextarea.addEventListener('keyup', this.checkDecisionTextarea.bind(this))
}
checkDecisionTextarea(event) {
event.preventDefault()
event.stopPropagation()
if (this.decisionTextarea.value.trim().length > 0) {
this.actions.find(o => o.role == 'validate').button.disabled = false
}
}
validate() {
let data = { comment: this.decisionTextarea.value }
this.commit(data)
}
onFailed() {
this.abort()
}
}
app.registerClass('TemplatesDecisionDialog', TemplatesDecisionDialog);
@@ -0,0 +1,35 @@
<style>
.tpl.testMail {
color: var(--eicui-base-color-info-110);
font-family: var(--eicui-base-font-family);
font-size: var(--eicui-base-font-size-l);
font-weight: 500;
letter-spacing: -.25px;
border-bottom: 1px solid var(--eicui-base-color-grey-25);
}
.tpl .test-email {
display: flex;
flex-direction: column;
gap: 5px;
}
.tpl .mail-address {
width: 30em;
}
</style>
<article eiccard eiccard collapsable collapsed hidden class="tpl testMail">
<header>
<h3>Sending a test email</h3>
</header>
<section>
<div class="tpl test-mail-dialog">
<div class="eicui-input-container test-email">
<div>Enter a valid email address</div>
<div>
<input eicinput type="text" name="email" eicinput value="" class="tpl mail-address">
</div>
</div>
</div>
</section>
</article>
@@ -0,0 +1,63 @@
class TemplatesMailTestDialog extends EICDialogContent {
actions = [
{
label: 'Cancel',
onclick: this.cancel.bind(this),
severity: 'secondary',
role: 'cancel'
},
{
label: 'Send test',
onclick: this.add.bind(this),
severity: 'primary',
role: 'add',
disabled: true
}
]
constructor() {
super()
Object.assign(this, app.helpers.validators)
}
DOMContentLoaded() {
this.form = new Form(this.find('.test-mail-dialog'))
this.mailInput = this.find('.mail-address')
this.mailInput.addEventListener('keyup', this.checkEmail.bind(this))
// Use user email by default
this.mailInput.value = app.User.identity.email || ''
// force validation on init
setTimeout(() => this.checkEmail(), 0)
}
checkEmail(event = null){
if(event){
event.preventDefault()
event.stopPropagation()
}
const addAction = this.actions.find(o => o.role === 'add')
if (!addAction || !addAction.button) {
return
}
const isValid = this.validators.isValidEmail(this.mailInput.value)
addAction.button.disabled = !isValid
}
add() {
if(!this.validators.isValidEmail(this.mailInput.value)) return
let data = { email: this.mailInput.value }
this.commit(data)
}
onFailed() {
this.abort()
}
}
app.registerClass('TemplatesMailTestDialog', TemplatesMailTestDialog)
@@ -0,0 +1,49 @@
<style>
.uplImg h6 {
margin-top: auto;
}
.uplImg .uplImg-AllowedExt {
text-align: center;
}
.dialog-spinner {
display: flex;
align-items: center;
justify-content: center;
padding: 1em;
font-size: 1.1em;
color: #333;
}
.eic-spinner {
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
width: 24px;
height: 24px;
animation: spin 1s linear infinite;
margin-right: 10px;
}
@keyframes spin {
0% { transform: rotate(0deg);}
100% { transform: rotate(360deg);}
}
</style>
<article eiccard eiccard collapsable collapsed hidden class="uplImg">
<header>
<h6>Upload images </h6>
<span>Allowed extensions:</span>
<div class="uplImg-AllowedExt">
<span eicbadge xlarge success>jpg</span>
<span eicbadge xlarge success>jpeg</span>
<span eicbadge xlarge success>png</span>
<span eicbadge xlarge success>svg</span>
</div>
</header>
<section>
<div class="forms upload-img-dialog">
<div class="eicui-input-container upload-img">
<div eicfileupload class="browseBtn"></div>
</div>
</div>
</section>
</article>
@@ -0,0 +1,112 @@
class TemplatesUplImgDialog extends EICDialogContent {
constructor() {
super();
Object.assign(this, app.helpers.validators); // Inject validators
this.actions = [
{
label: 'Cancel',
onclick: this.cancel.bind(this),
severity: 'secondary',
role: 'cancel'
}
];
}
DOMContentLoaded() {
const imgId = crypto.randomUUID()
const host = window.location.hostname
let envUrl = (host.split('.')[1] !== 'eismea') ? host.split('.')[1] + '.' : ''
// Initialize file upload
this.fileUpload = new FileUpload(this.find('.browseBtn'), {
uploadId: imgId,
uploadUrl: `https://myeic.${envUrl}eismea.eu/public/images/common/${imgId}`,
uploadMethod: 'PUT',
allowedExtensions: ['jpg', 'jpeg', 'png', 'svg'],
allowedMimes: ['image/jpeg', 'image/pjpeg', 'image/png', 'image/svg+xml'],
allowDrop: true,
maxFiles: 1,
minFiles: 1,
dndLabel: 'Drop your image here !',
imageTitle: '',
noUpload: false,
})
const dropArea = this.find('.file-drop-area')
const uplButton = this.find('.uploadBtn.custom-class')
const fileUpl = this.el.querySelector('.file-upload')
dropArea.addEventListener('change', () => {
const existingInput = fileUpl.querySelector('.tpl-imgTitle')
if (!existingInput) {
const inputTitle = ui.create(`
<input eicinput type="text" name="title" class="tpl-imgTitle" placeholder="title of your image" required>
`)
dropArea.appendChild(inputTitle)
// Desabled upload button if input Title empty
uplButton.disabled = true
// Add listener to input Title
inputTitle.addEventListener('input', () => {
const titleValue = inputTitle.value.trim()
if (titleValue) {
inputTitle.classList.remove('highlight')
uplButton.disabled = false
} else {
inputTitle.classList.add('highlight')
uplButton.disabled = true
}
this.fileUpload.options.imageTitle = inputTitle.value
})
}
})
// Event upload button
uplButton.addEventListener('click', () => {
this.fileUpload.onFileAdded.bind(this)
this.addFile()
})
}
// Handle File Added
addFile() {
const fileUpL = this.fileUpload
const uplUrl = fileUpL.options?.uploadUrl
const extension = uplUrl.split('.').pop()
const uplId = fileUpL.options?.uploadId
const fileName = uplId+'.'+extension
let data = {
id: uplId,
name: fileName,
type: extension,
path: '/common',
imageTitle: fileUpL.options?.imageTitle,
meta:'',
}
this.commit(data)
}
commit(data) {
this.result = data
// NE PAS appeler this.cancel() ou this.close() ici
}
showDialogSpinner(show = true) {
let spinner = this.find('.dialog-spinner')
if (!spinner && show) {
spinner = document.createElement('div')
spinner.className = 'dialog-spinner'
spinner.innerHTML = `<span class="eic-spinner"></span> Uploading...`
this.el.appendChild(spinner)
}
if (spinner) spinner.style.display = show ? 'block' : 'none'
}
}
// Register the class
app.registerClass('TemplatesUplImgDialog', TemplatesUplImgDialog)
@@ -0,0 +1,421 @@
<style>
.templateEditor header {
background: url('/app/assets/images/cards/templitorHeader.png') center/cover no-repeat;
}
.templateEditor header h1 {
align-items: center;
border-bottom: 1px solid var(--eicui-base-color-grey-15);
margin-bottom: -1px;
min-height: calc(3 * var(--eicui-base-spacing-m));
padding: calc(var(--eicui-base-spacing-3xl) * 2) var(--eicui-base-spacing-m) var(--eicui-base-spacing-s) var(--eicui-base-spacing-m);
display: block;
color: var(--eicui-base-color-white) !important;
text-shadow: 0 0 4px black;
font-size: x-large !important;
background-size: cover;
transition: all 0.4s;
}
article.templateEditor section{
padding-top: 0;
flex: 1;
}
.eicui-input-container.sticky {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 1000;
background: white; /* ou autre fond pour lisibilité */
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.templateEditor .template-field {
border: 1px solid var(--eicui-base-color-grey-10);
overflow: auto;
padding: 0.5em;
background-color: #fff;
}
.templateEditor .tplOpStartDate,
.templateEditor .tplOpEndDate {
width: 15em;
}
.tpl-editor .tplActions {
text-align: center;
}
.tpl-editor [eicapp] [eicrichtext] {
padding: var(--eicui-base-spacing-xs);
border: 1px solid var(--eicui-base-color-grey-10);
}
.tpl-editor .template-field.subject label {
font-style: italic;
}
.tpl-editor .file-input {
display: none;
}
.tpl-editor .tpl-edit-area {
width: 60vw;
}
.tpl-editor .path-container {
display: flex;
flex-direction: column;
gap: 5px;
margin-left: 5em;
align-items: flex-start;
}
.tpl-editor .input-button-wrapper {
display: flex;
align-items: center;
gap: 8px;
justify-content: flex-start;
width: 100%;
}
.tpl-editor .tplPath {
flex: 1;
min-width: 200px;
}
.tpl-editor .tpl-btn-path {
display: flex;
align-items: center;
justify-content: center;
padding: 5px 10px;
}
.tpl-editor .hidden {
display: none;
}
.tpl-editor .icon-spinner {
animation: spin 1s linear infinite;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.tpl-editor .tpl-spinButton{
border: 0;
}
.tpl-editor .hiddenInput {
position: absolute;
opacity: 0;
pointer-events: none;
width: 0;
}
@keyframes dots {
0% { content: "Loading"; }
33% { content: "Loading ."; }
66% { content: "Loading .."; }
100% { content: "Loading ..."; }
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.tpl-editor input[eicinput]{
height: 2em;
padding-bottom: 0.5em;
}
.tpl-editor .tpl-loadingTools {
font-size: 16px;
font-weight: bold;
color: #555;
animation: blink 1s infinite;
}
.tpl-editor .tpl-loadingTools::after {
content: "Loading";
animation: dots 1.5s infinite steps(1);
display: inline-block;
}
.tpl-editor .delete-img [eicbadge]{
position: relative;
}
.tpl-editor .he-imgSelectContainer{
width: 20%;
}
.tpl-editor .tpl-resizer {
resize: both;
overflow: hidden;
display: inline-block;
max-width: 100%;
}
.tpl-editor .he-imgItem.selected {
border: 2px solid blue;
background-color: lightgray;
}
.tpl-editor .he-imgItem {
transition: background-color 0.3s ease;
}
.tpl-editor .he-imgItem:hover {
background-color: #f0f0f0;
}
.tpl-editor .he-color-palette {
display: grid;
grid-template-columns: repeat(3, 1.5em);
gap: 0.5em;
position: fixed;
border: 1px solid #ccc;
padding: 2px;
background-color: #fff;
z-index: 1000;
}
.tpl-editor .he-colorOption {
width: 1.5em;
height: 1.5em;
cursor: pointer;
pointer-events: auto;
}
.tpl-editor .he-colorOption:hover {
border: 2px solid #000;
}
.tpl-editor .tpl-table {
border-collapse: collapse;
}
.tpl-editor .tpl-table td {
border: 1px solid #ccc;
padding: 10px;
position: relative;
}
.tpl-editor .he-listItems{
min-height: 100px;
}
.tpl-editor .tpl-history {
max-height: 12em;
overflow-y: auto;
}
.tpl-editor .tpl-history .data-set .row {
display: inline-block;
line-height: 1px;
}
.tpl-editor .template-history .footer {
font-size: x-small;
}
.tpl-editor .tpl-fullName,
.tpl-editor .tpl-comment {
display: grid;
}
.tpl-editor .tpl-comment {
white-space: normal;
word-wrap: break-word;
}
.tpl-editor .error-message {
color: red;
padding: 1em;
font-weight: bold;
text-align: center;
}
.tpl-editor .empty-message {
color: #999;
padding: 1em;
text-align: center;
}
.tpl-edit-area {
width: 100%;
position: relative;
}
.eicui-input-container {
display: flex;
align-items: center;
justify-content: space-between;
position: relative;
}
.tpl-edit-area {
position: relative;
width: 100%;
}
.tpl-history-wrapper {
position: absolute;
top: 0;
right: 0;
z-index: 10;
}
.tpl-history-wrapper .toggle-history {
margin-left: auto;
}
.tpl-history {
position: absolute;
top: 2.5em;
right: 0;
width: 15em;
overflow-y: auto;
background: white;
border: 1px solid var(--eicui-base-color-grey-10);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
z-index: 1000;
opacity: 0;
transform: translateX(100%);
pointer-events: none;
transition: transform 0.3s ease, opacity 0.3s ease;
}
.tpl-history:not(.collapsed) {
transform: translateX(0);
opacity: 1;
pointer-events: auto;
}
.tpl-edit-area .template-field {
max-height: 45vh;
}
@media (max-height: 700px) {
.tpl-edit-area .template-field {
max-height: 55vh;
}
}
@media (min-height: 900px) {
.tpl-edit-area .template-field {
max-height: 65vh;
}
}
.tpl-edit-area .template-field.preview{
max-height: unset;
}
</style>
<article eiccard class="templateEditor">
<header>
<h1>Template Designer</h1>
</header>
<section>
<div class="tpl-editor">
<article eiccard class="tplEditor" tplEditor>
<section>
<div class="cols-3">
<div>
<label small>Template name</label>
<input eicinput class="tplName tpl-inputMeta" name="tplName"
placeholder="your template name..." />
</div>
<div class="cols-2 right">
<div class="tplOpStartDate">
<label small>Operating start date</label>
<input eicinput type="text" class="tpl-formattedDateStart tpl-inputMeta" data-trigger="onStartDateClicked" />
<input type="datetime-local" class="tplStartDate tpl-inputMeta hiddenInput" data-trigger="syncDateInputs"/>
</div>
<div class="tplOpEndDate">
<label small>Operating end date</label>
<input eicinput primary type="text" class="tpl-formattedDateEnd tpl-inputMeta" data-trigger="onEndDateClicked"/>
<input type="datetime-local" class="tplEndDate tpl-inputMeta hiddenInput" data-trigger="syncDateInputs"/>
</div>
</div>
<div class="path-container">
<label small>Template path</label>
<div class="input-button-wrapper">
<span eicchip secondary><label class="tplPath tpl-inputMeta"
name="tplPath"></label></span>
<button eicbutton xsmall rounded primary class="tpl-btn-path"
data-trigger="onPathSearch" icon="icon-folder">
<i class="icon-folder"></i>
</button>
</div>
</div>
</div>
<div class="cols-2 left fields">
<div class="cols-1 left">
<menu small eictab vertical>
<li data-trigger="buildToolButtons" data-value="subject" title="Subject line - Mandatory for email"><label>Subject</label></li>
<li data-trigger="buildToolButtons" data-value="header"><label>Header</label></li>
<li data-trigger="buildToolButtons" data-value="main"><label>Main</label></li>
<li data-trigger="buildToolButtons" data-value="footer"><label>Footer</label></li>
<li data-trigger="buildToolButtons" data-value="altText" title="Plain-text version for email clients that don't support HTML"><label>Text (Alt.)</label></li>
<li data-trigger="buildToolButtons" data-value="preview" class="icon-preview" title="Preview the full template (header + main + footer)"><label>Preview</label></li>
</menu>
</div>
<div class="tpl-edit-area">
<div class="eicui-input-container">
<div class="tpl-loadingTools">Tools</div>
<menu small eictab horizontal class="tpl-toolButtons"></menu>
<div class="tpl-history-wrapper">
<button eicbutton xsmall class="toggle-history icon-history" title="Template history"></button>
<div class="tpl-history collapsed"></div>
</div>
</div>
<div class="template-field subject">
<label>Subject is required for sending mail</label>
<div class="content" contenteditable="true" aria-placeholder=""></div>
</div>
<div class="template-field header">
<label>Header</label>
<div eicrichtext class="content" contenteditable="true"></div>
</div>
<div class="template-field main">
<label>Main</label>
<div eicrichtext class="content" contenteditable="true"></div>
</div>
<div class="template-field footer">
<label>Footer</label>
<div eicrichtext class="content" contenteditable="true"></div>
</div>
<div class="template-field altText">
<label>Text (Alt.)</label>
<div eicrichtext class="content" contenteditable="true"></div>
</div>
<div class="template-field preview" contenteditable="false">
<label> Preview</label>
<div eicrichtext class="content" contenteditable="false"></div>
</div>
</div>
</section>
<footer>
<div class="cols-1 right">
<div class="tplActions">
<button eicbutton small primary class="tool-button he-uplImg hidden"
data-trigger="onUploadImage" title="Upload your own image to insert into your template">
<span>Upload image</span>
</button>
<button eicbutton small primary class="tpl-save hidden" data-trigger="saveHtml">
<span>Save</span>
</button>
<button eicbutton small primary class="tpl-sendTest hidden" data-trigger="onTestSend">
<span>Test mail</span>
</button>
<button eicbutton small primary class="tpl-request hidden" data-trigger="onRequestPub">
<span>Request publishing</span>
</button>
<button eicbutton small primary class="tpl-approved hidden" data-trigger="onApproved">
<span>Approve Template</span>
</button>
<button eicbutton small primary class="tpl-rejected hidden" data-trigger="onRejected">
<span>Reject Template</span>
</button>
</div>
</div>
</footer>
</article>
</div>
</section>
</article>
@@ -0,0 +1,788 @@
class TemplatesEditorView extends EICDomContent {
constructor(privileges) {
super('/templates', privileges)
Object.assign(this, app.helpers.activeAttributes)
Object.assign(this, app.helpers.basicDialogs)
}
DOMContentLoaded(options) {
for (let model in options.models) this[model] = options.models[model]
this.components = ui.eicfy(this.el)
this.templateId = options.id
this.decodedHtml = null;
this.decodedAltText = null;
(new Tab()).addTabs(this.findAll('menu li'), this.findAll('.template-field'));
this.setupRefs(this.components)
this.checkAccessAndLoadTemplate()
}
async checkAccessAndLoadTemplate() {
const tplEditorContainer = this.find('.tplEditor')
try {
const result = await this.templates.getReadableFolders()
this.authorizedPaths = result.authorizedPaths || []
if (this.authorizedPaths.length === 0) {
tplEditorContainer.innerHTML = `
<div style="padding: 2rem; text-align: center;">
<h2 style="color:#b00020;">Access Denied</h2>
<p>You are not authorized to access the template editor.</p>
</div>
`
return
}
this.loadTemplate()
} catch (err) {
console.error("Error checking template privileges:", err)
tplEditorContainer.innerHTML = `
<div style="padding: 2rem; text-align: center;">
<h2 style="color:#b00020;">Error</h2>
<p>Unable to check permissions due to a system error.</p>
</div>
`
}
}
async loadTemplate() {
const fieldSubj = this.find('.template-field.subject .content')
this.showLoading(fieldSubj)
const tplEditorContainer = this.find('.tplEditor')
this.gridHistory = new DataGrid(this.find('.tpl-history'), {
headers: [{ label: 'Date', type: 'markup', sortable: true }],
actions: []
})
try {
const result = await this.templates.getReadableFolders()
this.authorizedPaths = result.authorizedPaths || []
if (this.authorizedPaths.length === 0) {
tplEditorContainer.innerHTML = `
<div style="padding: 2rem; text-align: center;">
<h2 style="color:#b00020;">Access Denied</h2>
<p>You are not authorized to access the template editor.</p>
</div>
`
return
}
const currentTemplate = await this.templates.get(this.templateId)
if (!currentTemplate) {
ui.growl.append('Template not found. Please select a valid template.')
return
}
const templatePath = currentTemplate.path || '/'
const isAuthorized = this.authorizedPaths.some(authPath => templatePath.startsWith(authPath))
if (!isAuthorized) {
tplEditorContainer.innerHTML = `
<div style="padding: 2rem; text-align: center;">
<h2 style="color:#b00020;">Access Denied</h2>
<p>You do not have permission to access this template.</p>
</div>
`
return
}
this.editedTemplate = new TemplatesModel(currentTemplate)
const templateStatus = currentTemplate.status
if (templateStatus === 'submitted' || templateStatus === 'prod') {
const tplFields = this.findAll('.template-field, .tpl-inputMeta')
tplFields.forEach(field => {
if (field.tagName === 'INPUT' || field.tagName === 'TEXTAREA') {
field.disabled = true
} else {
field.setAttribute('contenteditable', 'false')
}
field.classList.add('disabled')
})
}
if (this.templates.hasPrivilege('edit')) {
this.toggleButton('onTestSend', ['draft', 'submitted'].includes(templateStatus))
this.toggleButton('saveHtml', ['draft', 'created'].includes(templateStatus))
this.toggleButton('onRequestPub', templateStatus === 'draft')
this.toggleButton('onUploadImage', ['draft', 'created'].includes(templateStatus))
this.toggleButton('onPathSearch', ['draft', 'created'].includes(templateStatus))
}
if (this.templates.hasPrivilege('approved')) {
this.toggleButton('onApproved', templateStatus === 'submitted')
this.toggleButton('onRejected', templateStatus === 'submitted')
}
this.currentPath = templatePath
this.find('.tplPath').textContent = this.currentPath
this.decodeHtmlBin(currentTemplate.html, currentTemplate.meta)
this.find('.tplName').value = currentTemplate.name || ' '
const currentDate = new Date()
const oneYearLater = new Date()
oneYearLater.setFullYear(currentDate.getFullYear() + 1)
const startDate = currentTemplate.startDate ? new Date(currentTemplate.startDate) : currentDate
const endDate = currentTemplate.endDate ? new Date(currentTemplate.endDate) : oneYearLater
this.find('.tpl-formattedDateStart').value = this.formatDateToDDMMYYYYHHMM(startDate)
this.find('.tpl-formattedDateEnd').value = this.formatDateToDDMMYYYYHHMM(endDate)
const headerContent = this.extractSection(this.decodedHtml, 'header')
const mainContent = this.extractSection(this.decodedHtml, 'main')
const footerContent = this.extractSection(this.decodedHtml, 'footer')
this.tplSubj = this.find('.template-field.subject')
this.tplHeader = this.find('.template-field.header')
this.tplMain = this.find('.template-field.main')
this.tplFooter = this.find('.template-field.footer')
this.tplAltText = this.find('.template-field.altText')
this.tplSubj.innerHTML = this.replaceMustaches(currentTemplate.meta.subject || ' ')
this.tplHeader.innerHTML = this.replaceMustaches(headerContent || ' ')
this.tplMain.innerHTML = this.replaceMustaches(mainContent || ' ')
this.tplFooter.innerHTML = this.replaceMustaches(footerContent || ' ')
this.tplAltText.innerText = this.decodedAltText || ' '
this.updatePreview()
const tplEditor = this.find('.tplEditor')
const images = await this.templates.getImages()
const tokens = await this.templates.getTechDDTokens(currentTemplate)
const tId = this.templateId
this.htmlEditor = new HtmlEditor(tplEditor, this, {
images,
tokens,
templateStatus,
tId,
externalHandlers: {
onTestSend: this.onTestSend.bind(this),
onUploadImage: this.onUploadImage.bind(this, templateStatus),
onRequestPub: async () => {
if (this.isDialogOpen) return
this.isDialogOpen = true
await this.confirmDialog({
title: 'Request review ?',
message: `You're about to request a review for this template.<br>
During the review process, the template will no longer be editable.
<div class="prompts">
<label small>Remarks or comments for the reviewer:</label>
<textarea name="comments" eictextarea maxlen="500" cols="50"/></textarea>
</div>`,
promptsClass: 'prompts',
okLabel: 'Request review',
severity: 'warning',
okSeverity: 'primary',
okPromise: async (data) => {
try {
await this.saveHtml('submitted', data.comments)
await this.loadTemplate()
return true
} finally {
this.isDialogOpen = false
}
}
}).finally(() => {
this.isDialogOpen = false
})
},
onApproved: async () => {
if (this.isDialogOpen) return
this.isDialogOpen = true
await this.confirmDialog({
title: 'Template approval ?',
message: `Approve this template ?<br>
Remarks or comments for the reviewer:
<div class="prompts">
<textarea name="comments" eictextarea maxlen="500" cols="50"/></textarea>
</div>`,
promptsClass: 'prompts',
okLabel: 'Approve',
severity: 'warning',
okSeverity: 'primary',
okPromise: async (data) => {
try {
await this.saveHtml('prod', data.comments)
await this.loadTemplate()
return true
} finally {
this.isDialogOpen = false
}
}
}).finally(() => {
this.isDialogOpen = false
})
},
onRejected: async () => {
if (this.isDialogOpen) return
this.isDialogOpen = true
await this.confirmDialog({
title: 'Template rejection ?',
message: `FeedBack<br>
<div class="prompts">
<textarea name="comments" eictextarea maxlen="500" cols="50"/></textarea>
</div>
`,
promptsClass: 'prompts',
okLabel: 'Reject',
severity: 'warning',
okSeverity: 'primary',
okPromise: async (data) => {
try {
await this.saveHtml('draft', data.comments)
this.loadTemplate()
return true
} finally {
this.isDialogOpen = false
}
}
}).finally(() => {
this.isDialogOpen = false
})
},
onPathSearch: this.onPathSearch.bind(this),
onStartDateClicked: this.onStartDateClicked.bind(this),
onEndDateClicked: this.onEndDateClicked.bind(this),
saveHtml: this.saveHtml.bind(this, templateStatus)
}
})
// Re-attach tab listeners after reload
if (typeof Tab === 'function') {
(new Tab()).addTabs(this.findAll('menu li'), this.findAll('.template-field'))
}
// Restore the last active tab if available (with a short delay to ensure listeners are attached)
if (typeof this._lastActiveTabIndex === 'number' && this._lastActiveTabIndex >= 0) {
const tabs = Array.from(this.findAll('menu li'))
if (tabs[this._lastActiveTabIndex]) {
setTimeout(() => {
tabs[this._lastActiveTabIndex].click()
// Force toolbar rebuild for the restored tab
const fieldTypes = ['subject', 'header', 'main', 'footer', 'altText', 'preview']
const fieldType = fieldTypes[this._lastActiveTabIndex] || 'subject'
if (this.htmlEditor && typeof this.htmlEditor.buildToolButtons === 'function') {
this.htmlEditor.buildToolButtons(fieldType)
}
}, 150)
}
}
this.gridHistory.clear()
const history = currentTemplate.statusHistory.sort((a, b) => new Date(b.dateTime) - new Date(a.dateTime))
history.forEach(item => {
const statusColor = {
draft: 'info',
created: 'secondary',
submitted: 'warning',
archived: 'primary',
prod: 'success'
}[item.value] || 'danger'
const oldestDate = new Date(item.dateTime).toLocaleDateString('fr-FR')
const fullName = `<span xsmall class="tpl-fullName">By ${item.changedBy.firstname} ${item.changedBy.lastname}</span>`
const status = `<span class="tpl-status" ${statusColor}>${item.value}</span>`
const comment = item.changedBy.comment?.trim()
? `<span xsmall info class="tpl-comment"><u>comment:</u> ${item.changedBy.comment}</span>`
: ''
const details = `
<div eiccard collapsable collapsed>
<span xsmall class="tpl-details">${oldestDate} - ${status}</span>
<div class="collapsible-content">
${fullName}
${comment}
</div>
</div>
`
const row = this.gridHistory.addRow(item.id, [details])
row.addEventListener('click', () => {
const content = row.querySelector('.collapsible-content')
content.style.display = content.style.display === 'none' || content.style.display === '' ? 'block' : 'none'
})
})
} catch (error) {
console.error("Error loading template:", error)
tplEditorContainer.innerHTML = `
<div style="padding: 2rem; text-align: center;">
<h2 style="color:#b00020;">Error</h2>
<p>Unable to load the template due to a system error.</p>
</div>
`
} finally {
this.hideLoading(fieldSubj)
}
const toggleBtn = document.querySelector('.toggle-history')
const historyPanel = document.querySelector('.tpl-history')
toggleBtn.addEventListener('click', (e) => {
e.stopPropagation();
historyPanel.classList.toggle('collapsed')
if (historyPanel.classList.contains('collapsed')) {
toggleBtn.classList.remove('icon-close')
toggleBtn.classList.add('icon-history')
} else {
toggleBtn.classList.remove('icon-history')
toggleBtn.classList.add('icon-close')
}
})
document.addEventListener('click', (e) => {
if (!historyPanel.contains(e.target) && !toggleBtn.contains(e.target)) {
historyPanel.classList.add('collapsed')
toggleBtn.classList.remove('icon-close')
toggleBtn.classList.add('icon-history')
}
})
}
updatePreview() {
if (!this.tplHeader || !this.tplMain || !this.tplFooter) return
const previewContent = `
<div class="tpl-preview-block">${this.tplHeader.innerHTML}</div>
<div class="tpl-preview-block">${this.tplMain.innerHTML}</div>
<div class="tpl-preview-block">${this.tplFooter.innerHTML}</div>
`
this.find('.template-field.preview .content').innerHTML = previewContent
}
onStartDateClicked() {
const startDateInput = this.find('.tplStartDate');
startDateInput.showPicker();
this.syncDateInputs(this.find('.tpl-formattedDateStart'), this.find('.tplStartDate'));
}
onEndDateClicked() {
const endDateInput = this.find('.tplEndDate');
endDateInput.showPicker();
this.syncDateInputs(this.find('.tpl-formattedDateEnd'), this.find('.tplEndDate'));
}
syncDateInputs(textInput, dateInput) {
dateInput.addEventListener('input', () => {
textInput.value = this.formatDateToDDMMYYYYHHMM(dateInput.value);
});
textInput.addEventListener('click', () => {
dateInput.showPicker();
});
}
formatDateToDDMMYYYYHHMM(dateString) {
const date = new Date(dateString);
const dateFormatter = new Intl.DateTimeFormat('fr-FR', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false // 24h format
});
const formattedDate = dateFormatter.format(date);
return formattedDate;
}
reformatDateToISO(dateInput) {
let dateObj;
if (typeof dateInput === 'string') {
const parts = dateInput.split(/[\s/:]/);
if (parts.length >= 5) {
const [day, month, year, hours, minutes] = parts;
dateObj = new Date(`${year}-${month}-${day}T${hours}:${minutes}:00`);
} else {
console.error('Invalid date format:', dateInput);
return '';
}
} else if (dateInput instanceof Date) {
dateObj = dateInput;
} else {
console.error('Expected a Date object or valid date string but received:', dateInput);
return '';
}
if (isNaN(dateObj.getTime())) {
console.error('Invalid Date object:', dateObj);
return '';
}
const day = String(dateObj.getDate()).padStart(2, '0')
const month = String(dateObj.getMonth() + 1).padStart(2, '0')
const year = dateObj.getFullYear()
const hours = String(dateObj.getHours()).padStart(2, '0')
const minutes = String(dateObj.getMinutes()).padStart(2, '0')
return `${year}-${month}-${day}T${hours}:${minutes}:00.000Z`
}
toggleButton(trigger, isVisible) {
const button = this.components.find(c => c.el.dataset.trigger === trigger)
if (button) {
requestAnimationFrame(() => {
button.el.classList.toggle('hidden', !isVisible)
})
}
}
async onTestSend() {
const button = this.find('.tpl-sendTest')
// Deactivate button and add spinner
this.showLoading(button)
try {
let result = await this.openDialog(
await this.loadContent(
'comms/templates/dialogs/TemplatesMailTestDialog',
{ title: `Send a test mail...` }
)
)
if (result) {
await this.templates.testMail(this.templateId, result.email)
ui.growl.append('Test mail sent successfully', 'success')
}
}
catch (error) {
console.error("Error on dialog UploadImage loading :", error)
ui.growl.append('Error sending test mail', 'error')
} finally {
// Reactivate button
this.hideLoading(button, '<span>Test mail</span>')
}
}
async onUploadImage(templateStatus) {
const button = this.find('.he-uplImg');
const tabs = Array.from(this.findAll('menu li'))
const activeTabIndex = tabs.findIndex(tab => tab.classList.contains('active'))
this._lastActiveTabIndex = activeTabIndex
this.showLoading(button)
let dialogInstance = null
try {
dialogInstance = await this.openDialog(
await this.loadContent(
'comms/templates/dialogs/TemplatesUplImgDialog',
{ title: 'Upload your own image...' }
)
)
if (!dialogInstance) {
return
}
if (dialogInstance.showDialogSpinner) dialogInstance.showDialogSpinner(true)
const response = await this.templates.saveImage(dialogInstance)
if (response?.success) {
ui.growl.append('Image saved successfully', 'success')
await this.saveHtml(templateStatus)
} else {
ui.growl.append('Error saving image', 'error')
}
} catch (error) {
console.error("Error on dialog UploadImage loading:", error)
} finally {
// Always hide the spinner and close dialog if needed
if (dialogInstance?.showDialogSpinner) {
dialogInstance.showDialogSpinner(false)
}
if (dialogInstance?.cancel) {
dialogInstance.cancel()
}
this.hideLoading(button, '<span>Upload image</span>')
}
}
// Decod html binary64 fron DB
decodeHtmlBin(html, meta) {
this.decodedHtml = html ? this.decodeBase64ToUTF8(html) : '';
this.decodedAltText = meta.altText ? this.decodeBase64ToUTF8(meta.altText) : ''
}
decodeBase64ToUTF8(base64Str) {
const binaryString = atob(base64Str)
const uint8Array = new Uint8Array(binaryString.length)
for (let i = 0; i < binaryString.length; i++) {
uint8Array[i] = binaryString.charCodeAt(i)
}
const decoder = new TextDecoder('utf-8')
return decoder.decode(uint8Array)
}
async onPathSearch() {
const button = this.find('.tpl-btn-path')
this.showLoading(button)
try {
let result = await this.templates.getReadableFolders()
if (!result || typeof result !== 'object') {
console.error("getReadableFolders returned invalid result", result)
return
}
let { templates, authorizedPaths, foldersWithFiles, rights } = result
if (!Array.isArray(authorizedPaths)) authorizedPaths = []
if (!authorizedPaths.includes('/templates')) authorizedPaths.unshift('/templates')
this.templates.ffs.authorizedPaths = authorizedPaths
this.templates.ffs.foldersWithFiles = foldersWithFiles || []
this.templates.ffs.rights = rights || []
if (!templates?.templates) {
templates = { templates }
}
const fileList = Array.isArray(templates.templates) ? templates.templates : []
this.templates.ffs.loadStructure(templates || {}, fileList)
this.templates.ffs.currentPath = '/templates'
this.templates.ffs.authorizedPaths = authorizedPaths
this.currentPath = this.find('.tplPath').textContent
let dialogResult = await this.openDialog(
await this.loadContent(
'templates/Ffs/dialogs/FileBrowserDialog',
{ title: `Select a path...` },
{
ffs: this.templates.ffs,
editable: false,
startPath: this.currentPath,
canManage: true,
templates: this.templates,
context: 'templates'
}
)
)
if (dialogResult) {
this.editedTemplate.path = dialogResult
this.find('.tplPath').textContent = dialogResult
}
} catch (error) {
console.error("Error on dialog PathSearch loading :", error)
} finally {
// Reactivate button
this.hideLoading(button)
}
}
extractSection(html, section) {
const regex = new RegExp(`<${section}.*?>([\\s\\S]*?)<\\/${section}>`, 'i')
const match = html.match(regex)
const extractedText = match ? match[1].trim() : ''
const normStr = this.normalizeText(extractedText)
return normStr
}
//Normalize special char. from Word copy/paste
normalizeText(str) {
return str
.replace(/[\u2018\u2019]/g, "'") //Replace by '
.replace(/[\u201C\u201D]/g, '"') // Replace “ ” by "
.replace(/\u00A0/g, ' ') // Replace space
}
toBase64UTF8(str) {
const encoder = new TextEncoder()
const uint8Array = encoder.encode(str)
let binaryString = ''
uint8Array.forEach(byte => {
binaryString += String.fromCharCode(byte)
});
return btoa(binaryString)
}
fromBase64UTF8(base64) {
const binaryString = atob(base64)
const uint8Array = new Uint8Array([...binaryString].map(char => char.charCodeAt(0)))
const decoder = new TextDecoder()
return decoder.decode(uint8Array)
}
async saveHtml(tplStatus, comment = null) {
const button = this.find('.tpl-save')
// Deactivate button and add spinner
this.showLoading(button)
// Save the current active tab index before reload
const tabs = Array.from(this.findAll('menu li'))
const activeTabIndex = tabs.findIndex(tab => tab.classList.contains('active'))
this._lastActiveTabIndex = activeTabIndex
try {
const newTplStatus = (tplStatus === 'created') ? 'draft' : tplStatus
const tplName = this.find('.tplName').value
const tplPath = this.find('.tplPath').textContent
const tplStartDate = this.reformatDateToISO(this.find('.tpl-formattedDateStart').value)
const tplEndDate = this.reformatDateToISO(this.find('.tpl-formattedDateEnd').value)
const curYear = new Date().getFullYear()
const tplType = 'mail'
const path = (tplPath ? (tplPath.startsWith('/') ? tplPath : '/' + tplPath) : '/Common/' + curYear)
// keep all inputs content
const tplSubject = this.cleanInvisibleChars(this.restoreMustaches(this.find('.template-field.subject').innerHTML))
const headerContent = this.cleanInvisibleChars(this.restoreMustaches(this.find('.template-field.header').innerHTML))
const mainContent = this.cleanInvisibleChars(this.restoreMustaches(this.find('.template-field.main').innerHTML))
const footerContent = this.cleanInvisibleChars(this.restoreMustaches(this.find('.template-field.footer').innerHTML))
const altTextContent = this.toBase64UTF8(this.find('.template-field.altText').innerText)
const newHtml = `<header>${headerContent}</header>
<main>${mainContent}</main>
<footer>${footerContent}</footer>`
this.updatePreview()
const refImgIds = this.extractImageIds(newHtml)
const data = {
id: this.templateId,
type: 'templateInfo',
name: tplName,
path: path,
html: this.toBase64UTF8(newHtml),
status: newTplStatus,
meta: {
subject: tplSubject,
type: tplType,
altText: altTextContent,
},
statusHistory: {
changedBy: {
euLoginId: '',
mail: '',
role: '',
comment: comment || '',
},
dateTime: '',
value: newTplStatus
},
startDate: tplStartDate,
endDate: tplEndDate,
imgRefs: refImgIds || '',
comment: comment || '',
}
const response = await this.editedTemplate.save(data)
if (response.success) {
ui.growl.append('Template saved successfully', 'success')
} else {
ui.growl.append('Error saving template', 'error')
}
} catch (error) {
console.error("Error saving template :", error)
} finally {
// Reactivate button
this.hideLoading(button, '<span>Save</span>')
}
}
cleanInvisibleChars(str) {
return str
.replace(/\u200B/g, '') // Unicode invisibles chars
.replace(/&ZeroWidthSpace;/gi, '') // HTML entity for zero-width space
.normalize('NFC') // Normalisation Unicode
.replace(/[\u200B-\u200D\uFEFF]/g, '') // zero-width & BOM
.replace(/&ZeroWidthSpace;/gi, '') // HTML entity
.replace(/[\u2018\u2019\u02BC]/g, "'") // smart apostrophes → '
.replace(/[\u201C\u201D\u00AB\u00BB]/g, '"') // smart quotes → "
.replace(/[\u2013\u2014\u2212]/g, '-') // dashes → -
.replace(/\u2026/g, '...') // ellipsis → ...
.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g, ' ') // weird spaces → normal space
.replace(/[\u0000-\u001F\u007F]/g, '') // control chars
.replace(/\s{2,}/g, ' ') // double spaces
.replace(/[ \t]+\n/g, '\n') // strip trailing space before newlines
.replace(/\n{3,}/g, '\n\n') // max 2 line breaks
.trim()
}
extractImageIds(htmlContent) {
const tempElement = document.createElement('div')
tempElement.innerHTML = htmlContent
const imgElements = tempElement.querySelectorAll('img')
const ids = [];
imgElements.forEach(img => {
if (img.id) {
ids.push(img.id)
}
})
return ids.join(',')
}
async onDecision(status) {
if (status === 'prod') {
let result = await this.confirmDialog({
title: 'APPROVE this template ?',
message: `<p>This approval will be final.</p>
<p>Are you sure?</p>`,
okLabel: 'Approve',
severity: 'warning',
okPromise: () => this.saveHtml(status, '')
})
if (result) {
ui.growl.append("Template approved !", 'success')
} else {
ui.growl.append("Error approval!", 'error')
}
} else {
let result = await this.openDialog(
await this.loadContent(
'comms/templates/dialogs/TemplatesDecisionDialog',
{ title: `Comment your decision...` }
)
)
if (result) {
await this.saveHtml(status, result.comment)
}
}
}
async addImage(data) {
const response = await this.editedTemplate.saveImage(data)
if (response.success) {
ui.growl.append('Image saved successfully', 'success')
this.loadTemplate(this.templateId)
} else {
ui.growl.append('Error saving image', 'error')
}
}
//Manage tokens mustaches
replaceMustaches(html) {
return html.replace(/\{\{(.*?)\}\}/g, function (match, p1) {
return `<span class="tpl-token" eicchip="" success="" data-original="${p1.trim()}">${p1.trim()}</span>`
});
}
restoreMustaches(html) {
return html.replace(/<span class="tpl-token"[^>]*data-original="(.*?)"[^>]*>.*?<\/span>/g, '{{$1}}')
}
}
app.registerClass('TemplatesEditorView', TemplatesEditorView);
@@ -0,0 +1,192 @@
<style>
.templitor > header { background: url('/app/assets/images/cards/templitorHeader.png') center/cover no-repeat; }
.templitor .search-bar{
grid-template-columns: auto min-content;
align-items: baseline;
}
.templitor .library .row {
display: grid;
grid-template-columns: auto 120px 120px;
}
.templitor .library .dataset .row:hover {
background-color: var(--eicui-base-color-grey-5) !important;
box-shadow:
inset 0 2px 4px rgba(0, 0, 0, 0.2),
inset 0 -1px 0 rgba(255, 255, 255, 0.4) !important;
transform: translateY(2px) !important;
}
.templitor .library .dataset .row.selected {
background-color: var(--eicui-base-color-grey-5) !important;
border-left: 5px solid var(--eicui-base-color-info);
box-shadow:
inset 0 2px 4px rgba(0, 0, 0, 0.2),
inset 0 -1px 0 rgba(255, 255, 255, 0.4) !important;
transform: translateY(2px) !important;
}
.templitor .library .dataset .row .cell:nth-child(3),
.templitor .library .dataset .row .cell:nth-child(4) {
text-align: center;
}
.templitor .library.thumbs header,
.templitor .library.thumbs footer { display:none; }
.templitor .library .dataset { max-height: 50vh; }
.templitor .library.thumbs .dataset { max-height: 55vh; }
.templitor .library.thumbs .dataset .row {
display: inline-grid;
width: 320px;
grid-template-columns: none;
border-left: 4px solid var(--app-color-info);
margin: var(--eicui-base-spacing-xs);
background: var(--eicui-base-color-white);
padding: var(--eicui-base-spacing-2xs);
box-shadow: 3px 3px var(--eicui-base-color-grey-20);
border-top: 1px solid var(--eicui-base-color-grey-20);
}
.templitor .tplInfos{
display: inline-block;
}
.templitor .library.thumbs .dataset .row .cell:nth-child(2) {
font-weight: bold;
grid-column: 1 / 3;
}
.templitor .library.thumbs .dataset .row .cell:nth-child(3) { grid-row: 2; grid-column: 1; text-align:left; }
.templitor .library.thumbs .dataset .row .cell:nth-child(4) {
grid-row: 2;
grid-column: 2;
text-align: right;
}
.templitor .tpl-createButton{
float: right;
}
.templitor .tpl-filters {
padding: var(--eicui-base-spacing-s) 0;
display: grid;
grid-auto-flow: column;
grid-gap: var(--eicui-base-spacing-m);
width: fit-content;
}
.templitor .preview {
width: 40vw;
transition: all 0.6s ;
opacity: 1;
}
.templitor .preview[disabled] { width: 0; opacity:0; }
.templitor .preview .html {
border: 1px solid #ccc;
padding: 10px;
border-radius: 5px;
position: inherit;
overflow: auto;
max-height: 50vh;
}
.templitor .preview .html img { max-width: 100%; height: auto; }
.templitor .preview .html table { table-layout: auto; }
.templitor .tpl-path{
display: inline-block;
padding: 0.2em 0.6em;
border-radius: 1em;
/*background-color: var(--eicui-base-color-accent-10);
color: var(--eicui-base-color-black);
*/
background-color: white !important;
color: white !important;
font-size: 0.75rem;
white-space: nowrap;
max-width: calc(100vw * 0.6);
overflow: hidden;
text-overflow: ellipsis;
}
.templitor .preview .html.not-editable::after {
content: 'Not Editable';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) rotate(-45deg);
font-size: 5rem;
color: rgba(200, 0, 0, 0.1); /* Transparent red */
z-index: 10;
pointer-events: none;
white-space: nowrap;
}
.templitor button[eicuser] span[eicbadge] {
visibility: hidden;
}
.templitor button.loading {
pointer-events: none;
opacity: 0.7;
}
.icon-spinner {
display: inline-block;
animation: spin 0.6s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.templitor .error-message {
color: red;
padding: 1em;
font-weight: bold;
text-align: center;
}
.templitor .empty-message {
color: #999;
padding: 1em;
text-align: center;
}
.templitor .tpl-filters {
padding: var(--eicui-base-spacing-s) 0;
display: grid;
grid-auto-flow: column;
grid-gap: var(--eicui-base-spacing-m);
width: fit-content;
}
</style>
<article eiccard media class="templitor">
<header>
<h1>Templates Manager</h1>
<h2>Documents & Templates</h2>
</header>
<section>
<article eiccard>
<section>
<div class="cols-2 search-bar">
<select eicselect data-ref="searchCriteria" data-change="onSearchChange" editable data-type="array" placeholder="Search on title, path or user"></select>
<button eicbutton xsmall rounded primary class="tpl-btn-path" data-trigger="onPathBrowse" icon="icon-folder"><i class="icon-folder"></i></button>
</div>
</section>
<section>
<div class="cols-2 right" >
<div class="tpl-filters"></div>
<button class="tpl-createButton" eicbutton small info data-trigger="onTemplateCreate"><span>Create</span></button>
</div>
<div class="cols-2 right">
<div class="library thumbs">
<div class="cols-2 right">
<div eicdatagrid class="templatesList" data-output="searchResults" data-async="results" ></div>
<div class="cols-2">
<button eicbutton rounded small primary data-value="grid" data-trigger="onTemplatesDisplay" icon="icon-list-ul"></button>
<button eicbutton rounded small primary data-value="thumbs" data-trigger="onTemplatesDisplay" icon="icon-table"></button>
</div>
</div>
</div>
<article eiccard class="preview" disabled>
<header>
<div class="cols-2 right">
<div>
<h1>Select a template in the library</h1>
<h2>Template preview</h2>
</div>
<button eicbutton xsmall rounded secondary data-trigger="onPreviewClose" icon="icon-cancel"></button>
</div>
</header>
<section><div class="html"></div></section>
</article>
</div>
</section>
</article>
</section>
</article>
@@ -0,0 +1,561 @@
class TemplatesManagerView extends EICDomContent {
constructor(privileges) {
super('/templates', privileges)
Object.assign(this, app.helpers.basicDialogs)
Object.assign(this, app.helpers.activeAttributes)
Object.assign(this, app.helpers.validators)
this.selectedTemplate = null
this.decodedHtml = null
this.decodedAltText = null
}
DOMContentLoaded(options) {
for (let model in options.models) this[model] = options.models[model]
this.components = ui.eicfy(this.el)
this.gridTemplates = new DataGrid(this.find('.library [eicdatagrid]'), {
headers: [
{ label: 'Name', filter: 'text', sortable: true },
{ label: 'Author', type: 'markup', filter: 'text', sortable: true },
{ label: 'Delete', type: 'button' },
{ label: 'Status', type: 'markup' },
{ label: 'Actions', type: 'markup' },
],
actions: []
})
this.gridTemplates.onRowClick = (row, event) => {
const target = event.target
const isButton = target.closest('.template-actions button')
if (!isButton) {
this.onTemplateSelect(row)
}
}
this.preview = new Card(this.find('.preview'))
this.previewContent = this.find('.preview .html').attachShadow({ mode: 'open' })
this.setupTriggers(this.components)
this.setupRefs(this.components)
this.setupStatusButtons()
this.components.searchCriteria.value = [app.User.identity.uuid]
}
async refreshTpl() {
this.gridTemplates.loading = true
try {
const result = await this.templates.getReadableFolders()
this.authorizedPaths = result.authorizedPaths || []
if (this.authorizedPaths.length === 0) {
this.output('searchResults', `<div style="padding: 2rem; text-align: center;">
<h2 style="color:#b00020;">Access Denied</h2>
<p>You're not authorized to access the templates dashboard</p>
</div>`)
return
}
const tpls = await this.templates.search(
this.components.searchCriteria.value,
this.getSelectedStatus()
)
if (tpls?.message === 'NO_ACCESS') {
this.output('searchResults', `<div style="padding: 2rem; text-align: center;">
<h2 style="color:#b00020;">Access Denied</h2>
<p>You're not authorized to view templates</p>
</div>`)
return
}
this.fillTemplates(tpls)
} catch (error) {
this.output('searchResults', `<div style="padding: 2rem; text-align: center;">
<h2 style="color:#b00020;">Unexpected Error</h2>
<p>An error occurred while loading templates. Please try again later</p>
</div>`)
console.error(error)
} finally {
this.gridTemplates.loading = false
}
}
onSearchChange(component, event) {
event.stopPropagation()
event.preventDefault()
this.refreshTpl()
}
setupStatusButtons() {
this.statusButtons = {}
for (let status in this.templates.getStatusLabel()) {
this.statusButtons[status] = new Button(null, { rounded: true, size: 'xsmall', severity: 'info', label: `<span>${this.templates.getStatusLabel()[status]}</span>` })
this.statusButtons[status].click = this.onStatusChange.bind(this, status)
this.find('.tpl-filters').append(this.statusButtons[status].el)
}
}
onStatusChange(status, event) {
event.stopPropagation()
event.preventDefault()
this.statusButtons[status].severity =
this.statusButtons[status].severity === 'info' ? 'secondary' : 'info'
this.refreshTpl()
}
getSelectedStatus() {
let selected = Object.keys(this.statusButtons).filter(status =>
this.statusButtons[status].severity === 'info'
)
return selected.length > 0 ? selected : Object.keys(this.statusButtons)
}
async onPathBrowse() {
const button = this.find('.tpl-btn-path')
this.showLoading(button)
let result = await this.templates.getReadableFolders()
let { templates, authorizedPaths } = result
if (!Array.isArray(authorizedPaths)) {
authorizedPaths = []
}
if (!authorizedPaths.includes('/templates')) authorizedPaths.unshift('/templates')
this.templates.ffs.authorizedPaths = authorizedPaths
if (!templates.templates) {
templates = { templates }
}
this.templates.ffs.loadStructure(templates || {}, [])
this.templates.ffs.currentPath = '/templates'
this.templates.ffs.authorizedPaths = authorizedPaths
let dialogResult = await this.openDialog(
await this.loadContent(
'templates/Ffs/dialogs/FileBrowserDialog',
{ title: `Select a path...` },
{
ffs: this.templates.ffs,
templates: this.templates.templates,
editable: false,
canManage: false,
startPath: '/templates',
}
)
)
if (dialogResult) {
const criteria = this.components.searchCriteria.value.filter(item => (!item.startsWith('/')))
this.components.searchCriteria.value = [...criteria, dialogResult]
}
this.hideLoading(button)
}
setupStatusButtons() {
this.statusButtons = {}
this.statusCounters = {}
for (let status in this.templates.getStatusLabel()) {
const label = this.templates.getStatusLabel()[status]
// Crée le bouton avec label
const button = new Button(null, {
rounded: true,
size: 'xsmall',
severity: 'info',
label: `<span>${label}</span>`
})
// Create the badge for the count
const badge = new Badge(null, { size: 'xxsmall' })
badge.value = '0'
button.el.append(badge.el)
// Store references to the button and badge
this.statusButtons[status] = button
this.statusCounters[status] = badge
this.statusButtons[status].click = this.onStatusChange.bind(this, status)
this.find('.tpl-filters').append(button.el)
}
}
updateStatusCounts(counts) {
for (let status in this.templates.getStatusLabel()) {
const count = counts[status] || 0
if (this.statusCounters[status]) {
this.statusCounters[status].value = count.toString()
}
}
}
fillTemplates(list) {
this.gridTemplates.clear()
this.gridTemplates.loading = true
let statusCounts = {}
for (let item of list) {
statusCounts[item.status] = (statusCounts[item.status] || 0) + 1
let statusBadge
switch (item.status) {
case 'draft': statusBadge = 'info'; break
case 'created': statusBadge = 'secondary'; break
case 'submitted': statusBadge = 'warning'; break
case 'archived': statusBadge = 'primary'; break
case 'prod': statusBadge = 'success'; break
default: statusBadge = 'danger'
}
let changeBy = ''
let oldest = item.statusHistory.find(() => true)
if (oldest) changeBy = oldest.changedBy
let oldestDate = new Date(oldest.dateTime).toLocaleDateString('fr-FR')
let fullName = changeBy.firstname + ' ' + changeBy.lastname
let statusLabel = item.status === 'prod' ? 'approved' : item.status
const dirs = item.path.split('/').filter(item => item)
const pathChips = dirs.map((dir, idx) => {
const path = dirs.slice(0, idx + 1).join('/')
return (`<span eicchip xxsmall info data-path="/${path}">${dir}</span>`)
}).join('')
let tplInfos = `<span eicchip ${statusBadge} xsmall outline><label>${statusLabel}</label></span>`
let tplTitle = `<div>${item.name}<br/><span xsmall class-"tplInfos">last action: ${oldestDate}<br/>by: ${fullName}</span></div>`
let deleteB = ''
if (item.status === 'created' || item.status === 'draft') {
deleteB = `<div><button eicbutton class="icon-bin delete-tpl" xsmall rounded danger type="button" data-id="${item.id}" data-trigger="onDeleteTemplate"></button><div>`
}
let tplActions = `
<div class="template-actions">
${
item.status !== 'prod'
? `<button eicbutton class="open-btn icon-pen" xsmall rounded primary data-id="${item.id}" type="button" data-trigger="onTemplateEdit" title="Edit this template"></button>`
: ''
}
<button eicbutton class="preview-btn icon-copy" xsmall rounded data-id="${item.id}" type="button" data-trigger="onTemplateClone" title="Clone this template"></button>
</div>
`
let row = this.gridTemplates.addRow(item.id, [pathChips, tplTitle, tplInfos, deleteB, tplActions])
row.dataset.type = 'file'
let previewButton = row.querySelector('[data-trigger="onTemplateSelect"]')
if (previewButton) {
previewButton.addEventListener('click', (event) => {
event.stopPropagation()
this.onTemplateSelect(row)
})
}
let editButton = row.querySelector('[data-trigger="onTemplateEdit"]')
if (editButton) {
editButton.addEventListener('click', (event) => {
event.stopPropagation()
this.onTemplateEdit(item.id)
})
}
let cloneButton = row.querySelector('[data-trigger="onTemplateClone"]')
if (cloneButton) {
cloneButton.addEventListener('click', (event) => {
event.stopPropagation()
this.onTemplateClone(item.id, event.currentTarget)
})
}
let deleteButton = row.querySelector('[data-trigger="onDeleteTemplate"]')
if (deleteButton) {
deleteButton.addEventListener('click', (event) => {
event.stopPropagation()
this.onDeleteTemplate(item.id, item.name)
})
}
}
this.updateStatusCounts(statusCounts)
this.gridTemplates.loading = false
}
async onTemplateSelect(row) {
const currentId = row.dataset.id
if (row.dataset.type == 'file') {
this.find('.preview').removeAttribute('disabled')
this.preview.loading = true
let data = await this.templates.get(currentId)
if (data) {
let rawHtml = data.html || ''
let html = this.replaceMustaches(this.decodeBase64Utf8(rawHtml))
html = html.replace(/[\u200B-\u200D\uFEFF]/g, '')
html = html
.replace(/\u200B/g, '')
.replace(/&ZeroWidthSpace;/gi, '')
this.previewContent.innerHTML = `<style>
span.tpl-token[eicchip] {
border-radius: 60px !important
background-color: var(--eicui-base-color-success-100)
color: var(--eicui-base-color-white)
font-size: 0.75rem
padding: var(--eicui-base-spacing-2xs) var(--eicui-base-spacing-s)
min-height: var(--eicui-base-spacing-xl)
display: inline-grid
grid-template-columns: min-content min-content min-content
min-height: 0
align-items: center
margin: 1px var(--eicui-base-spacing-2xs)
pointer-events: all
white-space: nowrap
position: relative
text-shadow: none
}
</style>\n${html}`
const images = this.previewContent.querySelectorAll('img')
images.forEach((img) => {
img.style.maxWidth = '100%'
img.style.height = 'auto'
})
this.findAll('.templatesList .row.selected').forEach(r => r.classList.remove('selected'))
row.classList.add('selected')
this.find('.preview').removeAttribute('disabled')
this.selectedTemplate = data
row.scrollIntoView({ behavior: 'smooth', block: 'start' })
} else {
this.find('.preview').removeAttribute('disabled')
ui.growl.append('Template not found', 'danger')
}
this.preview.loading = false
}
else if (row.dataset.type == 'folder') this.onFolderSelect(currentId)
}
async onDeleteTemplate(tplId, tplName) {
if (!this.templates.hasPrivilege('delete')) {
ui.growl.append("You do not have permissions to delete this template.", 'danger')
return
}
let result = await this.confirmDialog({
title: 'DELETE template ?',
message: `<p>You are about to permanently delete the template "<b>${tplName}</b>".</p>
<p>Are you sure?</p>`,
okLabel: 'Delete',
severity: 'danger',
okPromise: () => this.templates.delete(tplId)
})
if (result) {
ui.growl.append("Template deleted !", 'success')
this.refreshTpl()
} else {
ui.growl.append("Error deleting Template!", 'error')
}
}
onFolderSelect(path) {
this.templates.ffs.changeDir(path)
this.refreshTpl()
}
async onTemplateClone(tId, button) {
if (!button) return
button.classList.add('spin')
button.disabled = true
try {
const originalTpl = await this.templates.get(tId)
if (!originalTpl) {
ui.growl.append('Original template not found', 'danger')
return
}
const responseCreate = await this.templates.save({ status: 'created' })
if (responseCreate.success) {
const newId = responseCreate.payload.id
const responseClone = await this.createAndSaveNewTemplate(newId, originalTpl)
if (responseClone.success) {
app.Router.route(`/templates/${newId}`)
} else {
ui.growl.append('Error cloning template', 'error')
}
} else {
ui.growl.append('Error creating template', 'error')
}
} catch (error) {
console.error('Error cloning template:', error)
ui.growl.append('Error cloning template', 'error')
} finally {
button.classList.remove('spin')
button.disabled = false
}
}
async onTemplateEdit(tId) {
const button = this.find(`[data-id="${tId}"][data-trigger="onTemplateEdit"]`)
if (!button) return
button.classList.add('spin')
button.disabled = true
try {
app.Router.route(`/templates/${tId}`, { mode: 'edit', ffsData: this.templates.ffs })
} catch (error) {
console.error('Error opening template:', error)
ui.growl.append('Error opening template', 'error')
} finally {
button.classList.remove('spin')
button.disabled = false
}
}
/*Manage template record for new template
@status = created
*/
async onTemplateCreate() {
const button = this.find('.tpl-createButton');
if (!button) return
button.disabled = true;
button.classList.add('loading')
button.innerHTML = '<i class="icon-spinner spin"></i> Creating...'
const responseCreate = await this.templates.save({ status: 'created' })
if (responseCreate.success) {
this.newId = responseCreate.payload.id
const templateStatus = 'created'
const tplDate = new Date().toISOString()
const path = this.authorizedPaths?.[0]
const tplName = 'New template'
const html = btoa('<p>new template</p>')
const altText = ''
const subject = 'New template'
const tplData = {
id: this.newId,
type: 'templateInfo',
name: tplName,
path: path,
html: html,
status: templateStatus,
meta: {
subject: subject,
type: '',
altText: altText,
},
statusHistory: {
changedBy: {
euLoginId: app.User.identity.uuid,
mail: app.User.identity.mail,
role: app.User.identity.role,
},
dateTime: tplDate,
value: templateStatus,
},
startDate: tplDate,
endDate: tplDate,
}
const response = await this.templates.save(tplData)
if (response.success) {
app.Router.route(`/templates/${this.newId}`)
button.disabled = false
button.classList.remove('loading')
button.innerHTML = '<span>Create New Template</span>'
}
else {
ui.growl.append('Error creating template', 'error')
}
}
}
/*Manage template record for clone
@tplData
*/
async createAndSaveNewTemplate(newId, tplData = {}) {
const templateStatus = 'draft'
const tplDate = new Date().toISOString()
const path = tplData.path || this.authorizedPaths?.[0]
const tplName = tplData.name || ' template'
const html = tplData.html || btoa('<p>CLONE template</p>')
const altText = tplData.meta?.altText || ''
const subject = tplData.meta?.subject || ''
const data = {
id: newId,
type: 'templateInfo',
name: 'CLONE-' + tplName,
path: path,
html: html,
status: templateStatus,
meta: {
subject: 'CLONE-' + subject,
type: '',
altText: altText,
},
statusHistory: {
changedBy: {
euLoginId: '',
mail: '',
role: '',
},
dateTime: '',
value: templateStatus,
},
startDate: tplDate,
endDate: tplDate,
}
const response = await this.templates.save(data)
if (response.success) {
return { success: true, id: response.payload.recId }
}
else {
ui.growl.append('Error creating template', 'error')
}
}
getEarliestDateTime(statusHistory) {
if (!Array.isArray(statusHistory)) return null
return statusHistory.reduce((earliest, entry) => {
const entryDate = new Date(entry.dateTime)
return !earliest || entryDate < earliest ? entryDate : earliest
}, null)
}
onPreviewClose() {
this.find('.preview').setAttribute('disabled', '')
}
onTemplatesDisplay(event) {
let button = event._el
switch (button.dataset.value) {
case 'thumbs':
this.find('.library').classList.add('thumbs')
break
default:
this.find('.library').classList.remove('thumbs')
}
}
/**
* replaceMustaches : replaces {{mustache}} with a span with class tpl-token
* @param {string} html : the html to process
* @returns {string} : the processed html
*/
replaceMustaches(html) {
return html.replace(/\{\{(.*?)\}\}/g, function (match, p1) {
return `<span class="tpl-token" eicchip="" success="" data-original="${p1.trim()}">${p1.trim()}</span>`
})
}
decodeBase64Utf8(str) {
return decodeURIComponent(
Array.from(atob(str)).map(c =>
'%' + c.charCodeAt(0).toString(16).padStart(2, '0')
).join('')
)
}
}
app.registerClass('TemplatesManagerView', TemplatesManagerView)