Skip to content

Commit

Permalink
add tradução para os campos de busca avançada
Browse files Browse the repository at this point in the history
  • Loading branch information
jesielviana committed May 1, 2024
1 parent 612a32f commit a068eaf
Show file tree
Hide file tree
Showing 10 changed files with 129 additions and 64 deletions.
30 changes: 30 additions & 0 deletions public/locales/en/advanced.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"all": "All fields",
"title_text": "Title",
"publicationDate": "Year",
"author.name": "Autor",
"language": "Language",
"type": "Type",
"orgunit.name": "Institution",
"keyword_text": "Keyword",
"name_text": "Name",
"status": "Status",
"leader.name": "Leader",
"member.name": "Member",
"country": "Country",
"state": "State",
"city": "City",
"issn": "ISSN",
"issnl": "ISSN-L",
"qualis": "Qualis",
"espacenetTitle_text": "Title",
"inventor.name": "Inventor",
"depositDate": "Deposit year",
"kindCode": "Kind Code",
"countryCode": "Country code",
"lattesId": "Lattes",
"orcid": "Orcid",
"releaseYear": "Release year",
"registrationCountry": "Registration country",
"platform": "Platform"
}
29 changes: 2 additions & 27 deletions public/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -168,31 +168,6 @@
"For searches involving a large number of records, the export file may not be immediately available for download. In such cases, the download link for the file will be sent via email shortly.": "For searches involving a large number of records, the export file may not be immediately available for download. In such cases, the download link for the file will be sent via email shortly.",
"Enter your email in the field below:": "Enter your email in the field below:",
"Export processing. The download link will be sent to the e-mail address provided when the file is ready.": "Export processing. The download link will be sent to the e-mail address provided when the file is ready.",
"title_text": "Title",
"publicationDate": "Year",
"author.name": "Autor",
"language": "Language",
"type": "Type",
"orgunit.name": "Institution",
"keyword_text": "Keyword",
"name_text": "Name",
"status": "Status",
"leader.name": "Leader",
"member.name": "Member",
"country": "Country",
"state": "State",
"city": "City",
"issn": "ISSN",
"issnl": "ISSN-L",
"qualis": "Qualis",
"espacenetTitle_text": "Title",
"inventor.name": "Inventor",
"depositDate": "Deposit year",
"kindCode": "Kind Code",
"countryCode": "Country code",
"lattesId": "Lattes",
"orcid": "Orcid",
"releaseYear": "Release year",
"registrationCountry": "Registration country",
"platform": "Platform"
"Academic and/or research institutions": "Academic and/or research institutions",
"Active postgraduate programs evaluated by CAPES": "Active postgraduate programs evaluated by CAPES."
}
30 changes: 30 additions & 0 deletions public/locales/pt-BR/advanced.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"all": "Todos os campos",
"title_text": "Título",
"publicationDate": "Ano",
"author.name": "Autor",
"language": "Idioma",
"type": "Tipo",
"orgunit.name": "Organização",
"keyword_text": "Palavra-chave",
"name_text": "Nome",
"status": "Status",
"leader.name": "Líder",
"member.name": "Membro",
"country": "País",
"state": "Estado",
"city": "Cidade",
"issn": "ISSN",
"issnl": "ISSN-L",
"qualis": "Qualis",
"espacenetTitle_text": "Título",
"inventor.name": "Inventor",
"depositDate": "Ano de depóstito",
"kindCode": "Tipo",
"countryCode": "Código do país",
"lattesId": "Lattes",
"orcid": "Orcid",
"releaseYear": "Ano de lançamento",
"registrationCountry": "País de registro",
"platform": "Plataforma"
}
29 changes: 2 additions & 27 deletions public/locales/pt-BR/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -168,31 +168,6 @@
"For searches involving a large number of records, the export file may not be immediately available for download. In such cases, the download link for the file will be sent via email shortly.": "Para buscas que envolvem um grande volume de registros, o arquivo de exportação pode não estar prontamente disponível para download. Nessas situações, o link para baixar o arquivo será enviado por e-mail em breve.",
"Enter your email in the field below:": "Insira seu email no campo abaixo:",
"Export processing. The download link will be sent to the e-mail address provided when the file is ready.": "Exportação em processamento. O link para download será enviado para o e-mail informado quando o arquivo estiver pronto.",
"title_text": "Título",
"publicationDate": "Ano",
"author.name": "Autor",
"language": "Idioma",
"type": "Tipo",
"orgunit.name": "Instituição",
"keyword_text": "Palavra-chave",
"name_text": "Nome",
"status": "Status",
"leader.name": "Líder",
"member.name": "Membro",
"country": "País",
"state": "Estado",
"city": "Cidade",
"issn": "ISSN",
"issnl": "ISSN-L",
"qualis": "Qualis",
"espacenetTitle_text": "Título",
"inventor.name": "Inventor",
"depositDate": "Ano de depóstito",
"kindCode": "Tipo",
"countryCode": "Código do país",
"lattesId": "Lattes",
"orcid": "Orcid",
"releaseYear": "Ano de lançamento",
"registrationCountry": "País de registro",
"platform": "Plataforma"
"Academic and/or research institutions": "Instituições acadêmicas e/ou de pesquisa",
"Active postgraduate programs evaluated by CAPES": "Programas de pós-graduação ativos avaliados pela CAPES"
}
14 changes: 9 additions & 5 deletions src/components/AdvancedSearchBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
import { SearchBox, withSearch } from '@elastic/react-search-ui';
import { SearchContextState } from '@elastic/react-search-ui/lib/esm/withSearch';
import { useTranslation } from 'next-i18next';

import { useEffect, useState } from 'react';
import { IoAdd, IoArrowUndoOutline, IoClose, IoSearch } from 'react-icons/io5';

import ElasticSearchStatsService from '../services/ElasticSearchStatsService';
import styles from '../styles/AdvancedSearch.module.css';
import { QueryItem } from '../types/Entities';
Expand All @@ -23,12 +25,14 @@ const AdvancedSearchBox = ({
fieldNames,
toogleAdvancedConfig,
}: CustomSearchBoxProps) => {
const { t } = useTranslation('common');
const { t } = useTranslation(['advanced', 'common']);
const [docsCount, setDocsCount] = useState(localStorage.getItem(indexName));
const [query, setQuery] = useState(searchTerm);
const [queryField, setQueryField] = useState('all');
const [inputs, setInputs] = useState<QueryItem[]>([]);

fieldNames = fieldNames.map((field) => t(field));

const addInput = () => {
setInputs([...inputs, { value: '', field: 'all', operator: 'AND' }]);
};
Expand Down Expand Up @@ -104,10 +108,10 @@ const AdvancedSearchBox = ({
></textarea>
<HelpModal fields={fieldNames} />
<select className="form-select" value={queryField} onChange={(e) => setQueryField(e.target.value)}>
<option value="all">{t('All fields')}</option>
<option value="all">{t('all')}</option>
{fieldNames.map((field) => (
<option key={field} value={field}>
{t(field)}
{field}
</option>
))}
</select>
Expand Down Expand Up @@ -156,10 +160,10 @@ const AdvancedSearchBox = ({
onChange={(e) => handleChange({ field: e.target.value }, indice)}
className="form-select"
>
<option value="all">{t('All fields')}</option>
<option value="all">{t('all')}</option>
{fieldNames.map((field) => (
<option key={field} value={field}>
{t(field)}
{field}
</option>
))}
</select>
Expand Down
46 changes: 46 additions & 0 deletions src/components/SearchSanitization.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-ignore

import en from 'public/locales/en/advanced.json';
// @ts-ignore
import ptBr from 'public/locales/pt-BR/advanced.json';

export function findPropertyByValue(value: string) {
for (const property in ptBr) {
//@ts-ignore
if (ptBr[property] === value) {
return property;
}
}
for (const property in en) {
//@ts-ignore
if (en[property] === value) {
return property;
}
}
return value;
}

export function untranslatedFieldsNames(fullQuery: string) {
const regex = /\(([^:)]+):/g; // pega os nomes dos campos, palavra entre '(' e ':'.

const names = [];
let name;
while ((name = regex.exec(fullQuery))) {
names.push(name[1]);
}

const map = new Map();
names.forEach((name) => {
console.log('name', name);
const untranslated = findPropertyByValue(name);
console.log('untranslated', untranslated);
map.set(name, untranslated);
});

for (const [key, value] of map) {
fullQuery = fullQuery.replaceAll(key, value);
}
console.log('fullQuery', fullQuery);
return fullQuery;
}
3 changes: 2 additions & 1 deletion src/components/indicators/query/Query.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { QueryDslOperator, QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types';
import { Filter, FilterValue } from '@elastic/search-ui';
import QueryFormat from '../../../services/QueryFormat';
import { untranslatedFieldsNames } from '../../SearchSanitization';
type QueryProps = {
size: number;
indicadorName: string;
Expand Down Expand Up @@ -50,7 +51,7 @@ export function formatedQuery(
): QueryDslQueryContainer {
let query: QueryDslQueryContainer = {};
if (searchTerm.indexOf('(') >= 0) {
query = new QueryFormat().toElasticsearch(searchTerm, fields);
query = new QueryFormat().toElasticsearch(untranslatedFieldsNames(searchTerm), fields);
} else {
query = {
bool: {
Expand Down
6 changes: 5 additions & 1 deletion src/pages/api/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import ElasticsearchAPIConnector from '@elastic/search-ui-elasticsearch-connector';
import { NextApiRequest, NextApiResponse } from 'next';
import { untranslatedFieldsNames } from '../../components/SearchSanitization';
import logger from '../../services/Logger';
import QueryFormat from '../../services/QueryFormat';
// https://docs.elastic.co/search-ui/api/connectors/elasticsearch#customise-the-elasticsearch-request-body
Expand All @@ -23,7 +24,10 @@ function builConnector(index: string) {
// @ts-ignore
requestState.searchTerm = `(all:${requestState.searchTerm})`;
}
const fullQuery = new QueryFormat().toElasticsearch(requestState.searchTerm, Object.keys(searchFields));
console.log('requestState.searchTerm', requestState.searchTerm);
const query = untranslatedFieldsNames(requestState.searchTerm);
console.log('query', query);
const fullQuery = new QueryFormat().toElasticsearch(query, Object.keys(searchFields));
requestBody.query = fullQuery;
return requestBody;
}
Expand Down
4 changes: 2 additions & 2 deletions src/pages/dashboards/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export default function Dashboards() {
<img className="img-fluid" src="/images/dashboards/institutions.png" alt="ícone de instituições" />
</picture>
<div className="card-body">
<p className="card-text">{t('Institutions')}</p>
<p className="card-text">{t('Academic and/or research institutions')}</p>
</div>
</a>
</Link>
Expand All @@ -151,7 +151,7 @@ export default function Dashboards() {
/>
</picture>
<div className="card-body">
<p className="card-text">{t('Programs')}</p>
<p className="card-text">{t('Active postgraduate programs evaluated by CAPES')}</p>
</div>
</a>
</Link>
Expand Down
2 changes: 1 addition & 1 deletion src/pages/publications.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ type Props = {
};
export const getServerSideProps: GetServerSideProps<Props> = async ({ locale }) => ({
props: {
...(await serverSideTranslations(locale ?? 'en', ['common', 'navbar'])),
...(await serverSideTranslations(locale ?? 'en', ['common', 'navbar', 'advanced'])),
},
});

Expand Down

0 comments on commit a068eaf

Please sign in to comment.