From 8b511245c4e536e2f93b52d0d604b6a8da67c86a Mon Sep 17 00:00:00 2001 From: Eduardo Amorim Date: Thu, 18 Jun 2026 16:03:10 -0300 Subject: [PATCH] feat: reestrutura exemplos em pt/en/es e alinha contratos com a API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cria uma versão multilíngue do repositório de exemplos, separando em `pt/exemplos` (português), `en/examples` (inglês) e `es/ejemplos` (espanhol), com `core/` compartilhado na raiz. Antes de duplicar, corrige 5 exemplos que estavam inconsistentes com o contrato atual da API amonamarth: - POST /pendencies: usa objetos `company: {id}` / `pendencyType: {id}` em vez de `companyId` / `pendencyTypeId` (que retornavam 422). - POST /equipment-types: valores de `customFields[].type` corrigidos para o enum real (QUESTION/NUMBER/DATE/MULTIPLE_CHOICE) e assert. - GET /companies: `nameEq` / `orderBy` / `direction` (os nomes `nameContains` / `orderColumn` / `orderDirection` não existem e eram ignorados silenciosamente). - GET /locations/:id/service-providers: remove o `segmentId` não suportado pelo endpoint. - POST /pendencies/:id/actions/conclude: remove o body descartado. Nas traduções (en/es), comentários, logs e textos criados foram traduzidos, mas os valores de lookup (nameEq, nomes de dados reais) foram mantidos em português para não quebrar as consultas. Co-Authored-By: Claude Opus 4.8 (1M context) --- README.md | 38 ++--- {src/core => core}/client.js | 0 {src/core => core}/utils.js | 0 en/README.md | 40 +++++ en/examples/companies/get-companies.js | 78 +++++++++ .../companies/get-nearby-companies-usage.js | 29 ++++ en/examples/companies/nearby-companies-2.js | 28 +++ en/examples/companies/nearby-companies.js | 96 +++++++++++ .../equipment-types/create-equipment-type.js | 55 ++++++ .../equipments/change-equipment-location.js | 48 ++++++ .../create-location-without-coordinates.js | 43 +++++ en/examples/locations/create-location.js | 44 +++++ .../get-location-service-providers.js | 80 +++++++++ .../get-maintenance-types.js | 22 +++ .../add-maintenance-comment-collaborator.js | 52 ++++++ .../maintenances/cancel-maintenance.js | 34 ++++ ...create-maintenance-comment-collaborator.js | 75 ++++++++ .../create-maintenance-comment.js | 75 ++++++++ .../create-maintenance-with-address.js | 62 +++++++ .../create-maintenance-with-attachment.js | 161 ++++++++++++++++++ ...te-maintenance-with-schedule-suggestion.js | 60 +++++++ .../maintenances/get-canceled-maintenances.js | 32 ++++ .../get-maintenance-form-answers.js | 21 +++ .../maintenances/maintenance-stress-test.js | 63 +++++++ .../maintenances/reallocate-maintenance.js | 32 ++++ .../maintenances/reopen-maintenance.js | 32 ++++ en/examples/pendencies/conclude-pendency.js | 16 ++ en/examples/pendencies/create-pendency.js | 42 +++++ en/examples/pendencies/get-pendencies.js | 22 +++ en/examples/segments/get-segments.js | 22 +++ es/README.md | 40 +++++ es/ejemplos/empresas/empresas-cercanas-2.js | 28 +++ es/ejemplos/empresas/empresas-cercanas.js | 96 +++++++++++ es/ejemplos/empresas/obtener-empresas.js | 78 +++++++++ .../empresas/obtener-uso-empresas-cercanas.js | 29 ++++ .../equipos/cambiar-ubicacion-del-equipo.js | 48 ++++++ ...comentario-colaborador-al-mantenimiento.js | 52 ++++++ .../mantenimientos/cancelar-mantenimiento.js | 34 ++++ .../crear-mantenimiento-con-adjunto.js | 161 ++++++++++++++++++ ...antenimiento-con-comentario-colaborador.js | 75 ++++++++ .../crear-mantenimiento-con-comentario.js | 75 ++++++++ .../crear-mantenimiento-con-direccion.js | 62 +++++++ ...-mantenimiento-con-sugerencia-de-agenda.js | 60 +++++++ .../obtener-mantenimientos-cancelados.js | 32 ++++ ...uestas-de-formularios-del-mantenimiento.js | 21 +++ .../prueba-de-estres-mantenimientos.js | 63 +++++++ .../mantenimientos/reabrir-mantenimiento.js | 32 ++++ .../mantenimientos/reasignar-mantenimiento.js | 32 ++++ es/ejemplos/pendientes/concluir-pendiente.js | 16 ++ es/ejemplos/pendientes/crear-pendiente.js | 42 +++++ es/ejemplos/pendientes/obtener-pendientes.js | 22 +++ es/ejemplos/segmentos/obtener-segmentos.js | 22 +++ .../tipos-de-equipo/crear-tipo-de-equipo.js | 55 ++++++ .../obtener-tipos-de-mantenimiento.js | 22 +++ .../crear-ubicacion-sin-coordenadas.js | 43 +++++ es/ejemplos/ubicaciones/crear-ubicacion.js | 44 +++++ .../obtener-proveedores-de-la-ubicacion.js | 80 +++++++++ pt/README.md | 40 +++++ .../exemplos/empresas/empresas-proximas-2.js | 2 +- .../exemplos/empresas/empresas-proximas.js | 4 +- .../exemplos/empresas/obter-empresas.js | 24 +-- .../empresas/obter-uso-empresas-proximas.js | 4 +- .../alterar-local-do-equipamento.js | 4 +- .../locais/criar-local-sem-coordenadas.js | 4 +- .../exemplos/locais/criar-local.js | 4 +- .../locais/obter-fornecedores-do-local.js | 19 +-- ...ar-comentario-colaborador-na-manutencao.js | 4 +- .../manutencoes/cancelar-manutencao.js | 4 +- .../manutencoes/criar-manutencao-com-anexo.js | 6 +- ...r-manutencao-com-comentario-colaborador.js | 4 +- .../criar-manutencao-com-comentario.js | 4 +- .../criar-manutencao-com-endereco.js | 4 +- ...-manutencao-com-sugestao-de-agendamento.js | 4 +- .../obter-manutencoes-canceladas.js | 6 +- ...-respostas-de-formularios-da-manutencao.js | 4 +- .../manutencoes/reabrir-manutencao.js | 4 +- .../manutencoes/realocar-manutencao.js | 4 +- .../teste-de-estresse-manutencoes.js | 2 +- .../exemplos/pendencias/concluir-pendencia.js | 9 +- .../exemplos/pendencias/criar-pendencia.js | 8 +- .../exemplos/pendencias/obter-pendencias.js | 4 +- .../exemplos/segmentos/obter-segmentos.js | 4 +- .../criar-tipo-de-equipamento.js | 14 +- .../obter-tipos-de-manutencao.js | 4 +- 84 files changed, 2856 insertions(+), 108 deletions(-) rename {src/core => core}/client.js (100%) rename {src/core => core}/utils.js (100%) create mode 100644 en/README.md create mode 100644 en/examples/companies/get-companies.js create mode 100644 en/examples/companies/get-nearby-companies-usage.js create mode 100644 en/examples/companies/nearby-companies-2.js create mode 100644 en/examples/companies/nearby-companies.js create mode 100644 en/examples/equipment-types/create-equipment-type.js create mode 100644 en/examples/equipments/change-equipment-location.js create mode 100644 en/examples/locations/create-location-without-coordinates.js create mode 100644 en/examples/locations/create-location.js create mode 100644 en/examples/locations/get-location-service-providers.js create mode 100644 en/examples/maintenance-types/get-maintenance-types.js create mode 100644 en/examples/maintenances/add-maintenance-comment-collaborator.js create mode 100644 en/examples/maintenances/cancel-maintenance.js create mode 100644 en/examples/maintenances/create-maintenance-comment-collaborator.js create mode 100644 en/examples/maintenances/create-maintenance-comment.js create mode 100644 en/examples/maintenances/create-maintenance-with-address.js create mode 100644 en/examples/maintenances/create-maintenance-with-attachment.js create mode 100644 en/examples/maintenances/create-maintenance-with-schedule-suggestion.js create mode 100644 en/examples/maintenances/get-canceled-maintenances.js create mode 100644 en/examples/maintenances/get-maintenance-form-answers.js create mode 100644 en/examples/maintenances/maintenance-stress-test.js create mode 100644 en/examples/maintenances/reallocate-maintenance.js create mode 100644 en/examples/maintenances/reopen-maintenance.js create mode 100644 en/examples/pendencies/conclude-pendency.js create mode 100644 en/examples/pendencies/create-pendency.js create mode 100644 en/examples/pendencies/get-pendencies.js create mode 100644 en/examples/segments/get-segments.js create mode 100644 es/README.md create mode 100644 es/ejemplos/empresas/empresas-cercanas-2.js create mode 100644 es/ejemplos/empresas/empresas-cercanas.js create mode 100644 es/ejemplos/empresas/obtener-empresas.js create mode 100644 es/ejemplos/empresas/obtener-uso-empresas-cercanas.js create mode 100644 es/ejemplos/equipos/cambiar-ubicacion-del-equipo.js create mode 100644 es/ejemplos/mantenimientos/agregar-comentario-colaborador-al-mantenimiento.js create mode 100644 es/ejemplos/mantenimientos/cancelar-mantenimiento.js create mode 100644 es/ejemplos/mantenimientos/crear-mantenimiento-con-adjunto.js create mode 100644 es/ejemplos/mantenimientos/crear-mantenimiento-con-comentario-colaborador.js create mode 100644 es/ejemplos/mantenimientos/crear-mantenimiento-con-comentario.js create mode 100644 es/ejemplos/mantenimientos/crear-mantenimiento-con-direccion.js create mode 100644 es/ejemplos/mantenimientos/crear-mantenimiento-con-sugerencia-de-agenda.js create mode 100644 es/ejemplos/mantenimientos/obtener-mantenimientos-cancelados.js create mode 100644 es/ejemplos/mantenimientos/obtener-respuestas-de-formularios-del-mantenimiento.js create mode 100644 es/ejemplos/mantenimientos/prueba-de-estres-mantenimientos.js create mode 100644 es/ejemplos/mantenimientos/reabrir-mantenimiento.js create mode 100644 es/ejemplos/mantenimientos/reasignar-mantenimiento.js create mode 100644 es/ejemplos/pendientes/concluir-pendiente.js create mode 100644 es/ejemplos/pendientes/crear-pendiente.js create mode 100644 es/ejemplos/pendientes/obtener-pendientes.js create mode 100644 es/ejemplos/segmentos/obtener-segmentos.js create mode 100644 es/ejemplos/tipos-de-equipo/crear-tipo-de-equipo.js create mode 100644 es/ejemplos/tipos-de-mantenimiento/obtener-tipos-de-mantenimiento.js create mode 100644 es/ejemplos/ubicaciones/crear-ubicacion-sin-coordenadas.js create mode 100644 es/ejemplos/ubicaciones/crear-ubicacion.js create mode 100644 es/ejemplos/ubicaciones/obtener-proveedores-de-la-ubicacion.js create mode 100644 pt/README.md rename src/examples/companies/post-companies-near-by-2.js => pt/exemplos/empresas/empresas-proximas-2.js (93%) rename src/examples/companies/post-companies-near-by.js => pt/exemplos/empresas/empresas-proximas.js (96%) rename src/examples/companies/get-companies.js => pt/exemplos/empresas/obter-empresas.js (77%) rename src/examples/companies/get-companies-near-by-usage.js => pt/exemplos/empresas/obter-uso-empresas-proximas.js (88%) rename src/examples/equipments/post-change-equipment-location.js => pt/exemplos/equipamentos/alterar-local-do-equipamento.js (92%) rename src/examples/locations/post-create-location-with-no-coords.js => pt/exemplos/locais/criar-local-sem-coordenadas.js (90%) rename src/examples/locations/post-create-location.js => pt/exemplos/locais/criar-local.js (90%) rename src/examples/locations/get-locations-service-providers.js => pt/exemplos/locais/obter-fornecedores-do-local.js (82%) rename src/examples/maintenances/post-add-maintenance-coment-collaborator.js => pt/exemplos/manutencoes/adicionar-comentario-colaborador-na-manutencao.js (93%) rename src/examples/maintenances/post-cancel-maintenance.js => pt/exemplos/manutencoes/cancelar-manutencao.js (90%) rename src/examples/maintenances/post-create-maintenance-with-attachment.js => pt/exemplos/manutencoes/criar-manutencao-com-anexo.js (96%) rename src/examples/maintenances/post-create-maintenance-coment-collaborator.js => pt/exemplos/manutencoes/criar-manutencao-com-comentario-colaborador.js (95%) rename src/examples/maintenances/post-create-maintenance-coment.js => pt/exemplos/manutencoes/criar-manutencao-com-comentario.js (95%) rename src/examples/maintenances/post-create-maintenance-with-address.js => pt/exemplos/manutencoes/criar-manutencao-com-endereco.js (93%) rename src/examples/maintenances/post-create-maintenance-with-schedule-suggestion.js => pt/exemplos/manutencoes/criar-manutencao-com-sugestao-de-agendamento.js (93%) rename src/examples/maintenances/get-canceled-maintenances.js => pt/exemplos/manutencoes/obter-manutencoes-canceladas.js (83%) rename src/examples/maintenances/get-maintenance-forms-answers.js => pt/exemplos/manutencoes/obter-respostas-de-formularios-da-manutencao.js (84%) rename src/examples/maintenances/post-reopen-maintenance.js => pt/exemplos/manutencoes/reabrir-manutencao.js (89%) rename src/examples/maintenances/post-reallocate-maintenance.js => pt/exemplos/manutencoes/realocar-manutencao.js (89%) rename src/examples/maintenances/get-maintenance-stress.js => pt/exemplos/manutencoes/teste-de-estresse-manutencoes.js (97%) rename src/examples/pendencies/post-conclude-pendencies.js => pt/exemplos/pendencias/concluir-pendencia.js (61%) rename src/examples/pendencies/post-pendencies.js => pt/exemplos/pendencias/criar-pendencia.js (85%) rename src/examples/pendencies/get-pendencies.js => pt/exemplos/pendencias/obter-pendencias.js (83%) rename src/examples/segments/get-segments.js => pt/exemplos/segmentos/obter-segmentos.js (83%) rename src/examples/equipments-types/post-create-equipment-type.js => pt/exemplos/tipos-de-equipamento/criar-tipo-de-equipamento.js (78%) rename src/examples/maintenances-types/get-maintenance-types.js => pt/exemplos/tipos-de-manutencao/obter-tipos-de-manutencao.js (83%) diff --git a/README.md b/README.md index 5e0cdae..d0f34cd 100644 --- a/README.md +++ b/README.md @@ -8,31 +8,27 @@ Este é um repositório auxiliar contendo trechos de código e exemplos de uso. -## Pré-requisitos para executar o projeto +## Multilingual / Multilíngue -- Node.js version manager, caso não tenha o nvm instale seguindo estes passos - - [nvm para windows](https://github.com/coreybutler/nvm-windows) - - [nvm pra mac/linux](https://github.com/nvm-sh/nvm#installing-and-updating) +Os exemplos estão divididos em três versões, com comentários e textos no idioma correspondente. O código compartilhado (cliente HTTP e utilitários) fica na pasta `core` na raiz do repositório. -- Clonar este repositório localmente `git clone https://github.com/LeoFalco/amonamarth-examples.git` +The examples are split into three versions, with comments and text in the matching language. The shared code (HTTP client and utilities) lives in the `core` folder at the root of the repository. -- Na pasta do projeto executar os seguintes comandos +- 🇧🇷 **Português** — exemplos em `pt/exemplos/` · veja [pt/README.md](pt/README.md) +- 🇺🇸 **English** — examples in `en/examples/` · see [en/README.md](en/README.md) +- 🇪🇸 **Español** — ejemplos en `es/ejemplos/` · vea [es/README.md](es/README.md) - ```sh - nvm install # para instalar o nome - nvm use # troca para a versão do node.js instalada - npm install # instala as dependências do projeto - ``` +## Estrutura / Structure -- O projeto usa autenticação por de API key você pode declarar a sua dentro de um arquivo chamado `.env` -assim como na imagem: - - ![image](https://user-images.githubusercontent.com/25820906/178081437-c5939851-116e-44e1-8527-91dc6a63900c.png) - -## Executando arquivos +```text +amonamarth-examples/ +├── core/ # código compartilhado / shared code (client.js, utils.js) +├── data/ # arquivos de exemplo / example files +├── pt/ # exemplos em português / Portuguese examples +├── en/ # exemplos em inglês / English examples +└── es/ # ejemplos em espanhol / Spanish examples +``` -Os arquivos de exemplos estão na pasta `src/examples` é possível executa-los diretamente pelo node.js +Consulte o README de cada idioma para os pré-requisitos e as instruções de execução. -```sh - node src/examples/create-maintenance-with-attachment.js -``` +See the README for each language for prerequisites and run instructions. diff --git a/src/core/client.js b/core/client.js similarity index 100% rename from src/core/client.js rename to core/client.js diff --git a/src/core/utils.js b/core/utils.js similarity index 100% rename from src/core/utils.js rename to core/utils.js diff --git a/en/README.md b/en/README.md new file mode 100644 index 0000000..444bf69 --- /dev/null +++ b/en/README.md @@ -0,0 +1,40 @@ +# Amonamarth Examples (English) + +![Field Control ♥](https://img.shields.io/badge/Field%20Control-♥-blue.svg) +[![GitHub Super-Linter](https://github.com/FieldControl/amonamarth-examples/workflows/Lint/badge.svg)](https://github.com/marketplace/actions/super-linter) + + +:volcano: Amon Amarth, the public supplier management API, is a REST web service that exposes resources to make it easier for companies to integrate with their other systems. + +This is an auxiliary repository containing code snippets and usage examples. This is the **English** version of the examples. For the Portuguese version, see [pt/README.md](../pt/README.md). For the Spanish version, see [es/README.md](../es/README.md). + +## Prerequisites to run the project + +- Node.js version manager. If you do not have nvm, install it following these steps + - [nvm for windows](https://github.com/coreybutler/nvm-windows) + - [nvm for mac/linux](https://github.com/nvm-sh/nvm#installing-and-updating) + +- Clone this repository locally `git clone https://github.com/LeoFalco/amonamarth-examples.git` + +- In the project folder run the following commands + + ```sh + nvm install # to install node + nvm use # switch to the installed Node.js version + npm install # install the project dependencies + ``` + +- The project uses API key authentication. You can declare yours inside a file called `.env` +as shown in the image: + + ![image](https://user-images.githubusercontent.com/25820906/178081437-c5939851-116e-44e1-8527-91dc6a63900c.png) + +## Running files + +The English example files are in the `en/examples` folder. You can run them directly with Node.js + +```sh + node en/examples/maintenances/create-maintenance-with-attachment.js +``` + +> The shared code (HTTP client and utilities) lives in the `core` folder at the root of the repository. diff --git a/en/examples/companies/get-companies.js b/en/examples/companies/get-companies.js new file mode 100644 index 0000000..5c056e1 --- /dev/null +++ b/en/examples/companies/get-companies.js @@ -0,0 +1,78 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + // Get companies with exact name equal to "Field Control" + // Only one item per page + // Page one or first page + await client.get('/companies', { + params: { + page: 1, + perPage: 1, + nameEq: 'Field Control' + } + }).then(getData) + + // Get companies with exact name equal to "Field Control" + // Only two items per page + // Page one or first page + // From oldest to newest + await client.get('/companies', { + params: { + page: 1, + perPage: 2, + nameEq: 'Field Control', + orderBy: 'createdAt', + direction: 'asc' + } + }).then(getData) + + // Get companies that have a name identical to "Resolv" + // Only one item per page + // Page one or first page + await client.get('/companies', { + params: { + page: 1, + perPage: 1, + nameEq: 'Resolv' + } + }).then(getData) + + // Only two items per page + // Page one or first page + // With the name from Z to A + await client.get('/companies', { + params: { + page: 1, + perPage: 2, + orderBy: 'name', + direction: 'desc' + } + }).then(getData) + + // Only two items per page + // Page one or first page + // Farthest to nearest + // The "distanceRelativeTo" field must be a string containing the latitude and longitude, respectively ("latitude,longitude") + // The "distanceRelativeTo" field can only be provided if the orderColumn field is equal to "distance" + // Companies without coordinates will be placed at the end of the list + await client.get('/companies', { + params: { + page: 1, + perPage: 2, + orderBy: 'distance', + direction: 'desc', + distanceRelativeTo: '37.7749,-122.4194' + } + }).then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/companies/get-nearby-companies-usage.js b/en/examples/companies/get-nearby-companies-usage.js new file mode 100644 index 0000000..e123226 --- /dev/null +++ b/en/examples/companies/get-nearby-companies-usage.js @@ -0,0 +1,29 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + // Get company geolocation usage history + const result = await client.get('/companies/actions/nearby/usage').then(getData) + + assert.deepEqual(result, { + items: [ + { + id: 'eyJwayI6IlVTQUdFIzEiLCJzayI6IjIwMjMtMDcifQ==', + month: '2023-07', + quota: 2000, + usedQuota: 10 + } + ] + }) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/companies/nearby-companies-2.js b/en/examples/companies/nearby-companies-2.js new file mode 100644 index 0000000..99e63ed --- /dev/null +++ b/en/examples/companies/nearby-companies-2.js @@ -0,0 +1,28 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' + +async function run () { + // Get companies near "Avenida Abrão josé de lima 659" + const result = await client.post('/companies/actions/nearby', { + formattedAddress: 'Avenida Abrão josé de lima 659', + postalCode: '15110000', // optional + countryCode: null // optional + }, { + params: { + page: 1, + perPage: 2 + } + }) + + console.log('headers: ', result.headers) + console.log('data: ', result.data) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/companies/nearby-companies.js b/en/examples/companies/nearby-companies.js new file mode 100644 index 0000000..25c8157 --- /dev/null +++ b/en/examples/companies/nearby-companies.js @@ -0,0 +1,96 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + // Get companies near "Avenida Abrão josé de lima 659" + const result = await client.post('/companies/actions/nearby', { + formattedAddress: 'Avenida Abrão josé de lima 659', + postalCode: '15110000', // optional + countryCode: null // optional + }, { + params: { + page: 1, + perPage: 2 + } + }).then(getData) + + assert.deepEqual(result, { + items: [ + { + id: '5a135059-a054-46d1-b431-fb0f1036ccd4', + name: 'Field Control - Fornecedor 8817', + relativeDistance: { + distanceInMeters: 1680, // nearest first + relativeTo: { + latitude: -20.7972941, + longitude: -49.221242 + } + }, + address: { + city: 'Guapiaçu', + complement: null, + coords: { + latitude: -20.807428, + longitude: -49.2332 + }, + countryCode: 'BRA', + neighborhood: 'Guapiaçu', + number: '686', + state: 'São Paulo', + street: 'abrao jose de lima', + zipCode: '15110000' + }, + archived: false, + avatarUrl: 'https://s3.amazonaws.com/attachments.fieldcontrol.com.br/accounts/8817/company-logo.png', + createdAt: '2019-08-01T12:24:18Z' + }, + { + id: 'e75d361b-ceee-4c83-9962-b5ecb4272224', + name: 'Designers', + relativeDistance: { + distanceInMeters: 16463, + relativeTo: { + latitude: -20.7972941, + longitude: -49.221242 + } + }, + address: { + city: 'São José do Rio Preto', + complement: null, + coords: { + latitude: -20.8072548, + longitude: -49.3790862 + }, + countryCode: 'AUS', + neighborhood: 'Centro', + number: '12', + state: 'SP', + street: 'Rua Coronel Spínola de Castro', + zipCode: '15015500' + }, + archived: false, + avatarUrl: 'assets/images/avatars/avatar.jpg', + createdAt: '2020-08-04T19:26:48Z' + } + ], + pageInfo: { + hasNextPage: true, + hasPreviousPage: false, + page: 1, + pageCount: 4, + perPage: 2, + totalCount: 7 + } + }) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/equipment-types/create-equipment-type.js b/en/examples/equipment-types/create-equipment-type.js new file mode 100644 index 0000000..08ad57a --- /dev/null +++ b/en/examples/equipment-types/create-equipment-type.js @@ -0,0 +1,55 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + const segment = await client.get('/segments', { + params: { + page: 1, + perPage: 10, + nameEq: '001 - Ar condicionado' + } + }).then(getFistItem) + + const equipmentType = await client.post('/equipment-types', { + name: 'An equipment type', + archived: false, + segment: { + id: segment.id + }, + customFields: [ + { + name: 'Field 1', + type: 'QUESTION', + required: true + }, + { + name: 'Field 2', + type: 'NUMBER', + required: false + }, + { + name: 'Field 3', + type: 'DATE', + required: true + }, + { + name: 'Field 4', + type: 'MULTIPLE_CHOICE', + required: false + } + ] + }).then(getData) + + assert.equal(equipmentType.name, 'An equipment type') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/equipments/change-equipment-location.js b/en/examples/equipments/change-equipment-location.js new file mode 100644 index 0000000..466f4ca --- /dev/null +++ b/en/examples/equipments/change-equipment-location.js @@ -0,0 +1,48 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + const equipment = await client.get('/equipments', { + params: { + page: 1, + perPage: 1, + numberEq: '1997' + } + }).then(getFistItem) + + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '08980888015' + } + }).then(getFistItem) + + const updatedEquipment = await client.put(`/equipments/${equipment.id}`, { + name: 'Air conditioner Split with photo', + archived: false, + notes: 'Equipment registered through the collaborator app (updated)', + number: '1997', + qrCode: 'http://equipamentos.grupoimc.com.br/app/equipamentos/8469c863-0f37-4e58-a6f5-af2adfb20a82', + equipmentType: { + id: 'b894bdb9-b46b-4162-98a5-08c3b111a3a0' + }, + location: { + id: location.id + } + }).then(getData) + + console.log('updatedEquipment', updatedEquipment) + assert.equal(updatedEquipment.name, 'Air conditioner Split with photo') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/locations/create-location-without-coordinates.js b/en/examples/locations/create-location-without-coordinates.js new file mode 100644 index 0000000..d5c0508 --- /dev/null +++ b/en/examples/locations/create-location-without-coordinates.js @@ -0,0 +1,43 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + const locationGroup = await client.get('/location-groups', { + params: { + page: 1, + perPage: 10, + nameEq: 'Guapiaçu' + } + }).then(getFistItem) + + console.log('locationGroup', locationGroup) + + const location = await client.post('/locations', { + name: 'Test location 2', + locationGroup: { + id: locationGroup.id + }, + address: { + number: '500', + postalCode: '15045606', + streetName: 'Manoel Freitas de Assunção', + neighborhood: 'Rio sella', + city: 'São josé do rio preto', + state: 'SP', + coords: null + } + }).then(getData) + + assert.equal(location.name, 'Test location 2') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/locations/create-location.js b/en/examples/locations/create-location.js new file mode 100644 index 0000000..e4ef72c --- /dev/null +++ b/en/examples/locations/create-location.js @@ -0,0 +1,44 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + const locationGroup = await client.get('/location-groups', { + params: { + page: 1, + perPage: 10, + nameEq: 'São Paulo' + } + }).then(getFistItem) + + const location = await client.post('/locations', { + name: 'Test location 2', + locationGroup: { + id: locationGroup.id + }, + address: { + number: 'S/N', + postalCode: '12345678', + streetName: 'Test street', + neighborhood: 'Test neighborhood', + city: 'Test city', + state: 'SP', + coords: { + latitude: -23.123456, + longitude: -45.123456 + } + } + }).then(getData) + + assert.equal(location.name, 'Test location 2') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/locations/get-location-service-providers.js b/en/examples/locations/get-location-service-providers.js new file mode 100644 index 0000000..74fd24b --- /dev/null +++ b/en/examples/locations/get-location-service-providers.js @@ -0,0 +1,80 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + // looking up any location to use when opening a maintenance + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '46849145851' + } + }).then(getFistItem) + + const result = await client.get(`/locations/${location.id}/service-providers`).then(getData) + + assert.deepEqual(result, { + items: [ + { + id: '23adcaa6-fd7f-48c3-b42d-57df81993edc', + segment: { + id: '1d8a6476-2f12-4766-8941-87d4ee4baf45' + }, + maintenanceTypes: [ + { + id: '574a1a6d-3f29-4356-8cdb-29bdb3c3ab32' + }, + { + id: '9d1c80ea-ceba-478a-8bca-3525b9dba873' + } + ], + company: { + id: '5dc173b9-f3c7-5fff-a5f9-f4bcecd3cdb9' + } + } + ], + pageInfo: { + hasNextPage: true, + hasPreviousPage: false, + page: 1, + pageCount: 4, + perPage: 2, + totalCount: 7 + } + }) + + const serviceProviderDetail = await client.get(`/locations/${location.id}/service-providers/${result.items[0].id}`).then(getData) + + assert.deepEqual(serviceProviderDetail, { + id: '23adcaa6-fd7f-48c3-b42d-57df81993edc', + segment: { + id: '1d8a6476-2f12-4766-8941-87d4ee4baf45', + name: '001 - Ar condicionado' + }, + maintenanceTypes: [ + { + id: '574a1a6d-3f29-4356-8cdb-29bdb3c3ab32', + name: 'Manutenção corretiva' + }, + { + id: '9d1c80ea-ceba-478a-8bca-3525b9dba873', + name: 'Instalação' + } + ], + company: { + id: '5dc173b9-f3c7-5fff-a5f9-f4bcecd3cdb9', + name: 'Field control - Fornecedor 8817' + } + }) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/maintenance-types/get-maintenance-types.js b/en/examples/maintenance-types/get-maintenance-types.js new file mode 100644 index 0000000..2ae1c37 --- /dev/null +++ b/en/examples/maintenance-types/get-maintenance-types.js @@ -0,0 +1,22 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + await client.get('/maintenance-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Visita técnica' + } + }).then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/maintenances/add-maintenance-comment-collaborator.js b/en/examples/maintenances/add-maintenance-comment-collaborator.js new file mode 100644 index 0000000..9cd53ee --- /dev/null +++ b/en/examples/maintenances/add-maintenance-comment-collaborator.js @@ -0,0 +1,52 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + // "message": "page must be an integer number, page must not be less than 1, perPage must be an integer number, perPage must not be greater than 100, perPage must not be less than 1", + const maintenance = await client.get('/maintenances', { + params: { + page: 1, + perPage: 1, + numberEq: '00013259' + } + }).then(getFistItem) + + assert.equal(maintenance.number, '00013259') + + const comment = await client.post(`/maintenances/${maintenance.id}/comments`, { + message: 'example comment 2', + archived: false, + type: 'COLLABORATOR', + postedBy: { + name: 'Leo', + externalId: 'leo-falco', + avatarUrl: 'https://avatars.githubusercontent.com/u/25820906' + } + }).then(getData) + + assert.equal(comment.message, 'example comment 2') + assert.equal(comment.type, 'COLLABORATOR') + assert.equal(comment.postedBy.id, '5dc173b9-f3c7-5fff-a5f9-f4bcecd3cdb9') + assert.equal(comment.postedBy.name, 'Leo') + assert.equal(comment.postedBy.avatarUrl, 'https://avatars.githubusercontent.com/u/25820906') + + const commentsPage = await client.get(`/maintenances/${maintenance.id}/comments`, { + params: { + page: 1, + perPage: 1 + } + }).then(getData) + + assert.equal(commentsPage.items.length, 1) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/maintenances/cancel-maintenance.js b/en/examples/maintenances/cancel-maintenance.js new file mode 100644 index 0000000..6ae31ac --- /dev/null +++ b/en/examples/maintenances/cancel-maintenance.js @@ -0,0 +1,34 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import { strictEqual } from 'node:assert' + +async function run () { + const payload = { + cancellationReason: 'The board of directors team decided to cancel such activities!' + } + + const pendingMaintenance = await client.get('/maintenances', { + params: { + page: 1, + perPage: 1, + statusIn: 'PENDING' + } + }).then(getFistItem) + + const canceledMaintenance = await client.post(`/maintenances/${pendingMaintenance.id}/actions/cancel`, payload) + .then(getData) + + strictEqual(pendingMaintenance.id, canceledMaintenance.id) + strictEqual(canceledMaintenance.status, 'CANCELED') + strictEqual(canceledMaintenance.statusDescription, payload.cancellationReason) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/maintenances/create-maintenance-comment-collaborator.js b/en/examples/maintenances/create-maintenance-comment-collaborator.js new file mode 100644 index 0000000..3293708 --- /dev/null +++ b/en/examples/maintenances/create-maintenance-comment-collaborator.js @@ -0,0 +1,75 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + // looking up any location to use when opening a maintenance + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '46849145851' + } + }).then(getFistItem) + + // looking up any segment to use when opening a maintenance + const segment = await client.get('/segments', { + params: { + page: 1, + perPage: 1, + nameEq: '001 - Ar condicionado' + } + }).then(getFistItem) + + // looking up any maintenance type to use when opening a maintenance + const maintenanceType = await client.get('/maintenance-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Manutenção corretiva' + } + }).then(getFistItem) + + const maintenance = await client.post('/maintenances', { + message: 'Maintenance with linked attachments', + location: { id: location.id }, + segment: { id: segment.id }, + maintenanceType: { id: maintenanceType.id } + }).then(getData) + + const comment = await client.post(`/maintenances/${maintenance.id}/comments`, { + message: 'example comment', + archived: false, + type: 'COLLABORATOR', + postedBy: { + name: 'Leo', + externalId: 'leo-falco', + avatarUrl: 'https://avatars.githubusercontent.com/u/25820906' + } + }).then(getData) + + assert.equal(comment.message, 'example comment') + assert.equal(comment.type, 'COLLABORATOR') + assert.equal(comment.postedBy.id, '5dc173b9-f3c7-5fff-a5f9-f4bcecd3cdb9') + assert.equal(comment.postedBy.name, 'Leo') + assert.equal(comment.postedBy.avatarUrl, 'https://avatars.githubusercontent.com/u/25820906') + + const commentsPage = await client.get(`/maintenances/${maintenance.id}/comments`, { + params: { + page: 1, + perPage: 1 + } + }).then(getData) + + assert.equal(commentsPage.items.length, 1) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/maintenances/create-maintenance-comment.js b/en/examples/maintenances/create-maintenance-comment.js new file mode 100644 index 0000000..d1eda5f --- /dev/null +++ b/en/examples/maintenances/create-maintenance-comment.js @@ -0,0 +1,75 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + // looking up any location to use when opening a maintenance + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '46849145851' + } + }).then(getFistItem) + + // looking up any segment to use when opening a maintenance + const segment = await client.get('/segments', { + params: { + page: 1, + perPage: 1, + nameEq: '001 - Ar condicionado' + } + }).then(getFistItem) + + // looking up any maintenance type to use when opening a maintenance + const maintenanceType = await client.get('/maintenance-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Manutenção corretiva' + } + }).then(getFistItem) + + const maintenance = await client.post('/maintenances', { + message: 'Maintenance with linked attachments', + location: { id: location.id }, + segment: { id: segment.id }, + maintenanceType: { id: maintenanceType.id } + }).then(getData) + + const comment = await client.post(`/maintenances/${maintenance.id}/comments`, { + message: 'example comment', + archived: false, + type: 'COMPANY', + postedBy: { + name: 'Leo', + externalId: 'leo-falco', + avatarUrl: 'https://avatars.githubusercontent.com/u/25820906' + } + }).then(getData) + + assert.equal(comment.message, 'example comment') + assert.equal(comment.type, 'COMPANY') + assert.equal(comment.postedBy.id, '5dc173b9-f3c7-5fff-a5f9-f4bcecd3cdb9') + assert.equal(comment.postedBy.name, 'Leo') + assert.equal(comment.postedBy.avatarUrl, 'https://avatars.githubusercontent.com/u/25820906') + + const commentsPage = await client.get(`/maintenances/${maintenance.id}/comments`, { + params: { + page: 1, + perPage: 1 + } + }).then(getData) + + assert.equal(commentsPage.items.length, 1) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/maintenances/create-maintenance-with-address.js b/en/examples/maintenances/create-maintenance-with-address.js new file mode 100644 index 0000000..dd61b75 --- /dev/null +++ b/en/examples/maintenances/create-maintenance-with-address.js @@ -0,0 +1,62 @@ +import assert from 'node:assert' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' + +async function run () { + // looking up any location to use when opening a maintenance + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '46849145851' + } + }).then(getFistItem) + + // looking up any segment to use when opening a maintenance + const segment = await client.get('/segments', { + params: { + page: 1, + perPage: 1, + nameEq: 'Ar condicionado' + } + }).then(getFistItem) + + // looking up any maintenance type to use when opening a maintenance + const maintenanceType = await client.get('/maintenance-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Manutenção corretiva' + } + }).then(getFistItem) + + // creating a maintenance with a custom address + const maintenance = await client.post('/maintenances', { + message: 'Maintenance with custom address', + location: { id: location.id }, + segment: { id: segment.id }, + maintenanceType: { id: maintenanceType.id }, + address: { + state: 'SP', + city: 'São José do Rio Preto', + neighborhood: 'Jardim Planalto', + street: 'Avenida Waldemar Freitas de Assunção', + zipCode: '15045606', + number: '400', + complement: 'BL 00 AP 00', + coords: { + latitude: -20.7605767, + longitude: -49.3862704 + } + } + }).then(getData) + + assert.equal(maintenance.message, 'Maintenance with custom address') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/maintenances/create-maintenance-with-attachment.js b/en/examples/maintenances/create-maintenance-with-attachment.js new file mode 100644 index 0000000..5d0b516 --- /dev/null +++ b/en/examples/maintenances/create-maintenance-with-attachment.js @@ -0,0 +1,161 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData, getFistItem, getItems } from '../../../core/utils.js' +import FormData from 'form-data' +import { readFileSync, readdirSync } from 'node:fs' +import { join, extname, basename } from 'node:path' +import { fileURLToPath } from 'node:url' +import assert from 'node:assert' + +// Node.js upload example based on the official AWS documentation +// Adaptations were made because the official documentation uses only plain HTML +// link to the original documentation: https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html#sigv4-post-example-file-upload + +// utility function that returns a buffer and file metadata from an absolute path +async function readFile (absoluteFilePath) { + const extension = extname(absoluteFilePath).replace('.', '') + const buffer = readFileSync(absoluteFilePath) + const name = basename(absoluteFilePath) + const size = buffer.byteLength + return { + name, + buffer, + size, + extension + } +} + +// utility function to build the payload in multipart/form-data format +async function buildFormData ({ credentials, file }) { + const form = new FormData() + for (const [key, value] of Object.entries(credentials.fields)) { + form.append(key, value) + } + + form.append('file', file.buffer) + + return form +} + +// function that returns the headers required by the AWS upload endpoint +async function buildUploadHeaders ({ formData }) { + const boundary = formData.getBoundary() + const contentLength = formData.getLengthSync() + const contentType = `multipart/form-data; boundary=${boundary}` + + return { + 'content-type': contentType, + 'content-length': contentLength + } +} + +async function run () { + // reading example files located in the "data" folder at the root of this project + const currentDirPath = fileURLToPath(import.meta.url) + const dataDirPath = join(currentDirPath, '../../../../data') + const fileNames = readdirSync(dataDirPath) + const absoluteFileNames = fileNames.map(fileName => join(dataDirPath, fileName)) + + // array holding metadata and buffer for the files + const files = await Promise.all(absoluteFileNames.map(readFile)) + + const attachments = [] + + for (const file of files) { + // request to obtain the credentials that will be used for the upload later + const credentials = await client + .post('/attachments/actions/generate-upload-credentials', { + size: file.size, + extension: file.extension + }) + .then(getData) + + // building the payload with the file in multipart/form-data format + // and additional fields with the credentials required for authentication + const formData = await buildFormData({ credentials, file }) + + // building the headers required by the upload endpoint + const headers = await buildUploadHeaders({ formData }) + + // uploading directly to AWS S3 + await client.post(credentials.baseUrl, formData, { headers }) + + // saving the file name and link to attach to the maintenance later + attachments.push({ + title: file.name, + link: credentials.link + }) + } + + // looking up any location to use when opening a maintenance + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '46849145851' + } + }).then(getFistItem) + + // looking up any segment to use when opening a maintenance + const segment = await client.get('/segments', { + params: { + page: 1, + perPage: 1, + nameEq: '001 - Ar condicionado' + } + }).then(getFistItem) + + // looking up any maintenance type to use when opening a maintenance + const maintenanceType = await client.get('/maintenance-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Manutenção corretiva' + } + }).then(getFistItem) + + // creating a maintenance passing the attachments as an argument + const maintenance = await client.post('/maintenances', { + message: 'Maintenance with linked attachments', + location: { id: location.id }, + segment: { id: segment.id }, + maintenanceType: { id: maintenanceType.id }, + attachments + }).then(getData) + + // querying the page of attachments linked to the maintenance + const createdAttachments = await client.get(`maintenances/${maintenance.id}/attachments`, { + params: { + page: 1, + perPage: 10 + } + }).then(getItems) + + // checks if the number of attachments on the maintenance equals the expected count + assert.equal(createdAttachments.length, files.length) + + for (const attachment of createdAttachments) { + const file = files.find((file) => file.name === attachment.title) + + // checks if the title equals the expected one + assert.equal(attachment.title, file.name) + + // queries the file headers using the generated link + const { status, headers } = await client.head(attachment.link) + + // checks if 200 is returned when accessing the file link + assert.equal(status, 200) + + // checks if the file size equals the expected one + assert.equal(headers['content-length'], file.size) + } +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/maintenances/create-maintenance-with-schedule-suggestion.js b/en/examples/maintenances/create-maintenance-with-schedule-suggestion.js new file mode 100644 index 0000000..bf44c49 --- /dev/null +++ b/en/examples/maintenances/create-maintenance-with-schedule-suggestion.js @@ -0,0 +1,60 @@ +import assert from 'node:assert' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' + +async function run () { + // looking up any location to use when opening a maintenance + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '46849145851' + } + }).then(getFistItem) + + // looking up any segment to use when opening a maintenance + const segment = await client.get('/segments', { + params: { + page: 1, + perPage: 1, + nameEq: '001 - Ar condicionado' + } + }).then(getFistItem) + + // looking up any maintenance type to use when opening a maintenance + const maintenanceType = await client.get('/maintenance-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Manutenção corretiva' + } + }).then(getFistItem) + + const currentYear = new Date().getFullYear() + // creating a maintenance with a schedule suggestion + const maintenance = await client.post('/maintenances', { + message: 'Maintenance with linked attachments', + location: { id: location.id }, + segment: { id: segment.id }, + maintenanceType: { id: maintenanceType.id }, + scheduleSuggestions: [ + { + date: new Date().toISOString().split('T')[0], + time: '17:00' + }, + { + date: `${currentYear}-12-31`, + time: '23:59' + } + ] + }).then(getData) + + assert.equal(maintenance.message, 'Maintenance with linked attachments') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/maintenances/get-canceled-maintenances.js b/en/examples/maintenances/get-canceled-maintenances.js new file mode 100644 index 0000000..c5e756a --- /dev/null +++ b/en/examples/maintenances/get-canceled-maintenances.js @@ -0,0 +1,32 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + const maintenances = await client.get('/maintenances', { + params: { + page: 1, + perPage: 10, + direction: 'desc', + statusIn: 'CANCELED', + openedAtGte: '2025-01-01T00:00:00.000Z', + openedAtLte: '2025-06-30T23:59:59.999Z' + + } + }).then(getData) + + console.log('Total:', maintenances.length) + + for (const maintenance of maintenances) { + console.log('Maintenance:', maintenance) + } +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/maintenances/get-maintenance-form-answers.js b/en/examples/maintenances/get-maintenance-form-answers.js new file mode 100644 index 0000000..a319453 --- /dev/null +++ b/en/examples/maintenances/get-maintenance-form-answers.js @@ -0,0 +1,21 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + await client.get('/maintenances/e1c823ff-7000-4fde-90a6-aa4596169a76/form-answers/be46fbc1-fd70-4583-bad3-24403bf54ea5', { + params: { + page: 1, + perPage: 10 + } + }).then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/maintenances/maintenance-stress-test.js b/en/examples/maintenances/maintenance-stress-test.js new file mode 100644 index 0000000..4bc8205 --- /dev/null +++ b/en/examples/maintenances/maintenance-stress-test.js @@ -0,0 +1,63 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' + +async function run () { + const REQUEST_QUANTITY = 1 + + let completed = 0 + const promises = Array.from({ length: REQUEST_QUANTITY }).map(async (_, index) => { + const staredAt = Date.now() + + return { + index, + response: await client.get('/maintenances', { + params: { + page: 1, + perPage: 10 + } + }) + .then(res => { + completed++ + const completedAt = Date.now() + Object.assign(res, { + staredAt, + completedAt, + durationSeconds: (completedAt - staredAt) / 1000 + }) + console.log(`completed: ${completed}`) + console.log('durationSeconds: ', res.durationSeconds) + return res + }) + .catch(err => { + completed++ + const completedAt = Date.now() + Object.assign(err, { + staredAt, + completedAt, + durationSeconds: (completedAt - staredAt) / 1000 + }) + + console.log(`completed: ${completed}`) + console.log('durationSeconds: ', err.durationSeconds) + throw err + }) + } + }) + + const responses = await Promise.allSettled(promises) + + const successCount = responses.filter(result => result?.value?.response?.status / 100 === 2).length + const errorCount = responses.length - successCount + + console.log('successCount: ', successCount) + console.log('errorCount: ', errorCount) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/maintenances/reallocate-maintenance.js b/en/examples/maintenances/reallocate-maintenance.js new file mode 100644 index 0000000..a123796 --- /dev/null +++ b/en/examples/maintenances/reallocate-maintenance.js @@ -0,0 +1,32 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import { strictEqual } from 'node:assert' + +async function run () { + const pendingMaintenance = await client.get('/maintenances', { + params: { + page: 1, + perPage: 1, + statusIn: 'CANCELED' + } + }).then(getFistItem) + + const canceledMaintenance = await client.post(`/maintenances/${pendingMaintenance.id}/actions/reallocate`, { + message: 'This is a test reallocation reason!' + }) + .then(getData) + + strictEqual(pendingMaintenance.id, canceledMaintenance.id) + strictEqual(canceledMaintenance.status, 'NEW') + strictEqual(canceledMaintenance.statusDescription, 'This is a test reallocation reason!') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/maintenances/reopen-maintenance.js b/en/examples/maintenances/reopen-maintenance.js new file mode 100644 index 0000000..562a2a8 --- /dev/null +++ b/en/examples/maintenances/reopen-maintenance.js @@ -0,0 +1,32 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import { strictEqual } from 'node:assert' + +async function run () { + const pendingMaintenance = await client.get('/maintenances', { + params: { + page: 1, + perPage: 1, + statusIn: 'CANCELED' + } + }).then(getFistItem) + + const canceledMaintenance = await client.post(`/maintenances/${pendingMaintenance.id}/actions/reopen`, { + reopeningReason: 'This is a test reopening reason!' + }) + .then(getData) + + strictEqual(pendingMaintenance.id, canceledMaintenance.id) + strictEqual(canceledMaintenance.status, 'NEW') + strictEqual(canceledMaintenance.statusDescription, 'This is a test reopening reason!') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/pendencies/conclude-pendency.js b/en/examples/pendencies/conclude-pendency.js new file mode 100644 index 0000000..872116a --- /dev/null +++ b/en/examples/pendencies/conclude-pendency.js @@ -0,0 +1,16 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + await client.post('/pendencies/e5a288a5-af6f-4b2c-ab8f-abd4e21178c2/actions/conclude').then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/pendencies/create-pendency.js b/en/examples/pendencies/create-pendency.js new file mode 100644 index 0000000..fee864a --- /dev/null +++ b/en/examples/pendencies/create-pendency.js @@ -0,0 +1,42 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' + +async function run () { + // Get companies that contain "Field Control" in their names (case-insensitive) + // Only one item per page + // Page one or first page + const company = await client.get('/companies', { + params: { + page: 1, + perPage: 1, + nameEq: 'Field Control - Fornecedor 8817' + } + }).then(getFistItem) + + console.log('company: ', company) + + const pendencyType = await client.get('/pendencies-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Falta documento' + } + }).then(getFistItem) + + await client.post('/pendencies', { + title: '🚨 Test pendency created via API', + description: 'This is a test pendency created via API', + company: { id: company.id }, + pendencyType: { id: pendencyType.id } + }).then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/pendencies/get-pendencies.js b/en/examples/pendencies/get-pendencies.js new file mode 100644 index 0000000..7f94286 --- /dev/null +++ b/en/examples/pendencies/get-pendencies.js @@ -0,0 +1,22 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + await client.get('/pendencies', { + params: { + page: 1, + perPage: 20, + titleEq: 'awdawd' + } + }).then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/en/examples/segments/get-segments.js b/en/examples/segments/get-segments.js new file mode 100644 index 0000000..3cb2cc8 --- /dev/null +++ b/en/examples/segments/get-segments.js @@ -0,0 +1,22 @@ +// Example based on the documentation available at https://amonamarth.fieldcontrol.com.br/docs +// The data provided are only test examples and do not represent the truth + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + await client.get('/segments', { + params: { + page: 1, + perPage: 1, + nameEq: 'Ar condicionado é' + } + }).then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/README.md b/es/README.md new file mode 100644 index 0000000..296cf56 --- /dev/null +++ b/es/README.md @@ -0,0 +1,40 @@ +# Amonamarth Examples (Español) + +![Field Control ♥](https://img.shields.io/badge/Field%20Control-♥-blue.svg) +[![GitHub Super-Linter](https://github.com/FieldControl/amonamarth-examples/workflows/Lint/badge.svg)](https://github.com/marketplace/actions/super-linter) + + +:volcano: Amon Amarth, la API pública de gestión de proveedores, es un servicio web REST que expone recursos para facilitar que las empresas integren sus otros sistemas. + +Este es un repositorio auxiliar que contiene fragmentos de código y ejemplos de uso. Esta es la versión en **español** de los ejemplos. Para la versión en inglés, vea [en/README.md](../en/README.md). Para la versión en portugués, vea [pt/README.md](../pt/README.md). + +## Requisitos previos para ejecutar el proyecto + +- Gestor de versiones de Node.js. Si no tiene nvm, instálelo siguiendo estos pasos + - [nvm para windows](https://github.com/coreybutler/nvm-windows) + - [nvm para mac/linux](https://github.com/nvm-sh/nvm#installing-and-updating) + +- Clone este repositorio localmente `git clone https://github.com/LeoFalco/amonamarth-examples.git` + +- En la carpeta del proyecto ejecute los siguientes comandos + + ```sh + nvm install # para instalar node + nvm use # cambia a la versión de Node.js instalada + npm install # instala las dependencias del proyecto + ``` + +- El proyecto usa autenticación por API key. Puede declarar la suya dentro de un archivo llamado `.env` +como se muestra en la imagen: + + ![image](https://user-images.githubusercontent.com/25820906/178081437-c5939851-116e-44e1-8527-91dc6a63900c.png) + +## Ejecutando archivos + +Los archivos de ejemplo en español están en la carpeta `es/ejemplos`. Puede ejecutarlos directamente con Node.js + +```sh + node es/ejemplos/mantenimientos/crear-mantenimiento-con-adjunto.js +``` + +> El código compartido (cliente HTTP y utilidades) se encuentra en la carpeta `core` en la raíz del repositorio. diff --git a/es/ejemplos/empresas/empresas-cercanas-2.js b/es/ejemplos/empresas/empresas-cercanas-2.js new file mode 100644 index 0000000..a6cc16d --- /dev/null +++ b/es/ejemplos/empresas/empresas-cercanas-2.js @@ -0,0 +1,28 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' + +async function run () { + // Obtener empresas cercanas a "Avenida Abrão josé de lima 659" + const result = await client.post('/companies/actions/nearby', { + formattedAddress: 'Avenida Abrão josé de lima 659', + postalCode: '15110000', // opcional + countryCode: null // opcional + }, { + params: { + page: 1, + perPage: 2 + } + }) + + console.log('headers: ', result.headers) + console.log('data: ', result.data) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/empresas/empresas-cercanas.js b/es/ejemplos/empresas/empresas-cercanas.js new file mode 100644 index 0000000..93f3776 --- /dev/null +++ b/es/ejemplos/empresas/empresas-cercanas.js @@ -0,0 +1,96 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + // Obtener empresas cercanas a "Avenida Abrão josé de lima 659" + const result = await client.post('/companies/actions/nearby', { + formattedAddress: 'Avenida Abrão josé de lima 659', + postalCode: '15110000', // opcional + countryCode: null // opcional + }, { + params: { + page: 1, + perPage: 2 + } + }).then(getData) + + assert.deepEqual(result, { + items: [ + { + id: '5a135059-a054-46d1-b431-fb0f1036ccd4', + name: 'Field Control - Fornecedor 8817', + relativeDistance: { + distanceInMeters: 1680, // el más cercano primero + relativeTo: { + latitude: -20.7972941, + longitude: -49.221242 + } + }, + address: { + city: 'Guapiaçu', + complement: null, + coords: { + latitude: -20.807428, + longitude: -49.2332 + }, + countryCode: 'BRA', + neighborhood: 'Guapiaçu', + number: '686', + state: 'São Paulo', + street: 'abrao jose de lima', + zipCode: '15110000' + }, + archived: false, + avatarUrl: 'https://s3.amazonaws.com/attachments.fieldcontrol.com.br/accounts/8817/company-logo.png', + createdAt: '2019-08-01T12:24:18Z' + }, + { + id: 'e75d361b-ceee-4c83-9962-b5ecb4272224', + name: 'Designers', + relativeDistance: { + distanceInMeters: 16463, + relativeTo: { + latitude: -20.7972941, + longitude: -49.221242 + } + }, + address: { + city: 'São José do Rio Preto', + complement: null, + coords: { + latitude: -20.8072548, + longitude: -49.3790862 + }, + countryCode: 'AUS', + neighborhood: 'Centro', + number: '12', + state: 'SP', + street: 'Rua Coronel Spínola de Castro', + zipCode: '15015500' + }, + archived: false, + avatarUrl: 'assets/images/avatars/avatar.jpg', + createdAt: '2020-08-04T19:26:48Z' + } + ], + pageInfo: { + hasNextPage: true, + hasPreviousPage: false, + page: 1, + pageCount: 4, + perPage: 2, + totalCount: 7 + } + }) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/empresas/obtener-empresas.js b/es/ejemplos/empresas/obtener-empresas.js new file mode 100644 index 0000000..7530058 --- /dev/null +++ b/es/ejemplos/empresas/obtener-empresas.js @@ -0,0 +1,78 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + // Obtener empresas con nombre exacto igual a "Field Control" + // Solo un elemento por página + // Página uno o primera página + await client.get('/companies', { + params: { + page: 1, + perPage: 1, + nameEq: 'Field Control' + } + }).then(getData) + + // Obtener empresas con nombre exacto igual a "Field Control" + // Solo dos elementos por página + // Página uno o primera página + // De más antiguo a más reciente + await client.get('/companies', { + params: { + page: 1, + perPage: 2, + nameEq: 'Field Control', + orderBy: 'createdAt', + direction: 'asc' + } + }).then(getData) + + // Obtener empresas que tengan un nombre idéntico a "Resolv" + // Solo un elemento por página + // Página uno o primera página + await client.get('/companies', { + params: { + page: 1, + perPage: 1, + nameEq: 'Resolv' + } + }).then(getData) + + // Solo dos elementos por página + // Página uno o primera página + // Con el nombre de la Z a la A + await client.get('/companies', { + params: { + page: 1, + perPage: 2, + orderBy: 'name', + direction: 'desc' + } + }).then(getData) + + // Solo dos elementos por página + // Página uno o primera página + // De más lejano a más cercano + // El campo "distanceRelativeTo" debe ser una cadena que contenga la latitud y la longitud, respectivamente ("latitud,longitud") + // El campo "distanceRelativeTo" solo puede proporcionarse si el campo orderColumn es igual a "distance" + // Las empresas sin coordenadas se colocarán al final de la lista + await client.get('/companies', { + params: { + page: 1, + perPage: 2, + orderBy: 'distance', + direction: 'desc', + distanceRelativeTo: '37.7749,-122.4194' + } + }).then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/empresas/obtener-uso-empresas-cercanas.js b/es/ejemplos/empresas/obtener-uso-empresas-cercanas.js new file mode 100644 index 0000000..62209c9 --- /dev/null +++ b/es/ejemplos/empresas/obtener-uso-empresas-cercanas.js @@ -0,0 +1,29 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + // Obtener el historial de uso de geolocalización de empresas + const result = await client.get('/companies/actions/nearby/usage').then(getData) + + assert.deepEqual(result, { + items: [ + { + id: 'eyJwayI6IlVTQUdFIzEiLCJzayI6IjIwMjMtMDcifQ==', + month: '2023-07', + quota: 2000, + usedQuota: 10 + } + ] + }) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/equipos/cambiar-ubicacion-del-equipo.js b/es/ejemplos/equipos/cambiar-ubicacion-del-equipo.js new file mode 100644 index 0000000..1c14e28 --- /dev/null +++ b/es/ejemplos/equipos/cambiar-ubicacion-del-equipo.js @@ -0,0 +1,48 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + const equipment = await client.get('/equipments', { + params: { + page: 1, + perPage: 1, + numberEq: '1997' + } + }).then(getFistItem) + + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '08980888015' + } + }).then(getFistItem) + + const updatedEquipment = await client.put(`/equipments/${equipment.id}`, { + name: 'Aire acondicionado Split con foto', + archived: false, + notes: 'Equipo registrado a través de la app del colaborador (actualizado)', + number: '1997', + qrCode: 'http://equipamentos.grupoimc.com.br/app/equipamentos/8469c863-0f37-4e58-a6f5-af2adfb20a82', + equipmentType: { + id: 'b894bdb9-b46b-4162-98a5-08c3b111a3a0' + }, + location: { + id: location.id + } + }).then(getData) + + console.log('updatedEquipment', updatedEquipment) + assert.equal(updatedEquipment.name, 'Aire acondicionado Split con foto') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/mantenimientos/agregar-comentario-colaborador-al-mantenimiento.js b/es/ejemplos/mantenimientos/agregar-comentario-colaborador-al-mantenimiento.js new file mode 100644 index 0000000..062228e --- /dev/null +++ b/es/ejemplos/mantenimientos/agregar-comentario-colaborador-al-mantenimiento.js @@ -0,0 +1,52 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + // "message": "page must be an integer number, page must not be less than 1, perPage must be an integer number, perPage must not be greater than 100, perPage must not be less than 1", + const maintenance = await client.get('/maintenances', { + params: { + page: 1, + perPage: 1, + numberEq: '00013259' + } + }).then(getFistItem) + + assert.equal(maintenance.number, '00013259') + + const comment = await client.post(`/maintenances/${maintenance.id}/comments`, { + message: 'comentario de ejemplo 2', + archived: false, + type: 'COLLABORATOR', + postedBy: { + name: 'Leo', + externalId: 'leo-falco', + avatarUrl: 'https://avatars.githubusercontent.com/u/25820906' + } + }).then(getData) + + assert.equal(comment.message, 'comentario de ejemplo 2') + assert.equal(comment.type, 'COLLABORATOR') + assert.equal(comment.postedBy.id, '5dc173b9-f3c7-5fff-a5f9-f4bcecd3cdb9') + assert.equal(comment.postedBy.name, 'Leo') + assert.equal(comment.postedBy.avatarUrl, 'https://avatars.githubusercontent.com/u/25820906') + + const commentsPage = await client.get(`/maintenances/${maintenance.id}/comments`, { + params: { + page: 1, + perPage: 1 + } + }).then(getData) + + assert.equal(commentsPage.items.length, 1) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/mantenimientos/cancelar-mantenimiento.js b/es/ejemplos/mantenimientos/cancelar-mantenimiento.js new file mode 100644 index 0000000..2f59590 --- /dev/null +++ b/es/ejemplos/mantenimientos/cancelar-mantenimiento.js @@ -0,0 +1,34 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import { strictEqual } from 'node:assert' + +async function run () { + const payload = { + cancellationReason: '¡El equipo de la junta directiva decidió cancelar dichas actividades!' + } + + const pendingMaintenance = await client.get('/maintenances', { + params: { + page: 1, + perPage: 1, + statusIn: 'PENDING' + } + }).then(getFistItem) + + const canceledMaintenance = await client.post(`/maintenances/${pendingMaintenance.id}/actions/cancel`, payload) + .then(getData) + + strictEqual(pendingMaintenance.id, canceledMaintenance.id) + strictEqual(canceledMaintenance.status, 'CANCELED') + strictEqual(canceledMaintenance.statusDescription, payload.cancellationReason) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/mantenimientos/crear-mantenimiento-con-adjunto.js b/es/ejemplos/mantenimientos/crear-mantenimiento-con-adjunto.js new file mode 100644 index 0000000..bce0b82 --- /dev/null +++ b/es/ejemplos/mantenimientos/crear-mantenimiento-con-adjunto.js @@ -0,0 +1,161 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData, getFistItem, getItems } from '../../../core/utils.js' +import FormData from 'form-data' +import { readFileSync, readdirSync } from 'node:fs' +import { join, extname, basename } from 'node:path' +import { fileURLToPath } from 'node:url' +import assert from 'node:assert' + +// Ejemplo de carga con Node.js basado en la documentación oficial de AWS +// Se hicieron adaptaciones porque la documentación oficial usa solo HTML plano +// enlace a la documentación original: https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html#sigv4-post-example-file-upload + +// función utilitaria que devuelve un buffer y los metadatos del archivo a partir de una ruta absoluta +async function readFile (absoluteFilePath) { + const extension = extname(absoluteFilePath).replace('.', '') + const buffer = readFileSync(absoluteFilePath) + const name = basename(absoluteFilePath) + const size = buffer.byteLength + return { + name, + buffer, + size, + extension + } +} + +// función utilitaria para construir el payload en formato multipart/form-data +async function buildFormData ({ credentials, file }) { + const form = new FormData() + for (const [key, value] of Object.entries(credentials.fields)) { + form.append(key, value) + } + + form.append('file', file.buffer) + + return form +} + +// función que devuelve los headers requeridos por el endpoint de carga de AWS +async function buildUploadHeaders ({ formData }) { + const boundary = formData.getBoundary() + const contentLength = formData.getLengthSync() + const contentType = `multipart/form-data; boundary=${boundary}` + + return { + 'content-type': contentType, + 'content-length': contentLength + } +} + +async function run () { + // leyendo los archivos de ejemplo ubicados en la carpeta "data" en la raíz de este proyecto + const currentDirPath = fileURLToPath(import.meta.url) + const dataDirPath = join(currentDirPath, '../../../../data') + const fileNames = readdirSync(dataDirPath) + const absoluteFileNames = fileNames.map(fileName => join(dataDirPath, fileName)) + + // arreglo que contiene los metadatos y el buffer de los archivos + const files = await Promise.all(absoluteFileNames.map(readFile)) + + const attachments = [] + + for (const file of files) { + // solicitud para obtener las credenciales que se usarán más adelante para la carga + const credentials = await client + .post('/attachments/actions/generate-upload-credentials', { + size: file.size, + extension: file.extension + }) + .then(getData) + + // construyendo el payload con el archivo en formato multipart/form-data + // y campos adicionales con las credenciales requeridas para la autenticación + const formData = await buildFormData({ credentials, file }) + + // construyendo los headers requeridos por el endpoint de carga + const headers = await buildUploadHeaders({ formData }) + + // cargando directamente a AWS S3 + await client.post(credentials.baseUrl, formData, { headers }) + + // guardando el nombre y el enlace del archivo para adjuntarlo al mantenimiento más adelante + attachments.push({ + title: file.name, + link: credentials.link + }) + } + + // buscando cualquier ubicación para usar al abrir un mantenimiento + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '46849145851' + } + }).then(getFistItem) + + // buscando cualquier segmento para usar al abrir un mantenimiento + const segment = await client.get('/segments', { + params: { + page: 1, + perPage: 1, + nameEq: '001 - Ar condicionado' + } + }).then(getFistItem) + + // buscando cualquier tipo de mantenimiento para usar al abrir un mantenimiento + const maintenanceType = await client.get('/maintenance-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Manutenção corretiva' + } + }).then(getFistItem) + + // creando un mantenimiento pasando los adjuntos como argumento + const maintenance = await client.post('/maintenances', { + message: 'Mantenimiento con adjuntos vinculados', + location: { id: location.id }, + segment: { id: segment.id }, + maintenanceType: { id: maintenanceType.id }, + attachments + }).then(getData) + + // consultando la página de adjuntos vinculados al mantenimiento + const createdAttachments = await client.get(`maintenances/${maintenance.id}/attachments`, { + params: { + page: 1, + perPage: 10 + } + }).then(getItems) + + // verifica si la cantidad de adjuntos del mantenimiento es igual a la cantidad esperada + assert.equal(createdAttachments.length, files.length) + + for (const attachment of createdAttachments) { + const file = files.find((file) => file.name === attachment.title) + + // verifica si el título es igual al esperado + assert.equal(attachment.title, file.name) + + // consulta los headers del archivo usando el enlace generado + const { status, headers } = await client.head(attachment.link) + + // verifica si se devuelve 200 al acceder al enlace del archivo + assert.equal(status, 200) + + // verifica si el tamaño del archivo es igual al esperado + assert.equal(headers['content-length'], file.size) + } +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/mantenimientos/crear-mantenimiento-con-comentario-colaborador.js b/es/ejemplos/mantenimientos/crear-mantenimiento-con-comentario-colaborador.js new file mode 100644 index 0000000..271bdcf --- /dev/null +++ b/es/ejemplos/mantenimientos/crear-mantenimiento-con-comentario-colaborador.js @@ -0,0 +1,75 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + // buscando cualquier ubicación para usar al abrir un mantenimiento + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '46849145851' + } + }).then(getFistItem) + + // buscando cualquier segmento para usar al abrir un mantenimiento + const segment = await client.get('/segments', { + params: { + page: 1, + perPage: 1, + nameEq: '001 - Ar condicionado' + } + }).then(getFistItem) + + // buscando cualquier tipo de mantenimiento para usar al abrir un mantenimiento + const maintenanceType = await client.get('/maintenance-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Manutenção corretiva' + } + }).then(getFistItem) + + const maintenance = await client.post('/maintenances', { + message: 'Mantenimiento con adjuntos vinculados', + location: { id: location.id }, + segment: { id: segment.id }, + maintenanceType: { id: maintenanceType.id } + }).then(getData) + + const comment = await client.post(`/maintenances/${maintenance.id}/comments`, { + message: 'comentario de ejemplo', + archived: false, + type: 'COLLABORATOR', + postedBy: { + name: 'Leo', + externalId: 'leo-falco', + avatarUrl: 'https://avatars.githubusercontent.com/u/25820906' + } + }).then(getData) + + assert.equal(comment.message, 'comentario de ejemplo') + assert.equal(comment.type, 'COLLABORATOR') + assert.equal(comment.postedBy.id, '5dc173b9-f3c7-5fff-a5f9-f4bcecd3cdb9') + assert.equal(comment.postedBy.name, 'Leo') + assert.equal(comment.postedBy.avatarUrl, 'https://avatars.githubusercontent.com/u/25820906') + + const commentsPage = await client.get(`/maintenances/${maintenance.id}/comments`, { + params: { + page: 1, + perPage: 1 + } + }).then(getData) + + assert.equal(commentsPage.items.length, 1) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/mantenimientos/crear-mantenimiento-con-comentario.js b/es/ejemplos/mantenimientos/crear-mantenimiento-con-comentario.js new file mode 100644 index 0000000..137c02e --- /dev/null +++ b/es/ejemplos/mantenimientos/crear-mantenimiento-con-comentario.js @@ -0,0 +1,75 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + // buscando cualquier ubicación para usar al abrir un mantenimiento + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '46849145851' + } + }).then(getFistItem) + + // buscando cualquier segmento para usar al abrir un mantenimiento + const segment = await client.get('/segments', { + params: { + page: 1, + perPage: 1, + nameEq: '001 - Ar condicionado' + } + }).then(getFistItem) + + // buscando cualquier tipo de mantenimiento para usar al abrir un mantenimiento + const maintenanceType = await client.get('/maintenance-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Manutenção corretiva' + } + }).then(getFistItem) + + const maintenance = await client.post('/maintenances', { + message: 'Mantenimiento con adjuntos vinculados', + location: { id: location.id }, + segment: { id: segment.id }, + maintenanceType: { id: maintenanceType.id } + }).then(getData) + + const comment = await client.post(`/maintenances/${maintenance.id}/comments`, { + message: 'comentario de ejemplo', + archived: false, + type: 'COMPANY', + postedBy: { + name: 'Leo', + externalId: 'leo-falco', + avatarUrl: 'https://avatars.githubusercontent.com/u/25820906' + } + }).then(getData) + + assert.equal(comment.message, 'comentario de ejemplo') + assert.equal(comment.type, 'COMPANY') + assert.equal(comment.postedBy.id, '5dc173b9-f3c7-5fff-a5f9-f4bcecd3cdb9') + assert.equal(comment.postedBy.name, 'Leo') + assert.equal(comment.postedBy.avatarUrl, 'https://avatars.githubusercontent.com/u/25820906') + + const commentsPage = await client.get(`/maintenances/${maintenance.id}/comments`, { + params: { + page: 1, + perPage: 1 + } + }).then(getData) + + assert.equal(commentsPage.items.length, 1) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/mantenimientos/crear-mantenimiento-con-direccion.js b/es/ejemplos/mantenimientos/crear-mantenimiento-con-direccion.js new file mode 100644 index 0000000..1356e6d --- /dev/null +++ b/es/ejemplos/mantenimientos/crear-mantenimiento-con-direccion.js @@ -0,0 +1,62 @@ +import assert from 'node:assert' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' + +async function run () { + // buscando cualquier ubicación para usar al abrir un mantenimiento + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '46849145851' + } + }).then(getFistItem) + + // buscando cualquier segmento para usar al abrir un mantenimiento + const segment = await client.get('/segments', { + params: { + page: 1, + perPage: 1, + nameEq: 'Ar condicionado' + } + }).then(getFistItem) + + // buscando cualquier tipo de mantenimiento para usar al abrir un mantenimiento + const maintenanceType = await client.get('/maintenance-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Manutenção corretiva' + } + }).then(getFistItem) + + // creando un mantenimiento con una dirección personalizada + const maintenance = await client.post('/maintenances', { + message: 'Mantenimiento con dirección personalizada', + location: { id: location.id }, + segment: { id: segment.id }, + maintenanceType: { id: maintenanceType.id }, + address: { + state: 'SP', + city: 'São José do Rio Preto', + neighborhood: 'Jardim Planalto', + street: 'Avenida Waldemar Freitas de Assunção', + zipCode: '15045606', + number: '400', + complement: 'BL 00 AP 00', + coords: { + latitude: -20.7605767, + longitude: -49.3862704 + } + } + }).then(getData) + + assert.equal(maintenance.message, 'Mantenimiento con dirección personalizada') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/mantenimientos/crear-mantenimiento-con-sugerencia-de-agenda.js b/es/ejemplos/mantenimientos/crear-mantenimiento-con-sugerencia-de-agenda.js new file mode 100644 index 0000000..897371d --- /dev/null +++ b/es/ejemplos/mantenimientos/crear-mantenimiento-con-sugerencia-de-agenda.js @@ -0,0 +1,60 @@ +import assert from 'node:assert' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' + +async function run () { + // buscando cualquier ubicación para usar al abrir un mantenimiento + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '46849145851' + } + }).then(getFistItem) + + // buscando cualquier segmento para usar al abrir un mantenimiento + const segment = await client.get('/segments', { + params: { + page: 1, + perPage: 1, + nameEq: '001 - Ar condicionado' + } + }).then(getFistItem) + + // buscando cualquier tipo de mantenimiento para usar al abrir un mantenimiento + const maintenanceType = await client.get('/maintenance-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Manutenção corretiva' + } + }).then(getFistItem) + + const currentYear = new Date().getFullYear() + // creando un mantenimiento con una sugerencia de agenda + const maintenance = await client.post('/maintenances', { + message: 'Mantenimiento con adjuntos vinculados', + location: { id: location.id }, + segment: { id: segment.id }, + maintenanceType: { id: maintenanceType.id }, + scheduleSuggestions: [ + { + date: new Date().toISOString().split('T')[0], + time: '17:00' + }, + { + date: `${currentYear}-12-31`, + time: '23:59' + } + ] + }).then(getData) + + assert.equal(maintenance.message, 'Mantenimiento con adjuntos vinculados') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/mantenimientos/obtener-mantenimientos-cancelados.js b/es/ejemplos/mantenimientos/obtener-mantenimientos-cancelados.js new file mode 100644 index 0000000..2572cc9 --- /dev/null +++ b/es/ejemplos/mantenimientos/obtener-mantenimientos-cancelados.js @@ -0,0 +1,32 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + const maintenances = await client.get('/maintenances', { + params: { + page: 1, + perPage: 10, + direction: 'desc', + statusIn: 'CANCELED', + openedAtGte: '2025-01-01T00:00:00.000Z', + openedAtLte: '2025-06-30T23:59:59.999Z' + + } + }).then(getData) + + console.log('Total:', maintenances.length) + + for (const maintenance of maintenances) { + console.log('Mantenimiento:', maintenance) + } +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/mantenimientos/obtener-respuestas-de-formularios-del-mantenimiento.js b/es/ejemplos/mantenimientos/obtener-respuestas-de-formularios-del-mantenimiento.js new file mode 100644 index 0000000..fc633f6 --- /dev/null +++ b/es/ejemplos/mantenimientos/obtener-respuestas-de-formularios-del-mantenimiento.js @@ -0,0 +1,21 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + await client.get('/maintenances/e1c823ff-7000-4fde-90a6-aa4596169a76/form-answers/be46fbc1-fd70-4583-bad3-24403bf54ea5', { + params: { + page: 1, + perPage: 10 + } + }).then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/mantenimientos/prueba-de-estres-mantenimientos.js b/es/ejemplos/mantenimientos/prueba-de-estres-mantenimientos.js new file mode 100644 index 0000000..58a2bad --- /dev/null +++ b/es/ejemplos/mantenimientos/prueba-de-estres-mantenimientos.js @@ -0,0 +1,63 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' + +async function run () { + const REQUEST_QUANTITY = 1 + + let completed = 0 + const promises = Array.from({ length: REQUEST_QUANTITY }).map(async (_, index) => { + const staredAt = Date.now() + + return { + index, + response: await client.get('/maintenances', { + params: { + page: 1, + perPage: 10 + } + }) + .then(res => { + completed++ + const completedAt = Date.now() + Object.assign(res, { + staredAt, + completedAt, + durationSeconds: (completedAt - staredAt) / 1000 + }) + console.log(`completed: ${completed}`) + console.log('durationSeconds: ', res.durationSeconds) + return res + }) + .catch(err => { + completed++ + const completedAt = Date.now() + Object.assign(err, { + staredAt, + completedAt, + durationSeconds: (completedAt - staredAt) / 1000 + }) + + console.log(`completed: ${completed}`) + console.log('durationSeconds: ', err.durationSeconds) + throw err + }) + } + }) + + const responses = await Promise.allSettled(promises) + + const successCount = responses.filter(result => result?.value?.response?.status / 100 === 2).length + const errorCount = responses.length - successCount + + console.log('successCount: ', successCount) + console.log('errorCount: ', errorCount) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/mantenimientos/reabrir-mantenimiento.js b/es/ejemplos/mantenimientos/reabrir-mantenimiento.js new file mode 100644 index 0000000..2e54234 --- /dev/null +++ b/es/ejemplos/mantenimientos/reabrir-mantenimiento.js @@ -0,0 +1,32 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import { strictEqual } from 'node:assert' + +async function run () { + const pendingMaintenance = await client.get('/maintenances', { + params: { + page: 1, + perPage: 1, + statusIn: 'CANCELED' + } + }).then(getFistItem) + + const canceledMaintenance = await client.post(`/maintenances/${pendingMaintenance.id}/actions/reopen`, { + reopeningReason: '¡Este es un motivo de reapertura de prueba!' + }) + .then(getData) + + strictEqual(pendingMaintenance.id, canceledMaintenance.id) + strictEqual(canceledMaintenance.status, 'NEW') + strictEqual(canceledMaintenance.statusDescription, '¡Este es un motivo de reapertura de prueba!') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/mantenimientos/reasignar-mantenimiento.js b/es/ejemplos/mantenimientos/reasignar-mantenimiento.js new file mode 100644 index 0000000..254c689 --- /dev/null +++ b/es/ejemplos/mantenimientos/reasignar-mantenimiento.js @@ -0,0 +1,32 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import { strictEqual } from 'node:assert' + +async function run () { + const pendingMaintenance = await client.get('/maintenances', { + params: { + page: 1, + perPage: 1, + statusIn: 'CANCELED' + } + }).then(getFistItem) + + const canceledMaintenance = await client.post(`/maintenances/${pendingMaintenance.id}/actions/reallocate`, { + message: '¡Este es un motivo de reasignación de prueba!' + }) + .then(getData) + + strictEqual(pendingMaintenance.id, canceledMaintenance.id) + strictEqual(canceledMaintenance.status, 'NEW') + strictEqual(canceledMaintenance.statusDescription, '¡Este es un motivo de reasignación de prueba!') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/pendientes/concluir-pendiente.js b/es/ejemplos/pendientes/concluir-pendiente.js new file mode 100644 index 0000000..131a491 --- /dev/null +++ b/es/ejemplos/pendientes/concluir-pendiente.js @@ -0,0 +1,16 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + await client.post('/pendencies/e5a288a5-af6f-4b2c-ab8f-abd4e21178c2/actions/conclude').then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/pendientes/crear-pendiente.js b/es/ejemplos/pendientes/crear-pendiente.js new file mode 100644 index 0000000..59c9a65 --- /dev/null +++ b/es/ejemplos/pendientes/crear-pendiente.js @@ -0,0 +1,42 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' + +async function run () { + // Obtener empresas que contengan "Field Control" en sus nombres (sin distinción de mayúsculas) + // Solo un elemento por página + // Página uno o primera página + const company = await client.get('/companies', { + params: { + page: 1, + perPage: 1, + nameEq: 'Field Control - Fornecedor 8817' + } + }).then(getFistItem) + + console.log('company: ', company) + + const pendencyType = await client.get('/pendencies-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Falta documento' + } + }).then(getFistItem) + + await client.post('/pendencies', { + title: '🚨 Pendiente de prueba creado vía API', + description: 'Este es un pendiente de prueba creado vía API', + company: { id: company.id }, + pendencyType: { id: pendencyType.id } + }).then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/pendientes/obtener-pendientes.js b/es/ejemplos/pendientes/obtener-pendientes.js new file mode 100644 index 0000000..131846f --- /dev/null +++ b/es/ejemplos/pendientes/obtener-pendientes.js @@ -0,0 +1,22 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + await client.get('/pendencies', { + params: { + page: 1, + perPage: 20, + titleEq: 'awdawd' + } + }).then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/segmentos/obtener-segmentos.js b/es/ejemplos/segmentos/obtener-segmentos.js new file mode 100644 index 0000000..c6081a9 --- /dev/null +++ b/es/ejemplos/segmentos/obtener-segmentos.js @@ -0,0 +1,22 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + await client.get('/segments', { + params: { + page: 1, + perPage: 1, + nameEq: 'Ar condicionado é' + } + }).then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/tipos-de-equipo/crear-tipo-de-equipo.js b/es/ejemplos/tipos-de-equipo/crear-tipo-de-equipo.js new file mode 100644 index 0000000..1dd3df7 --- /dev/null +++ b/es/ejemplos/tipos-de-equipo/crear-tipo-de-equipo.js @@ -0,0 +1,55 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + const segment = await client.get('/segments', { + params: { + page: 1, + perPage: 10, + nameEq: '001 - Ar condicionado' + } + }).then(getFistItem) + + const equipmentType = await client.post('/equipment-types', { + name: 'Un tipo de equipo', + archived: false, + segment: { + id: segment.id + }, + customFields: [ + { + name: 'Campo 1', + type: 'QUESTION', + required: true + }, + { + name: 'Campo 2', + type: 'NUMBER', + required: false + }, + { + name: 'Campo 3', + type: 'DATE', + required: true + }, + { + name: 'Campo 4', + type: 'MULTIPLE_CHOICE', + required: false + } + ] + }).then(getData) + + assert.equal(equipmentType.name, 'Un tipo de equipo') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/tipos-de-mantenimiento/obtener-tipos-de-mantenimiento.js b/es/ejemplos/tipos-de-mantenimiento/obtener-tipos-de-mantenimiento.js new file mode 100644 index 0000000..e438fe3 --- /dev/null +++ b/es/ejemplos/tipos-de-mantenimiento/obtener-tipos-de-mantenimiento.js @@ -0,0 +1,22 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' + +async function run () { + await client.get('/maintenance-types', { + params: { + page: 1, + perPage: 1, + nameEq: 'Visita técnica' + } + }).then(getData) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/ubicaciones/crear-ubicacion-sin-coordenadas.js b/es/ejemplos/ubicaciones/crear-ubicacion-sin-coordenadas.js new file mode 100644 index 0000000..f802ab8 --- /dev/null +++ b/es/ejemplos/ubicaciones/crear-ubicacion-sin-coordenadas.js @@ -0,0 +1,43 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + const locationGroup = await client.get('/location-groups', { + params: { + page: 1, + perPage: 10, + nameEq: 'Guapiaçu' + } + }).then(getFistItem) + + console.log('locationGroup', locationGroup) + + const location = await client.post('/locations', { + name: 'Ubicación de prueba 2', + locationGroup: { + id: locationGroup.id + }, + address: { + number: '500', + postalCode: '15045606', + streetName: 'Manoel Freitas de Assunção', + neighborhood: 'Rio sella', + city: 'São josé do rio preto', + state: 'SP', + coords: null + } + }).then(getData) + + assert.equal(location.name, 'Ubicación de prueba 2') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/ubicaciones/crear-ubicacion.js b/es/ejemplos/ubicaciones/crear-ubicacion.js new file mode 100644 index 0000000..a68db86 --- /dev/null +++ b/es/ejemplos/ubicaciones/crear-ubicacion.js @@ -0,0 +1,44 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + const locationGroup = await client.get('/location-groups', { + params: { + page: 1, + perPage: 10, + nameEq: 'São Paulo' + } + }).then(getFistItem) + + const location = await client.post('/locations', { + name: 'Ubicación de prueba 2', + locationGroup: { + id: locationGroup.id + }, + address: { + number: 'S/N', + postalCode: '12345678', + streetName: 'Calle de prueba', + neighborhood: 'Barrio de prueba', + city: 'Ciudad de prueba', + state: 'SP', + coords: { + latitude: -23.123456, + longitude: -45.123456 + } + } + }).then(getData) + + assert.equal(location.name, 'Ubicación de prueba 2') +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/es/ejemplos/ubicaciones/obtener-proveedores-de-la-ubicacion.js b/es/ejemplos/ubicaciones/obtener-proveedores-de-la-ubicacion.js new file mode 100644 index 0000000..74933a6 --- /dev/null +++ b/es/ejemplos/ubicaciones/obtener-proveedores-de-la-ubicacion.js @@ -0,0 +1,80 @@ +// Ejemplo basado en la documentación disponible en https://amonamarth.fieldcontrol.com.br/docs +// Los datos proporcionados son solo ejemplos de prueba y no representan la realidad + +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' +import assert from 'node:assert' + +async function run () { + // buscando cualquier ubicación para usar al abrir un mantenimiento + const location = await client.get('/locations', { + params: { + page: 1, + perPage: 1, + documentNumberEq: '46849145851' + } + }).then(getFistItem) + + const result = await client.get(`/locations/${location.id}/service-providers`).then(getData) + + assert.deepEqual(result, { + items: [ + { + id: '23adcaa6-fd7f-48c3-b42d-57df81993edc', + segment: { + id: '1d8a6476-2f12-4766-8941-87d4ee4baf45' + }, + maintenanceTypes: [ + { + id: '574a1a6d-3f29-4356-8cdb-29bdb3c3ab32' + }, + { + id: '9d1c80ea-ceba-478a-8bca-3525b9dba873' + } + ], + company: { + id: '5dc173b9-f3c7-5fff-a5f9-f4bcecd3cdb9' + } + } + ], + pageInfo: { + hasNextPage: true, + hasPreviousPage: false, + page: 1, + pageCount: 4, + perPage: 2, + totalCount: 7 + } + }) + + const serviceProviderDetail = await client.get(`/locations/${location.id}/service-providers/${result.items[0].id}`).then(getData) + + assert.deepEqual(serviceProviderDetail, { + id: '23adcaa6-fd7f-48c3-b42d-57df81993edc', + segment: { + id: '1d8a6476-2f12-4766-8941-87d4ee4baf45', + name: '001 - Ar condicionado' + }, + maintenanceTypes: [ + { + id: '574a1a6d-3f29-4356-8cdb-29bdb3c3ab32', + name: 'Manutenção corretiva' + }, + { + id: '9d1c80ea-ceba-478a-8bca-3525b9dba873', + name: 'Instalação' + } + ], + company: { + id: '5dc173b9-f3c7-5fff-a5f9-f4bcecd3cdb9', + name: 'Field control - Fornecedor 8817' + } + }) +} + +run() + .catch(err => { + const error = err.isAxiosError ? err.toJSON() : err + console.log('error: ', error) + process.exit(1) + }) diff --git a/pt/README.md b/pt/README.md new file mode 100644 index 0000000..1f24e3d --- /dev/null +++ b/pt/README.md @@ -0,0 +1,40 @@ +# Amonamarth Examples (Português) + +![Field Control ♥](https://img.shields.io/badge/Field%20Control-♥-blue.svg) +[![GitHub Super-Linter](https://github.com/FieldControl/amonamarth-examples/workflows/Lint/badge.svg)](https://github.com/marketplace/actions/super-linter) + + +:volcano: Amon Amarth ou API publica do gestão de fornecedores é um web service rest que expõe os recursos afim de facilitar a que empresas façam integrações com seus outros sistemas. + +Este é um repositório auxiliar contendo trechos de código e exemplos de uso. Esta é a versão em **português** dos exemplos. Para a versão em inglês, veja [en/README.md](../en/README.md). Para a versão em espanhol, veja [es/README.md](../es/README.md). + +## Pré-requisitos para executar o projeto + +- Node.js version manager, caso não tenha o nvm instale seguindo estes passos + - [nvm para windows](https://github.com/coreybutler/nvm-windows) + - [nvm pra mac/linux](https://github.com/nvm-sh/nvm#installing-and-updating) + +- Clonar este repositório localmente `git clone https://github.com/LeoFalco/amonamarth-examples.git` + +- Na pasta do projeto executar os seguintes comandos + + ```sh + nvm install # para instalar o node + nvm use # troca para a versão do Node.js instalada + npm install # instala as dependências do projeto + ``` + +- O projeto usa autenticação por de API key você pode declarar a sua dentro de um arquivo chamado `.env` +assim como na imagem: + + ![image](https://user-images.githubusercontent.com/25820906/178081437-c5939851-116e-44e1-8527-91dc6a63900c.png) + +## Executando arquivos + +Os arquivos de exemplos em português estão na pasta `pt/exemplos` é possível executa-los diretamente pelo Node.js + +```sh + node pt/exemplos/manutencoes/criar-manutencao-com-anexo.js +``` + +> O código compartilhado (cliente HTTP e utilitários) fica na pasta `core` na raiz do repositório. diff --git a/src/examples/companies/post-companies-near-by-2.js b/pt/exemplos/empresas/empresas-proximas-2.js similarity index 93% rename from src/examples/companies/post-companies-near-by-2.js rename to pt/exemplos/empresas/empresas-proximas-2.js index 88bd0e6..828876b 100644 --- a/src/examples/companies/post-companies-near-by-2.js +++ b/pt/exemplos/empresas/empresas-proximas-2.js @@ -1,7 +1,7 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' +import { client } from '../../../core/client.js' async function run () { // Obter empresas próximas a "Avenida Abrão josé de lima 659" diff --git a/src/examples/companies/post-companies-near-by.js b/pt/exemplos/empresas/empresas-proximas.js similarity index 96% rename from src/examples/companies/post-companies-near-by.js rename to pt/exemplos/empresas/empresas-proximas.js index 5f83166..c6cb2a2 100644 --- a/src/examples/companies/post-companies-near-by.js +++ b/pt/exemplos/empresas/empresas-proximas.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' import assert from 'node:assert' async function run () { diff --git a/src/examples/companies/get-companies.js b/pt/exemplos/empresas/obter-empresas.js similarity index 77% rename from src/examples/companies/get-companies.js rename to pt/exemplos/empresas/obter-empresas.js index 5d9e7ce..16eefe6 100644 --- a/src/examples/companies/get-companies.js +++ b/pt/exemplos/empresas/obter-empresas.js @@ -1,22 +1,22 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' async function run () { - // Obter empresas que contenham "Field Control" em seus nomes (não sensitivo) + // Obter empresas com nome exato igual a "Field Control" // Apenas um item por página // Página um ou primeira página await client.get('/companies', { params: { page: 1, perPage: 1, - nameContains: 'Field Control' + nameEq: 'Field Control' } }).then(getData) - // Obter empresas que contenham "Field Control" em seus nomes (não sensitivo) + // Obter empresas com nome exato igual a "Field Control" // Apenas dois itens por página // Página um ou primeira página // Da mais antiga para a mais recente @@ -24,9 +24,9 @@ async function run () { params: { page: 1, perPage: 2, - nameContains: 'Field Control', - orderColumn: 'createdAt', - orderDirection: 'asc' + nameEq: 'Field Control', + orderBy: 'createdAt', + direction: 'asc' } }).then(getData) @@ -48,8 +48,8 @@ async function run () { params: { page: 1, perPage: 2, - orderColumn: 'name', - orderDirection: 'desc' + orderBy: 'name', + direction: 'desc' } }).then(getData) @@ -63,8 +63,8 @@ async function run () { params: { page: 1, perPage: 2, - orderColumn: 'distance', - orderDirection: 'desc', + orderBy: 'distance', + direction: 'desc', distanceRelativeTo: '37.7749,-122.4194' } }).then(getData) diff --git a/src/examples/companies/get-companies-near-by-usage.js b/pt/exemplos/empresas/obter-uso-empresas-proximas.js similarity index 88% rename from src/examples/companies/get-companies-near-by-usage.js rename to pt/exemplos/empresas/obter-uso-empresas-proximas.js index 9330225..5c9926d 100644 --- a/src/examples/companies/get-companies-near-by-usage.js +++ b/pt/exemplos/empresas/obter-uso-empresas-proximas.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' import assert from 'node:assert' async function run () { diff --git a/src/examples/equipments/post-change-equipment-location.js b/pt/exemplos/equipamentos/alterar-local-do-equipamento.js similarity index 92% rename from src/examples/equipments/post-change-equipment-location.js rename to pt/exemplos/equipamentos/alterar-local-do-equipamento.js index f842663..3887f93 100644 --- a/src/examples/equipments/post-change-equipment-location.js +++ b/pt/exemplos/equipamentos/alterar-local-do-equipamento.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' import assert from 'node:assert' async function run () { diff --git a/src/examples/locations/post-create-location-with-no-coords.js b/pt/exemplos/locais/criar-local-sem-coordenadas.js similarity index 90% rename from src/examples/locations/post-create-location-with-no-coords.js rename to pt/exemplos/locais/criar-local-sem-coordenadas.js index 9825acd..96cb3ee 100644 --- a/src/examples/locations/post-create-location-with-no-coords.js +++ b/pt/exemplos/locais/criar-local-sem-coordenadas.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' import assert from 'node:assert' async function run () { diff --git a/src/examples/locations/post-create-location.js b/pt/exemplos/locais/criar-local.js similarity index 90% rename from src/examples/locations/post-create-location.js rename to pt/exemplos/locais/criar-local.js index fb79f07..793bd0f 100644 --- a/src/examples/locations/post-create-location.js +++ b/pt/exemplos/locais/criar-local.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' import assert from 'node:assert' async function run () { diff --git a/src/examples/locations/get-locations-service-providers.js b/pt/exemplos/locais/obter-fornecedores-do-local.js similarity index 82% rename from src/examples/locations/get-locations-service-providers.js rename to pt/exemplos/locais/obter-fornecedores-do-local.js index 29d19c4..f7c0896 100644 --- a/src/examples/locations/get-locations-service-providers.js +++ b/pt/exemplos/locais/obter-fornecedores-do-local.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' import assert from 'node:assert' async function run () { @@ -15,20 +15,7 @@ async function run () { } }).then(getFistItem) - // consultando um segmento qualquer para usar na abertura de manutenção - const segment = await client.get('/segments', { - params: { - page: 1, - perPage: 1, - nameEq: '001 - Ar condicionado' - } - }).then(getFistItem) - - const result = await client.get(`/locations/${location.id}/service-providers`, { - params: { - segmentId: segment.id - } - }).then(getData) + const result = await client.get(`/locations/${location.id}/service-providers`).then(getData) assert.deepEqual(result, { items: [ diff --git a/src/examples/maintenances/post-add-maintenance-coment-collaborator.js b/pt/exemplos/manutencoes/adicionar-comentario-colaborador-na-manutencao.js similarity index 93% rename from src/examples/maintenances/post-add-maintenance-coment-collaborator.js rename to pt/exemplos/manutencoes/adicionar-comentario-colaborador-na-manutencao.js index 4e0767e..24095d3 100644 --- a/src/examples/maintenances/post-add-maintenance-coment-collaborator.js +++ b/pt/exemplos/manutencoes/adicionar-comentario-colaborador-na-manutencao.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' import assert from 'node:assert' async function run () { diff --git a/src/examples/maintenances/post-cancel-maintenance.js b/pt/exemplos/manutencoes/cancelar-manutencao.js similarity index 90% rename from src/examples/maintenances/post-cancel-maintenance.js rename to pt/exemplos/manutencoes/cancelar-manutencao.js index f737269..9893954 100644 --- a/src/examples/maintenances/post-cancel-maintenance.js +++ b/pt/exemplos/manutencoes/cancelar-manutencao.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' import { strictEqual } from 'node:assert' async function run () { diff --git a/src/examples/maintenances/post-create-maintenance-with-attachment.js b/pt/exemplos/manutencoes/criar-manutencao-com-anexo.js similarity index 96% rename from src/examples/maintenances/post-create-maintenance-with-attachment.js rename to pt/exemplos/manutencoes/criar-manutencao-com-anexo.js index aaaa17d..9ffcdcd 100644 --- a/src/examples/maintenances/post-create-maintenance-with-attachment.js +++ b/pt/exemplos/manutencoes/criar-manutencao-com-anexo.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData, getFistItem, getItems } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem, getItems } from '../../../core/utils.js' import FormData from 'form-data' import { readFileSync, readdirSync } from 'node:fs' import { join, extname, basename } from 'node:path' @@ -54,7 +54,7 @@ async function buildUploadHeaders ({ formData }) { async function run () { // lendo arquivos de exemplo que estão na pasta "data" na raiz desse projeto const currentDirPath = fileURLToPath(import.meta.url) - const dataDirPath = join(currentDirPath, '../../../data') + const dataDirPath = join(currentDirPath, '../../../../data') const fileNames = readdirSync(dataDirPath) const absoluteFileNames = fileNames.map(fileName => join(dataDirPath, fileName)) diff --git a/src/examples/maintenances/post-create-maintenance-coment-collaborator.js b/pt/exemplos/manutencoes/criar-manutencao-com-comentario-colaborador.js similarity index 95% rename from src/examples/maintenances/post-create-maintenance-coment-collaborator.js rename to pt/exemplos/manutencoes/criar-manutencao-com-comentario-colaborador.js index 1a16cbe..4e39cbe 100644 --- a/src/examples/maintenances/post-create-maintenance-coment-collaborator.js +++ b/pt/exemplos/manutencoes/criar-manutencao-com-comentario-colaborador.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' import assert from 'node:assert' async function run () { diff --git a/src/examples/maintenances/post-create-maintenance-coment.js b/pt/exemplos/manutencoes/criar-manutencao-com-comentario.js similarity index 95% rename from src/examples/maintenances/post-create-maintenance-coment.js rename to pt/exemplos/manutencoes/criar-manutencao-com-comentario.js index 66f186f..f57cf1f 100644 --- a/src/examples/maintenances/post-create-maintenance-coment.js +++ b/pt/exemplos/manutencoes/criar-manutencao-com-comentario.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' import assert from 'node:assert' async function run () { diff --git a/src/examples/maintenances/post-create-maintenance-with-address.js b/pt/exemplos/manutencoes/criar-manutencao-com-endereco.js similarity index 93% rename from src/examples/maintenances/post-create-maintenance-with-address.js rename to pt/exemplos/manutencoes/criar-manutencao-com-endereco.js index 4ca0da6..cc53604 100644 --- a/src/examples/maintenances/post-create-maintenance-with-address.js +++ b/pt/exemplos/manutencoes/criar-manutencao-com-endereco.js @@ -1,6 +1,6 @@ import assert from 'node:assert' -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' async function run () { // consultando um local qualquer para usar na abertura de manutenção diff --git a/src/examples/maintenances/post-create-maintenance-with-schedule-suggestion.js b/pt/exemplos/manutencoes/criar-manutencao-com-sugestao-de-agendamento.js similarity index 93% rename from src/examples/maintenances/post-create-maintenance-with-schedule-suggestion.js rename to pt/exemplos/manutencoes/criar-manutencao-com-sugestao-de-agendamento.js index f1d3f4d..b9bec58 100644 --- a/src/examples/maintenances/post-create-maintenance-with-schedule-suggestion.js +++ b/pt/exemplos/manutencoes/criar-manutencao-com-sugestao-de-agendamento.js @@ -1,6 +1,6 @@ import assert from 'node:assert' -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' async function run () { // consultando um local qualquer para usar na abertura de manutenção diff --git a/src/examples/maintenances/get-canceled-maintenances.js b/pt/exemplos/manutencoes/obter-manutencoes-canceladas.js similarity index 83% rename from src/examples/maintenances/get-canceled-maintenances.js rename to pt/exemplos/manutencoes/obter-manutencoes-canceladas.js index 4663dcc..76d9930 100644 --- a/src/examples/maintenances/get-canceled-maintenances.js +++ b/pt/exemplos/manutencoes/obter-manutencoes-canceladas.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' async function run () { const maintenances = await client.get('/maintenances', { @@ -20,7 +20,7 @@ async function run () { console.log('Total:', maintenances.length) for (const maintenance of maintenances) { - + console.log('Manutenção:', maintenance) } } diff --git a/src/examples/maintenances/get-maintenance-forms-answers.js b/pt/exemplos/manutencoes/obter-respostas-de-formularios-da-manutencao.js similarity index 84% rename from src/examples/maintenances/get-maintenance-forms-answers.js rename to pt/exemplos/manutencoes/obter-respostas-de-formularios-da-manutencao.js index 88881af..7b50b96 100644 --- a/src/examples/maintenances/get-maintenance-forms-answers.js +++ b/pt/exemplos/manutencoes/obter-respostas-de-formularios-da-manutencao.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' async function run () { await client.get('/maintenances/e1c823ff-7000-4fde-90a6-aa4596169a76/form-answers/be46fbc1-fd70-4583-bad3-24403bf54ea5', { diff --git a/src/examples/maintenances/post-reopen-maintenance.js b/pt/exemplos/manutencoes/reabrir-manutencao.js similarity index 89% rename from src/examples/maintenances/post-reopen-maintenance.js rename to pt/exemplos/manutencoes/reabrir-manutencao.js index 97ea9a4..192423d 100644 --- a/src/examples/maintenances/post-reopen-maintenance.js +++ b/pt/exemplos/manutencoes/reabrir-manutencao.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' import { strictEqual } from 'node:assert' async function run () { diff --git a/src/examples/maintenances/post-reallocate-maintenance.js b/pt/exemplos/manutencoes/realocar-manutencao.js similarity index 89% rename from src/examples/maintenances/post-reallocate-maintenance.js rename to pt/exemplos/manutencoes/realocar-manutencao.js index 9373994..00555e3 100644 --- a/src/examples/maintenances/post-reallocate-maintenance.js +++ b/pt/exemplos/manutencoes/realocar-manutencao.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' import { strictEqual } from 'node:assert' async function run () { diff --git a/src/examples/maintenances/get-maintenance-stress.js b/pt/exemplos/manutencoes/teste-de-estresse-manutencoes.js similarity index 97% rename from src/examples/maintenances/get-maintenance-stress.js rename to pt/exemplos/manutencoes/teste-de-estresse-manutencoes.js index e35ddea..240c290 100644 --- a/src/examples/maintenances/get-maintenance-stress.js +++ b/pt/exemplos/manutencoes/teste-de-estresse-manutencoes.js @@ -1,7 +1,7 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' +import { client } from '../../../core/client.js' async function run () { const REQUEST_QUANTITY = 1 diff --git a/src/examples/pendencies/post-conclude-pendencies.js b/pt/exemplos/pendencias/concluir-pendencia.js similarity index 61% rename from src/examples/pendencies/post-conclude-pendencies.js rename to pt/exemplos/pendencias/concluir-pendencia.js index 8c1e2cd..bcf9d4e 100644 --- a/src/examples/pendencies/post-conclude-pendencies.js +++ b/pt/exemplos/pendencias/concluir-pendencia.js @@ -1,14 +1,11 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' async function run () { - await client.post('/pendencies/e5a288a5-af6f-4b2c-ab8f-abd4e21178c2/actions/conclude', { - title: 'Pendência de teste criada via API', - description: 'Esta é uma pendência de teste criada via API' - }).then(getData) + await client.post('/pendencies/e5a288a5-af6f-4b2c-ab8f-abd4e21178c2/actions/conclude').then(getData) } run() diff --git a/src/examples/pendencies/post-pendencies.js b/pt/exemplos/pendencias/criar-pendencia.js similarity index 85% rename from src/examples/pendencies/post-pendencies.js rename to pt/exemplos/pendencias/criar-pendencia.js index 09020cb..af0f1a7 100644 --- a/src/examples/pendencies/post-pendencies.js +++ b/pt/exemplos/pendencias/criar-pendencia.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' async function run () { // Obter empresas que contenham "Field Control" em seus nomes (não sensitivo) @@ -29,8 +29,8 @@ async function run () { await client.post('/pendencies', { title: '🚨 Pendência de teste criada via API', description: 'Esta é uma pendência de teste criada via API', - companyId: company.id, - pendencyTypeId: pendencyType.id + company: { id: company.id }, + pendencyType: { id: pendencyType.id } }).then(getData) } diff --git a/src/examples/pendencies/get-pendencies.js b/pt/exemplos/pendencias/obter-pendencias.js similarity index 83% rename from src/examples/pendencies/get-pendencies.js rename to pt/exemplos/pendencias/obter-pendencias.js index b7729b4..b7906df 100644 --- a/src/examples/pendencies/get-pendencies.js +++ b/pt/exemplos/pendencias/obter-pendencias.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' async function run () { await client.get('/pendencies', { diff --git a/src/examples/segments/get-segments.js b/pt/exemplos/segmentos/obter-segmentos.js similarity index 83% rename from src/examples/segments/get-segments.js rename to pt/exemplos/segmentos/obter-segmentos.js index 3c0b110..eee5610 100644 --- a/src/examples/segments/get-segments.js +++ b/pt/exemplos/segmentos/obter-segmentos.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' async function run () { await client.get('/segments', { diff --git a/src/examples/equipments-types/post-create-equipment-type.js b/pt/exemplos/tipos-de-equipamento/criar-tipo-de-equipamento.js similarity index 78% rename from src/examples/equipments-types/post-create-equipment-type.js rename to pt/exemplos/tipos-de-equipamento/criar-tipo-de-equipamento.js index 3be2ef8..77f5756 100644 --- a/src/examples/equipments-types/post-create-equipment-type.js +++ b/pt/exemplos/tipos-de-equipamento/criar-tipo-de-equipamento.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData, getFistItem } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData, getFistItem } from '../../../core/utils.js' import assert from 'node:assert' async function run () { @@ -23,28 +23,28 @@ async function run () { customFields: [ { name: 'Campo 1', - type: 'text', + type: 'QUESTION', required: true }, { name: 'Campo 2', - type: 'number', + type: 'NUMBER', required: false }, { name: 'Campo 3', - type: 'date', + type: 'DATE', required: true }, { name: 'Campo 4', - type: 'select', + type: 'MULTIPLE_CHOICE', required: false } ] }).then(getData) - assert.equal(equipmentType.name, 'Local de teste 2') + assert.equal(equipmentType.name, 'Um tipo de equipamento') } run() diff --git a/src/examples/maintenances-types/get-maintenance-types.js b/pt/exemplos/tipos-de-manutencao/obter-tipos-de-manutencao.js similarity index 83% rename from src/examples/maintenances-types/get-maintenance-types.js rename to pt/exemplos/tipos-de-manutencao/obter-tipos-de-manutencao.js index c99a486..709eedc 100644 --- a/src/examples/maintenances-types/get-maintenance-types.js +++ b/pt/exemplos/tipos-de-manutencao/obter-tipos-de-manutencao.js @@ -1,8 +1,8 @@ // Exemplo baseado na documentação disponível em https://amonamarth.fieldcontrol.com.br/docs // Os dados informados são apenas exemplos de testes e não representam a verdade -import { client } from '../../core/client.js' -import { getData } from '../../core/utils.js' +import { client } from '../../../core/client.js' +import { getData } from '../../../core/utils.js' async function run () { await client.get('/maintenance-types', {