Skip to content

Commit

Permalink
Merge pull request #14 from MauGaP/feature/localization
Browse files Browse the repository at this point in the history
regionalization
  • Loading branch information
MauGaP authored Dec 2, 2023
2 parents 425b66f + dc6f5ab commit 0e7971f
Show file tree
Hide file tree
Showing 10 changed files with 160 additions and 43 deletions.
14 changes: 7 additions & 7 deletions client/addfriends.script.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ function addFriendRow() {
idInput.value = table.rows.length; // Sequential ID based on the row count
idCell.appendChild(idInput);

// Create name cell
// Name cell with translated default value
var nameCell = newRow.insertCell(1);
var nameInput = createInputField('text', 'name', 'Nombre');
var nameInput = createInputField('text', 'name', languageData[currentLanguage].defaultName);
nameCell.appendChild(nameInput);

// Create email cell
// Email cell with translated default value
var emailCell = newRow.insertCell(2);
var emailInput = createInputField('email', 'email', '[email protected]');
var emailInput = createInputField('email', 'email', languageData[currentLanguage].defaultEmail);
emailCell.appendChild(emailInput);

// Create exclude cell
Expand All @@ -26,11 +26,11 @@ function addFriendRow() {
excludeCell.appendChild(excludeInput);
}

function createInputField(type, name, value) {
function createInputField(type, name, defaultValue) {
var input = document.createElement('input');
input.type = type;
input.name = name;
input.value = value;
input.onblur = saveToSessionStorage; // Attach the onblur event
input.value = defaultValue;
input.onblur = saveToSessionStorage;
return input;
}
32 changes: 32 additions & 0 deletions client/languageswitcher.script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
function switchLanguage(lang) {
document.getElementById('headerTitle').textContent = languageData[lang]['headerTitle'];
document.getElementById('addFriendsButton').textContent = languageData[lang]['addFriends'];
document.getElementById('clearAllButton').textContent = languageData[lang]['clearAll'];
document.getElementById('sendEmailsButton').textContent = languageData[lang]['sendEmails'];
document.getElementById('nameTh').textContent = languageData[lang]['nameTh'];
document.getElementById('emailTh').textContent = languageData[lang]['emailTh'];
document.getElementById('exclusionTh').textContent = languageData[lang]['exclusionTh'];

document.querySelectorAll("#friendsTable input[name='name']").forEach(input => {
if (input.value === languageData['en'].defaultName || input.value === languageData['es'].defaultName) {
input.value = languageData[lang].defaultName;
}
});
document.querySelectorAll("#friendsTable input[name='email']").forEach(input => {
if (input.value === languageData['en'].defaultEmail || input.value === languageData['es'].defaultEmail) {
input.value = languageData[lang].defaultEmail;
}
});
}

function toggleLanguage() {
currentLanguage = currentLanguage === 'es' ? 'en' : 'es';
sessionStorage.setItem('preferredLanguage', currentLanguage); // Store in session storage
switchLanguage(currentLanguage);
updateLanguageSwitcherText();
}

function updateLanguageSwitcherText() {
const switcherText = currentLanguage === 'es' ? 'Switch to English' : 'Cambiar a Español';
document.getElementById('languageSwitcher').textContent = switcherText;
}
37 changes: 21 additions & 16 deletions client/sendassignments.script.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
function sendAssignmentsToServer() {
const assignments = JSON.parse(sessionStorage.getItem('secretSantaAssignments'));
if (!assignments) {
console.error('No assignments found in session storage');
return;
}
const assignments = JSON.parse(sessionStorage.getItem('secretSantaAssignments'));
const language = sessionStorage.getItem('preferredLanguage') || 'es'; // Default to Spanish if not set

fetch('http://localhost:3500/send-emails', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ assignments: assignments })
})
if (!assignments) {
console.error('No assignments found in session storage');
return;
}

fetch('http://localhost:3500/send-emails', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
assignments: assignments,
language: language, // Include the language preference in the request
}),
})
.then(response => response.text())
.then(data => {
console.log('Response from server:', data);
// You can add more UI feedback here, e.g., a success message
console.log('Response from server:', data);
// Additional UI feedback for success can be added here
})
.catch(error => {
console.error('Error sending assignments:', error);
// Handle the error in the UI as well
console.error('Error sending assignments:', error);
// Handle the error in the UI as well
});
}
24 changes: 24 additions & 0 deletions client/translation.l18n.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const languageData = {
en: {
headerTitle: `🎅 Secret Santa's Draw 🎅`,
addFriends: 'Add More Friends',
clearAll: 'Clear All',
sendEmails: 'Send Emails',
nameTh: 'Name',
emailTh: 'Email',
exclusionTh: 'Exclusions (Comma separated names)',
defaultName: 'Name',
defaultEmail: '[email protected]',
},
es: {
headerTitle: '🎅 Sorteo del Amigo Invisible 🎅',
addFriends: 'Añadir más amigos',
clearAll: 'Borrar todos',
sendEmails: 'Enviar correos',
nameTh: 'Nombre',
emailTh: 'Correo',
exclusionTh: 'Exclusiones (Nombres separados por coma)',
defaultName: 'Nombre',
defaultEmail: '[email protected]',
},
};
26 changes: 17 additions & 9 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,23 @@
<script src="client/restoresession.script.js"></script>
<script src="client/savesession.script.js"></script>
<script src="client/sendassignments.script.js"></script>
<script src="client/languageswitcher.script.js"></script>
<script src="client/translation.l18n.js"></script>

<!-- Inline Script for Event Listener -->
<script>
document.addEventListener('DOMContentLoaded', function () {
const storedLanguage = sessionStorage.getItem('preferredLanguage');
currentLanguage = storedLanguage ? storedLanguage : 'es'; // Use stored language or default to Spanish
switchLanguage(currentLanguage);
updateLanguageSwitcherText();
restoreFromSessionStorage();
});
</script>

<header>
<h1>Sorteo del Amigo Invisible</h1>
<a href="javascript:void(0)" id="languageSwitcher" onclick="toggleLanguage()">Switch to English</a>
<h1 id="headerTitle">🎅 Sorteo del Amigo Invisible 🎅</h1>
</header>

<main>
Expand All @@ -36,16 +43,17 @@ <h1>Sorteo del Amigo Invisible</h1>

<section class="friend-list">
<form id="friendForm">
<button type="button" class="button" onclick="addFriendRow()">Añadir más amigos</button>
<button type="button" class="button button-right" onclick="clearParticipants()">Borrar
todos</button>
<button id="addFriendsButton" type="button" class="button" onclick="addFriendRow()">Añadir más
amigos</button>
<button id="clearAllButton" type="button" class="button button-right"
onclick="clearParticipants()">Borrar todos</button>
<table id="friendsTable">
<thead>
<tr>
<th style="display: none;">ID</th>
<th>Nombre</th>
<th>Email</th>
<th>Exclusiones (Nombres separados por comma)</th>
<th id="nameTh">Nombre</th>
<th id="emailTh">Email</th>
<th id="exclusionTh">Exclusiones (Nombres separados por comma)</th>
</tr>
</thead>
<tbody>
Expand All @@ -65,8 +73,8 @@ <h1>Sorteo del Amigo Invisible</h1>
</tr>
</tbody>
</table>
<button type="button" class="button button-center" onclick="sendAssignmentsToServer()">Enviar
correos</button>
<button id="sendEmailsButton" type="button" class="button button-center"
onclick="sendAssignmentsToServer()">Enviar correos</button>
</form>
</section>
</main>
Expand Down
Empty file added readme.md
Empty file.
12 changes: 9 additions & 3 deletions server/emailsender.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
const nodemailer = require('nodemailer');
const createSecretSantaEmail = require('./emailtemplate.js');
const createSecretSantaEmailEN = require('./englishemailtemplate');
const createSecretSantaEmailES = require('./spanishemailtemplate');

async function sendEmails(assignments) {
async function sendEmails(assignments, language) {
language = language || 'es';
const transporter = nodemailer.createTransport({
service: 'hotmail',
auth: {
Expand All @@ -10,13 +12,17 @@ async function sendEmails(assignments) {
},
});

const createSecretSantaEmail = language === 'es' ? createSecretSantaEmailES : createSecretSantaEmailEN;

for (const person of assignments) {
const emailContent = createSecretSantaEmail(person.name, person.secretSantaFor);

const subject = language === 'es' ? '🎄Tu amigo invisible esta Navidad🌟' : '🎄Your Secret Santa this Christmas🌟';

const mailOptions = {
from: process.env.EMAIL_USER,
to: person.email,
subject: '🎄Tu amigo invisible esta Navidad🌟',
subject: subject,
html: emailContent,
};

Expand Down
43 changes: 43 additions & 0 deletions server/englishemailtemplate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
function createSecretSantaEmailEN(receiverName, secretSantaFor) {
return `
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
color: #333;
text-align: center;
padding: 20px;
}
.container {
background-color: #fff;
border-radius: 10px;
padding: 20px;
margin: 20px auto;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.header {
font-size: 24px;
color: #d33;
}
.message {
font-size: 16px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">🎅 Secret Santa Assignment 🎅</div>
<div class="message">
<p>Hello <strong>${receiverName}</strong>,</p>
<p>🎄 You have been chosen to be the Secret Santa for: <strong>${secretSantaFor}</strong>!</p>
<p>Remember, it's a secret and have fun picking a 🎁gift🎁!!</p>
<p>🌟Happy Holidays!🌟</p>
</div>
</div>
</body>
</html>`;
}

module.exports = createSecretSantaEmailEN;
9 changes: 4 additions & 5 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,13 @@ const port = 3500;
app.use(bodyParser.json());
app.use(cors({ origin: '*' })); // Allows requests from all origins

app.post('/send-emails', (req, res) => {
app.post('/send-emails', async (req, res) => {
try {
const assignments = req.body.assignments; // Expecting assignments to be in the request body
sendEmails(assignments);
res.status(200).send('Emails are being sent.');
await sendEmails(req.body.assignments, req.body.language);
res.send('Emails sent successfully.');
} catch (error) {
console.error(error);
res.status(500).send('An error occurred while sending emails.');
res.status(500).send('Error sending emails');
}
});

Expand Down
6 changes: 3 additions & 3 deletions server/emailtemplate.js → server/spanishemailtemplate.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function createSecretSantaEmail(receiverName, secretSantaFor) {
function createSecretSantaEmailES(receiverName, secretSantaFor) {
return `
<html>
<head>
Expand Down Expand Up @@ -33,11 +33,11 @@ function createSecretSantaEmail(receiverName, secretSantaFor) {
<p>Hola <strong>${receiverName}</strong>,</p>
<p>🎄Te toco ser el amigo invisible de: <strong>${secretSantaFor}</strong>!</p>
<p>Recorda que es un secreto y divertite buscando un 🎁regalo🎁!!</p>
<p>🌟Happy Holidays!🌟</p>
<p>🌟¡Felices Fiestas!🌟</p>
</div>
</div>
</body>
</html>`;
}

module.exports = createSecretSantaEmail;
module.exports = createSecretSantaEmailES;

0 comments on commit 0e7971f

Please sign in to comment.