diff --git a/client/src/__test__/utils/PortugueseUtils.test.ts b/client/src/__test__/utils/PortugueseUtils.test.ts new file mode 100644 index 0000000..2c239a2 --- /dev/null +++ b/client/src/__test__/utils/PortugueseUtils.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest'; +import { translateTimeAgoPtBr, translateTimeLeftPtBr } from '../../utils/PortugueseUtils'; +// import USER_LANG from '../../types/UserLangs'; + +describe('Portuguese Utils unit tests', () => { + // const target = USER_LANG.PORTUGUESE; + + it('should translate all time ago messages', () => { + expect(translateTimeAgoPtBr('years ago', 2)).toBe('2 anos atrás'); + expect(translateTimeAgoPtBr('year ago', 1)).toBe('1 ano atrás'); + expect(translateTimeAgoPtBr('months ago', 2)).toBe('2 meses atrás'); + expect(translateTimeAgoPtBr('month ago', 1)).toBe('1 mês atrás'); + expect(translateTimeAgoPtBr('days ago', 2)).toBe('2 dias atrás'); + expect(translateTimeAgoPtBr('day ago', 1)).toBe('1 dia atrás'); + expect(translateTimeAgoPtBr('hours ago', 2)).toBe('2 horas atrás'); + expect(translateTimeAgoPtBr('hour ago', 1)).toBe('1 hora atrás'); + expect(translateTimeAgoPtBr('minutes ago', 2)).toBe('2 minutos atrás'); + expect(translateTimeAgoPtBr('minute ago', 1)).toBe('1 minuto atrás'); + expect(translateTimeAgoPtBr('seconds ago', 2)).toBe('2 segundos atrás'); + expect(translateTimeAgoPtBr('second ago', 1)).toBe('1 segundo atrás'); + expect(translateTimeAgoPtBr('lala', 1)).toBe('Momentos atrás'); + expect(translateTimeAgoPtBr('null', 1)).toBe('Momentos atrás'); + expect(translateTimeAgoPtBr('null', 0)).toBe('Momentos atrás'); + }); + + it('should translate all time left messages', () => { + expect(translateTimeLeftPtBr('years left', 2)).toBe('2 anos restantes'); + expect(translateTimeLeftPtBr('year left', 1)).toBe('1 ano restante'); + expect(translateTimeLeftPtBr('months left', 2)).toBe('2 meses restantes'); + expect(translateTimeLeftPtBr('month left', 1)).toBe('1 mês restante'); + expect(translateTimeLeftPtBr('days left', 2)).toBe('2 dias restantes'); + expect(translateTimeLeftPtBr('day left', 1)).toBe('1 dia restante'); + expect(translateTimeLeftPtBr('lala', 1)).toBe('lala'); + expect(translateTimeLeftPtBr('null', 1)).toBe('null'); + expect(translateTimeLeftPtBr('null', 0)).toBe('null'); + }); +}); \ No newline at end of file diff --git a/client/src/components/LoginForm/index.tsx b/client/src/components/LoginForm/index.tsx index 4719a8a..d4bdb2f 100644 --- a/client/src/components/LoginForm/index.tsx +++ b/client/src/components/LoginForm/index.tsx @@ -16,7 +16,7 @@ import { import { Link, useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import AuthContext from '../../context/AuthContext'; -import { translateMessage } from '../../utils/TranslatorUtils'; +import { translateServerResponse } from '../../utils/TranslatorUtils'; import { handleDefaultLang } from '../../lang-service/LangHandler'; /** @@ -53,7 +53,7 @@ function LoginForm({ prefix }: { prefix: string }): JSX.Element { const form = event.currentTarget; if (form.checkValidity() === false) { setFormInvalid(true); - setErrorMessage(translateMessage('Please fill in your username and password!', i18n.language)); + setErrorMessage(translateServerResponse('Please fill in your username and password!', i18n.language)); return; } @@ -70,10 +70,10 @@ function LoginForm({ prefix }: { prefix: string }): JSX.Element { catch (e) { setFormInvalid(true); if (typeof e === 'string') { - setErrorMessage(translateMessage(e, i18n.language)); + setErrorMessage(translateServerResponse(e, i18n.language)); } else if (e instanceof Error) { - setErrorMessage(translateMessage(e.message, i18n.language)); + setErrorMessage(translateServerResponse(e.message, i18n.language)); } } }; diff --git a/client/src/utils/PortugueseUtils.ts b/client/src/utils/PortugueseUtils.ts index e3b9eb7..245b675 100644 --- a/client/src/utils/PortugueseUtils.ts +++ b/client/src/utils/PortugueseUtils.ts @@ -3,7 +3,7 @@ * * @param {string} textValue The text message to be translated. * @param {number} numberValue The number value to be used in the message. - * @returns The message translated. + * @returns The translated message. */ function translateTimeAgoPtBr(textValue: string, numberValue: number): string { if (textValue.includes('year')) { @@ -16,7 +16,7 @@ function translateTimeAgoPtBr(textValue: string, numberValue: number): string { ? `${numberValue} meses atrás` : `${numberValue} mês atrás`; } - else if (textValue.includes('days')) { + else if (textValue.includes('day')) { return textValue.includes('s ') ? `${numberValue} dias atrás` : `${numberValue} dia atrás`; @@ -26,12 +26,12 @@ function translateTimeAgoPtBr(textValue: string, numberValue: number): string { ? `${numberValue} horas atrás` : `${numberValue} hora atrás`; } - else if (textValue.includes('minutes')) { + else if (textValue.includes('minute')) { return textValue.includes('s ') ? `${numberValue} minutos atrás` : `${numberValue} minuto atrás`; } - else if (textValue.includes('seconds')) { + else if (textValue.includes('second')) { return textValue.includes('s ') ? `${numberValue} segundos atrás` : `${numberValue} segundo atrás`; @@ -45,7 +45,7 @@ function translateTimeAgoPtBr(textValue: string, numberValue: number): string { * * @param {string} textValue The text message to be translated. * @param {number} numberValue The number value to be used in the message. - * @returns The message translated. + * @returns The translated message. */ function translateTimeLeftPtBr(textValue: string, numberValue: number): string { if (textValue.includes('year')) { @@ -66,4 +66,58 @@ function translateTimeLeftPtBr(textValue: string, numberValue: number): string { return textValue; } -export { translateTimeAgoPtBr, translateTimeLeftPtBr }; +/** + * Translates a server response message from English to brazilian Portuguese. + * + * @param {string} message The text message to be translated. + * @returns The translated message. + */ +function translateServerResponsePtBr(message: string): string { + switch (message) { + case 'Bad password: Password must have at least at least 8 characters, 1 uppercase, 1 special character': { + return 'Senha fraca: Senha deve possuir pelo menos 8 letras, 1 maiúscula, 1 caracter especial'; + } + case 'Bad password: Password must have at least 1 uppercase, 1 special character': { + return 'Senha fraca: Senha deve possuir pelo menos 1 maiúscula, 1 caracter especial'; + } + case 'Bad password: Password must have at least 1 special character': { + return 'Senha fraca: Senha deve possuir pelo menos 1 caracter especial'; + } + case 'Email already exists!': { + return 'E-mail já cadastrado!'; + } + case 'Forbidden! Access denied!': { + return 'Proibido! Acesso negado'; + } + case 'Internal Server Error!': { + return 'Erro Interno do Servidor!'; + } + case 'Max login attempt limit reached. Please wait 30 minutes': { + return 'Limite máximo de tentativas atingido. Por favor aguarde 30 minutos'; + } + case 'Please fill in all the fields': { + return 'Por ravor, preencha todos os campos'; + } + case 'Please fill in your username and password!': { + return 'Por favor, informe seu e-mail e senha!'; + } + case 'Please type at least 3 characters': { + return 'Por favor, digite pelo menos 3 letras'; + } + case 'The maximum text length is 2000': { + return 'O tamanho máximo do texto é 2000'; + } + case 'Unknown error': { + return 'Erro desconhecido'; + } + case 'Wrong or missing information!': { + return 'Informação errada ou incompleta!'; + } + case 'Wrong user or password': { + return 'E-mail ou senha inválidos!'; + } + default: return message; + } +} + +export { translateTimeAgoPtBr, translateTimeLeftPtBr, translateServerResponsePtBr }; diff --git a/client/src/utils/RussianUtils.ts b/client/src/utils/RussianUtils.ts index 0e40fa8..f0c86f6 100644 --- a/client/src/utils/RussianUtils.ts +++ b/client/src/utils/RussianUtils.ts @@ -1,3 +1,10 @@ +/** + * Translates a time ago message from English to Russian. + * + * @param {string} textValue The text message to be translated. + * @param {number} numberValue The number value to be used in the message. + * @returns The translated message. + */ function translateTimeAgoRu(textValue: string, numberValue: number): string { if (textValue.includes('year')) { return textValue.includes('s ') @@ -33,4 +40,84 @@ function translateTimeAgoRu(textValue: string, numberValue: number): string { return 'Несколько минут назад'; } -export { translateTimeAgoRu }; +/** + * Translates a time left message from English to Russian. + * + * @param {string} textValue The text message to be translated. + * @param {number} numberValue The number value to be used in the message. + * @returns The translated message. + */ +function translateTimeLeftRu(textValue: string, numberValue: number): string { + if (textValue.includes('year')) { + return textValue.includes('s ') + ? `осталось ${numberValue} лет` + : `Остался ${numberValue} год`; + } + else if (textValue.includes('month')) { + return textValue.includes('s ') + ? `осталось ${numberValue} месяцев` + : `Остался ${numberValue} месяц`; + } + else if (textValue.includes('day')) { + return textValue.includes('s ') + ? `осталось ${numberValue} дней` + : `Остался ${numberValue} день`; + } + return textValue; +} + +/** + * Translates a server response message from English to Russian. + * + * @param {string} message The text message to be translated. + * @returns The translated message. + */ +function translateServerResponseRu(message: string): string { + switch (message) { + case 'Bad password: Password must have at least at least 8 characters, 1 uppercase, 1 special character': { + return 'Неправильный пароль: Пароль должен содержать не менее 8 символов, 1 заглавную букву, 1 специальный символ.'; + } + case 'Bad password: Password must have at least 1 uppercase, 1 special character': { + return 'Неправильный пароль: Пароль должен содержать как минимум 1 заглавную букву и 1 специальный символ.'; + } + case 'Bad password: Password must have at least 1 special character': { + return 'Неправильный пароль: Пароль должен содержать хотя бы 1 специальный символ.'; + } + case 'Email already exists!': { + return 'Электронная почта уже существует!'; + } + case 'Forbidden! Access denied!': { + return 'Запрещено! Доступ запрещен!'; + } + case 'Internal Server Error!': { + return 'Внутренняя ошибка сервера!'; + } + case 'Max login attempt limit reached. Please wait 30 minutes': { + return 'Достигнут максимальный лимит попыток входа. Пожалуйста, подождите 30 минут'; + } + case 'Please fill in all the fields': { + return 'Пожалуйста, заполните все поля'; + } + case 'Please fill in your username and password!': { + return 'Пожалуйста, введите свое имя пользователя и пароль!'; + } + case 'Please type at least 3 characters': { + return 'Пожалуйста, введите не менее 3 символов'; + } + case 'The maximum text length is 2000': { + return 'Максимальная длина текста — 2000.'; + } + case 'Unknown error': { + return 'Неизвестная ошибка'; + } + case 'Wrong or missing information!': { + return 'Неверная или отсутствующая информация!'; + } + case 'Wrong user or password': { + return 'Неправильный пользователь или пароль'; + } + default: return message; + } +} + +export { translateTimeAgoRu, translateTimeLeftRu, translateServerResponseRu }; diff --git a/client/src/utils/SpanishUtils.ts b/client/src/utils/SpanishUtils.ts index c03b2db..8409090 100644 --- a/client/src/utils/SpanishUtils.ts +++ b/client/src/utils/SpanishUtils.ts @@ -3,7 +3,7 @@ * * @param {string} textValue The text message to be translated. * @param {number} numberValue The number value to be used in the message. - * @returns The message translated. + * @returns The translated message. */ function translateTimeAgoEs(textValue: string, numberValue: number): string { if (textValue.includes('year')) { @@ -45,7 +45,7 @@ function translateTimeAgoEs(textValue: string, numberValue: number): string { * * @param {string} textValue The text message to be translated. * @param {number} numberValue The number value to be used in the message. - * @returns The message translated. + * @returns The translated message. */ function translateTimeLeftEs(textValue: string, numberValue: number): string { if (textValue.includes('year')) { @@ -66,4 +66,58 @@ function translateTimeLeftEs(textValue: string, numberValue: number): string { return textValue; } -export { translateTimeAgoEs, translateTimeLeftEs }; +/** + * Translates a server response message from English to Spanish. + * + * @param {string} message The text message to be translated. + * @returns The translated message. + */ +function translateServerResponseEs(message: string): string { + switch (message) { + case 'Bad password: Password must have at least at least 8 characters, 1 uppercase, 1 special character': { + return 'Contraseña inválida: La contraseña debe tener al menos 8 caracteres, 1 mayúscula y 1 carácter especial'; + } + case 'Bad password: Password must have at least 1 uppercase, 1 special character': { + return 'Contraseña inválida: La contraseña debe tener al menos 1 mayúscula y 1 carácter especial'; + } + case 'Bad password: Password must have at least 1 special character': { + return 'Contraseña inválida: La contraseña debe tener al menos 1 carácter especial'; + } + case 'Email already exists!': { + return '¡El correo ya está registrado!'; + } + case 'Forbidden! Access denied!': { + return '¡Prohibido! Acceso denegado'; + } + case 'Internal Server Error!': { + return '¡Error interno del servidor!'; + } + case 'Max login attempt limit reached. Please wait 30 minutes': { + return 'Has alcanzado el límite máximo de intentos de inicio de sesión. Por favor, espera 30 minutos'; + } + case 'Please fill in all the fields': { + return 'Por favor, completa todos los campos'; + } + case 'Please fill in your username and password!': { + return '¡Por favor, ingresa tu nombre de usuario y contraseña!'; + } + case 'Please type at least 3 characters': { + return '¡Por favor, escriba al menos 3 caracteres'; + } + case 'The maximum text length is 2000': { + return 'La longitud máxima del texto es 2000'; + } + case 'Unknown error': { + return 'Error desconocido'; + } + case 'Wrong or missing information!': { + return '¡Información incorrecta o incompleta!'; + } + case 'Wrong user or password': { + return '¡Usuario o contraseña incorrectos!'; + } + default: return message; + } +} + +export { translateTimeAgoEs, translateTimeLeftEs, translateServerResponseEs }; diff --git a/client/src/utils/TranslatorUtils.ts b/client/src/utils/TranslatorUtils.ts index ad1bd84..17506ac 100644 --- a/client/src/utils/TranslatorUtils.ts +++ b/client/src/utils/TranslatorUtils.ts @@ -1,25 +1,8 @@ import { TaskResponse } from '../types/TaskResponse'; import USER_LANG from '../types/UserLangs'; -import { translateTimeAgoPtBr, translateTimeLeftPtBr } from './PortugueseUtils'; -import { translateTimeAgoRu } from './RussianUtils'; -import { translateTimeAgoEs, translateTimeLeftEs } from './SpanishUtils'; - -/** - * Translates all responses from tasks server API. - * - * @param {TaskResponse[]} tasks The tasks to be translated. - * @param {string} target The target language. - * @returns {TaskResponse[]} Array of tasks translated into the target language. - */ -function translateTaskResponse(tasks: TaskResponse[], target: string): TaskResponse[] { - tasks.forEach((task: TaskResponse) => { - task.lastUpdate = translateMessage(task.lastUpdate, target); - if (task.dueDateFmt) { - task.dueDateFmt = translateMessage(task.dueDateFmt, target); - } - }); - return tasks; -} +import { translateServerResponsePtBr, translateTimeAgoPtBr, translateTimeLeftPtBr } from './PortugueseUtils'; +import { translateServerResponseRu, translateTimeAgoRu, translateTimeLeftRu } from './RussianUtils'; +import { translateServerResponseEs, translateTimeAgoEs, translateTimeLeftEs } from './SpanishUtils'; /** * Translates a given message to a given language @@ -28,16 +11,16 @@ function translateTaskResponse(tasks: TaskResponse[], target: string): TaskRespo * @param {string} target The target language. One of USER_LANG * @returns {string} The translated message. */ -function translateMessage(message: string, target: string): string { +function translateTimeMessage(message: string, target: string): string { if (target === USER_LANG.ENGLISH) { return message; } - if (message.includes(' ago')) { - const firstSpace = message.indexOf(' '); - const numberValue = parseInt(message.substring(0, firstSpace)); - const textValue = message.substring(firstSpace).trim(); + const firstSpace = message.indexOf(' '); + const numberValue = parseInt(message.substring(0, firstSpace)); + const textValue = message.substring(firstSpace).trim(); + if (message.includes(' ago')) { if (target === USER_LANG.PORTUGUESE) { return translateTimeAgoPtBr(textValue, numberValue); } @@ -49,229 +32,52 @@ function translateMessage(message: string, target: string): string { } if (message.includes(' left')) { - const firstSpace = message.indexOf(' '); - const numberValue = parseInt(message.substring(0, firstSpace)); - const textValue = message.substring(firstSpace).trim(); - if (target === USER_LANG.PORTUGUESE) { return translateTimeLeftPtBr(textValue, numberValue); } if (target === USER_LANG.SPANISH) { return translateTimeLeftEs(textValue, numberValue); } - switch (textValue) { - case 'years left': { - if (lang === USER_LANG.RUSSIAN) { - return `осталось ${numberValue} лет`; - } - break; - } - case 'year left': { - if (lang === USER_LANG.RUSSIAN) { - return `Остался ${numberValue} год`; - } - break; - } - case 'months left': { - if (lang === USER_LANG.RUSSIAN) { - return `осталось ${numberValue} месяцев`; - } - break; - } - case 'month left': { - if (lang === USER_LANG.RUSSIAN) { - return `Остался ${numberValue} месяц`; - } - break; - } - case 'days left': { - if (lang === USER_LANG.RUSSIAN) { - return `осталось ${numberValue} дней`; - } - break; - } - case 'day left': { - if (lang === USER_LANG.RUSSIAN) { - return `Остался ${numberValue} день`; - } - break; - } - } + + return translateTimeLeftRu(textValue, numberValue); } - switch (message) { - case 'Bad password: Password must have at least at least 8 characters, 1 uppercase, 1 special character': { - if (lang === USER_LANG.PORTUGUESE) { - return 'Senha fraca: Senha deve possuir pelo menos 8 letras, 1 maiúscula, 1 caracter especial'; - } - else if (lang === USER_LANG.SPANISH) { - return 'Contraseña inválida: La contraseña debe tener al menos 8 caracteres, 1 mayúscula y 1 carácter especial'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Неправильный пароль: Пароль должен содержать не менее 8 символов, 1 заглавную букву, 1 специальный символ.'; - } - break; - } - case 'Bad password: Password must have at least 1 uppercase, 1 special character': { - if (lang === USER_LANG.PORTUGUESE) { - return 'Senha fraca: Senha deve possuir pelo menos 1 maiúscula, 1 caracter especial'; - } - else if (lang === USER_LANG.SPANISH) { - return 'Contraseña inválida: La contraseña debe tener al menos 1 mayúscula y 1 carácter especial'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Неправильный пароль: Пароль должен содержать как минимум 1 заглавную букву и 1 специальный символ.'; - } - break; - } - case 'Bad password: Password must have at least 1 special character': { - if (lang === USER_LANG.PORTUGUESE) { - return 'Senha fraca: Senha deve possuir pelo menos 1 caracter especial'; - } - else if (lang === USER_LANG.SPANISH) { - return 'Contraseña inválida: La contraseña debe tener al menos 1 carácter especial'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Неправильный пароль: Пароль должен содержать хотя бы 1 специальный символ.'; - } - break; - } - case 'Email already exists!': { - if (lang === USER_LANG.PORTUGUESE) { - return 'E-mail já cadastrado!'; - } - else if (lang === USER_LANG.SPANISH) { - return '¡El correo ya está registrado!'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Электронная почта уже существует!'; - } - break; - } - case 'Forbidden! Access denied!': { - if (lang === USER_LANG.PORTUGUESE) { - return 'Proibido! Acesso negado'; - } - else if (lang === USER_LANG.SPANISH) { - return '¡Prohibido! Acceso denegado'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Запрещено! Доступ запрещен!'; - } - break; - } - case 'Internal Server Error!': { - if (lang === USER_LANG.PORTUGUESE) { - return 'Erro Interno do Servidor!'; - } - else if (lang === USER_LANG.SPANISH) { - return '¡Error interno del servidor!'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Внутренняя ошибка сервера!'; - } - break; - } - case 'Max login attempt limit reached. Please wait 30 minutes': { - if (lang === USER_LANG.PORTUGUESE) { - return 'Limite máximo de tentativas atingido. Por favor aguarde 30 minutos'; - } - else if (lang === USER_LANG.SPANISH) { - return 'Has alcanzado el límite máximo de intentos de inicio de sesión. Por favor, espera 30 minutos'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Достигнут максимальный лимит попыток входа. Пожалуйста, подождите 30 минут'; - } - break; - } - case 'Please fill in all the fields': { - if (lang === USER_LANG.PORTUGUESE) { - return 'Por ravor, preencha todos os campos'; - } - else if (lang === USER_LANG.SPANISH) { - return 'Por favor, completa todos los campos'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Пожалуйста, заполните все поля'; - } - break; - } - case 'Please fill in your username and password!': { - if (lang === USER_LANG.PORTUGUESE) { - return 'Por favor, informe seu e-mail e senha!'; - } - else if (lang === USER_LANG.SPANISH) { - return '¡Por favor, ingresa tu nombre de usuario y contraseña!'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Пожалуйста, введите свое имя пользователя и пароль!'; - } - break; - } - case 'Please type at least 3 characters': { - if (lang === USER_LANG.PORTUGUESE) { - return 'Por favor, digite pelo menos 3 letras'; - } - else if (lang === USER_LANG.SPANISH) { - return '¡Por favor, escriba al menos 3 caracteres'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Пожалуйста, введите не менее 3 символов'; - } - break; - } - case 'The maximum text length is 2000': { - if (lang === USER_LANG.PORTUGUESE) { - return 'O tamanho máximo do texto é 2000'; - } - else if (lang === USER_LANG.SPANISH) { - return 'La longitud máxima del texto es 2000'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Максимальная длина текста — 2000.'; - } - break; - } - case 'Unknown error': { - if (lang === USER_LANG.PORTUGUESE) { - return 'Erro desconhecido'; - } - else if (lang === USER_LANG.SPANISH) { - return 'Error desconocido'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Неизвестная ошибка'; - } - break; - } - case 'Wrong or missing information!': { - if (lang === USER_LANG.PORTUGUESE) { - return 'Informação errada ou incompleta!'; - } - else if (lang === USER_LANG.SPANISH) { - return '¡Información incorrecta o incompleta!'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Неверная или отсутствующая информация!'; - } - break; - } - case 'Wrong user or password': { - if (lang === USER_LANG.PORTUGUESE) { - return 'E-mail ou senha inválidos!'; - } - else if (lang === USER_LANG.SPANISH) { - return '¡Usuario o contraseña incorrectos!'; - } - else if (lang === USER_LANG.RUSSIAN) { - return 'Неправильный пользователь или пароль'; - } - break; - } - default: return ''; + return message; +} + +/** + * Translates a server response message from English to a target language. + * + * @param {string} message The text message to be translated. + * @param {string} target The target language to be translated. + * @returns The translated message. + */ +function translateServerResponse(message: string, target: string): string { + if (target === USER_LANG.PORTUGUESE) { + return translateServerResponsePtBr(message); } + if (target === USER_LANG.SPANISH) { + return translateServerResponseEs(message); + } + + return translateServerResponseRu(message); +} - return ''; +/** + * Translates all responses from tasks server API. + * + * @param {TaskResponse[]} tasks The tasks to be translated. + * @param {string} target The target language. + * @returns {TaskResponse[]} Array of tasks translated into the target language. + */ +function translateTaskResponse(tasks: TaskResponse[], target: string): TaskResponse[] { + tasks.forEach((task: TaskResponse) => { + task.lastUpdate = translateTimeMessage(task.lastUpdate, target); + if (task.dueDateFmt) { + task.dueDateFmt = translateTimeMessage(task.dueDateFmt, target); + } + }); + return tasks; } -export { translateTaskResponse, translateMessage }; +export { translateTaskResponse, translateServerResponse }; diff --git a/client/src/views/Home/index.tsx b/client/src/views/Home/index.tsx index 1e7a976..f349d22 100644 --- a/client/src/views/Home/index.tsx +++ b/client/src/views/Home/index.tsx @@ -14,7 +14,7 @@ import { NoteResponse } from '../../types/NoteResponse'; import api from '../../api-service/api'; import ApiConfig from '../../api-service/apiConfig'; import { handleDefaultLang } from '../../lang-service/LangHandler'; -import { translateMessage } from '../../utils/TranslatorUtils'; +import { translateServerResponse } from '../../utils/TranslatorUtils'; /** * Home page component. @@ -34,10 +34,10 @@ function Home(): JSX.Element { const handleError = (e: unknown): void => { if (typeof e === 'string') { - setErrorMessage(translateMessage(e, i18n.language)); + setErrorMessage(translateServerResponse(e, i18n.language)); } else if (e instanceof Error) { - setErrorMessage(translateMessage(e.message, i18n.language)); + setErrorMessage(translateServerResponse(e.message, i18n.language)); } }; @@ -71,7 +71,7 @@ function Home(): JSX.Element { const form = event.currentTarget; if (form.checkValidity() === false) { setFormInvalid(true); - setErrorMessage(translateMessage('Please type at least 3 characters', i18n.language)); + setErrorMessage(translateServerResponse('Please type at least 3 characters', i18n.language)); return; } diff --git a/client/src/views/Note/index.tsx b/client/src/views/Note/index.tsx index 39aba2a..86db9d0 100644 --- a/client/src/views/Note/index.tsx +++ b/client/src/views/Note/index.tsx @@ -7,7 +7,7 @@ import TaskNoteRequest from '../../types/TaskNoteRequest'; import { NoteResponse } from '../../types/NoteResponse'; import api from '../../api-service/api'; import ApiConfig from '../../api-service/apiConfig'; -import { translateMessage } from '../../utils/TranslatorUtils'; +import { translateServerResponse } from '../../utils/TranslatorUtils'; import './style.css'; type NoteAction = 'add' | 'edit'; @@ -29,11 +29,11 @@ function Note(): JSX.Element { const handleError = (e: unknown): void => { if (typeof e === 'string') { - setErrorMessage(translateMessage(e, i18n.language)); + setErrorMessage(translateServerResponse(e, i18n.language)); setFormInvalid(true); } else if (e instanceof Error) { - setErrorMessage(translateMessage(e.message, i18n.language)); + setErrorMessage(translateServerResponse(e.message, i18n.language)); setFormInvalid(true); } }; @@ -92,13 +92,13 @@ function Note(): JSX.Element { const form = event.currentTarget; if (form.checkValidity() === false) { setFormInvalid(true); - setErrorMessage(translateMessage('Please fill in all the fields', i18n.language)); + setErrorMessage(translateServerResponse('Please fill in all the fields', i18n.language)); return; } if (form.note_description.value.length > 2000) { setFormInvalid(true); - setErrorMessage(translateMessage('The maximum text length is 2000', i18n.language)); + setErrorMessage(translateServerResponse('The maximum text length is 2000', i18n.language)); return; } diff --git a/client/src/views/Task/index.tsx b/client/src/views/Task/index.tsx index c77b299..0476249 100644 --- a/client/src/views/Task/index.tsx +++ b/client/src/views/Task/index.tsx @@ -22,7 +22,7 @@ import { TaskResponse, TaskUrlResponse } from '../../types/TaskResponse'; import { useTranslation } from 'react-i18next'; import api from '../../api-service/api'; import ApiConfig from '../../api-service/apiConfig'; -import { translateMessage, translateTaskResponse } from '../../utils/TranslatorUtils'; +import { translateServerResponse, translateTaskResponse } from '../../utils/TranslatorUtils'; import './style.css'; type TaskAction = 'add' | 'edit'; @@ -47,11 +47,11 @@ function Task(): JSX.Element { const handleError = (e: unknown): void => { if (typeof e === 'string') { - setErrorMessage(translateMessage(e, i18n.language)); + setErrorMessage(translateServerResponse(e, i18n.language)); setFormInvalid(true); } else if (e instanceof Error) { - setErrorMessage(translateMessage(e.message, i18n.language)); + setErrorMessage(translateServerResponse(e.message, i18n.language)); setFormInvalid(true); } }; @@ -119,7 +119,7 @@ function Task(): JSX.Element { const form = event.currentTarget; if (form.checkValidity() === false) { setFormInvalid(true); - setErrorMessage(translateMessage('Please fill in all the fields', i18n.language)); + setErrorMessage(translateServerResponse('Please fill in all the fields', i18n.language)); return; }