Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 22 additions & 17 deletions my_compassion/controllers/auto_texts.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,55 +3,60 @@
"fra": """Bonjour %s,


Je te souhaite de belles fêtes de Noël!
Bonne nouvelle de Bethléem !

Il y a très longtemps, par une nuit silencieuse, des bergers gardaient leurs moutons. Soudain, un ange leur apparut et leur apporta une merveilleuse nouvelle: Jésus était né! Les bergers furent d'abord effrayés, mais l'ange leur dit de se réjouir, car l'enfant apportait la paix et l'espoir à tous les hommes.
Très loin d'ici, à Bethléem, un petit bébé du nom de Jésus est né, entouré d'amour, dans une petite étable. Marie et Joseph étaient allés à Bethléem et n'avaient pas trouvé de meilleur endroit où passer la nuit. C'est ainsi que Jésus est venu au monde - dans une simple crèche.

Les bergers se mirent alors immédiatement en route pour voir l'enfant. Lorsqu'ils le trouvèrent, ils surent que Dieu avait préparé un grand cadeau pour nous tous. C'est la joie que nous pouvons célébrer chaque année à Noël.
Même loin de chez eux, ils ont rapidement reçu de la visite. Des anges avaient annoncé la bonne nouvelle à des bergers, qui sont venus voir le bébé. Jésus a aussi reçu la visite de trois rois mages, qui ont fait tout un voyage pour lui apporter des cadeaux !

Je te souhaite le meilleur pour la nouvelle année, à toi et à ceux que tu aimes.
Jésus est venu donner la joie, la paix et l’espérance au monde entier.

Je souhaite que cette lumière remplisse aussi ton cœur et que tu passes un très joyeux Noël !


%s
""",
"eng": """Hello %s,
"eng": """Hey %s,


Good news from Bethlehem!

I wish you a very merry Christmas!
Far away, in Bethlehem, a little baby named Jesus was born, surrounded by love, in a little stable. Mary and Joseph had gone to Bethlehem and couldn’t find a better place to spend the night. That’s how Jesus came into the world - in a manger.

A long time ago, on a quiet night, shepherds were watching over their sheep. Suddenly, an angel appeared to them and brought wonderful news: Jesus was born! The shepherds were scared at first, but the angel told them to rejoice because the child would bring peace and hope to all people.
Even far from home, it wasn’t long before they had visitors. Angels had announced the good news to shepherds, who came to see the baby. Jesus was even visited by three wise kings, who had gone on a long trip to bring him gifts!

The shepherds immediately set off to see the child, and when they found him, they knew that God had prepared a great gift for us all. This is the joy that we celebrate every year at Christmas.
Jesus came to give joy, peace, and hope to the whole world.

I wish you and your loved ones all the best for the New Year.
I hope this light fills your heart too, and that you have a very Merry Christmas!


%s
""",
"por": """Olá %s,


Desejo a você um Natal maravilhoso!
Boas notícias de Belém!
Muito longe daqui, em Belém, nasceu um pequeno bebê chamado Jesus, rodeado de amor, em um pequeno estábulo. Maria e José tinham ido a Belém e não encontraram melhor lugar para passar a noite. Foi assim que Jesus veio ao mundo - em uma simples manjedoura.

Há muito tempo, em uma noite tranquila, os pastores estavam cuidando de suas ovelhas. De repente, um anjo apareceu para eles e trouxe uma notícia maravilhosa: Jesus havia nascido! A princípio, os pastores ficaram assustados, mas o anjo lhes disse para se alegrarem porque a criança traria paz e esperança a todas as pessoas.
Mesmo longe de casa, eles rapidamente receberam visitas. Anjos anunciaram a boa notícia aos pastores, que vieram ver o bebê. Jesus também recebeu a visita de três reis magos, que fizeram uma longa viagem para lhe trazer presentes!

Os pastores partiram imediatamente para ver a criança e, quando a encontraram, souberam que Deus havia preparado um grande presente para todos nós. Esta é a alegria que podemos celebrar todos os anos no Natal.
Jesus veio trazer alegria, paz e esperança ao mundo inteiro.

Desejo a você e a seus entes queridos tudo de bom para o Ano Novo.
Desejo que essa luz também encha seu coração e que você tenha um Natal muito feliz!


%s
""",
"spa": """Hola %s


¡Te deseo una maravillosa Navidad!
¡Buenas noticias desde Belén!

Hace mucho tiempo, en una noche tranquila, unos pastores cuidaban de sus ovejas. De repente, se les apareció un ángel y les dio una noticia maravillosa: ¡Jesús había nacido! Los pastores se asustaron al principio, pero el ángel les dijo que se alegraran porque el niño traería paz y esperanza a todos los pueblos.
En un pequeño establo, lejos de aquí, nació Jesús, un pequeño bebé rodeado de amor. María y José habían viajado a Belén y no encontraron un alojamiento mejor. Así fue como Jesús vino al mundo en un sencillo pesebre. Estaban lejos de su hogar y, aun así, pronto recibieron visitas. Los ángeles anunciaron la buena noticia, y los pastores vinieron a ver al bebé. Incluso los tres sabios emprendieron el camino y llevaron regalos a Jesús. Jesús vino para traer alegría, paz y esperanza a todo el mundo.

Los pastores salieron inmediatamente a ver al niño y, cuando lo encontraron, supieron que Dios había preparado un gran regalo para todos nosotros. Esta es la alegría que podemos celebrar cada año en Navidad.
Te deseo que esta luz ilumine también tu corazón y te regale muchos momentos felices en Navidad.

¡Te deseo a ti y a tus seres queridos todo lo mejor para el Año Nuevo!
¡Feliz Navidad!


%s
Expand Down
18 changes: 17 additions & 1 deletion my_compassion/controllers/my2_letters.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,13 +213,20 @@ def my2_render_new_letter_page(self, **kwargs):
.with_context(bin_size=False)
)

popup_templates = (
request.env["correspondence.prewritten.letter"]
.sudo()
.search([("status", "=", "active")])
)

return request.render(
"my_compassion.my2_new_letter_page",
{
"selected_child": child,
"sponsorship_ids": sponsorships,
"templates": templates,
"draft": draft,
"text_templates": popup_templates,
},
)

Expand Down Expand Up @@ -490,12 +497,20 @@ def my2_get_letter_status(self, **post):
def get_letter_templates(self, **kw):
"""
This controller returns the currently active letter template.
MODIFIED: It now accepts a 'template_id' parameter to fetch a specific one.
"""

template_id = self._safe_int(kw.get("template_id"), None)
domain = [("status", "=", "active")]
limit = 1

if template_id:
domain.append(("id", "=", template_id))

templates = (
request.env["correspondence.prewritten.letter"]
.sudo()
.search([("status", "=", "active")], limit=1)
.search(domain, limit=limit)
)

template_text = templates.text or ""
Expand All @@ -510,6 +525,7 @@ def get_letter_templates(self, **kw):
self._check_sponsored_child_access(child)
except (AccessError, ValueError):
_logger.warning("Invalid child access for letter template.")

replacements = {
"%child%": child.preferred_name or "",
"%firstname%": partner.preferred_name or partner.name or "",
Expand Down
23 changes: 2 additions & 21 deletions my_compassion/models/correspondence_prewritten_letter.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ class My2CorrespondencePreWrittenLetter(models.Model):
_rec_name = "name"

# == Fields ==
name = fields.Char(required=True)
text = fields.Text(string="Text")
name = fields.Char(required=True, translate=True)
text = fields.Text(required=True, translate=True)
start_date = fields.Date(
help="The date from which this template is valid.",
required=True,
Expand Down Expand Up @@ -122,22 +122,3 @@ def _check_non_overlapping_schedule(self):
raise ValidationError(
_("Cannot schedule a template that is already expired.")
)

# Only check for overlaps if the current record is scheduled
if record.is_active and record.start_date and record.end_date:
domain = [
("id", "!=", record.id),
("is_active", "=", True),
("start_date", "<=", record.end_date),
("end_date", ">=", record.start_date),
]

conflicting_records = self.search(domain)
if conflicting_records:
conflict_details = "\n".join(
f"{c.name} {c.start_date} to {c.end_date}"
for c in conflicting_records
)
raise ValidationError(
_("Conflicts with the following records:\n" + conflict_details)
)
1 change: 1 addition & 0 deletions my_compassion/models/correspondence_s2b_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class CorrespondenceS2BGenerator(models.Model):
user_id = fields.Many2one("res.users", index=True)
child_id = fields.Many2one("compassion.child", index=True)
partner_id = fields.Many2one(related="user_id.partner_id", readonly=True)
text_template_id = fields.Many2one("correspondence.prewritten.letter")

def set_sponsorship_from_user_and_child(self):
for generator in self:
Expand Down
92 changes: 59 additions & 33 deletions my_compassion/static/src/js/my2_letter_template_loader.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,69 @@
/**
* Handles the selection of template images by adding an ID to the clicked image
* and removing it from any previously selected image.
*
* Is used in /templates/pages/my2_new_letter.xml
* Fetches a letter template from the server and populates the text input field with it.
*
* Used in /templates/pages/my2_new_letter.xml
*/
document.addEventListener("DOMContentLoaded", () => {
const textInput = document.getElementById("letter-input");
const childSelector = document.getElementById("child-dropdown");
const TEMPLATE_URL = `/my2/children/letter/templates`;
// Open the modal when the select element is clicked
document.getElementById("letter_template").addEventListener("click", function (event) {
event.preventDefault();
$("#textTemplateSelectionModal").modal("show");
});
document.body.addEventListener("click", function (event) {
const clickedButton = event.target.closest(".text-template-item");

const fetchTemplate = (childId) => {
if (!textInput) {
console.error("Required HTML element #letter-input is missing.");
return;
}
fetch(`${TEMPLATE_URL}?child_id=${childId}`)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
if (data && data.template_text) {
textInput.value = data.template_text;
}
})
.catch((error) => {
console.error("Failed to fetch template:", error);
});
};
if (clickedButton) {
const templateId = clickedButton.dataset.templateId;
if (!templateId) {
console.error("'data-template-id' is undefined.");
return;
}
// Store the template ID in a hidden input for later use if needed
const hiddenInput = document.getElementById("selected_template_id");
if (hiddenInput) {
hiddenInput.value = templateId;
} else {
console.error("Could not find '#selected_template_id' to store template ID.");
}

const childSelector = document.getElementById("child-dropdown");
if (!childSelector) {
console.error("Could not find '#child-dropdown'.");
return;
}
const childId = childSelector.value;

const TEMPLATE_URL = `/my2/children/letter/templates`;

if (childSelector) {
// Fetch template on initial load only if input is empty
if (!textInput.value) {
fetchTemplate(childSelector.value);
fetch(`${TEMPLATE_URL}?child_id=${childId}&template_id=${templateId}`)
.then((response) => {
// 1. Open curly brace
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json(); // 2. Explicit return
}) // 3. Close curly brace
.then((data) => {
if (data && data.template_text) {
const targetInput = document.getElementById("letter-input");
if (targetInput) {
targetInput.value = data.template_text;
// Trigger input event so framework/listeners detect the change
targetInput.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
} else {
console.error("Could not find '#letter-input' for insertion.");
}
} else {
console.error("Fetch did not return 'template_text'.");
}
})
.catch((error) => {
console.error("Fetch failed:", error); // Fixed typo "etch"
});
}
// Re-fetch template when child selection changes
childSelector.addEventListener("change", (event) => {
fetchTemplate(event.target.value);
});
}
});
});
5 changes: 3 additions & 2 deletions my_compassion/static/src/js/my2_new_letter_clear_button.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ document.addEventListener("DOMContentLoaded", function () {
this.$("#selected-template").remove();

// Restore the select template button label to default
const buttonLabel = this.$("#template-selection-label");
const buttonLabel = this.$("#template-selection-label, #text-template-selection-label");
if (buttonLabel.length) {
buttonLabel.text(_t("Select a template"));
}
Expand Down Expand Up @@ -81,7 +81,8 @@ document.addEventListener("DOMContentLoaded", function () {
* @private
*/
_toggleClearButton: function () {
const hasText = this.$("#letter-input").val().trim().length > 0;
const letterText = this.$("#letter-input").val();
const hasText = letterText && letterText.trim().length > 0;
const selectedTemplate = this.$("#selected-template").length > 0;
const hasAttachments = this.$("#letter-attachments")[0].files.length > 0;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ document.addEventListener("DOMContentLoaded", function () {

// Get all template images
const templateImages = document.querySelectorAll(".template-image");
const textInputs = document.querySelectorAll(".text-template-item");

// Add click event listener to each image
templateImages.forEach((image) => {
Expand Down Expand Up @@ -42,4 +43,13 @@ document.addEventListener("DOMContentLoaded", function () {
targetDiv.appendChild(img);
});
});

textInputs.forEach((textInput) => {
textInput.addEventListener("click", function () {
// Replace the button's label content with the template name selected
const button_label_element = document.getElementById("text-template-selection-label");
const selectedTemplateName = textInput.innerText;
button_label_element.textContent = selectedTemplateName;
});
});
});
Loading