From 4d554fd40bb032fb32ca3c2280f1372223c448a9 Mon Sep 17 00:00:00 2001 From: Matheus Coitinho Date: Thu, 14 Aug 2025 20:19:25 -0300 Subject: [PATCH 1/9] adiciona funcionalidades para cadastro e listagem de locais de coleta --- src/controllers/locais-coleta-controller.js | 48 ++++++++- src/routes/locais.js | 103 ++++++++++++++++++++ src/validators/localColeta-cadastro.js | 25 +++++ src/validators/localColeta-listagem.js | 8 ++ 4 files changed, 183 insertions(+), 1 deletion(-) create mode 100644 src/validators/localColeta-cadastro.js create mode 100644 src/validators/localColeta-listagem.js diff --git a/src/controllers/locais-coleta-controller.js b/src/controllers/locais-coleta-controller.js index 771a7ef3..c65fe274 100644 --- a/src/controllers/locais-coleta-controller.js +++ b/src/controllers/locais-coleta-controller.js @@ -1,9 +1,11 @@ +import { pick } from 'lodash'; + import BadRequestExeption from '../errors/bad-request-exception'; import models from '../models'; import codigos from '../resources/codigos-http'; const { - Relevo, Solo, Vegetacao, sequelize, + Relevo, Solo, Vegetacao, LocalColeta, Cidade, FaseSucessional, sequelize, } = models; export const cadastrarSolo = (request, response, next) => { @@ -120,4 +122,48 @@ export const buscarVegetacoes = (request, response, next) => { .catch(next); }; +export const cadastrarLocalColeta = async (request, response, next) => { + try { + const dados = pick(request.body, ['descricao', 'complemento', 'cidade_id', 'fase_sucessional_id']); + const localColeta = await LocalColeta.create(dados); + response.status(201).json(localColeta); + } catch (error) { + next(error); + } +}; + +export const buscarLocaisColeta = async (request, response, next) => { + try { + const { cidadeId } = request.query; + const { limite, pagina } = request.paginacao; + const offset = (pagina - 1) * limite; + + const where = {}; + if (cidadeId) { + where.cidade_id = cidadeId; + } + + const { count, rows } = await LocalColeta.findAndCountAll({ + where, + include: [ + { model: Cidade }, + { model: FaseSucessional }, + ], + limit: limite, + offset, + }); + + response.status(200).json({ + metadados: { + total: count, + pagina, + limite, + }, + locaisColeta: rows, + }); + } catch (error) { + next(error); + } +}; + export default {}; diff --git a/src/routes/locais.js b/src/routes/locais.js index 0e5fa934..b095a036 100644 --- a/src/routes/locais.js +++ b/src/routes/locais.js @@ -1,5 +1,8 @@ +import listagensMiddleware from '../middlewares/listagens-middleware'; import tokensMiddleware, { TIPOS_USUARIOS } from '../middlewares/tokens-middleware'; import validacoesMiddleware from '../middlewares/validacoes-middleware'; +import localColetaCadastroEsquema from '../validators/localColeta-cadastro'; +import localColetaListagemEsquema from '../validators/localColeta-listagem'; import nomeEsquema from '../validators/nome-obrigatorio'; const controller = require('../controllers/locais-coleta-controller'); @@ -233,4 +236,104 @@ export default app => { .get([ controller.buscarVegetacoes, ]); + + /** + * @swagger + * /locais-coleta: + * post: + * summary: Cadastra um novo local de coleta + * tags: [Locais] + * requestBody: + * required: true + * content: + * application/json: + * schema: + * type: object + * properties: + * descricao: + * type: string + * complemento: + * type: string + * cidade_id: + * type: integer + * fase_sucessional_id: + * type: integer + * required: + * - descricao + * - cidade_id + * example: + * descricao: "Próximo ao rio" + * complemento: "Entrada pela fazenda" + * cidade_id: 1 + * fase_sucessional_id: 2 + * responses: + * 201: + * description: Local de coleta cadastrado com sucesso + * '400': + * $ref: '#/components/responses/BadRequest' + * '401': + * $ref: '#/components/responses/Unauthorized' + * '403': + * $ref: '#/components/responses/Forbidden' + */ + app.route('/locais-coleta') + .post([ + tokensMiddleware([ + TIPOS_USUARIOS.CURADOR, + TIPOS_USUARIOS.OPERADOR, + ]), + validacoesMiddleware(localColetaCadastroEsquema), + controller.cadastrarLocalColeta, + ]) + /** + * @swagger + * /locais-coleta: + * get: + * summary: Lista os locais de coleta + * tags: [Locais] + * parameters: + * - in: query + * name: cidadeId + * schema: + * type: integer + * description: Filtrar por ID da cidade + * - in: query + * name: pagina + * schema: + * type: integer + * description: Número da página + * - in: query + * name: limite + * schema: + * type: integer + * description: Quantidade de resultados por página + * responses: + * 200: + * description: Lista de locais de coleta + * content: + * application/json: + * schema: + * type: object + * properties: + * metadados: + * type: object + * locaisColeta: + * type: array + * items: + * type: object + * '401': + * $ref: '#/components/responses/Unauthorized' + * '403': + * $ref: '#/components/responses/Forbidden' + */ + .get([ + tokensMiddleware([ + TIPOS_USUARIOS.CURADOR, + TIPOS_USUARIOS.OPERADOR, + TIPOS_USUARIOS.IDENTIFICADOR, + ]), + listagensMiddleware, + validacoesMiddleware(localColetaListagemEsquema), + controller.buscarLocaisColeta, + ]); }; diff --git a/src/validators/localColeta-cadastro.js b/src/validators/localColeta-cadastro.js new file mode 100644 index 00000000..6f1c8530 --- /dev/null +++ b/src/validators/localColeta-cadastro.js @@ -0,0 +1,25 @@ +export default { + descricao: { + in: ['body'], + isString: true, + notEmpty: true, + errorMessage: 'Descrição é obrigatória.', + }, + complemento: { + in: ['body'], + isString: true, + optional: true, + }, + cidade_id: { + in: ['body'], + isInt: true, + notEmpty: true, + errorMessage: 'ID da cidade é obrigatório e deve ser um número inteiro.', + }, + fase_sucessional_id: { + in: ['body'], + isInt: true, + optional: true, + errorMessage: 'ID da fase sucessional deve ser um número inteiro.', + }, +}; diff --git a/src/validators/localColeta-listagem.js b/src/validators/localColeta-listagem.js new file mode 100644 index 00000000..8149d4a0 --- /dev/null +++ b/src/validators/localColeta-listagem.js @@ -0,0 +1,8 @@ +export default { + cidadeId: { + in: ['query'], + isInt: true, + optional: true, + errorMessage: 'ID da cidade deve ser um número inteiro.', + }, +}; From acb50af8b5dd1e3cd5ec12f0eb23f73a072685ff Mon Sep 17 00:00:00 2001 From: Matheus Coitinho Date: Thu, 14 Aug 2025 20:24:08 -0300 Subject: [PATCH 2/9] =?UTF-8?q?adiciona=20lodash=20como=20depend=C3=AAncia?= =?UTF-8?q?=20no=20projeto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index e0dd9559..3308bbfa 100644 --- a/package.json +++ b/package.json @@ -66,6 +66,7 @@ "handlebars": "^4.7.8", "jsonwebtoken": "9.0.2", "knex": "2.5.1", + "lodash": "^4.17.21", "moment": "^2.24.0", "moment-timezone": "^0.5.21", "morgan": "1.10.0", From b947eeaeb253ce74158fbd3430ec229bf30c9022 Mon Sep 17 00:00:00 2001 From: Matheus Coitinho Date: Sun, 17 Aug 2025 23:09:29 -0300 Subject: [PATCH 3/9] =?UTF-8?q?adiciona=20campo=20descricao=5Flocal=5Fcole?= =?UTF-8?q?ta=20e=20atualiza=20valida=C3=A7=C3=B5es=20no=20cadastro=20de?= =?UTF-8?q?=20tombos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/controllers/tombos-controller.js | 42 +++++++++++--------------- src/models/Tombo.js | 4 +++ src/resources/errors/500-taxonomias.js | 1 + src/validators/tombo-cadastro.js | 7 ++--- 4 files changed, 25 insertions(+), 29 deletions(-) diff --git a/src/controllers/tombos-controller.js b/src/controllers/tombos-controller.js index b1e50352..7b7ef209 100644 --- a/src/controllers/tombos-controller.js +++ b/src/controllers/tombos-controller.js @@ -104,22 +104,21 @@ export const cadastro = (request, response, next) => { return undefined; }) .then(() => { - let json = {}; - // /////////CRIA LOCAL DE COLETA//////////// - if (paisagem) { - json = pick(paisagem, ['descricao', 'solo_id', 'relevo_id', 'vegetacao_id', 'fase_sucessional_id']); - } - if (localidade.complemento) { - json.complemento = localidade.complemento; + if(!localidade || !localidade.complemento){ + throw new BadRequestExeption(400); } - json.cidade_id = localidade.cidade_id; - return LocalColeta.create(json, { transaction }); + return LocalColeta.findOne({ + where: { + id: localidade.complemento, + }, + transaction, + }); }) .then(localColeta => { if (!localColeta) { - throw new BadRequestExeption(400); + throw new BadRequestExeption(533); } - principal.local_coleta_id = localColeta.id; + return undefined; }) // //////////////CRIA COLECOES ANEXAS/////////// .then(() => { @@ -271,11 +270,15 @@ export const cadastro = (request, response, next) => { data_coleta_mes: principal.data_coleta.mes, data_coleta_ano: principal.data_coleta.ano, numero_coleta: principal.numero_coleta, - local_coleta_id: principal.local_coleta_id, + local_coleta_id: localidade.complemento, cor: principal.cor, coletor_id: coletor, }; + if(paisagem.descricao) { + jsonTombo.descricao_local_coleta = paisagem.descricao; + } + if (observacoes) { jsonTombo.observacao = observacoes; } @@ -1022,8 +1025,6 @@ export const obterTombo = async (request, response, next) => { let resposta = {}; let dadosTombo = {}; - // eslint-disable-next-line - // console.error(id); Promise.resolve() .then(() => Tombo.findOne({ @@ -1052,6 +1053,7 @@ export const obterTombo = async (request, response, next) => { 'data_identificacao_dia', 'data_identificacao_mes', 'data_identificacao_ano', + 'descricao_local_coleta', ], include: [ { @@ -1187,22 +1189,12 @@ export const obterTombo = async (request, response, next) => { vegetacaoInicial: tombo.vegetaco !== null ? tombo.vegetaco?.nome : '', faseInicial: tombo.locais_coletum !== null && tombo.locais_coletum?.fase_sucessional !== null ? tombo.locais_coletum?.fase_sucessional?.numero : '', - // coletoresInicial: tombo.coletores.map((coletor) => ({ - // key: `${coletor.id}`, - // label: coletor.nome, - // })), coletor: tombo.coletore ? { id: tombo.coletore?.id, nome: tombo.coletore?.nome, } : null, - // coletorComplementar: tombo.coletorComplementar - // ? { - // hcf: tombo.coletorComplementar.hcf, - // complementares: tombo.coletorComplementar.complementares, - // } - // : '', colecaoInicial: tombo.colecoes_anexa !== null ? tombo.colecoes_anexa?.tipo : '', complementoInicial: tombo.localizacao !== null && tombo.localizacao !== undefined ? tombo.localizacao?.complemento : '', hcf: tombo.hcf, @@ -1211,6 +1203,7 @@ export const obterTombo = async (request, response, next) => { observacao: tombo.observacao !== null ? tombo.observacao : '', tipo: tombo.tipo !== null ? tombo.tipo?.nome : '', numero_coleta: tombo.numero_coleta, + descricao_local_coleta: tombo.descricao_local_coleta !== null ? tombo.descricao_local_coleta : '', herbario: tombo.herbario !== null ? `${tombo.herbario?.sigla} - ${tombo.herbario?.nome}` : '', localizacao: { latitude: tombo.latitude !== null ? tombo.latitude : '', @@ -1231,6 +1224,7 @@ export const obterTombo = async (request, response, next) => { complemento: tombo.locais_coletum?.complemento !== null ? tombo.locais_coletum?.complemento : '', }, local_coleta: { + id: tombo.locais_coletum !== null ? tombo.locais_coletum?.id : '', descricao: tombo.locais_coletum !== null && tombo.locais_coletum?.descricao !== null ? tombo.locais_coletum.descricao : '', solo: tombo.solo !== null ? tombo.solo?.nome : '', relevo: tombo.relevo !== null ? tombo.relevo?.nome : '', diff --git a/src/models/Tombo.js b/src/models/Tombo.js index 44ac13ad..2cf1bb12 100644 --- a/src/models/Tombo.js +++ b/src/models/Tombo.js @@ -261,6 +261,10 @@ export default (Sequelize, DataTypes) => { type: DataTypes.INTEGER, allowNull: true, }, + descricao_local_coleta: { + type: DataTypes.TEXT, + allowNull: true, + }, }; const options = { diff --git a/src/resources/errors/500-taxonomias.js b/src/resources/errors/500-taxonomias.js index 21df4ab2..9c5705bb 100644 --- a/src/resources/errors/500-taxonomias.js +++ b/src/resources/errors/500-taxonomias.js @@ -31,4 +31,5 @@ export default { 530: 'Vegetação não encontrada.', 531: 'Fase sucessional não encontrada.', 532: 'Autor não encontrado.', + 533: 'Local de coleta não encontrado.', }; diff --git a/src/validators/tombo-cadastro.js b/src/validators/tombo-cadastro.js index 487362b4..7b5e619e 100644 --- a/src/validators/tombo-cadastro.js +++ b/src/validators/tombo-cadastro.js @@ -108,11 +108,8 @@ export default { }, 'json.localidade.complemento': { in: 'body', - isString: true, - optional: true, - isLength: { - options: [{ min: 3 }], - }, + isInt: true, + isEmpty: false, }, 'json.paisagem.solo_id': { in: 'body', From 55f129243ca806553acf359f76f94d4b05d64f81 Mon Sep 17 00:00:00 2001 From: Matheus Coitinho Date: Wed, 20 Aug 2025 19:29:09 -0300 Subject: [PATCH 4/9] =?UTF-8?q?adiciona=20fun=C3=A7=C3=A3o=20para=20aprova?= =?UTF-8?q?r=20pend=C3=AAncias=20e=20atualiza=20o=20controlador=20de=20tom?= =?UTF-8?q?bos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/controllers/pendencias-controller.js | 476 ++++++++++++++++++++++- src/controllers/tombos-controller.js | 247 ++++-------- 2 files changed, 556 insertions(+), 167 deletions(-) diff --git a/src/controllers/pendencias-controller.js b/src/controllers/pendencias-controller.js index 6c8dc919..b658b955 100644 --- a/src/controllers/pendencias-controller.js +++ b/src/controllers/pendencias-controller.js @@ -29,6 +29,7 @@ const { ColecaoAnexa, TomboIdentificador, Identificador, + ColetorComplementar, } = models; export const listagem = (request, response, next) => { @@ -1455,6 +1456,479 @@ export const aprovarComJsonId = (alteracao, hcf, transaction) => { ); }; +export const aprovarPendencia = async (alteracao, hcf, transaction) => { + if (!alteracao || !hcf) { + throw new BadRequestExeption(404); + } + + const tomboAtual = await Tombo.findOne({ + where: { hcf, ativo: true }, + transaction, + raw: true, + nest: true, + }); + + if (!tomboAtual) { + throw new BadRequestExeption(404); + } + + const updateTombo = {}; + const nomesCientificosPartes = []; + + if (alteracao.nomes_populares !== undefined) { + updateTombo.nomes_populares = alteracao.nomes_populares; + } + + if (alteracao.numero_coleta !== undefined) { + updateTombo.numero_coleta = alteracao.numero_coleta; + } + + if (alteracao.observacao !== undefined) { + updateTombo.observacao = alteracao.observacao; + } + + if (alteracao.cor !== undefined) { + updateTombo.cor = alteracao.cor.toUpperCase(); + } + + if (alteracao.data_coleta_dia !== undefined) { + updateTombo.data_coleta_dia = alteracao.data_coleta_dia; + } + + if (alteracao.data_coleta_mes !== undefined) { + updateTombo.data_coleta_mes = alteracao.data_coleta_mes; + } + + if (alteracao.data_coleta_ano !== undefined) { + updateTombo.data_coleta_ano = alteracao.data_coleta_ano; + } + + if (alteracao.data_identificacao_dia !== undefined) { + updateTombo.data_identificacao_dia = alteracao.data_identificacao_dia; + } + + if (alteracao.data_identificacao_mes !== undefined) { + updateTombo.data_identificacao_mes = alteracao.data_identificacao_mes; + } + + if (alteracao.data_identificacao_ano !== undefined) { + updateTombo.data_identificacao_ano = alteracao.data_identificacao_ano; + } + + if (alteracao.latitude !== undefined) { + updateTombo.latitude = typeof alteracao.latitude === 'string' + ? converteParaDecimal(alteracao.latitude) + : alteracao.latitude; + } + + if (alteracao.longitude !== undefined) { + updateTombo.longitude = typeof alteracao.longitude === 'string' + ? converteParaDecimal(alteracao.longitude) + : alteracao.longitude; + } + + if (alteracao.altitude !== undefined) { + updateTombo.altitude = alteracao.altitude; + } + + if (alteracao.entidade_id !== undefined) { + const herbario = await Herbario.findOne({ + where: { id: alteracao.entidade_id }, + transaction, + raw: true, + nest: true, + }); + + if (!herbario) { + throw new BadRequestExeption(404); + } + updateTombo.entidade_id = alteracao.entidade_id; + } + + if (alteracao.tipo_id !== undefined) { + const tipo = await Tipo.findOne({ + where: { id: alteracao.tipo_id }, + transaction, + raw: true, + nest: true, + }); + + if (!tipo) { + throw new BadRequestExeption(404); + } + updateTombo.tipo_id = alteracao.tipo_id; + } + + if (alteracao.familia_id !== undefined) { + if (alteracao.familia_id) { + const familia = await Familia.findOne({ + where: { id: alteracao.familia_id }, + transaction, + raw: true, + nest: true, + }); + + if (!familia) { + throw new BadRequestExeption(404); + } + + updateTombo.familia_id = alteracao.familia_id; + nomesCientificosPartes.push(familia.nome); + } else { + updateTombo.familia_id = null; + } + + updateTombo.sub_familia_id = null; + updateTombo.genero_id = null; + updateTombo.especie_id = null; + updateTombo.sub_especie_id = null; + updateTombo.variedade_id = null; + } + + if (alteracao.sub_familia_id !== undefined) { + if (alteracao.sub_familia_id) { + const subfamilia = await Subfamilia.findOne({ + where: { + id: alteracao.sub_familia_id, + familia_id: updateTombo.familia_id || tomboAtual.familia_id, + }, + transaction, + raw: true, + nest: true, + }); + + if (!subfamilia) { + throw new BadRequestExeption(404); + } + + updateTombo.sub_familia_id = alteracao.sub_familia_id; + nomesCientificosPartes.push(subfamilia.nome); + } else { + updateTombo.sub_familia_id = null; + } + + updateTombo.genero_id = null; + updateTombo.especie_id = null; + updateTombo.sub_especie_id = null; + updateTombo.variedade_id = null; + } + + if (alteracao.genero_id !== undefined) { + if (alteracao.genero_id) { + const genero = await Genero.findOne({ + where: { + id: alteracao.genero_id, + familia_id: updateTombo.familia_id || tomboAtual.familia_id, + }, + transaction, + raw: true, + nest: true, + }); + + if (!genero) { + throw new BadRequestExeption(404); + } + + updateTombo.genero_id = alteracao.genero_id; + nomesCientificosPartes.push(genero.nome); + } else { + updateTombo.genero_id = null; + } + + updateTombo.especie_id = null; + updateTombo.sub_especie_id = null; + updateTombo.variedade_id = null; + } + + if (alteracao.especie_id !== undefined) { + if (alteracao.especie_id) { + const especie = await Especie.findOne({ + where: { + id: alteracao.especie_id, + genero_id: updateTombo.genero_id || tomboAtual.genero_id, + }, + transaction, + raw: true, + nest: true, + }); + + if (!especie) { + throw new BadRequestExeption(404); + } + + updateTombo.especie_id = alteracao.especie_id; + nomesCientificosPartes.push(especie.nome); + } else { + updateTombo.especie_id = null; + } + + updateTombo.sub_especie_id = null; + updateTombo.variedade_id = null; + } + + if (alteracao.sub_especie_id !== undefined) { + if (alteracao.sub_especie_id) { + const subespecie = await Subespecie.findOne({ + where: { + id: alteracao.sub_especie_id, + especie_id: updateTombo.especie_id || tomboAtual.especie_id, + }, + transaction, + raw: true, + nest: true, + }); + + if (!subespecie) { + throw new BadRequestExeption(404); + } + + updateTombo.sub_especie_id = alteracao.sub_especie_id; + nomesCientificosPartes.push(subespecie.nome); + } else { + updateTombo.sub_especie_id = null; + } + + updateTombo.variedade_id = null; + } + + if (alteracao.variedade_id !== undefined) { + if (alteracao.variedade_id) { + const variedade = await Variedade.findOne({ + where: { + id: alteracao.variedade_id, + especie_id: updateTombo.especie_id || tomboAtual.especie_id, + }, + transaction, + raw: true, + nest: true, + }); + + if (!variedade) { + throw new BadRequestExeption(404); + } + + updateTombo.variedade_id = alteracao.variedade_id; + nomesCientificosPartes.push(variedade.nome); + } else { + updateTombo.variedade_id = null; + } + } + + if (nomesCientificosPartes.length > 0) { + updateTombo.nome_cientifico = nomesCientificosPartes.join(' '); + } + + if (alteracao.local_coleta_id !== undefined) { + const localColeta = await LocalColeta.findOne({ + where: { id: alteracao.local_coleta_id }, + transaction, + raw: true, + nest: true, + }); + + if (!localColeta) { + throw new BadRequestExeption(404); + } + + updateTombo.local_coleta_id = alteracao.local_coleta_id; + } + + if (alteracao.descricao_local_coleta !== undefined) { + updateTombo.descricao_local_coleta = alteracao.descricao_local_coleta; + } + + if (alteracao.solo_id !== undefined) { + if (alteracao.solo_id) { + const soloId = typeof alteracao.solo_id === 'object' ? alteracao.solo_id.key : alteracao.solo_id; + const solo = await Solo.findOne({ + where: { id: soloId }, + transaction, + raw: true, + nest: true, + }); + + if (!solo) { + throw new BadRequestExeption(404); + } + + updateTombo.solo_id = soloId; + } else { + updateTombo.solo_id = null; + } + } + + if (alteracao.relevo_id !== undefined) { + if (alteracao.relevo_id) { + const relevoId = typeof alteracao.relevo_id === 'object' ? alteracao.relevo_id.key : alteracao.relevo_id; + const relevo = await Relevo.findOne({ + where: { id: relevoId }, + transaction, + raw: true, + nest: true, + }); + + if (!relevo) { + throw new BadRequestExeption(404); + } + + updateTombo.relevo_id = relevoId; + } else { + updateTombo.relevo_id = null; + } + } + + if (alteracao.vegetacao_id !== undefined) { + if (alteracao.vegetacao_id) { + const vegetacaoId = typeof alteracao.vegetacao_id === 'object' ? alteracao.vegetacao_id.key : alteracao.vegetacao_id; + const vegetacao = await Vegetacao.findOne({ + where: { id: vegetacaoId }, + transaction, + raw: true, + nest: true, + }); + + if (!vegetacao) { + throw new BadRequestExeption(404); + } + + updateTombo.vegetacao_id = vegetacaoId; + } else { + updateTombo.vegetacao_id = null; + } + } + + if (alteracao.coletor_id !== undefined) { + if (alteracao.coletor_id) { + const coletor = await Coletor.findOne({ + where: { id: alteracao.coletor_id }, + transaction, + raw: true, + nest: true, + }); + + if (!coletor) { + throw new BadRequestExeption(404); + } + + const numeroColeta = updateTombo.numero_coleta; + if (numeroColeta && coletor.numero && coletor.numero < numeroColeta) { + await Coletor.update({ + numero: numeroColeta, + }, { + where: { id: alteracao.coletor_id }, + transaction, + }); + } + + updateTombo.coletor_id = alteracao.coletor_id; + } else { + updateTombo.coletor_id = null; + } + } + + if (Object.keys(updateTombo).length > 0) { + await Tombo.update(updateTombo, { + where: { hcf }, + transaction, + }); + } + + if (alteracao.identificadores && Array.isArray(alteracao.identificadores)) { + await TomboIdentificador.destroy({ + where: { tombo_hcf: hcf }, + transaction, + }); + + const identificadoresPromises = alteracao.identificadores.map(async (identificadorId, index) => { + const identificador = await Identificador.findOne({ + where: { id: identificadorId }, + transaction, + raw: true, + nest: true, + }); + + if (!identificador) { + throw new BadRequestExeption(404); + } + + return TomboIdentificador.create({ + tombo_hcf: hcf, + identificador_id: identificadorId, + ordem: index + 1, + }, { transaction }); + }); + + await Promise.all(identificadoresPromises); + } + + if (alteracao.complementares !== undefined) { + await ColetorComplementar.destroy({ + where: { hcf }, + transaction, + }); + + if (alteracao.complementares) { + await ColetorComplementar.create({ + hcf, + complementares: alteracao.complementares, + }, { transaction }); + } + } + + if (alteracao.colecoes_anexas_tipo !== undefined || alteracao.colecoes_anexas_observacoes !== undefined) { + const tomboAtualizado = await Tombo.findOne({ + where: { hcf }, + transaction, + raw: true, + nest: true, + }); + + if (tomboAtualizado.colecao_anexa_id) { + const updateColecao = {}; + + if (alteracao.colecoes_anexas_tipo !== undefined) { + updateColecao.tipo = alteracao.colecoes_anexas_tipo; + } + + if (alteracao.colecoes_anexas_observacoes !== undefined) { + updateColecao.observacoes = alteracao.colecoes_anexas_observacoes; + } + + if (Object.keys(updateColecao).length > 0) { + await ColecaoAnexa.update(updateColecao, { + where: { id: tomboAtualizado.colecao_anexa_id }, + transaction, + }); + } + } else if (alteracao.colecoes_anexas_tipo || alteracao.colecoes_anexas_observacoes) { + const novaColecao = await ColecaoAnexa.create({ + tipo: alteracao.colecoes_anexas_tipo, + observacoes: alteracao.colecoes_anexas_observacoes, + }, { transaction }); + + await Tombo.update({ + colecao_anexa_id: novaColecao.id, + }, { + where: { hcf }, + transaction, + }); + } + } + + const tomboFinal = await Tombo.findOne({ + where: { hcf, ativo: true }, + transaction, + raw: true, + nest: true, + }); + + return { + success: true, + message: 'Pendência aprovada com sucesso', + tombo: tomboFinal, + }; +}; + export const aprovarComJsonNome = (alteracao, hcf, transaction) => { const parametros = {}; @@ -2002,7 +2476,7 @@ export function aceitarPendencia(request, response, next) { .then(alt => { if (status === 'APROVADO') { const objetoAlterado = JSON.parse(alt.tombo_json); - retorno = aprovarComJsonId(objetoAlterado, alt.tombo_hcf, transaction); + retorno = aprovarPendencia(objetoAlterado, alt.tombo_hcf, transaction); } return retorno; }); diff --git a/src/controllers/tombos-controller.js b/src/controllers/tombos-controller.js index 7b7ef209..e2ee8995 100644 --- a/src/controllers/tombos-controller.js +++ b/src/controllers/tombos-controller.js @@ -12,6 +12,7 @@ import { converteInteiroParaRomano } from '../helpers/tombo'; import models from '../models'; import codigos from '../resources/codigos-http'; import verifyRecaptcha from '../utils/verify-recaptcha'; +import { aprovarPendencia } from './pendencias-controller'; const { Solo, Relevo, Cidade, Estado, Vegetacao, FaseSucessional, Pais, Tipo, LocalColeta, Familia, sequelize, @@ -104,7 +105,7 @@ export const cadastro = (request, response, next) => { return undefined; }) .then(() => { - if(!localidade || !localidade.complemento){ + if (!localidade || !localidade.complemento) { throw new BadRequestExeption(400); } return LocalColeta.findOne({ @@ -275,7 +276,7 @@ export const cadastro = (request, response, next) => { coletor_id: coletor, }; - if(paisagem.descricao) { + if (paisagem.descricao) { jsonTombo.descricao_local_coleta = paisagem.descricao; } @@ -447,208 +448,119 @@ function alteracaoIdentificador(request, transaction) { }); } -function alteracaoCuradorouOperador(request, response, next) { +function alteracaoCuradorouOperador(request, response, transaction) { const { body } = request; + const update = {}; const nomePopular = body?.principal?.nome_popular; + if (nomePopular) update.nomes_populares = nomePopular; const entidadeId = body?.principal?.entidade_id; - const numeroColeta = body.principal.numero_coleta; - const dataColeta = body.principal.data_coleta; + if (entidadeId) update.entidade_id = entidadeId; + const numeroColeta = body?.principal?.numero_coleta; + if (numeroColeta) update.numero_coleta = numeroColeta; + const dataColeta = body?.principal?.data_coleta; + if (dataColeta?.dia) update.data_coleta_dia = dataColeta.dia; + if (dataColeta?.mes) update.data_coleta_mes = dataColeta.mes; + if (dataColeta?.ano) update.data_coleta_ano = dataColeta.ano; const tipoId = body?.principal?.tipo_id; - const { cor } = body.principal || null; + if (tipoId) update.tipo_id = tipoId; + const { cor } = body.principal || {}; + if (cor) update.cor = cor; const familiaId = body?.taxonomia?.familia_id; + if (familiaId) update.familia_id = familiaId; const subfamiliaId = body?.taxonomia?.sub_familia_id; + if (subfamiliaId) update.sub_familia_id = subfamiliaId; const generoId = body?.taxonomia?.genero_id; + if (generoId) update.genero_id = generoId; const especieId = body?.taxonomia?.especie_id; + if (especieId) update.especie_id = especieId; const subespecieId = body?.taxonomia?.sub_especie_id; + if (subespecieId) update.sub_especie_id = subespecieId; const variedadeId = body?.taxonomia?.variedade_id; + if (variedadeId) update.variedade_id = variedadeId; - const { latitude } = body.localidade || null; - const { longitude } = body.localidade || null; - const { altitude } = body.localidade || null; - const cidadeId = body.localidade.cidade_id; - const { complemento } = body.localidade || null; + const latitude = body?.localidade?.latitude; + if (latitude) update.latitude = converteParaDecimal(latitude); + const longitude = body?.localidade?.longitude; + if (longitude) update.longitude = converteParaDecimal(longitude); + const altitude = body?.localidade?.altitude; + if (altitude) update.altitude = altitude; + const complemento = body?.localidade?.complemento; + if (complemento) update.local_coleta_id = complemento; const soloId = body?.paisagem?.solo_id; - const { descricao } = body.paisagem || null; + if (soloId) update.solo_id = soloId; + const descricao = body?.paisagem?.descricao; + if (descricao) update.descricao_local_coleta = descricao; const relevoId = body?.paisagem?.relevo_id; + if (relevoId) update.relevo_id = relevoId; const vegetacaoId = body?.paisagem?.vegetacao_id; - const faseSucessionalId = body?.paisagem.fase_sucessional_id; + if (vegetacaoId) update.vegetacao_id = vegetacaoId; + const faseSucessionalId = body?.paisagem?.fase_sucessional_id; + if (faseSucessionalId) update.fase_sucessional_id = faseSucessionalId; - const { identificadores } = body.identificacao || null; + const identificadores = body?.identificacao?.identificadores; + if (identificadores?.length) update.identificadores = identificadores; const dataIdentificacao = body?.identificacao?.data_identificacao; - - const { coletores } = body || null; - const complementares = body?.coletor_complementar?.complementares || null; + if (dataIdentificacao?.dia) update.data_identificacao_dia = dataIdentificacao.dia; + if (dataIdentificacao?.mes) update.data_identificacao_mes = dataIdentificacao.mes; + if (dataIdentificacao?.ano) update.data_identificacao_ano = dataIdentificacao.ano; + + const coletores = body?.coletores; + if (coletores) update.coletor_id = coletores; + const complementares = body?.coletor_complementar?.complementares; + if (complementares) update.complementares = complementares; const colecoesAnexasTipo = body?.colecoes_anexas?.tipo; + if (colecoesAnexasTipo) update.colecoes_anexas_tipo = colecoesAnexasTipo; const colecoesAnexasObservacoes = body?.colecoes_anexas?.observacoes; - - const { observacoes } = body || null; + if (colecoesAnexasObservacoes) update.colecoes_anexas_observacoes = colecoesAnexasObservacoes; + const { observacoes } = body || {}; + if (observacoes) update.observacao = observacoes; const { tombo_id: tomboId } = request.params; - const update = {}; - - if (nomePopular) { - update.nomes_populares = nomePopular; - } - - if (entidadeId) { - update.entidade_id = entidadeId; - } - - if (numeroColeta) { - update.numero_coleta = numeroColeta; - } - - if (dataColeta) { - update.data_coleta = dataColeta; - } - - if (tipoId) { - update.tipo_id = tipoId; - } - - if (cor) { - update.cor = cor; - } - - if (familiaId) { - update.familia_id = familiaId; - } - if (subfamiliaId) { - update.sub_familia_id = subfamiliaId; - } - if (generoId) { - update.genero_id = generoId; - } - if (especieId) { - update.especie_id = especieId; - } - if (subespecieId) { - update.sub_especie_id = subespecieId; - } - if (variedadeId) { - update.variedade_id = variedadeId; - } - - if (latitude) { - update.latitude = converteParaDecimal(latitude); - } - - if (longitude) { - update.longitude = converteParaDecimal(longitude); - } - - if (altitude) { - update.altitude = altitude; - } - - if (cidadeId) { - update.cidade_id = cidadeId; - } - if (complemento) { - update.complemento = complemento; - } - - if (soloId) { - update.solo_id = soloId; - } - - if (descricao) { - update.descricao = descricao; - } - - if (relevoId) { - update.relevo_id = relevoId; - } - - if (vegetacaoId) { - update.vegetacao_id = vegetacaoId; - } - - if (faseSucessionalId) { - update.fase_sucessional_id = faseSucessionalId; - } - - if (identificadores && identificadores.length > 0) { - update.identificadores = identificadores; - } - - if (dataIdentificacao) { - update.data_identificacao = dataIdentificacao; - } - - if (coletores) { - update.coletores = coletores; - } - - if (complementares) { - update.complementares = complementares; - } - - if (colecoesAnexasTipo) { - update.colecoes_anexas_tipo = colecoesAnexasTipo; - } - - if (colecoesAnexasObservacoes) { - update.colecoes_anexas_observacoes = colecoesAnexasObservacoes; - } - - if (observacoes) { - update.observacao = observacoes; - } - - return Promise.resolve() - .then(() => { - - if (request.usuario.tipo_usuario_id === 2) { // OPERADOR - Alteracao.create({ - tombo_hcf: tomboId, - usuario_id: request.usuario.id, - status: 'ESPERANDO', // operador fica em espera e curador APROVADO {ESPERANDO - para nao esquecer} - tombo_json: JSON.stringify(update), - ativo: true, - identificacao: 1, - }).then(tombos => { - response.status(codigos.BUSCAR_UM_ITEM) - .json(tombos); - }) - .catch(next); - } else if (request.usuario.tipo_usuario_id === 1) { // CURADOR - Alteracao.create({ - tombo_hcf: tomboId, - usuario_id: request.usuario.id, - status: 'APROVADO', // operador fica em espera e curador APROVADO {ESPERANDO - para nao esquecer} - tombo_json: JSON.stringify(update), - ativo: true, - identificacao: 1, - }).then(tombos => { - response.status(codigos.BUSCAR_UM_ITEM) - .json(tombos); - }) - .catch(next); + return Alteracao.create({ + tombo_hcf: tomboId, + usuario_id: request.usuario.id, + status: 'ESPERANDO', + tombo_json: JSON.stringify(update), + ativo: true, + identificacao: 1, + }, { transaction }) + .then(alteracaoCriada => { + if (request.usuario.tipo_usuario_id === 1) { + return aprovarPendencia(update, tomboId, transaction) + .then(() => Alteracao.update({ status: 'APROVADO' }, { + where: { id: alteracaoCriada.id }, + transaction, + })) + .then(() => alteracaoCriada.toJSON()); + } if (request.usuario.tipo_usuario_id !== 2) { + throw new BadRequestExeption(421); } + return alteracaoCriada.toJSON(); }); } export function alteracao(request, response, next) { - const callback = transaction => { + return sequelize.transaction(transaction => { if (request.usuario.tipo_usuario_id === 3) { return alteracaoIdentificador(request, transaction); } if (request.usuario.tipo_usuario_id === 1 || request.usuario.tipo_usuario_id === 2) { - return alteracaoCuradorouOperador(request, response, next); + return alteracaoCuradorouOperador(request, response, transaction); } - return Promise.reject(new BadRequestExeption(421)); - }; - sequelize.transaction(callback) + throw new BadRequestExeption(421); + + }) .then(() => { if (request.usuario.tipo_usuario_id === 3) { response.status(codigos.EDITAR_SEM_RETORNO).send(); } }) - .catch(next); + .catch(err => { + next(err); + }); } export const desativar = (request, response, next) => { @@ -1184,8 +1096,11 @@ export const obterTombo = async (request, response, next) => { especieInicial: tombo.especy !== null ? tombo.especy?.id : '', subespecieInicial: tombo.sub_especy !== null ? tombo.sub_especy?.id : '', variedadeInicial: tombo.variedade !== null ? tombo.variedade?.id : '', + idSoloInicial: tombo.solo !== null ? tombo.solo?.id : '', soloInicial: tombo.solo !== null ? tombo.solo?.nome : '', + idRelevoInicial: tombo.relevo !== null ? tombo.relevo?.id : '', relevoInicial: tombo.relevo !== null ? tombo.relevo?.nome : '', + idVegetacaoInicial: tombo.vegetaco !== null ? tombo.vegetaco?.id : '', vegetacaoInicial: tombo.vegetaco !== null ? tombo.vegetaco?.nome : '', faseInicial: tombo.locais_coletum !== null && tombo.locais_coletum?.fase_sucessional !== null ? tombo.locais_coletum?.fase_sucessional?.numero : '', From ec5b496cee0c8c7a086c790676e0440b89c9dcb8 Mon Sep 17 00:00:00 2001 From: Matheus Coitinho Date: Thu, 21 Aug 2025 17:13:55 -0300 Subject: [PATCH 5/9] =?UTF-8?q?altera=20nome=20do=20campo=20descricao=5Flo?= =?UTF-8?q?cal=5Fcoleta=20para=20descricao=20e=20ajusta=20refer=C3=AAncias?= =?UTF-8?q?=20no=20c=C3=B3digo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 1 - src/controllers/locais-coleta-controller.js | 3 +- src/controllers/pendencias-controller.js | 10 ++--- src/controllers/tombos-controller.js | 45 +++++++++++++++------ src/models/Tombo.js | 2 +- 5 files changed, 39 insertions(+), 22 deletions(-) diff --git a/package.json b/package.json index 3308bbfa..e0dd9559 100644 --- a/package.json +++ b/package.json @@ -66,7 +66,6 @@ "handlebars": "^4.7.8", "jsonwebtoken": "9.0.2", "knex": "2.5.1", - "lodash": "^4.17.21", "moment": "^2.24.0", "moment-timezone": "^0.5.21", "morgan": "1.10.0", diff --git a/src/controllers/locais-coleta-controller.js b/src/controllers/locais-coleta-controller.js index c65fe274..5d888fc5 100644 --- a/src/controllers/locais-coleta-controller.js +++ b/src/controllers/locais-coleta-controller.js @@ -1,5 +1,4 @@ -import { pick } from 'lodash'; - +import pick from '~/helpers/pick'; import BadRequestExeption from '../errors/bad-request-exception'; import models from '../models'; import codigos from '../resources/codigos-http'; diff --git a/src/controllers/pendencias-controller.js b/src/controllers/pendencias-controller.js index b658b955..5f3998da 100644 --- a/src/controllers/pendencias-controller.js +++ b/src/controllers/pendencias-controller.js @@ -1733,13 +1733,13 @@ export const aprovarPendencia = async (alteracao, hcf, transaction) => { updateTombo.local_coleta_id = alteracao.local_coleta_id; } - if (alteracao.descricao_local_coleta !== undefined) { - updateTombo.descricao_local_coleta = alteracao.descricao_local_coleta; + if (alteracao.descricao !== undefined) { + updateTombo.descricao = alteracao.descricao; } if (alteracao.solo_id !== undefined) { if (alteracao.solo_id) { - const soloId = typeof alteracao.solo_id === 'object' ? alteracao.solo_id.key : alteracao.solo_id; + const soloId = alteracao.solo_id; const solo = await Solo.findOne({ where: { id: soloId }, transaction, @@ -1759,7 +1759,7 @@ export const aprovarPendencia = async (alteracao, hcf, transaction) => { if (alteracao.relevo_id !== undefined) { if (alteracao.relevo_id) { - const relevoId = typeof alteracao.relevo_id === 'object' ? alteracao.relevo_id.key : alteracao.relevo_id; + const relevoId = alteracao.relevo_id; const relevo = await Relevo.findOne({ where: { id: relevoId }, transaction, @@ -1779,7 +1779,7 @@ export const aprovarPendencia = async (alteracao, hcf, transaction) => { if (alteracao.vegetacao_id !== undefined) { if (alteracao.vegetacao_id) { - const vegetacaoId = typeof alteracao.vegetacao_id === 'object' ? alteracao.vegetacao_id.key : alteracao.vegetacao_id; + const vegetacaoId = alteracao.vegetacao_id; const vegetacao = await Vegetacao.findOne({ where: { id: vegetacaoId }, transaction, diff --git a/src/controllers/tombos-controller.js b/src/controllers/tombos-controller.js index e2ee8995..ff772d2e 100644 --- a/src/controllers/tombos-controller.js +++ b/src/controllers/tombos-controller.js @@ -277,7 +277,7 @@ export const cadastro = (request, response, next) => { }; if (paisagem.descricao) { - jsonTombo.descricao_local_coleta = paisagem.descricao; + jsonTombo.descricao = paisagem.descricao; } if (observacoes) { @@ -489,14 +489,35 @@ function alteracaoCuradorouOperador(request, response, transaction) { const complemento = body?.localidade?.complemento; if (complemento) update.local_coleta_id = complemento; - const soloId = body?.paisagem?.solo_id; - if (soloId) update.solo_id = soloId; + const soloIdRaw = body?.paisagem?.solo_id; + if (soloIdRaw !== undefined) { + if (soloIdRaw) { + const soloId = typeof soloIdRaw === 'object' ? soloIdRaw.key : soloIdRaw; + update.solo_id = soloId; + } else { + update.solo_id = null; + } + } + const relevoIdRaw = body?.paisagem?.relevo_id; + if (relevoIdRaw !== undefined) { + if (relevoIdRaw) { + const relevoId = typeof relevoIdRaw === 'object' ? relevoIdRaw.key : relevoIdRaw; + update.relevo_id = relevoId; + } else { + update.relevo_id = null; + } + } + const vegetacaoIdRaw = body?.paisagem?.vegetacao_id; + if (vegetacaoIdRaw !== undefined) { + if (vegetacaoIdRaw) { + const vegetacaoId = typeof vegetacaoIdRaw === 'object' ? vegetacaoIdRaw.key : vegetacaoIdRaw; + update.vegetacao_id = vegetacaoId; + } else { + update.vegetacao_id = null; + } + } const descricao = body?.paisagem?.descricao; - if (descricao) update.descricao_local_coleta = descricao; - const relevoId = body?.paisagem?.relevo_id; - if (relevoId) update.relevo_id = relevoId; - const vegetacaoId = body?.paisagem?.vegetacao_id; - if (vegetacaoId) update.vegetacao_id = vegetacaoId; + if (descricao) update.descricao = descricao; const faseSucessionalId = body?.paisagem?.fase_sucessional_id; if (faseSucessionalId) update.fase_sucessional_id = faseSucessionalId; @@ -558,9 +579,7 @@ export function alteracao(request, response, next) { response.status(codigos.EDITAR_SEM_RETORNO).send(); } }) - .catch(err => { - next(err); - }); + .catch(next); } export const desativar = (request, response, next) => { @@ -965,7 +984,7 @@ export const obterTombo = async (request, response, next) => { 'data_identificacao_dia', 'data_identificacao_mes', 'data_identificacao_ano', - 'descricao_local_coleta', + 'descricao', ], include: [ { @@ -1118,7 +1137,7 @@ export const obterTombo = async (request, response, next) => { observacao: tombo.observacao !== null ? tombo.observacao : '', tipo: tombo.tipo !== null ? tombo.tipo?.nome : '', numero_coleta: tombo.numero_coleta, - descricao_local_coleta: tombo.descricao_local_coleta !== null ? tombo.descricao_local_coleta : '', + descricao: tombo.descricao !== null ? tombo.descricao : '', herbario: tombo.herbario !== null ? `${tombo.herbario?.sigla} - ${tombo.herbario?.nome}` : '', localizacao: { latitude: tombo.latitude !== null ? tombo.latitude : '', diff --git a/src/models/Tombo.js b/src/models/Tombo.js index 2cf1bb12..0759eadb 100644 --- a/src/models/Tombo.js +++ b/src/models/Tombo.js @@ -261,7 +261,7 @@ export default (Sequelize, DataTypes) => { type: DataTypes.INTEGER, allowNull: true, }, - descricao_local_coleta: { + descricao: { type: DataTypes.TEXT, allowNull: true, }, From 243c731452b5898752a0242c8b0a63abe650f16a Mon Sep 17 00:00:00 2001 From: Matheus Coitinho Date: Thu, 21 Aug 2025 19:02:04 -0300 Subject: [PATCH 6/9] =?UTF-8?q?adiciona=20espa=C3=A7o=20em=20branco=20para?= =?UTF-8?q?=20melhorar=20a=20legibilidade=20do=20c=C3=B3digo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/controllers/locais-coleta-controller.js | 1 + src/controllers/pendencias-controller.js | 545 -------------------- src/controllers/tombos-controller.js | 2 +- 3 files changed, 2 insertions(+), 546 deletions(-) diff --git a/src/controllers/locais-coleta-controller.js b/src/controllers/locais-coleta-controller.js index 0467ed91..738f443e 100644 --- a/src/controllers/locais-coleta-controller.js +++ b/src/controllers/locais-coleta-controller.js @@ -1,4 +1,5 @@ import pick from '~/helpers/pick'; + import BadRequestExeption from '../errors/bad-request-exception'; import models from '../models'; import codigos from '../resources/codigos-http'; diff --git a/src/controllers/pendencias-controller.js b/src/controllers/pendencias-controller.js index 5f3998da..5d8677b9 100644 --- a/src/controllers/pendencias-controller.js +++ b/src/controllers/pendencias-controller.js @@ -5,7 +5,6 @@ import codigos from '../resources/codigos-http'; const { Alteracao, - Autor, Usuario, Herbario, Solo, @@ -17,7 +16,6 @@ const { sequelize, Sequelize: { Op }, Tombo, - TomboColetor, Especie, Variedade, Coletor, @@ -1098,364 +1096,6 @@ export const visualizarAlteracaoOperador = (json, alteracao, transaction) => { }); }; -async function atualizarIdentificadoresDeTombo(tomboHcf, novosIdentificadores) { - return sequelize.transaction(async transaction => { - await TomboIdentificador.destroy({ - where: { - tombo_hcf: tomboHcf, - }, - transaction, - }); - - const novosIdentificadoresPromise = novosIdentificadores.map((identificadorId, index) => - TomboIdentificador.create( - { - tombo_hcf: tomboHcf, - identificador_id: identificadorId, - ordem: index + 1, - }, - { - transaction, - } - ) - ); - - await Promise.all(novosIdentificadoresPromise); - }); -} - -export const aprovarComJson = async (changes, hcf, response, next) => { - const alteracao = changes; - - if (alteracao.identificadores) { - // identificadoresObjeto.usuario_id = alteracao.identificadores; - await atualizarIdentificadoresDeTombo(hcf, alteracao.identificadores); - } - - return Promise.resolve() - .then(() => { - if (alteracao.familia_id) { - if (!alteracao.sub_familia_id) { - alteracao.sub_familia_id = null; - } - if (!alteracao.genero_id) { - alteracao.genero_id = null; - } - if (!alteracao.especie_id) { - alteracao.especie_id = null; - } - if (!alteracao.sub_especie_id) { - alteracao.sub_especie_id = null; - } - if (!alteracao.variedade_id) { - alteracao.variedade_id = null; - } - } - - if (alteracao.genero_id) { - if (!alteracao.especie_id) { - alteracao.especie_id = null; - } - if (!alteracao.sub_especie_id) { - alteracao.sub_especie_id = null; - } - if (!alteracao.variedade_id) { - alteracao.variedade_id = null; - } - } - - if (alteracao.especie_id) { - if (!alteracao.sub_especie_id) { - alteracao.sub_especie_id = null; - } - if (!alteracao.variedade_id) { - alteracao.variedade_id = null; - } - } - - if (alteracao.data_coleta) { - if (alteracao.data_coleta.dia) { - alteracao.data_coleta_dia = alteracao.data_coleta.dia; - } - if (alteracao.data_coleta.mes) { - alteracao.data_coleta_mes = alteracao.data_coleta.mes; - } - if (alteracao.data_coleta.ano) { - alteracao.data_coleta_ano = alteracao.data_coleta.ano; - } - } - - if (alteracao.cidade_id || alteracao.complemento || alteracao.solo_id || alteracao.descricao || alteracao.relevo_id - || alteracao.vegetacao_id || alteracao.fase_sucessional_id) { - const tomboColetaAlteracao = {}; - - if (alteracao.cidade_id) { - tomboColetaAlteracao.cidade_id = alteracao.cidade_id; - } - - if (alteracao.complemento) { - tomboColetaAlteracao.complemento = alteracao.complemento; - } - - if (alteracao.solo_id) { - tomboColetaAlteracao.solo_id = alteracao.solo_id; - } - - if (alteracao.descricao) { - tomboColetaAlteracao.descricao = alteracao.descricao; - } - - if (alteracao.relevo_id) { - tomboColetaAlteracao.relevo_id = alteracao.relevo_id; - } - - if (alteracao.vegetacao_id) { - tomboColetaAlteracao.vegetacao_id = alteracao.vegetacao_id; - } - - if (alteracao.fase_sucessional_id) { - tomboColetaAlteracao.fase_sucessional_id = alteracao.fase_sucessional_id; - } - - Tombo.findOne({ - where: { - hcf, - ativo: true, - }, - }).then(tombo => { - LocalColeta.update(tomboColetaAlteracao, { - where: { - id: tombo.dataValues.local_coleta_id, - }, - }); - }); - } - - if (alteracao.coletores) { - for (let i = 0; i < alteracao.coletores.length; i += 1) { - TomboColetor.findOrCreate({ - where: { - tombo_hcf: hcf, - coletor_id: alteracao.coletores[i], - }, - }).spread((userResult, created) => { - // userResult is the user instance - - if (created) { - console.warn(userResult); - } - }); - } - } - - if (alteracao.colecoes_anexas_tipo || alteracao.colecoes_anexas_observacoes) { - const colecoesObjeto = {}; - - if (alteracao.colecoes_anexas_tipo) { - colecoesObjeto.tipo = alteracao.colecoes_anexas_tipo; - } - - if (alteracao.colecoes_anexas_observacoes) { - colecoesObjeto.observacoes = alteracao.colecoes_anexas_observacoes; - } - Tombo.findOne({ - where: { - hcf, - }, - }).then(tombo => { - ColecaoAnexa.update(colecoesObjeto, { - where: { - id: tombo.dataValues.colecao_anexa_id, - }, - }); - }); - } - - if (alteracao.identificadores || alteracao.data_identificacao) { - const identificadoresObjeto = {}; - - if (alteracao.data_identificacao) { - if (alteracao.data_identificacao.dia) { - identificadoresObjeto.data_identificacao_dia = alteracao.data_identificacao.dia; - } - - if (alteracao.data_identificacao.mes) { - identificadoresObjeto.data_identificacao_mes = alteracao.data_identificacao.mes; - } - - if (alteracao.data_identificacao.ano) { - identificadoresObjeto.data_identificacao_ano = alteracao.data_identificacao.ano; - } - } - Alteracao.update(identificadoresObjeto, { - where: { - tombo_hcf: hcf, - }, - }); - } - Tombo.update(alteracao, { - where: { - hcf, - ativo: true, - }, - }).then(updateResponse => { - response.status(codigos.BUSCAR_UM_ITEM) - .json(updateResponse); - }) - .catch(next); - }); - - // ); -}; - -export const aprovarComJsonId = (alteracao, hcf, transaction) => { - const parametros = {}; - - return Tombo.findOne({ - where: { - hcf, - }, - transaction, - }) - .then(tombo => { - parametros.tombo = tombo; - }) - .then(() => { - if (alteracao.genero_nome) { - return Genero.findOrCreate({ - where: { - nome: alteracao.genero_nome, - }, - defaults: { - nome: alteracao.genero_nome, - familia_id: parametros.tombo.dataValues.familia_id, - ativo: true, - }, - attributes: ['id', 'nome'], - transaction, - }) - .then(([genero]) => { - parametros.genero = genero; - }); - } - return undefined; - }) - .then(() => { - if (alteracao.especie_nome) { - const iniciais = alteracao.autor.match(/([A-Z])/g).join('.'); - return Autor.findOrCreate({ - where: { - nome: alteracao.autor, - }, - defaults: { - nome: alteracao.autor, - iniciais, - ativo: true, - }, - attributes: ['id', 'nome', 'iniciais'], - transaction, - }) - .then(([autor]) => Especie.findOrCreate({ - where: { - nome: alteracao.especie_nome, - }, - defaults: { - nome: alteracao.especie_nome, - genero_id: parametros.tombo.dataValues.genero_id, - familia_id: parametros.tombo.dataValues.familia_id, - autor_id: autor.id, - ativo: true, - }, - attributes: ['id', 'nome'], - transaction, - }) - .then(([especie]) => { - parametros.especie = especie; - })); - } - return undefined; - }) - .then(() => { - if (alteracao.subfamilia_nome) { - return Subfamilia.findOne({ - where: { - nome: alteracao.subfamilia_nome, - }, - attributes: ['id', 'nome'], - transaction, - }) - .then(subfamilia => { - parametros.subfamilia = subfamilia; - }); - } - return undefined; - }) - .then(() => { - if (alteracao.subespecie_nome) { - return Subespecie.findOne({ - where: { - nome: alteracao.subespecie_nome, - }, - attributes: ['id', 'nome'], - transaction, - }) - .then(subEspecie => { - parametros.subespecie = subEspecie; - }); - } - return undefined; - }) - .then(() => { - if (alteracao.variedade_nome) { - return Variedade.findOne({ - where: { - nome: alteracao.variedade_nome, - }, - attributes: ['id', 'nome'], - transaction, - }) - .then(variedade => { - parametros.variedade = variedade; - }); - } - return undefined; - }) - .then(() => parametros.tombo.update({ - especie_id: parametros.especie ? parametros.especie.id : parametros.tombo.especie_id, - genero_id: parametros.genero ? parametros.genero.id : parametros.tombo.genero_id, - subfamilia_id: parametros.subfamilia ? parametros.subfamilia.id : parametros.tombo.subfamilia_id, - subespecie_id: parametros.subespecie ? parametros.subespecie.id : parametros.tombo.subespecie_id, - variedade_id: parametros.variedade ? parametros.variedade.id : parametros.tombo.variedade_id, - }, { - transaction, - })) - .then(() => - Promise.all([ - Genero.findOne({ - where: { - id: parametros.tombo.genero_id, - }, - attributes: ['nome'], - transaction, - }), - Especie.findOne({ - where: { - id: parametros.tombo.especie_id, - }, - attributes: ['nome'], - transaction, - }), - ]) - ) - .then(([genero, especie]) => - parametros.tombo.update({ - nome_cientifico: `${genero.nome} ${especie.nome}`, - }, { - transaction, - }) - ); -}; - export const aprovarPendencia = async (alteracao, hcf, transaction) => { if (!alteracao || !hcf) { throw new BadRequestExeption(404); @@ -1929,191 +1569,6 @@ export const aprovarPendencia = async (alteracao, hcf, transaction) => { }; }; -export const aprovarComJsonNome = (alteracao, hcf, transaction) => { - const parametros = {}; - - return Familia.findOne({ - where: { - nome: { [Op.like]: `%${alteracao.familia_nome}%` }, - }, - transaction, - }) - .then(familia => { - if (familia) { - return familia; - } - return Familia.create({ nome: alteracao.familia_nome }, transaction); - }) - .then(familia => { - if (familia) { - parametros.familia = familia; - } - if (alteracao.subfamilia_nome) { - return Subfamilia.findOne({ - where: { - nome: { [Op.like]: `%${alteracao.subfamilia_nome}%` }, - }, - transaction, - }); - } - return undefined; - }) - .then(subfamilia => { - if (subfamilia) { - parametros.subfamilia = subfamilia; - } else if (alteracao.subfamilia_nome) { - return Subfamilia.create({ nome: alteracao.subfamilia_nome }, transaction); - } - return undefined; - }) - .then(subfamilia => { - if (subfamilia) { - parametros.subfamilia = subfamilia; - } - if (alteracao.genero_nome) { - return Genero.findOne({ - where: { - nome: { [Op.like]: `%${alteracao.genero_nome}%` }, - }, - transaction, - }); - } - return undefined; - }) - .then(genero => { - if (genero) { - parametros.genero = genero; - } else if (alteracao.genero_nome) { - return Genero.create({ - where: { - nome: { [Op.like]: `%${alteracao.genero_nome}%` }, - }, - transaction, - }); - } - return undefined; - }) - .then(genero => { - if (alteracao.genero_nome) { - parametros.genero = genero; - } - if (alteracao.especie_nome) { - return Especie.findOne({ - where: { - nome: { [Op.like]: `%${alteracao.especie_nome}%` }, - }, - transaction, - }); - } - return undefined; - }) - .then(especie => { - if (especie) { - parametros.especie = especie; - } else if (alteracao.especie_nome) { - return Especie.create({ - where: { - nome: { [Op.like]: `%${alteracao.especie_nome}%` }, - }, - transaction, - }); - } - return undefined; - }) - .then(especie => { - if (alteracao.especie_nome) { - parametros.especie = especie; - } - if (alteracao.subespecie_nome) { - return Subespecie.findOne({ - where: { - nome: { [Op.like]: `%${alteracao.subespecie_nome}%` }, - }, - transaction, - }); - } - return undefined; - }) - .then(subspecie => { - if (subspecie) { - parametros.subespecie = subspecie; - } else if (alteracao.subespecie_nome) { - return Subespecie.create({ - where: { - nome: { [Op.like]: `%${alteracao.subespecie_nome}%` }, - }, - transaction, - }); - } - return undefined; - }) - .then(subspecie => { - if (alteracao.subespecie_nome) { - parametros.subespecie = subspecie; - } - if (alteracao.variedade_nome) { - return Variedade.findOne({ - where: { - nome: { [Op.like]: `%${alteracao.variedade_nome}%` }, - }, - transaction, - }); - } - return undefined; - }) - .then(variedade => { - if (variedade) { - parametros.variedade = variedade; - } else if (alteracao.variedade_nome) { - return Variedade.create({ - where: { - nome: { [Op.like]: `%${alteracao.variedade_nome}%` }, - }, - transaction, - }); - } - return undefined; - }) - .then(variedade => { - if (alteracao.variedade_nome) { - parametros.variedade = variedade; - } - const update = {}; - if (parametros.familia) { - update.familia_id = parametros.familia.id; - update.nome_cientifico = `${parametros.familia.nome} `; - } - if (parametros.subfamilia) { - update.sub_familia_id = parametros.subfamilia.id; - update.nome_cientifico += `${parametros.subfamilia.nome} `; - } - if (parametros.genero) { - update.genero_id = parametros.genero.id; - update.nome_cientifico += `${parametros.genero.nome} `; - } - if (parametros.especie) { - update.especie_id = parametros.especie.id; - update.nome_cientifico += `${parametros.especie.nome} `; - } - if (parametros.subespecie) { - update.sub_especie_id = parametros.subespecie.id; - update.nome_cientifico += `${parametros.subespecie.nome} `; - } - if (parametros.variedade) { - update.variedade_id = parametros.variedade.id; - update.nome_cientifico += `${parametros.variedade.nome}`; - } - return Tombo.update(update, { - where: { - hcf, - ativo: true, - }, - transaction, - }); - }) - .then(() => true); -}; - export const visualizarComJsonNome = (alteracao, hcf, transaction) => new Promise((resolve, reject) => { Tombo.findOne({ where: { diff --git a/src/controllers/tombos-controller.js b/src/controllers/tombos-controller.js index 277f502b..a3d4ca72 100644 --- a/src/controllers/tombos-controller.js +++ b/src/controllers/tombos-controller.js @@ -105,7 +105,7 @@ export const cadastro = (request, response, next) => { return undefined; }) .then(() => { - if(!localidade?.complemento){ + if (!localidade?.complemento) { throw new BadRequestExeption(400); } return LocalColeta.findOne({ From c69596dcde18da02d353ef344c2aee21023cca1b Mon Sep 17 00:00:00 2001 From: Matheus Coitinho Date: Sat, 23 Aug 2025 18:14:57 -0300 Subject: [PATCH 7/9] =?UTF-8?q?altera=20refer=C3=AAncias=20de=20'complemen?= =?UTF-8?q?to'=20para=20'local=5Fcoleta=5Fid'=20nos=20controladores=20e=20?= =?UTF-8?q?validadores?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/controllers/pendencias-controller.js | 6 ++-- src/controllers/tombos-controller.js | 44 ++++++------------------ src/validators/tombo-alteracao.js | 2 +- src/validators/tombo-cadastro.js | 2 +- 4 files changed, 16 insertions(+), 38 deletions(-) diff --git a/src/controllers/pendencias-controller.js b/src/controllers/pendencias-controller.js index 5d8677b9..4d216be7 100644 --- a/src/controllers/pendencias-controller.js +++ b/src/controllers/pendencias-controller.js @@ -1739,7 +1739,7 @@ export async function visualizar(request, response, next) { if (objetoAlterado.data_coleta?.ano) parametros.data_coleta_ano = objetoAlterado.data_coleta.ano; if (objetoAlterado.cor) parametros.cor = objetoAlterado.cor; if (objetoAlterado.altitude) parametros.altitude = objetoAlterado.altitude; - if (objetoAlterado.complemento) parametros.complemento = objetoAlterado.complemento; + if (objetoAlterado.local_coleta_id) parametros.local_coleta_id = objetoAlterado.local_coleta_id; if (objetoAlterado.descricao) parametros.descricao = objetoAlterado.descricao; if (objetoAlterado.data_identificacao?.dia) parametros.data_identificacao_dia = objetoAlterado.data_identificacao.dia; if (objetoAlterado.data_identificacao?.mes) parametros.data_identificacao_mes = objetoAlterado.data_identificacao.mes; @@ -1844,8 +1844,8 @@ export async function visualizar(request, response, next) { if (parametros.cidade && (!tombo?.locais_coletum?.cidade?.id || tombo.locais_coletum.cidade.id !== parametros.cidade.id)) { jsonRetorno.push({ key: '15', campo: 'Cidade', antigo: tombo?.locais_coletum?.cidade?.nome || '', novo: parametros.cidade.nome }); } - if (parametros.complemento && tombo?.locais_coletum?.complemento !== parametros.complemento) { - jsonRetorno.push({ key: '16', campo: 'Complemento', antigo: tombo?.locais_coletum?.complemento || '', novo: parametros.complemento }); + if (parametros.local_coleta_id && tombo?.locais_coletum?.local_coleta_id !== parametros.local_coleta_id) { + jsonRetorno.push({ key: '16', campo: 'Local de Coleta', antigo: tombo?.locais_coletum?.local_coleta_id || '', novo: parametros.local_coleta_id }); } if (parametros.solo && (!tombo?.locais_coletum?.solo?.id || tombo.locais_coletum.solo.id !== parametros.solo.id)) { jsonRetorno.push({ key: '17', campo: 'Solo', antigo: tombo?.locais_coletum?.solo?.nome || '', novo: parametros.solo.nome }); diff --git a/src/controllers/tombos-controller.js b/src/controllers/tombos-controller.js index a3d4ca72..478f40fe 100644 --- a/src/controllers/tombos-controller.js +++ b/src/controllers/tombos-controller.js @@ -105,12 +105,12 @@ export const cadastro = (request, response, next) => { return undefined; }) .then(() => { - if (!localidade?.complemento) { + if (!localidade?.local_coleta_id) { throw new BadRequestExeption(400); } return LocalColeta.findOne({ where: { - id: localidade.complemento, + id: localidade.local_coleta_id, }, transaction, }); @@ -271,7 +271,7 @@ export const cadastro = (request, response, next) => { data_coleta_mes: principal.data_coleta.mes, data_coleta_ano: principal.data_coleta.ano, numero_coleta: principal.numero_coleta, - local_coleta_id: localidade.complemento, + local_coleta_id: localidade.local_coleta_id, cor: principal.cor, coletor_id: coletor, }; @@ -486,36 +486,14 @@ function alteracaoCuradorouOperador(request, response, transaction) { if (longitude) update.longitude = converteParaDecimal(longitude); const altitude = body?.localidade?.altitude; if (altitude) update.altitude = altitude; - const complemento = body?.localidade?.complemento; - if (complemento) update.local_coleta_id = complemento; - - const soloIdRaw = body?.paisagem?.solo_id; - if (soloIdRaw !== undefined) { - if (soloIdRaw) { - const soloId = typeof soloIdRaw === 'object' ? soloIdRaw.key : soloIdRaw; - update.solo_id = soloId; - } else { - update.solo_id = null; - } - } - const relevoIdRaw = body?.paisagem?.relevo_id; - if (relevoIdRaw !== undefined) { - if (relevoIdRaw) { - const relevoId = typeof relevoIdRaw === 'object' ? relevoIdRaw.key : relevoIdRaw; - update.relevo_id = relevoId; - } else { - update.relevo_id = null; - } - } - const vegetacaoIdRaw = body?.paisagem?.vegetacao_id; - if (vegetacaoIdRaw !== undefined) { - if (vegetacaoIdRaw) { - const vegetacaoId = typeof vegetacaoIdRaw === 'object' ? vegetacaoIdRaw.key : vegetacaoIdRaw; - update.vegetacao_id = vegetacaoId; - } else { - update.vegetacao_id = null; - } - } + const localColeta = body?.localidade?.local_coleta_id; + if (localColeta) update.local_coleta_id = localColeta; + const soloId = body?.paisagem?.solo_id; + if(soloId) update.solo_id = soloId; + const relevoId = body?.paisagem?.relevo_id; + if(relevoId) update.relevo_id = relevoId; + const vegetacaoId = body?.paisagem?.vegetacao_id; + if(vegetacaoId) update.vegetacao_id = vegetacaoId; const descricao = body?.paisagem?.descricao; if (descricao) update.descricao = descricao; const faseSucessionalId = body?.paisagem?.fase_sucessional_id; diff --git a/src/validators/tombo-alteracao.js b/src/validators/tombo-alteracao.js index 008838cc..6cc7ae53 100644 --- a/src/validators/tombo-alteracao.js +++ b/src/validators/tombo-alteracao.js @@ -98,7 +98,7 @@ export default { isEmpty: false, isInt: true, }, - 'json.localidade.complemento': { + 'json.localidade.local_coleta_id': { in: 'body', isString: true, isEmpty: false, diff --git a/src/validators/tombo-cadastro.js b/src/validators/tombo-cadastro.js index 7b5e619e..ed0510f6 100644 --- a/src/validators/tombo-cadastro.js +++ b/src/validators/tombo-cadastro.js @@ -106,7 +106,7 @@ export default { isEmpty: false, isInt: true, }, - 'json.localidade.complemento': { + 'json.localidade.local_coleta_id': { in: 'body', isInt: true, isEmpty: false, From 6f8db6a3ec25e2ac3a38557d7261240b09decb84 Mon Sep 17 00:00:00 2001 From: Matheus Coitinho Date: Sat, 23 Aug 2025 18:15:24 -0300 Subject: [PATCH 8/9] =?UTF-8?q?ajusta=20formata=C3=A7=C3=A3o=20e=20melhora?= =?UTF-8?q?=20a=20legibilidade=20do=20c=C3=B3digo=20no=20controlador=20de?= =?UTF-8?q?=20tombos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/controllers/tombos-controller.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/controllers/tombos-controller.js b/src/controllers/tombos-controller.js index 478f40fe..3ba38c18 100644 --- a/src/controllers/tombos-controller.js +++ b/src/controllers/tombos-controller.js @@ -489,11 +489,11 @@ function alteracaoCuradorouOperador(request, response, transaction) { const localColeta = body?.localidade?.local_coleta_id; if (localColeta) update.local_coleta_id = localColeta; const soloId = body?.paisagem?.solo_id; - if(soloId) update.solo_id = soloId; + if (soloId) update.solo_id = soloId; const relevoId = body?.paisagem?.relevo_id; - if(relevoId) update.relevo_id = relevoId; + if (relevoId) update.relevo_id = relevoId; const vegetacaoId = body?.paisagem?.vegetacao_id; - if(vegetacaoId) update.vegetacao_id = vegetacaoId; + if (vegetacaoId) update.vegetacao_id = vegetacaoId; const descricao = body?.paisagem?.descricao; if (descricao) update.descricao = descricao; const faseSucessionalId = body?.paisagem?.fase_sucessional_id; From e73925fa0140a6e2d6c605a7be3170470ce0f3e0 Mon Sep 17 00:00:00 2001 From: Matheus Coitinho Date: Sat, 23 Aug 2025 18:27:03 -0300 Subject: [PATCH 9/9] =?UTF-8?q?refatora=20valida=C3=A7=C3=B5es=20de=20camp?= =?UTF-8?q?os=20no=20m=C3=A9todo=20aprovarPendencia=20para=20simplificar?= =?UTF-8?q?=20a=20l=C3=B3gica=20de=20verifica=C3=A7=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/controllers/pendencias-controller.js | 329 ++++++++++------------- 1 file changed, 144 insertions(+), 185 deletions(-) diff --git a/src/controllers/pendencias-controller.js b/src/controllers/pendencias-controller.js index 4d216be7..76f42c4b 100644 --- a/src/controllers/pendencias-controller.js +++ b/src/controllers/pendencias-controller.js @@ -1171,7 +1171,7 @@ export const aprovarPendencia = async (alteracao, hcf, transaction) => { updateTombo.altitude = alteracao.altitude; } - if (alteracao.entidade_id !== undefined) { + if (alteracao.entidade_id) { const herbario = await Herbario.findOne({ where: { id: alteracao.entidade_id }, transaction, @@ -1185,7 +1185,7 @@ export const aprovarPendencia = async (alteracao, hcf, transaction) => { updateTombo.entidade_id = alteracao.entidade_id; } - if (alteracao.tipo_id !== undefined) { + if (alteracao.tipo_id) { const tipo = await Tipo.findOne({ where: { id: alteracao.tipo_id }, transaction, @@ -1199,25 +1199,21 @@ export const aprovarPendencia = async (alteracao, hcf, transaction) => { updateTombo.tipo_id = alteracao.tipo_id; } - if (alteracao.familia_id !== undefined) { - if (alteracao.familia_id) { - const familia = await Familia.findOne({ - where: { id: alteracao.familia_id }, - transaction, - raw: true, - nest: true, - }); - - if (!familia) { - throw new BadRequestExeption(404); - } + if (alteracao.familia_id) { + const familia = await Familia.findOne({ + where: { id: alteracao.familia_id }, + transaction, + raw: true, + nest: true, + }); - updateTombo.familia_id = alteracao.familia_id; - nomesCientificosPartes.push(familia.nome); - } else { - updateTombo.familia_id = null; + if (!familia) { + throw new BadRequestExeption(404); } + updateTombo.familia_id = alteracao.familia_id; + nomesCientificosPartes.push(familia.nome); + updateTombo.sub_familia_id = null; updateTombo.genero_id = null; updateTombo.especie_id = null; @@ -1225,140 +1221,120 @@ export const aprovarPendencia = async (alteracao, hcf, transaction) => { updateTombo.variedade_id = null; } - if (alteracao.sub_familia_id !== undefined) { - if (alteracao.sub_familia_id) { - const subfamilia = await Subfamilia.findOne({ - where: { - id: alteracao.sub_familia_id, - familia_id: updateTombo.familia_id || tomboAtual.familia_id, - }, - transaction, - raw: true, - nest: true, - }); - - if (!subfamilia) { - throw new BadRequestExeption(404); - } + if (alteracao.sub_familia_id) { + const subfamilia = await Subfamilia.findOne({ + where: { + id: alteracao.sub_familia_id, + familia_id: updateTombo.familia_id || tomboAtual.familia_id, + }, + transaction, + raw: true, + nest: true, + }); - updateTombo.sub_familia_id = alteracao.sub_familia_id; - nomesCientificosPartes.push(subfamilia.nome); - } else { - updateTombo.sub_familia_id = null; + if (!subfamilia) { + throw new BadRequestExeption(404); } + updateTombo.sub_familia_id = alteracao.sub_familia_id; + nomesCientificosPartes.push(subfamilia.nome); + updateTombo.genero_id = null; updateTombo.especie_id = null; updateTombo.sub_especie_id = null; updateTombo.variedade_id = null; } - if (alteracao.genero_id !== undefined) { - if (alteracao.genero_id) { - const genero = await Genero.findOne({ - where: { - id: alteracao.genero_id, - familia_id: updateTombo.familia_id || tomboAtual.familia_id, - }, - transaction, - raw: true, - nest: true, - }); - - if (!genero) { - throw new BadRequestExeption(404); - } + if (alteracao.genero_id) { + const genero = await Genero.findOne({ + where: { + id: alteracao.genero_id, + familia_id: updateTombo.familia_id || tomboAtual.familia_id, + }, + transaction, + raw: true, + nest: true, + }); - updateTombo.genero_id = alteracao.genero_id; - nomesCientificosPartes.push(genero.nome); - } else { - updateTombo.genero_id = null; + if (!genero) { + throw new BadRequestExeption(404); } + updateTombo.genero_id = alteracao.genero_id; + nomesCientificosPartes.push(genero.nome); + updateTombo.especie_id = null; updateTombo.sub_especie_id = null; updateTombo.variedade_id = null; } - if (alteracao.especie_id !== undefined) { - if (alteracao.especie_id) { - const especie = await Especie.findOne({ - where: { - id: alteracao.especie_id, - genero_id: updateTombo.genero_id || tomboAtual.genero_id, - }, - transaction, - raw: true, - nest: true, - }); - - if (!especie) { - throw new BadRequestExeption(404); - } + if (alteracao.especie_id) { + const especie = await Especie.findOne({ + where: { + id: alteracao.especie_id, + genero_id: updateTombo.genero_id || tomboAtual.genero_id, + }, + transaction, + raw: true, + nest: true, + }); - updateTombo.especie_id = alteracao.especie_id; - nomesCientificosPartes.push(especie.nome); - } else { - updateTombo.especie_id = null; + if (!especie) { + throw new BadRequestExeption(404); } + updateTombo.especie_id = alteracao.especie_id; + nomesCientificosPartes.push(especie.nome); + updateTombo.sub_especie_id = null; updateTombo.variedade_id = null; } - if (alteracao.sub_especie_id !== undefined) { - if (alteracao.sub_especie_id) { - const subespecie = await Subespecie.findOne({ - where: { - id: alteracao.sub_especie_id, - especie_id: updateTombo.especie_id || tomboAtual.especie_id, - }, - transaction, - raw: true, - nest: true, - }); - - if (!subespecie) { - throw new BadRequestExeption(404); - } + if (alteracao.sub_especie_id) { + const subespecie = await Subespecie.findOne({ + where: { + id: alteracao.sub_especie_id, + especie_id: updateTombo.especie_id || tomboAtual.especie_id, + }, + transaction, + raw: true, + nest: true, + }); - updateTombo.sub_especie_id = alteracao.sub_especie_id; - nomesCientificosPartes.push(subespecie.nome); - } else { - updateTombo.sub_especie_id = null; + if (!subespecie) { + throw new BadRequestExeption(404); } + updateTombo.sub_especie_id = alteracao.sub_especie_id; + nomesCientificosPartes.push(subespecie.nome); + updateTombo.variedade_id = null; } - if (alteracao.variedade_id !== undefined) { - if (alteracao.variedade_id) { - const variedade = await Variedade.findOne({ - where: { - id: alteracao.variedade_id, - especie_id: updateTombo.especie_id || tomboAtual.especie_id, - }, - transaction, - raw: true, - nest: true, - }); - - if (!variedade) { - throw new BadRequestExeption(404); - } + if (alteracao.variedade_id) { + const variedade = await Variedade.findOne({ + where: { + id: alteracao.variedade_id, + especie_id: updateTombo.especie_id || tomboAtual.especie_id, + }, + transaction, + raw: true, + nest: true, + }); - updateTombo.variedade_id = alteracao.variedade_id; - nomesCientificosPartes.push(variedade.nome); - } else { - updateTombo.variedade_id = null; + if (!variedade) { + throw new BadRequestExeption(404); } + + updateTombo.variedade_id = alteracao.variedade_id; + nomesCientificosPartes.push(variedade.nome); } if (nomesCientificosPartes.length > 0) { updateTombo.nome_cientifico = nomesCientificosPartes.join(' '); } - if (alteracao.local_coleta_id !== undefined) { + if (alteracao.local_coleta_id) { const localColeta = await LocalColeta.findOne({ where: { id: alteracao.local_coleta_id }, transaction, @@ -1377,93 +1353,74 @@ export const aprovarPendencia = async (alteracao, hcf, transaction) => { updateTombo.descricao = alteracao.descricao; } - if (alteracao.solo_id !== undefined) { - if (alteracao.solo_id) { - const soloId = alteracao.solo_id; - const solo = await Solo.findOne({ - where: { id: soloId }, - transaction, - raw: true, - nest: true, - }); - - if (!solo) { - throw new BadRequestExeption(404); - } + if (alteracao.solo_id) { + const solo = await Solo.findOne({ + where: { id: alteracao.solo_id }, + transaction, + raw: true, + nest: true, + }); - updateTombo.solo_id = soloId; - } else { - updateTombo.solo_id = null; + if (!solo) { + throw new BadRequestExeption(404); } - } - if (alteracao.relevo_id !== undefined) { - if (alteracao.relevo_id) { - const relevoId = alteracao.relevo_id; - const relevo = await Relevo.findOne({ - where: { id: relevoId }, - transaction, - raw: true, - nest: true, - }); + updateTombo.solo_id = alteracao.solo_id; + } - if (!relevo) { - throw new BadRequestExeption(404); - } + if (alteracao.relevo_id) { + const relevo = await Relevo.findOne({ + where: { id: alteracao.relevo_id }, + transaction, + raw: true, + nest: true, + }); - updateTombo.relevo_id = relevoId; - } else { - updateTombo.relevo_id = null; + if (!relevo) { + throw new BadRequestExeption(404); } - } - if (alteracao.vegetacao_id !== undefined) { - if (alteracao.vegetacao_id) { - const vegetacaoId = alteracao.vegetacao_id; - const vegetacao = await Vegetacao.findOne({ - where: { id: vegetacaoId }, - transaction, - raw: true, - nest: true, - }); + updateTombo.relevo_id = alteracao.relevo_id; + } - if (!vegetacao) { - throw new BadRequestExeption(404); - } + if (alteracao.vegetacao_id) { + const vegetacao = await Vegetacao.findOne({ + where: { id: alteracao.vegetacao_id }, + transaction, + raw: true, + nest: true, + }); - updateTombo.vegetacao_id = vegetacaoId; - } else { - updateTombo.vegetacao_id = null; + if (!vegetacao) { + throw new BadRequestExeption(404); } + + updateTombo.vegetacao_id = alteracao.vegetacao_id; } - if (alteracao.coletor_id !== undefined) { - if (alteracao.coletor_id) { - const coletor = await Coletor.findOne({ + if (alteracao.coletor_id) { + const coletor = await Coletor.findOne({ + where: { id: alteracao.coletor_id }, + transaction, + raw: true, + nest: true, + }); + + if (!coletor) { + throw new BadRequestExeption(404); + } + + const numeroColeta = updateTombo.numero_coleta; + if (numeroColeta && coletor.numero && coletor.numero < numeroColeta) { + await Coletor.update({ + numero: numeroColeta, + }, { where: { id: alteracao.coletor_id }, transaction, - raw: true, - nest: true, }); - - if (!coletor) { - throw new BadRequestExeption(404); - } - - const numeroColeta = updateTombo.numero_coleta; - if (numeroColeta && coletor.numero && coletor.numero < numeroColeta) { - await Coletor.update({ - numero: numeroColeta, - }, { - where: { id: alteracao.coletor_id }, - transaction, - }); - } - - updateTombo.coletor_id = alteracao.coletor_id; - } else { - updateTombo.coletor_id = null; } + + updateTombo.coletor_id = alteracao.coletor_id; } if (Object.keys(updateTombo).length > 0) { @@ -1569,6 +1526,8 @@ export const aprovarPendencia = async (alteracao, hcf, transaction) => { }; }; +// ...existing code... + export const visualizarComJsonNome = (alteracao, hcf, transaction) => new Promise((resolve, reject) => { Tombo.findOne({ where: {