From 61ca20eff04ef40dc3f6a9a6f267af55f5801a27 Mon Sep 17 00:00:00 2001 From: Jean Date: Thu, 4 Jan 2024 23:35:23 -0300 Subject: [PATCH 01/36] refactor/alterado querys do codigo para utilizar o orm sequelize no projeto --- package-lock.json | 325 ++++++++++++++++++++++++++- package.json | 6 +- src/config/dbConfig.js | 24 +- src/controllers/AuthController.js | 37 +-- src/controllers/UsuarioController.js | 79 ++++--- src/models/arquivos.js | 30 +++ src/models/cargosModel.js | 26 +++ src/models/planilhasModel.js | 34 +++ src/models/proviModel.js | 45 ++++ src/models/provisionamentoModel.js | 68 ++++++ src/models/tipoDeServicoModel.js | 26 +++ src/models/usuarioModel.js | 47 ++++ 12 files changed, 686 insertions(+), 61 deletions(-) create mode 100644 src/models/arquivos.js create mode 100644 src/models/cargosModel.js create mode 100644 src/models/planilhasModel.js create mode 100644 src/models/proviModel.js create mode 100644 src/models/provisionamentoModel.js create mode 100644 src/models/tipoDeServicoModel.js create mode 100644 src/models/usuarioModel.js diff --git a/package-lock.json b/package-lock.json index 9aa062e..b0ae458 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,7 +16,9 @@ "jsonwebtoken": "^9.0.0", "md5": "^2.3.0", "mongoose": "^7.2.0", - "postgres": "^3.3.5" + "pg": "^8.11.3", + "postgres": "^3.3.5", + "sequelize": "^6.35.2" }, "devDependencies": { "nodemon": "^3.0.1" @@ -31,6 +33,19 @@ "sparse-bitfield": "^3.0.3" } }, + "node_modules/@types/debug": { + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz", + "integrity": "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==", + "dependencies": { + "@types/ms": "*" + } + }, + "node_modules/@types/ms": { + "version": "0.7.34", + "resolved": "https://registry.npmjs.org/@types/ms/-/ms-0.7.34.tgz", + "integrity": "sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==" + }, "node_modules/@types/node": { "version": "20.8.9", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.9.tgz", @@ -39,6 +54,11 @@ "undici-types": "~5.26.4" } }, + "node_modules/@types/validator": { + "version": "13.11.7", + "resolved": "https://registry.npmjs.org/@types/validator/-/validator-13.11.7.tgz", + "integrity": "sha512-q0JomTsJ2I5Mv7dhHhQLGjMvX0JJm5dyZ1DXQySIUzU1UlwzB8bt+R6+LODUbz0UDIOvEzGc28tk27gBJw2N8Q==" + }, "node_modules/@types/webidl-conversions": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.2.tgz", @@ -162,6 +182,14 @@ "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==" }, + "node_modules/buffer-writer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/buffer-writer/-/buffer-writer-2.0.0.tgz", + "integrity": "sha512-a7ZpuTZU1TRtnwyCNW3I5dc0wWNC3VR9S++Ewyk2HHZdrO3CQJqSpd+95Us590V6AL7JqUAH2IwZ/398PmNFgw==", + "engines": { + "node": ">=4" + } + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -311,6 +339,11 @@ "url": "https://github.com/motdotla/dotenv?sponsor=1" } }, + "node_modules/dottie": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/dottie/-/dottie-2.0.6.tgz", + "integrity": "sha512-iGCHkfUc5kFekGiqhe8B/mdaurD+lakO9txNnTvKtA6PISrw86LgqHvRzWYPyoE2Ph5aMIrCw9/uko6XHTKCwA==" + }, "node_modules/ecdsa-sig-formatter": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", @@ -587,6 +620,14 @@ "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", "dev": true }, + "node_modules/inflection": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/inflection/-/inflection-1.13.4.tgz", + "integrity": "sha512-6I/HUDeYFfuNCVS3td055BaXBwKYuzw7K3ExVMStBowKo9oOAMJIXIHvdyR3iboTCp1b+1i5DSkIZTcwIktuDw==", + "engines": [ + "node >= 0.4.0" + ] + }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", @@ -794,6 +835,25 @@ "node": "*" } }, + "node_modules/moment": { + "version": "2.30.1", + "resolved": "https://registry.npmjs.org/moment/-/moment-2.30.1.tgz", + "integrity": "sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==", + "engines": { + "node": "*" + } + }, + "node_modules/moment-timezone": { + "version": "0.5.44", + "resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.44.tgz", + "integrity": "sha512-nv3YpzI/8lkQn0U6RkLd+f0W/zy/JnoR5/EyPz/dNkPTBjA2jNLCVxaiQ8QpeLymhSZvX0wCL5s27NQWdOPwAw==", + "dependencies": { + "moment": "^2.29.4" + }, + "engines": { + "node": "*" + } + }, "node_modules/mongodb": { "version": "5.9.0", "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-5.9.0.tgz", @@ -1016,6 +1076,11 @@ "node": ">= 0.8" } }, + "node_modules/packet-reader": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/packet-reader/-/packet-reader-1.0.0.tgz", + "integrity": "sha512-HAKu/fG3HpHFO0AA8WE8q2g+gBJaZ9MG7fcKk+IJPLTGAD6Psw4443l+9DGRbOIh3/aXr7Phy0TjilYivJo5XQ==" + }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -1029,6 +1094,89 @@ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" }, + "node_modules/pg": { + "version": "8.11.3", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.11.3.tgz", + "integrity": "sha512-+9iuvG8QfaaUrrph+kpF24cXkH1YOOUeArRNYIxq1viYHZagBxrTno7cecY1Fa44tJeZvaoG+Djpkc3JwehN5g==", + "dependencies": { + "buffer-writer": "2.0.0", + "packet-reader": "1.0.0", + "pg-connection-string": "^2.6.2", + "pg-pool": "^3.6.1", + "pg-protocol": "^1.6.0", + "pg-types": "^2.1.0", + "pgpass": "1.x" + }, + "engines": { + "node": ">= 8.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.1.1" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.1.1.tgz", + "integrity": "sha512-xWPagP/4B6BgFO+EKz3JONXv3YDgvkbVrGw2mTo3D6tVDQRh1e7cqVGvyR3BE+eQgAvx1XhW/iEASj4/jCWl3Q==", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.6.2.tgz", + "integrity": "sha512-ch6OwaeaPYcova4kKZ15sbJ2hKb/VP48ZD2gE7i1J+L4MspCtBMAx8nMgz7bksc7IojCIIWuEhHibSMFH8m8oA==" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.6.1.tgz", + "integrity": "sha512-jizsIzhkIitxCGfPRzJn1ZdcosIt3pz9Sh3V01fm1vZnbnCMgmGl5wvGGdNN2EL9Rmb0EcFoCkixH4Pu+sP9Og==", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.6.0.tgz", + "integrity": "sha512-M+PDm637OY5WM307051+bsDia5Xej6d9IR4GwJse1qA1DIhiKlksvrneZOYQq42OM+spubpcNYEo2FcKQrDk+Q==" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "dependencies": { + "split2": "^4.1.0" + } + }, "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", @@ -1050,6 +1198,41 @@ "url": "https://github.com/sponsors/porsager" } }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.0.tgz", + "integrity": "sha512-xy3pmLuQqRBZBXDULy7KbaitYqLcmxigw14Q5sj8QBVLqEwXfeybIKVWiqAXTlcvdvb0+xkOtDbfQMOf4lST1w==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/proxy-addr": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", @@ -1124,6 +1307,11 @@ "node": ">=8.10.0" } }, + "node_modules/retry-as-promised": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/retry-as-promised/-/retry-as-promised-7.0.4.tgz", + "integrity": "sha512-XgmCoxKWkDofwH8WddD0w85ZfqYz+ZHlr5yo+3YUCfycWawU56T5ckWXsScsj5B8tqUcIG67DxXByo3VUgiAdA==" + }, "node_modules/safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", @@ -1190,6 +1378,96 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" }, + "node_modules/sequelize": { + "version": "6.35.2", + "resolved": "https://registry.npmjs.org/sequelize/-/sequelize-6.35.2.tgz", + "integrity": "sha512-EdzLaw2kK4/aOnWQ7ed/qh3B6/g+1DvmeXr66RwbcqSm/+QRS9X0LDI5INBibsy4eNJHWIRPo3+QK0zL+IPBHg==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/sequelize" + } + ], + "dependencies": { + "@types/debug": "^4.1.8", + "@types/validator": "^13.7.17", + "debug": "^4.3.4", + "dottie": "^2.0.6", + "inflection": "^1.13.4", + "lodash": "^4.17.21", + "moment": "^2.29.4", + "moment-timezone": "^0.5.43", + "pg-connection-string": "^2.6.1", + "retry-as-promised": "^7.0.4", + "semver": "^7.5.4", + "sequelize-pool": "^7.1.0", + "toposort-class": "^1.0.1", + "uuid": "^8.3.2", + "validator": "^13.9.0", + "wkx": "^0.5.0" + }, + "engines": { + "node": ">=10.0.0" + }, + "peerDependenciesMeta": { + "ibm_db": { + "optional": true + }, + "mariadb": { + "optional": true + }, + "mysql2": { + "optional": true + }, + "oracledb": { + "optional": true + }, + "pg": { + "optional": true + }, + "pg-hstore": { + "optional": true + }, + "snowflake-sdk": { + "optional": true + }, + "sqlite3": { + "optional": true + }, + "tedious": { + "optional": true + } + } + }, + "node_modules/sequelize-pool": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/sequelize-pool/-/sequelize-pool-7.1.0.tgz", + "integrity": "sha512-G9c0qlIWQSK29pR/5U2JF5dDQeqqHRragoyahj/Nx4KOOQ3CPPfzxnfqFPCSB7x5UgjOgnZ61nSxz+fjDpRlJg==", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/sequelize/node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/sequelize/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, "node_modules/serve-static": { "version": "1.15.0", "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", @@ -1270,6 +1548,14 @@ "memory-pager": "^1.0.2" } }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "engines": { + "node": ">= 10.x" + } + }, "node_modules/statuses": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", @@ -1310,6 +1596,11 @@ "node": ">=0.6" } }, + "node_modules/toposort-class": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toposort-class/-/toposort-class-1.0.1.tgz", + "integrity": "sha512-OsLcGGbYF3rMjPUf8oKktyvCiUxSbqMMS39m33MAjLTC1DVIH6x3WSt63/M77ihI09+Sdfk1AXvfhCEeUmC7mg==" + }, "node_modules/touch": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.0.tgz", @@ -1372,6 +1663,22 @@ "node": ">= 0.4.0" } }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/validator": { + "version": "13.11.0", + "resolved": "https://registry.npmjs.org/validator/-/validator-13.11.0.tgz", + "integrity": "sha512-Ii+sehpSfZy+At5nPdnyMhx78fEoPDkR2XW/zimHEL3MyGJQOCQ7WeP20jPYRz7ZCpcKLB21NxuXHF3bxjStBQ==", + "engines": { + "node": ">= 0.10" + } + }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", @@ -1400,6 +1707,22 @@ "node": ">=12" } }, + "node_modules/wkx": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/wkx/-/wkx-0.5.0.tgz", + "integrity": "sha512-Xng/d4Ichh8uN4l0FToV/258EjMGU9MGcA0HV2d9B/ZpZB3lqQm7nkOdZdm5GhKtLLhAE7PiVQwN4eN+2YJJUg==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "engines": { + "node": ">=0.4" + } + }, "node_modules/yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", diff --git a/package.json b/package.json index bd8d6f5..6c10822 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "apiprovisionamento", - "version": "1.0.0", + "version": "1.5.0", "description": "", "main": "server.js", "type": "module", @@ -22,6 +22,8 @@ "jsonwebtoken": "^9.0.0", "md5": "^2.3.0", "mongoose": "^7.2.0", - "postgres": "^3.3.5" + "pg": "^8.11.3", + "postgres": "^3.3.5", + "sequelize": "^6.35.2" } } diff --git a/src/config/dbConfig.js b/src/config/dbConfig.js index 43a62e5..eb1df78 100644 --- a/src/config/dbConfig.js +++ b/src/config/dbConfig.js @@ -1,5 +1,4 @@ -import postgres from "postgres"; -// import Client from "pg"; +import { Sequelize } from "sequelize"; import * as dotenv from "dotenv"; dotenv.config(); @@ -9,14 +8,17 @@ let dbPort = process.env.SUPABASE_PORT; let dbUsername = process.env.SUPABASE_DBUSER; let dbHostName = process.env.SUPABASE_HOSTNAME; -// const db = postgres(`postgresql://postgres:${dbPassword}@${dbURL}:${dbPort}/postgres`) - -const db = postgres(`postgresql://postgres:${dbPassword}@${dbURL}:${dbPort}/postgres`, { - host : dbURL, - port : dbPort, - database : dbHostName, - user : dbUsername, - password : dbPassword, +const sequelize = new Sequelize({ + dialect: 'postgres', + host: dbURL, + username: dbUsername, + password: dbPassword, + database: dbHostName, + port: dbPort, + define: { + timestamps: false, + underscored: false + } }) -export default db; \ No newline at end of file +export default sequelize; \ No newline at end of file diff --git a/src/controllers/AuthController.js b/src/controllers/AuthController.js index 96c1152..2d19358 100644 --- a/src/controllers/AuthController.js +++ b/src/controllers/AuthController.js @@ -1,7 +1,7 @@ -import db from "../config/dbConfig.js"; import md5 from "md5"; import constants from "../constants/constants.js"; import jwt from "jsonwebtoken"; +import User from "../models/usuarioModel.js"; const SECRET = process.env.SECRET; const responseModel = { @@ -25,30 +25,39 @@ export default { const passwordEncrypted = md5(password); try { - const userLogin = - await db`SELECT id, "nomeFuncionario", "emailFuncionario" AS "email", "senhaFuncionario" AS "password", "admin", "permissaoDoColaborador", "status" - FROM "tbUsuarios" where "emailFuncionario" = ${email} AND "senhaFuncionario" = ${passwordEncrypted}`; + // const userLogin = + // await db`SELECT id, "nomeFuncionario", "emailFuncionario" AS "email", "senhaFuncionario" AS "password", "admin", "permissaoDoColaborador", "status" + // FROM "tbUsuarios" where "emailFuncionario" = ${email} AND "senhaFuncionario" = ${passwordEncrypted}`; - response.success = userLogin.length > 0; + const userLogin = await User.findAll({ + where: { + emailFuncionario: email, + senhaFuncionario: passwordEncrypted + } + }) + + const resUserLogin = userLogin.map((element) => element.dataValues) + + response.success = resUserLogin.length > 0; if (response.success) { - if (userLogin[0].status != 1) { + if (resUserLogin[0].status != 1) { res.status(401); response.error = constants["401"].inactiveUser; return res.json(response); } - const token = jwt.sign({ id: userLogin[0].id }, SECRET, { + const token = jwt.sign({ id: resUserLogin[0].id }, SECRET, { expiresIn: 86400000, // 1 dia para expiração do token }); - response.data = userLogin; + response.data = resUserLogin; const objAuth = { user: { - id: userLogin[0].id, - nomeFuncionario: userLogin[0].nomeFuncionario, - email: userLogin[0].email, - admin: userLogin[0].admin, - permissaoDoColaborador: userLogin[0].permissaoDoColaborador, - status: userLogin[0].status, + id: resUserLogin[0].id, + nomeFuncionario: resUserLogin[0].nomeFuncionario, + email: resUserLogin[0].email, + admin: resUserLogin[0].admin, + permissaoDoColaborador: resUserLogin[0].permissaoDoColaborador, + status: resUserLogin[0].status, }, auth: true, token: token, diff --git a/src/controllers/UsuarioController.js b/src/controllers/UsuarioController.js index 1b6281e..a999db7 100644 --- a/src/controllers/UsuarioController.js +++ b/src/controllers/UsuarioController.js @@ -2,6 +2,7 @@ import db from "../config/dbConfig.js"; import md5 from "md5"; import constants from "../constants/constants.js"; +import User from "../models/usuarioModel.js"; const responseModel = { success: false, @@ -22,27 +23,30 @@ export default { second: "2-digit", timeZoneName: "short", }); - + try { - const tbUsuarios = await db` - SELECT id, "nomeFuncionario", "cargoFuncionario", "emailFuncionario", "admin", "status", "permissaoDoColaborador", "created_at", "update_at" - FROM "tbUsuarios" - ORDER BY status DESC, id ASC - `; - if (tbUsuarios.length > 0) { - + const findAllUsers = await User.findAll({ + order: [ + ["status", "DESC"], + ["id", "ASC"], + ], + }); + + const resFindAllUsers = findAllUsers.map((element) => element.dataValues); + + if (resFindAllUsers.length > 0) { // Formatar a data para cada registro retornado - const tbUsuariosFormatado = tbUsuarios.map((row) => { + const resFindAllUsersFormatado = resFindAllUsers.map((row) => { return { ...row, created_at: dataFormatada.format(row.created_at), update_at: dataFormatada.format(row.update_at), }; }); - + response.success = true; - response.data = tbUsuariosFormatado; - response.found = tbUsuariosFormatado.length; + response.data = resFindAllUsersFormatado; + response.found = resFindAllUsersFormatado.length; } else { response.success = false; response.data = []; @@ -53,10 +57,8 @@ export default { response.error = constants["500"].errorOccurred; return res.status(500).json(response); } - return res.json(response); }, - async listaUsuario(req, res) { const response = { ...responseModel }; @@ -74,18 +76,25 @@ export default { response.data = []; try { - const userIdRes = - await db`SELECT id, "nomeFuncionario", "cargoFuncionario", "emailFuncionario", "admin", "created_at" FROM "tbUsuarios" WHERE "id" = ${userId}`; + + const findUserByID = await User.findOne({ + where: { + id: userId, + }, + }); + + const userIdRes = [findUserByID.dataValues]; + response.success = userIdRes.length > 0; - // Formatar a data para cada registro retornado - const userIdResFormatado = userIdRes.map((row) => { - return { - ...row, - created_at: dataFormatada.format(row.created_at), - update_at: dataFormatada.format(row.update_at), - }; - }); + // Formatar a data para cada registro retornado + const userIdResFormatado = userIdRes.map((row) => { + return { + ...row, + created_at: dataFormatada.format(row.created_at), + update_at: dataFormatada.format(row.update_at), + }; + }); if (response.success) { response.success = true; @@ -100,7 +109,6 @@ export default { response.error = constants["500"].errorOccurred; return res.status(500).json(response); } - return res.json(response); }, @@ -130,7 +138,9 @@ export default { } else { query = await db` INSERT INTO "tbUsuarios" ("nomeFuncionario", "cargoFuncionario", "emailFuncionario", "senhaFuncionario", "created_at", "admin", "permissaoDoColaborador", "update_at", "status") - VALUES (${nomeFuncionario}, ${cargoFuncionario}, ${emailFuncionario}, ${passwordEncrypted}, ${dataAtual}, ${typeof admin === "boolean" ? admin : null }, ${permissaoDoColaborador}, NULL, ${parseInt(status)}) + VALUES (${nomeFuncionario}, ${cargoFuncionario}, ${emailFuncionario}, ${passwordEncrypted}, ${dataAtual}, ${ + typeof admin === "boolean" ? admin : null + }, ${permissaoDoColaborador}, NULL, ${parseInt(status)}) RETURNING *;`; response.success = query.length > 0; @@ -145,7 +155,7 @@ export default { emailFuncionario, admin, permissaoDoColaborador, - status + status, }; return res.status(201).json(response); } else { @@ -183,7 +193,7 @@ export default { UPDATE "tbUsuarios" SET "nomeFuncionario"=${nomeFuncionario}, "cargoFuncionario"=${cargoFuncionario}, "emailFuncionario"=${emailFuncionario}, "senhaFuncionario"=${passwordEncrypted}, "admin"=${admin}, "permissaoDoColaborador"=${permissaoDoColaborador}, "update_at"=${dataAtual}, "status"=${status} WHERE "id"=${userId} - RETURNING *;` + RETURNING *;`; response.success = query.length > 0; @@ -197,18 +207,21 @@ export default { emailFuncionario, admin, permissaoDoColaborador, - status + status, }; return res.status(201).json(response); } else { response.error = constants["404"].userNotFound; } - } catch (error) { console.error("ERRO:", error); - if (error.message.includes('duplicate key value violates unique constraint "tbUsuarios_emailFuncionario_key"')) { - console.error('ERRO de chave duplicada'); - response.error = constants['409'].emailAlreadyExiste; + if ( + error.message.includes( + 'duplicate key value violates unique constraint "tbUsuarios_emailFuncionario_key"' + ) + ) { + console.error("ERRO de chave duplicada"); + response.error = constants["409"].emailAlreadyExiste; return res.status(409).json(response); } else { response.error = constants["500"].errorOccurred; diff --git a/src/models/arquivos.js b/src/models/arquivos.js new file mode 100644 index 0000000..8ac3879 --- /dev/null +++ b/src/models/arquivos.js @@ -0,0 +1,30 @@ +import { DataTypes } from "sequelize"; +import sequelize from "../config/dbConfig"; + +const Files = sequelize.define("tbArquivos", { + id: { + type: DataTypes.BIGINT, + primaryKey: true, + autoIncrement: true, + }, + nome: { + type: DataTypes.STRING, + allowNull: true, + }, + url: { + type: DataTypes.STRING, + allowNull: true, + }, + created_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, + update_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, +}); + +export default Files; \ No newline at end of file diff --git a/src/models/cargosModel.js b/src/models/cargosModel.js new file mode 100644 index 0000000..628c118 --- /dev/null +++ b/src/models/cargosModel.js @@ -0,0 +1,26 @@ +import { DataTypes } from "sequelize"; +import sequelize from "../config/dbConfig"; + +const Positions = sequelize.define("tbCargos", { + id: { + type: DataTypes.BIGINT, + primaryKey: true, + autoIncrement: true, + }, + cargoFuncionario: { + type: DataTypes.STRING, + allowNull: true + }, + created_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, + update_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, +}); + +export default Positions; \ No newline at end of file diff --git a/src/models/planilhasModel.js b/src/models/planilhasModel.js new file mode 100644 index 0000000..86d4e7e --- /dev/null +++ b/src/models/planilhasModel.js @@ -0,0 +1,34 @@ +import { DataTypes } from "sequelize"; +import sequelize from "../config/dbConfig"; + +const Spreadsheets = sequelize.define("tbPlanilhas", { + id: { + type: DataTypes.BIGINT, + primaryKey: true, + autoIncrement: true, + }, + nomePlanilha: { + type: DataTypes.STRING, + allowNull: true, + }, + urlPlanilha: { + type: DataTypes.STRING, + allowNull: true, + }, + planilhaSelecionada: { + type: DataTypes.BIGINT, + allowNull: true, + }, + created_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, + update_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, +}); + +export default Spreadsheets; \ No newline at end of file diff --git a/src/models/proviModel.js b/src/models/proviModel.js new file mode 100644 index 0000000..8a5ebca --- /dev/null +++ b/src/models/proviModel.js @@ -0,0 +1,45 @@ +import { DataTypes } from "sequelize"; +import sequelize from "../config/dbConfig"; + +const OldProv = sequelize.define("PROVISIONAMENTO", { + id: { + type: DataTypes.BIGINT, + primaryKey: true, + autoIncrement: true, + }, + clientes: { + type: DataTypes.STRING, + allowNull: true, + }, + tecnicoRua: { + type: DataTypes.STRING, + allowNull: true, + }, + numberSerial: { + type: DataTypes.STRING, + allowNull: true, + }, + tipoDeAtivacao: { + type: DataTypes.STRING, + allowNull: true, + }, + posicionamento: { + type: DataTypes.STRING, + allowNull: true, + }, + patrimonioNX: { + type: DataTypes.STRING, + allowNull: true, + }, + tecnicoSup: { + type: DataTypes.STRING, + allowNull: true, + }, + data: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, +}); + +export default OldProv; \ No newline at end of file diff --git a/src/models/provisionamentoModel.js b/src/models/provisionamentoModel.js new file mode 100644 index 0000000..69e2374 --- /dev/null +++ b/src/models/provisionamentoModel.js @@ -0,0 +1,68 @@ +import { DataTypes } from "sequelize"; +import sequelize from "../config/dbConfig"; +import User from "./usuarioModel"; +import ServiceType from "./tipoDeServicoModel"; + +const Provisioning = sequelize.define("tbProvisionamento", { + id: { + type: DataTypes.BIGINT, + primaryKey: true, + autoIncrement: true, + }, + nomeCliente: { + type: DataTypes.STRING, + allowNull: true, + }, + enderecoCliente: { + type: DataTypes.STRING, + allowNull: true, + }, + tecnicoRua: { + type: DataTypes.BIGINT, + allowNull: true, + references: { + model: User, + key: "id", + }, + }, + numeroDeSerie: { + type: DataTypes.STRING, + allowNull: true, + }, + posicionamento: { + type: DataTypes.STRING, + allowNull: true, + }, + patrimonioNaxos: { + type: DataTypes.STRING, + allowNull: true, + }, + tecnicoSup: { + type: DataTypes.BIGINT, + allowNull: true, + references: { + model: User, + key: "id", + }, + }, + tipoDeServico: { + type: DataTypes.BIGINT, + allowNull: true, + references: { + model: ServiceType, + key: "id", + }, + }, + created_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, + update_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, +}); + +export default Provisioning; \ No newline at end of file diff --git a/src/models/tipoDeServicoModel.js b/src/models/tipoDeServicoModel.js new file mode 100644 index 0000000..ba953fb --- /dev/null +++ b/src/models/tipoDeServicoModel.js @@ -0,0 +1,26 @@ +import { DataTypes } from "sequelize"; +import sequelize from "../config/dbConfig"; + +const ServiceType = sequelize.define("tbTipoDeServico", { + id: { + type: DataTypes.BIGINT, + primaryKey: true, + autoIncrement: true, + }, + tipoDeServico: { + type: DataTypes.STRING, + allowNull: true, + }, + created_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, + update_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, +}); + +export default ServiceType; \ No newline at end of file diff --git a/src/models/usuarioModel.js b/src/models/usuarioModel.js new file mode 100644 index 0000000..6b812de --- /dev/null +++ b/src/models/usuarioModel.js @@ -0,0 +1,47 @@ +import { DataTypes, Sequelize } from "sequelize"; +import sequelize from "../config/dbConfig.js"; + +const User = sequelize.define("tbUsuarios", { + id: { + type: DataTypes.BIGINT, + primaryKey: true, + autoIncrement: true, + }, + nomeFuncionario: { + type: DataTypes.STRING, + allowNull: true, + }, + cargoFuncionario: { + type: DataTypes.STRING, + allowNull: true, + }, + emailFuncionario: { + type: DataTypes.STRING, + allowNull: true, + unique: true, + }, + admin: { + type: DataTypes.BOOLEAN, + allowNull: true + }, + permissaoDoColaborador: { + type: DataTypes.STRING, + allowNull: true + }, + status: { + type: DataTypes.INTEGER, + allowNull: true + }, + created_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + allowNull: true, + }, + update_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + allowNull: true + } +}); + +export default User; \ No newline at end of file From 9c5eedfeffa4c25bbcd1329ecd066b84fd7453b5 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 17 Feb 2024 17:15:51 -0300 Subject: [PATCH 02/36] inserido model sequelize nos controllers --- package-lock.json | 4 +- src/controllers/ArquivosController.js | 58 ++--- src/controllers/ProvisionamentoController.js | 227 +++++------------- src/controllers/ServicosController.js | 6 +- src/models/{arquivos.js => arquivosModel.js} | 12 +- src/models/{proviModel.js => oldProvModel.js} | 8 +- src/models/tipoDeServicoModel.js | 11 +- 7 files changed, 106 insertions(+), 220 deletions(-) rename src/models/{arquivos.js => arquivosModel.js} (71%) rename src/models/{proviModel.js => oldProvModel.js} (82%) diff --git a/package-lock.json b/package-lock.json index b0ae458..040a2a1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "apiprovisionamento", - "version": "1.0.0", + "version": "1.5.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "apiprovisionamento", - "version": "1.0.0", + "version": "1.5.0", "license": "ISC", "dependencies": { "body-parser": "^1.20.2", diff --git a/src/controllers/ArquivosController.js b/src/controllers/ArquivosController.js index 5f00dd8..a1777a2 100644 --- a/src/controllers/ArquivosController.js +++ b/src/controllers/ArquivosController.js @@ -1,5 +1,6 @@ import db from "../config/dbConfig.js"; import constants from "../constants/constants.js"; +import Files from "../models/arquivosModel.js"; const responseModel = { success: false, @@ -12,33 +13,14 @@ export default { async listaArquivos(req, res) { const response = { ...responseModel }; response.data = []; - const dataFormatada = new Intl.DateTimeFormat("pt-BR", { - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - // weekday: 'long', - year: "numeric", - month: "2-digit", - day: "2-digit", - timeZone: "America/Sao_Paulo", - }); - const tbArquivos = await db`SELECT * FROM "tbArquivos"`; + const tbArquivos = await Files.findAll(); try { - - const resListaArquivosFormatado = tbArquivos.map((row) => { - return { - ...row, - created_at: dataFormatada.format(row.data), - update_at: dataFormatada.format(row.data) - }; - }); - if (tbArquivos.length > 0) { response.success = true; - response.found = resListaArquivosFormatado.length; - response.data.push(resListaArquivosFormatado); + response.found = tbArquivos.length; + response.data = tbArquivos } else { response.error = constants["404"].noFilesFound; } @@ -52,22 +34,19 @@ export default { async inserirArquivo(req, res) { const response = { ...responseModel }; - const dataAtual = new Date(); - const { + const { nomeArquivo, urlArquivo } = req.body; - let query = ""; try { - query = await db` - INSERT INTO "tbArquivos" ("nome", "url", "created_at", "update_at") - VALUES (${nomeArquivo}, ${urlArquivo}, ${dataAtual}, NULL) - RETURNING *;`; - - response.success = query.length > 0; + const resInserirArquivo = await Files.create({ + nome: nomeArquivo, + url: urlArquivo + }) - if (response.success) { + if (resInserirArquivo) { + console.log('Arquivo inserido com sucesso:', resInserirArquivo.toJSON()); response.success = true; response.data = constants['201'].fileCreatedSuccessfully } else { @@ -121,19 +100,15 @@ export default { async deletarArquivo(req, res) { const response = { ...responseModel }; const arqId = req.params.id; - let query = ""; try { - query = await db` - DELETE FROM "tbArquivos" WHERE "id"=${arqId} - RETURNING *;` + const resDeletarArquivo = await Files.findByPk(arqId); - response.success = query.length > 0; - if (response.success) { - response.success = query.length > 0; - response.data = query.length; - response.found = query.length; + if (resDeletarArquivo) { + response.success = true + response.found = resDeletarArquivo.length; response.data = constants["200"].deletedFile; + await resDeletarArquivo.destroy(); return res.status(200).json(response); } else { response.error = constants["404"].noFilesFound; @@ -143,7 +118,6 @@ export default { response.error = constants["500"].errorOccurred; return res.status(500).json(response); } - return res.json(response) } }; diff --git a/src/controllers/ProvisionamentoController.js b/src/controllers/ProvisionamentoController.js index 9702de3..6701632 100644 --- a/src/controllers/ProvisionamentoController.js +++ b/src/controllers/ProvisionamentoController.js @@ -1,7 +1,8 @@ -import express, { response } from "express"; +import { Op } from "sequelize"; import db from "../config/dbConfig.js"; import constants from "../constants/constants.js"; import json from "body-parser"; +import OldProv from "../models/oldProvModel.js" const responseModel = { success: false, @@ -13,35 +14,17 @@ const responseModel = { export default { async listaClientes(req, res) { const response = { ...responseModel }; - const dataFormatada = new Intl.DateTimeFormat("pt-BR", { - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - // weekday: 'long', - year: "numeric", - month: "2-digit", - day: "2-digit", - timeZone: "America/Sao_Paulo", - }); response.data = []; try { - const tbClientesProvisionados = await db`SELECT * FROM "PROVISIONAMENTO"`; - - // Formatar a data para cada registro retornado - const tbClientesProvisionadosFormatado = tbClientesProvisionados.map((row) => { - return { - ...row, - data: dataFormatada.format(row.data), - }; - }); + const tbClientesProvisionados = await OldProv.findAll(); - response.success = tbClientesProvisionadosFormatado.length > 0; + response.success = tbClientesProvisionados.length > 0; if (response.success) { response.success = true; - response.found = tbClientesProvisionadosFormatado.length; - response.data.push(tbClientesProvisionadosFormatado); + response.found = tbClientesProvisionados.length; + response.data = tbClientesProvisionados; } else { response.data = constants['404'].noCustomersFound } @@ -58,36 +41,23 @@ export default { async buscaCliente(req, res) { const response = { ...responseModel }; const { nomeCliente } = req.body; - const dataFormatada = new Intl.DateTimeFormat("pt-BR", { - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - // weekday: 'long', - year: "numeric", - month: "2-digit", - day: "2-digit", - timeZone: "America/Sao_Paulo", - }); response.data = []; - const resCliente = - await db`SELECT * FROM "PROVISIONAMENTO" WHERE "clientes" LIKE '%' || ${nomeCliente} || '%';`; - - // Formatar a data para cada registro retornado - const resClienteFormatado = resCliente.map((row) => { - return { - ...row, - data: dataFormatada.format(row.data), - }; + const resCliente = await OldProv.findAll({ + where: { + clientes: { + [Op.like]: `%${nomeCliente}%` // Correção aqui + } + } }); - response.success = resClienteFormatado.length > 0; + response.success = resCliente.length > 0; try { if (response.success) { response.success = true; - response.found = resClienteFormatado.length; - response.data.push(resClienteFormatado); + response.found = resCliente.length; + response.data = resCliente } else { response.error = constants["404"].userNotFound; return res.status(404).json(response); @@ -103,36 +73,23 @@ export default { async buscaServicoTecnico(req, res) { const response = { ...responseModel }; const { tecnicoRua } = req.body; - const dataFormatada = new Intl.DateTimeFormat("pt-BR", { - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - // weekday: 'long', - year: "numeric", - month: "2-digit", - day: "2-digit", - timeZone: "America/Sao_Paulo", - }); response.data = []; - const resTecnicoRua = - await db`SELECT * FROM "PROVISIONAMENTO" WHERE "tecnicoRua" LIKE '%' || ${tecnicoRua} || '%';`; - - // Formatar a data para cada registro retornado - const resTecnicoRuaFormatado = resTecnicoRua.map((row) => { - return { - ...row, - data: dataFormatada.format(row.data), - }; + const resTecnicoRua = await OldProv.findAll({ + where: { + tecnicoRua: { + [Op.like]: `%${tecnicoRua}%` + } + } }); - response.success = resTecnicoRuaFormatado.length > 0; + response.success = resTecnicoRua.length > 0; try { if (response.success) { response.success = true; - response.found = resTecnicoRuaFormatado.length; - response.data.push(resTecnicoRuaFormatado); + response.found = resTecnicoRua.length; + response.data = resTecnicoRua; } else { response.error = constants["404"].userNotFound; return res.status(404).json(response); @@ -148,36 +105,23 @@ export default { async buscaServicoSuporte(req, res) { const response = { ...responseModel }; const { tecnicoSup } = req.body; - const dataFormatada = new Intl.DateTimeFormat("pt-BR", { - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - // weekday: 'long', - year: "numeric", - month: "2-digit", - day: "2-digit", - timeZone: "America/Sao_Paulo", - }); response.data = []; - const resTecnicoSup = - await db`SELECT * FROM "PROVISIONAMENTO" WHERE "tecnicoSup" LIKE '%' || ${tecnicoSup} || '%';`; - - // Formatar a data para cada registro retornado - const resTecnicoSupFormatado = resTecnicoSup.map((row) => { - return { - ...row, - data: dataFormatada.format(row.data), - }; + const resTecnicoSup = await OldProv.findAll({ + where: { + tecnicoSup: { + [Op.like]: `%${tecnicoSup}%` + } + } }); - response.success = resTecnicoSupFormatado.length > 0; + response.success = resTecnicoSup.length > 0; try { if (response.success) { response.success = true; - response.found = resTecnicoSupFormatado.length; - response.data.push(resTecnicoSupFormatado); + response.found = resTecnicoSup.length; + response.data = resTecnicoSup; } else { response.error = constants["404"].userNotFound; return res.status(404).json(response); @@ -193,35 +137,22 @@ export default { async buscaSerialNumber(req, res) { const response = { ...responseModel }; let numberSerial = req.params.id; - const dataFormatada = new Intl.DateTimeFormat("pt-BR", { - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - // weekday: 'long', - year: "numeric", - month: "2-digit", - day: "2-digit", - timeZone: "America/Sao_Paulo", - }); response.data = []; try { - let resNumberSerial = - await db`SELECT * FROM "PROVISIONAMENTO" WHERE "numberSerial" LIKE '%' || ${numberSerial} || '%';`; - - // Formatar a data para cada registro retornado - let resNumberSerialFormatado = resNumberSerial.map((row) => { - return { - ...row, - data: dataFormatada.format(row.data), - }; - }); - - response.success = resNumberSerialFormatado.length > 0; + const resNumberSerial = await OldProv.findAll({ + where: { + numberSerial: { + [Op.like]: `%${numberSerial}%` + } + } + }) + + response.success = resNumberSerial.length > 0; if (response.success) { - response.success = resNumberSerialFormatado.length; - response.found = resNumberSerialFormatado.length; - response.data = resNumberSerialFormatado; + response.success = resNumberSerial.length; + response.found = resNumberSerial.length; + response.data = resNumberSerial; } else { response.error = constants["404"].userNotFound; return res.status(404).json(response); @@ -237,35 +168,20 @@ export default { async buscaPatrimonio(req, res) { const response = { ...responseModel }; let patrimonioNX = req.params.id; - const dataFormatada = new Intl.DateTimeFormat("pt-BR", { - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - year: "numeric", - month: "2-digit", - day: "2-digit", - timeZone: "America/Sao_Paulo", - }); response.data = []; try { - let resNumeroPatrimonioNX = - // await db`SELECT * FROM "PROVISIONAMENTO" WHERE "patrimonioNX" = "${patrimonioNX}"`; - await db`SELECT * FROM "PROVISIONAMENTO" WHERE "patrimonioNX" LIKE '%' || ${patrimonioNX} || '%';`; - - // Formatar a data para cada registro retornado - let resNumeroPatrimonioNXFormatado = resNumeroPatrimonioNX.map((row) => { - return { - ...row, - data: dataFormatada.format(row.data), - }; - }); - - response.success = resNumeroPatrimonioNXFormatado.length > 0; + const resNumeroPatrimonioNX = await OldProv.findAll({ + where: { + patrimonioNX: patrimonioNX + } + }) + + response.success = resNumeroPatrimonioNX.length > 0; if (response.success) { - response.success = resNumeroPatrimonioNXFormatado.length; - response.found = resNumeroPatrimonioNXFormatado.length; - response.data.push(resNumeroPatrimonioNXFormatado); + response.success = resNumeroPatrimonioNX.length; + response.found = resNumeroPatrimonioNX.length; + response.data = resNumeroPatrimonioNX; } else { response.error = constants["404"].heritageNotFound; return res.status(404).json(response); @@ -281,36 +197,21 @@ export default { async buscaTipoDeServico(req, res) { const response = { ...responseModel }; const { tipoDeAtivacao } = req.body; - const dataFormatada = new Intl.DateTimeFormat("pt-BR", { - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - // weekday: 'long', - year: "numeric", - month: "2-digit", - day: "2-digit", - timeZone: "America/Sao_Paulo", - }); response.data = []; - const resTipoDeAtivacao = - await db`SELECT * FROM "PROVISIONAMENTO" WHERE "tipoDeAtivacao" LIKE '%' || ${tipoDeAtivacao} || '%';`; - - // Formatar a data para cada registro retornado - const resTipoDeAtivacaoFormatado = resTipoDeAtivacao.map((row) => { - return { - ...row, - data: dataFormatada.format(row.data), - }; - }); + const resTipoDeAtivacao = await OldProv.findAll({ + where: { + tipoDeAtivacao: tipoDeAtivacao + } + }) - response.success = resTipoDeAtivacaoFormatado.length > 0; + response.success = resTipoDeAtivacao.length > 0; try { if (response.success) { response.success = true; - response.found = resTipoDeAtivacaoFormatado.length; - response.data.push(resTipoDeAtivacaoFormatado); + response.found = resTipoDeAtivacao.length; + response.data = resTipoDeAtivacao; } else { response.error = constants["404"].userNotFound; return res.status(404).json(response); @@ -350,8 +251,6 @@ export default { if (response.success) { response.success = true; response.found = dataAtual.length; - // response.data = query; - // response.data.push("PROVISIONADO COM SUCESSO"); response.data = constants["201"].successfullyProvisioned; } else { response.error = constants["404"].userNotFound; diff --git a/src/controllers/ServicosController.js b/src/controllers/ServicosController.js index 8dbd3af..8e3ef6d 100644 --- a/src/controllers/ServicosController.js +++ b/src/controllers/ServicosController.js @@ -1,5 +1,6 @@ import db from "../config/dbConfig.js"; import constants from "../constants/constants.js"; +import ServiceType from "../models/tipoDeServicoModel.js"; const responseModel = { success: false, @@ -14,7 +15,8 @@ export default { response.data = []; try { - const tbTipoDeServico = await db`SELECT * FROM "tbTipoDeServico"`; + const tbTipoDeServico = await ServiceType.findAll(); + // const tbTipoDeServico = await db`SELECT * FROM "tbTipoDeServico"`; response.success = tbTipoDeServico.length > 0; if (response.success) { @@ -25,7 +27,7 @@ export default { response.error = constants["404"].noServiceFound; } } catch (e) { - console.error("ERROR:", e); + console.error("ERROR:", e.message); } return res.json(response); }, diff --git a/src/models/arquivos.js b/src/models/arquivosModel.js similarity index 71% rename from src/models/arquivos.js rename to src/models/arquivosModel.js index 8ac3879..43e5c60 100644 --- a/src/models/arquivos.js +++ b/src/models/arquivosModel.js @@ -1,5 +1,5 @@ -import { DataTypes } from "sequelize"; -import sequelize from "../config/dbConfig"; +import { DataTypes, Sequelize } from "sequelize"; +import sequelize from "../config/dbConfig.js"; const Files = sequelize.define("tbArquivos", { id: { @@ -9,11 +9,11 @@ const Files = sequelize.define("tbArquivos", { }, nome: { type: DataTypes.STRING, - allowNull: true, + allowNull: false, }, url: { type: DataTypes.STRING, - allowNull: true, + allowNull: false, }, created_at: { type: DataTypes.DATE, @@ -25,6 +25,10 @@ const Files = sequelize.define("tbArquivos", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, +}, +{ + tableName: "tbArquivos", + freezeTableName: true }); export default Files; \ No newline at end of file diff --git a/src/models/proviModel.js b/src/models/oldProvModel.js similarity index 82% rename from src/models/proviModel.js rename to src/models/oldProvModel.js index 8a5ebca..788eaf6 100644 --- a/src/models/proviModel.js +++ b/src/models/oldProvModel.js @@ -1,5 +1,5 @@ import { DataTypes } from "sequelize"; -import sequelize from "../config/dbConfig"; +import sequelize from "../config/dbConfig.js"; const OldProv = sequelize.define("PROVISIONAMENTO", { id: { @@ -37,9 +37,13 @@ const OldProv = sequelize.define("PROVISIONAMENTO", { }, data: { type: DataTypes.DATE, - defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + defaultValue: sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, +}, +{ + tableName: "PROVISIONAMENTO", + freezeTableName: true }); export default OldProv; \ No newline at end of file diff --git a/src/models/tipoDeServicoModel.js b/src/models/tipoDeServicoModel.js index ba953fb..316501c 100644 --- a/src/models/tipoDeServicoModel.js +++ b/src/models/tipoDeServicoModel.js @@ -1,5 +1,5 @@ import { DataTypes } from "sequelize"; -import sequelize from "../config/dbConfig"; +import sequelize from "../config/dbConfig.js"; const ServiceType = sequelize.define("tbTipoDeServico", { id: { @@ -13,14 +13,17 @@ const ServiceType = sequelize.define("tbTipoDeServico", { }, created_at: { type: DataTypes.DATE, - defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + defaultValue: DataTypes.NOW, allowNull: true, }, update_at: { type: DataTypes.DATE, - defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + defaultValue: DataTypes.NOW, allowNull: true, }, +}, { + tableName: "tbTipoDeServico", + freezeTableName: true }); -export default ServiceType; \ No newline at end of file +export default ServiceType; From cb733dad3cbc52b85999fe91bfd280db0642de2b Mon Sep 17 00:00:00 2001 From: Jean Date: Sat, 17 Feb 2024 21:35:23 -0300 Subject: [PATCH 03/36] inserido metodo update no controller arquivo --- src/controllers/ArquivosController.js | 59 ++++++++++++--------------- src/models/cargosModel.js | 2 +- src/models/planilhasModel.js | 2 +- src/models/provisionamentoModel.js | 2 +- 4 files changed, 30 insertions(+), 35 deletions(-) diff --git a/src/controllers/ArquivosController.js b/src/controllers/ArquivosController.js index a1777a2..ae45423 100644 --- a/src/controllers/ArquivosController.js +++ b/src/controllers/ArquivosController.js @@ -20,7 +20,7 @@ export default { if (tbArquivos.length > 0) { response.success = true; response.found = tbArquivos.length; - response.data = tbArquivos + response.data = tbArquivos; } else { response.error = constants["404"].noFilesFound; } @@ -34,60 +34,55 @@ export default { async inserirArquivo(req, res) { const response = { ...responseModel }; - const { - nomeArquivo, - urlArquivo - } = req.body; + const { nomeArquivo, urlArquivo } = req.body; try { const resInserirArquivo = await Files.create({ nome: nomeArquivo, - url: urlArquivo - }) + url: urlArquivo, + }); if (resInserirArquivo) { - console.log('Arquivo inserido com sucesso:', resInserirArquivo.toJSON()); + console.log( + "Arquivo inserido com sucesso:", + resInserirArquivo.toJSON() + ); response.success = true; - response.data = constants['201'].fileCreatedSuccessfully + response.data = constants["201"].fileCreatedSuccessfully; } else { - response.data = constants['404'].noFilesFound - return res.status(404).json(response) + response.data = constants["404"].noFilesFound; + return res.status(404).json(response); } - } catch (error) { console.error("ERROR", error); response.error = constants["500"].errorOccurred; return res.status(500).json(response); } - return res.json(response) + return res.json(response); }, - + async atualizarArquivo(req, res) { const response = { ...responseModel }; const dataAtual = new Date(); const arqId = req.params.id; - const { - nomeArquivo, - urlArquivo - } = req.body; - let query = ""; + const { nomeArquivo, urlArquivo } = req.body; - try { - query = await db` - UPDATE "tbArquivos" SET "nome"=${nomeArquivo}, "url"=${urlArquivo}, "update_at"=${dataAtual} - WHERE "id"=${arqId} - RETURNING *;` + const atualizaArquivo = { + nome: nomeArquivo, + url: urlArquivo, + }; - response.success = query.length > 0; + try { + const arquivo = await Files.findByPk(arqId); - if (response.success) { + if (arquivo) { + await arquivo.update(atualizaArquivo); response.success = true; - response.found = query.length; + // response.found = resAtualizarArquivo.length; response.data = constants["201"].fileUpdateSuccess; } else { - response.error = constants["404"].noFilesFound + response.error = constants["404"].noFilesFound; } - } catch (error) { console.error("ERROR", error); response.error = constants["500"].errorOccurred; @@ -105,7 +100,7 @@ export default { const resDeletarArquivo = await Files.findByPk(arqId); if (resDeletarArquivo) { - response.success = true + response.success = true; response.found = resDeletarArquivo.length; response.data = constants["200"].deletedFile; await resDeletarArquivo.destroy(); @@ -118,6 +113,6 @@ export default { response.error = constants["500"].errorOccurred; return res.status(500).json(response); } - return res.json(response) - } + return res.json(response); + }, }; diff --git a/src/models/cargosModel.js b/src/models/cargosModel.js index 628c118..d583285 100644 --- a/src/models/cargosModel.js +++ b/src/models/cargosModel.js @@ -1,5 +1,5 @@ import { DataTypes } from "sequelize"; -import sequelize from "../config/dbConfig"; +import sequelize from "../config/dbConfig.js"; const Positions = sequelize.define("tbCargos", { id: { diff --git a/src/models/planilhasModel.js b/src/models/planilhasModel.js index 86d4e7e..5705fb9 100644 --- a/src/models/planilhasModel.js +++ b/src/models/planilhasModel.js @@ -1,5 +1,5 @@ import { DataTypes } from "sequelize"; -import sequelize from "../config/dbConfig"; +import sequelize from "../config/dbConfig.js"; const Spreadsheets = sequelize.define("tbPlanilhas", { id: { diff --git a/src/models/provisionamentoModel.js b/src/models/provisionamentoModel.js index 69e2374..4d363ad 100644 --- a/src/models/provisionamentoModel.js +++ b/src/models/provisionamentoModel.js @@ -1,5 +1,5 @@ import { DataTypes } from "sequelize"; -import sequelize from "../config/dbConfig"; +import sequelize from "../config/dbConfig.js"; import User from "./usuarioModel"; import ServiceType from "./tipoDeServicoModel"; From 1e5dc4323b63b86467859c6cac9b5bce80fc16ac Mon Sep 17 00:00:00 2001 From: Jean Date: Sat, 17 Feb 2024 21:53:16 -0300 Subject: [PATCH 04/36] inserido sequelize no model de cargo --- src/constants/constants.js | 3 +- src/controllers/CargoController.js | 10 +++--- src/models/cargosModel.js | 51 +++++++++++++++++------------- src/routes/routes.js | 2 +- 4 files changed, 37 insertions(+), 29 deletions(-) diff --git a/src/constants/constants.js b/src/constants/constants.js index 7811bb1..dea834b 100644 --- a/src/constants/constants.js +++ b/src/constants/constants.js @@ -36,7 +36,8 @@ export default { noServiceFound: "Nenhum Serviço Encontrato", noProductsFound: "Nenhum produto encontrado!", noListsFound: "Nenhuma lista foi encontrada", - noCustomersFound: "Nenhum cliente encontrado" + noCustomersFound: "Nenhum cliente encontrado", + noPositionsFound: "Nenhum cargo encontrado" }, 409: { status: 409, diff --git a/src/controllers/CargoController.js b/src/controllers/CargoController.js index a2390ff..2a4a92b 100644 --- a/src/controllers/CargoController.js +++ b/src/controllers/CargoController.js @@ -1,5 +1,6 @@ import db from "../config/dbConfig.js"; import constants from "../constants/constants.js"; +import Positions from "../models/cargosModel.js"; const responseModel = { success: false, @@ -12,18 +13,17 @@ export default { async listaCargo(req, res) { const response = { ...responseModel }; response.data = []; - let query; try { - query = await db`SELECT * FROM "tbCargos"`; + const listaCargos = await Positions.findAll() - response.success = query.length > 0; + response.success = listaCargos.length > 0; if (response.success) { response.success = true; - response.data = query + response.data = listaCargos } else { - response.data = constants['404'].noServiceFound + response.data = constants['404'].noPositionsFound return res.status(404).json(response) } } catch (error) { diff --git a/src/models/cargosModel.js b/src/models/cargosModel.js index d583285..582f68d 100644 --- a/src/models/cargosModel.js +++ b/src/models/cargosModel.js @@ -1,26 +1,33 @@ -import { DataTypes } from "sequelize"; +import { DataTypes, Sequelize } from "sequelize"; import sequelize from "../config/dbConfig.js"; -const Positions = sequelize.define("tbCargos", { - id: { - type: DataTypes.BIGINT, - primaryKey: true, - autoIncrement: true, +const Positions = sequelize.define( + "tbCargos", + { + id: { + type: DataTypes.BIGINT, + primaryKey: true, + autoIncrement: true, + }, + cargoFuncionario: { + type: DataTypes.STRING, + allowNull: true, + }, + created_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, + update_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, }, - cargoFuncionario: { - type: DataTypes.STRING, - allowNull: true - }, - created_at: { - type: DataTypes.DATE, - defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), - allowNull: true, - }, - update_at: { - type: DataTypes.DATE, - defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), - allowNull: true, - }, -}); + { + tableName: "tbCargos", + freezeTableName: true, + } +); -export default Positions; \ No newline at end of file +export default Positions; diff --git a/src/routes/routes.js b/src/routes/routes.js index ecd2c75..6bd6ec3 100644 --- a/src/routes/routes.js +++ b/src/routes/routes.js @@ -27,7 +27,7 @@ router .get("/listaArquivos", verifyJWT, ArquivosController.listaArquivos) .get("/listaServicos", verifyJWT, ServicosController.listaTipoDeServico) - .get("/listaCargo", verifyJWT, CargoController.listaCargo) + .get("/listaCargos", verifyJWT, CargoController.listaCargo) .post("/login", AuthController.login) From 5f73a544f9e614b976f06735d0ae816f34300196 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Mon, 19 Feb 2024 00:26:15 -0300 Subject: [PATCH 05/36] inserido docker - ajustado rotas com sequelize --- .dockerignore | 1 + Dockerfile | 13 ++++++ docker-compose.yml | 12 ++++++ package.json | 4 +- src/controllers/ProvisionamentoController.js | 43 ++++++++++++-------- src/controllers/ServicosController.js | 40 ++++++++++-------- 6 files changed, 79 insertions(+), 34 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100644 docker-compose.yml diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b512c09 --- /dev/null +++ b/.dockerignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..018e721 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM node:alpine + +RUN mkdir -p /usr/app/apiProvisionamento +WORKDIR /usr/app/apiProvisionamento + +COPY package*.json ./ +RUN npm install + +COPY . . + +EXPOSE 3000 + +CMD [ "npm", "start" ] \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..f7b9ddb --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,12 @@ +version: '3' + +services: + app: + build: . + command: npm run dev + ports: + - 3000:3000 + volumes: + - .:/usr/app/apiProvisionamento + environment: + - NODE_ENV=development \ No newline at end of file diff --git a/package.json b/package.json index 6c10822..d085c3a 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,11 @@ { "name": "apiprovisionamento", - "version": "1.5.0", + "version": "1.6.0", "description": "", "main": "server.js", "type": "module", "scripts": { - "dev": "nodemon server.js", + "dev": "nodemon --legacy-watch server.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], diff --git a/src/controllers/ProvisionamentoController.js b/src/controllers/ProvisionamentoController.js index 6701632..7766a66 100644 --- a/src/controllers/ProvisionamentoController.js +++ b/src/controllers/ProvisionamentoController.js @@ -238,19 +238,28 @@ export default { tecnicoSup, tipoDeServico, } = req.body; - let query = ""; + // let query = ""; try { - query = await db` - INSERT INTO "tbProvisionamento" ("nomeCliente", "enderecoCliente", "tecnicoRua", "numeroDeSerie", "posicionamento", "patrimonioNaxos", "tecnicoSup", "created_at", "update_at", "tipoDeServico") - VALUES (${nomeCliente}, ${enderecoCliente}, ${tecnicoRua}, ${numeroDeSerie}, ${posicionamento}, ${patrimonioNaxos}, ${tecnicoSup}, ${dataAtual}, ${dataAtual}, ${tipoDeServico}) - RETURNING *;`; + const provisionaCliente = await OldProv.create({ + clientes: nomeCliente, + tecnicoRua: tecnicoRua, + numberSerial: numeroDeSerie, + tipoDeAtivacao: tipoDeServico, + posicionamento: posicionamento, + patrimonioNX: patrimonioNaxos, + tecnicoSup: tecnicoSup + }) + // query = await db` + // INSERT INTO "tbProvisionamento" ("nomeCliente", "enderecoCliente", "tecnicoRua", "numeroDeSerie", "posicionamento", "patrimonioNaxos", "tecnicoSup", "created_at", "update_at", "tipoDeServico") + // VALUES (${nomeCliente}, ${enderecoCliente}, ${tecnicoRua}, ${numeroDeSerie}, ${posicionamento}, ${patrimonioNaxos}, ${tecnicoSup}, ${dataAtual}, ${dataAtual}, ${tipoDeServico}) + // RETURNING *;`; - response.success = query.length > 0; + response.success = provisionaCliente.length > 0; if (response.success) { response.success = true; - response.found = dataAtual.length; + response.found = provisionaCliente.length; response.data = constants["201"].successfullyProvisioned; } else { response.error = constants["404"].userNotFound; @@ -271,15 +280,17 @@ export default { let query = ""; try { - query = await db` - DELETE FROM "tbProvisionamento" - WHERE "id" = ${clienteId} - RETURNING *;`; - - response.success = query.length > 0; - if (response.success) { - response.data = query.length; - response.found = query.length; + const removeCliente = await OldProv.findByPk(clienteId) + // query = await db` + // DELETE FROM "tbProvisionamento" + // WHERE "id" = ${clienteId} + // RETURNING *;`; + + // response.success = query.length > 0; + if (removeCliente) { + response.success = true + response.found = removeCliente.length; + await removeCliente.destroy(); response.data = constants["200"].deletedClient; } else { response.error = constants["404"].userNotFound; diff --git a/src/controllers/ServicosController.js b/src/controllers/ServicosController.js index 8e3ef6d..bee99c1 100644 --- a/src/controllers/ServicosController.js +++ b/src/controllers/ServicosController.js @@ -68,19 +68,25 @@ export default { const dataAtual = new Date(); const serviceId = req.params.id; const { tipoDeServico } = req.body; - let query = ""; + // let query = ""; + + const atualizaServico = { + tipoDeServico: tipoDeServico + } try { - query = await db` - UPDATE "tbTipoDeServico" SET "tipoDeServico"=${tipoDeServico}, "update_at"=${dataAtual} - WHERE "id"=${serviceId} - RETURNING *;`; + const servico = await ServiceType.findByPk(serviceId); + // query = await db` + // UPDATE "tbTipoDeServico" SET "tipoDeServico"=${tipoDeServico}, "update_at"=${dataAtual} + // WHERE "id"=${serviceId} + // RETURNING *;`; - response.success = query.length > 0; + // response.success = query.length > 0; - if (response.success) { + if (servico) { + await servico.update(atualizaServico); response.success = true; - response.found = query.length; + response.found = servico.length; response.data = constants["201"].serviceUpdateSuccess; } else { response.error = constants["404"].noServiceFound; @@ -97,17 +103,19 @@ export default { async deletarTipoDeServico(req, res) { const response = { ...responseModel }; const serviceId = req.params.id; - let query = ""; + // let query = ""; try { - query = await db` - DELETE FROM "tbTipoDeServico" WHERE "id"=${serviceId} - RETURNING *;`; + const deletaServico = await ServiceType.findByPk(serviceId); + // query = await db` + // DELETE FROM "tbTipoDeServico" WHERE "id"=${serviceId} + // RETURNING *;`; - response.success = query.length > 0; - if (response.success) { - response.data = query.length; - response.found = query.length; + // response.success = query.length > 0; + if (deletaServico) { + response.success = true; + response.found = deletaServico.length; + await deletaServico.destroy(); response.data = constants["200"].serviceDeleted; return res.status(200).json(response); } else { From 5a8b874c3e28bfb275ae073d07a449dc4aecae3e Mon Sep 17 00:00:00 2001 From: Jean Date: Sun, 25 Feb 2024 16:40:26 -0300 Subject: [PATCH 06/36] alterado msgs das contants --- src/constants/constants.js | 50 +++++++++++++++++++------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/src/constants/constants.js b/src/constants/constants.js index dea834b..8bf687f 100644 --- a/src/constants/constants.js +++ b/src/constants/constants.js @@ -1,56 +1,56 @@ export default { 200: { status: 200, - userError: "Usuário não pode ser criado", + userError: "Usuário Não Pode Ser Criado", deletedUser: "Usuário Deletado", - deletedClient: "Cliente deletado", - deletedDuplicates: "Duplicados foram deletados!", - serviceDeleted: "Serviço deletado", - deletedFile: "Arquivo deletado" + deletedClient: "Cliente Deletado", + deletedDuplicates: "Duplicados Foram Deletados!", + serviceDeleted: "Serviço Deletado", + deletedFile: "Arquivo Deletado" }, 201: { status: 201, - userSuccess: "Usuário foi criado com Sucesso", - userUpdateSuccess: "Usuário foi atualizado com Sucesso", + userSuccess: "Usuário Foi Criado com Sucesso", + userUpdateSuccess: "Usuário foi Atualizado com Sucesso", successfullyProvisioned: "Provisionado com Sucesso", - serviceCreatedSuccessfully: "Serviço criado com Sucesso", - serviceUpdateSuccess: "Serviço atualizado com Sucesso", - fileCreatedSuccessfully: "Arquivo criado com Sucesso", - fileUpdateSuccess: "Arquivo atualizado com Sucesso" + serviceCreatedSuccessfully: "Serviço Criado com Sucesso", + serviceUpdateSuccess: "Serviço Atualizado com Sucesso", + fileCreatedSuccessfully: "Arquivo Criado com Sucesso", + fileUpdateSuccess: "Arquivo Atualizado com Sucesso" }, 401: { status: 401, - tokenItsNotValid: "Token inválido", - userLoginError: "Login ou senha incorretos", + tokenItsNotValid: "Token Inválido", + userLoginError: "Login ou Senha Incorretos", inactiveUser: "Usuário Inativo" }, 403: { status: 403, - tokenNotFound: "Token de autenticação não fornecido.", + tokenNotFound: "Token de Autenticação não Fornecido.", }, 404: { status: 404, - userNotFound: "Usuário não encontrado", - heritageNotFound: "Patrimonio não encontrado", - noFilesFound: "Nenhum arquivo encontrado!", + userNotFound: "Usuário Não Encontrado", + heritageNotFound: "Patrimonio Não Encontrado", + noFilesFound: "Nenhum Arquivo Encontrado!", noServiceFound: "Nenhum Serviço Encontrato", - noProductsFound: "Nenhum produto encontrado!", - noListsFound: "Nenhuma lista foi encontrada", - noCustomersFound: "Nenhum cliente encontrado", - noPositionsFound: "Nenhum cargo encontrado" + noProductsFound: "Nenhum Produto Encontrado!", + noListsFound: "Nenhuma Lista Foi Encontrada", + noCustomersFound: "Nenhum Cliente Encontrado", + noPositionsFound: "Nenhum Cargo Encontrado" }, 409: { status: 409, - userAlreadyExist: "Usuário já existe na nossa base de dados", - emailAlreadyExiste: "O email já está em uso.", + userAlreadyExist: "Usuário já Existe na Nossa Base de Dados", + emailAlreadyExiste: "O Email já Está em Uso.", }, 422: { status: 422, - requiredfields: "Preencha todos os campos", + requiredfields: "Preencha Todos os Campos", userNotDefined: "user: É obrigatório" }, 500: { status: 500, - errorOccurred: "Ocorreu um erro ao processar a solicitação.", + errorOccurred: "Ocorreu um erro ao Processar a Solicitação.", } }; \ No newline at end of file From b93291cdcb1fa11a4b10060af77ce3de63fec3f9 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Wed, 13 Mar 2024 16:46:44 -0300 Subject: [PATCH 07/36] refatorado const response e data response, inserido diretorio helpers --- src/controllers/ArquivosController.js | 12 +---- src/controllers/AuthController.js | 9 +--- src/controllers/CargoController.js | 10 +---- src/controllers/ProvisionamentoController.js | 29 +----------- src/controllers/ServicosController.js | 29 ++---------- src/controllers/UsuarioController.js | 37 +++------------ src/helpers/dataFormatadaHelper.js | 9 ++++ src/helpers/responseModelHelper.js | 6 +++ src/models/usuarioModel.js | 4 ++ src/models/usuariosModel.js | 47 ++++++++++++++++++++ 10 files changed, 83 insertions(+), 109 deletions(-) create mode 100644 src/helpers/dataFormatadaHelper.js create mode 100644 src/helpers/responseModelHelper.js create mode 100644 src/models/usuariosModel.js diff --git a/src/controllers/ArquivosController.js b/src/controllers/ArquivosController.js index ae45423..d68e278 100644 --- a/src/controllers/ArquivosController.js +++ b/src/controllers/ArquivosController.js @@ -1,17 +1,12 @@ import db from "../config/dbConfig.js"; import constants from "../constants/constants.js"; import Files from "../models/arquivosModel.js"; +import { responseModel } from "../helpers/responseModelHelper.js"; -const responseModel = { - success: false, - found: 0, - data: [], - error: "", -}; +const response = { ...responseModel }; export default { async listaArquivos(req, res) { - const response = { ...responseModel }; response.data = []; const tbArquivos = await Files.findAll(); @@ -33,7 +28,6 @@ export default { }, async inserirArquivo(req, res) { - const response = { ...responseModel }; const { nomeArquivo, urlArquivo } = req.body; try { @@ -62,7 +56,6 @@ export default { }, async atualizarArquivo(req, res) { - const response = { ...responseModel }; const dataAtual = new Date(); const arqId = req.params.id; const { nomeArquivo, urlArquivo } = req.body; @@ -93,7 +86,6 @@ export default { }, async deletarArquivo(req, res) { - const response = { ...responseModel }; const arqId = req.params.id; try { diff --git a/src/controllers/AuthController.js b/src/controllers/AuthController.js index 2d19358..f167cd9 100644 --- a/src/controllers/AuthController.js +++ b/src/controllers/AuthController.js @@ -3,17 +3,12 @@ import constants from "../constants/constants.js"; import jwt from "jsonwebtoken"; import User from "../models/usuarioModel.js"; const SECRET = process.env.SECRET; +import { responseModel } from "../helpers/responseModelHelper.js"; -const responseModel = { - success: false, - found: 0, - data: [], - error: "", -}; +const response = { ...responseModel }; export default { async login(req, res) { - const response = { ...responseModel }; response.data = []; let { email, password } = req.body; diff --git a/src/controllers/CargoController.js b/src/controllers/CargoController.js index 2a4a92b..f9309a9 100644 --- a/src/controllers/CargoController.js +++ b/src/controllers/CargoController.js @@ -1,17 +1,11 @@ import db from "../config/dbConfig.js"; import constants from "../constants/constants.js"; import Positions from "../models/cargosModel.js"; - -const responseModel = { - success: false, - found: 0, - data: [], - error: "", -}; +import { responseModel } from "../helpers/responseModelHelper.js"; +const response = { ...responseModel }; export default { async listaCargo(req, res) { - const response = { ...responseModel }; response.data = []; try { diff --git a/src/controllers/ProvisionamentoController.js b/src/controllers/ProvisionamentoController.js index 7766a66..28bbf52 100644 --- a/src/controllers/ProvisionamentoController.js +++ b/src/controllers/ProvisionamentoController.js @@ -3,17 +3,12 @@ import db from "../config/dbConfig.js"; import constants from "../constants/constants.js"; import json from "body-parser"; import OldProv from "../models/oldProvModel.js" +import { responseModel } from "../helpers/responseModelHelper.js"; -const responseModel = { - success: false, - found: 0, - data: [], - error: "", -}; +const response = { ...responseModel }; export default { async listaClientes(req, res) { - const response = { ...responseModel }; response.data = []; try { @@ -39,7 +34,6 @@ export default { }, async buscaCliente(req, res) { - const response = { ...responseModel }; const { nomeCliente } = req.body; response.data = []; @@ -71,7 +65,6 @@ export default { }, async buscaServicoTecnico(req, res) { - const response = { ...responseModel }; const { tecnicoRua } = req.body; response.data = []; @@ -103,7 +96,6 @@ export default { }, async buscaServicoSuporte(req, res) { - const response = { ...responseModel }; const { tecnicoSup } = req.body; response.data = []; @@ -135,7 +127,6 @@ export default { }, async buscaSerialNumber(req, res) { - const response = { ...responseModel }; let numberSerial = req.params.id; response.data = []; @@ -166,7 +157,6 @@ export default { }, async buscaPatrimonio(req, res) { - const response = { ...responseModel }; let patrimonioNX = req.params.id; response.data = []; @@ -195,7 +185,6 @@ export default { }, async buscaTipoDeServico(req, res) { - const response = { ...responseModel }; const { tipoDeAtivacao } = req.body; response.data = []; @@ -225,9 +214,7 @@ export default { }, async provisionaClientes(req, res) { - const response = { ...responseModel }; response.data = []; - const dataAtual = new Date(); const { nomeCliente, enderecoCliente, @@ -238,7 +225,6 @@ export default { tecnicoSup, tipoDeServico, } = req.body; - // let query = ""; try { const provisionaCliente = await OldProv.create({ @@ -250,10 +236,6 @@ export default { patrimonioNX: patrimonioNaxos, tecnicoSup: tecnicoSup }) - // query = await db` - // INSERT INTO "tbProvisionamento" ("nomeCliente", "enderecoCliente", "tecnicoRua", "numeroDeSerie", "posicionamento", "patrimonioNaxos", "tecnicoSup", "created_at", "update_at", "tipoDeServico") - // VALUES (${nomeCliente}, ${enderecoCliente}, ${tecnicoRua}, ${numeroDeSerie}, ${posicionamento}, ${patrimonioNaxos}, ${tecnicoSup}, ${dataAtual}, ${dataAtual}, ${tipoDeServico}) - // RETURNING *;`; response.success = provisionaCliente.length > 0; @@ -274,19 +256,12 @@ export default { }, async removeCliente(req, res) { - const response = { ...responseModel }; response.data = []; let clienteId = req.params.id; - let query = ""; try { const removeCliente = await OldProv.findByPk(clienteId) - // query = await db` - // DELETE FROM "tbProvisionamento" - // WHERE "id" = ${clienteId} - // RETURNING *;`; - // response.success = query.length > 0; if (removeCliente) { response.success = true response.found = removeCliente.length; diff --git a/src/controllers/ServicosController.js b/src/controllers/ServicosController.js index bee99c1..6b3c35d 100644 --- a/src/controllers/ServicosController.js +++ b/src/controllers/ServicosController.js @@ -1,22 +1,16 @@ import db from "../config/dbConfig.js"; import constants from "../constants/constants.js"; import ServiceType from "../models/tipoDeServicoModel.js"; +import { responseModel } from "../helpers/responseModelHelper.js"; -const responseModel = { - success: false, - found: 0, - data: [], - error: "", -}; +const response = { ...responseModel }; export default { async listaTipoDeServico(req, res) { - const response = { ...responseModel }; response.data = []; try { const tbTipoDeServico = await ServiceType.findAll(); - // const tbTipoDeServico = await db`SELECT * FROM "tbTipoDeServico"`; response.success = tbTipoDeServico.length > 0; if (response.success) { @@ -33,7 +27,6 @@ export default { }, async criarTipoDeServico(req, res) { - const response = { ...responseModel }; const dataAtual = new Date(); const { tipoDeServico } = req.body; let query = ""; @@ -64,24 +57,16 @@ export default { }, async atualizaTipoDeServico(req, res) { - const response = { ...responseModel }; const dataAtual = new Date(); const serviceId = req.params.id; const { tipoDeServico } = req.body; - // let query = ""; const atualizaServico = { - tipoDeServico: tipoDeServico - } + tipoDeServico: tipoDeServico, + }; try { const servico = await ServiceType.findByPk(serviceId); - // query = await db` - // UPDATE "tbTipoDeServico" SET "tipoDeServico"=${tipoDeServico}, "update_at"=${dataAtual} - // WHERE "id"=${serviceId} - // RETURNING *;`; - - // response.success = query.length > 0; if (servico) { await servico.update(atualizaServico); @@ -101,17 +86,11 @@ export default { }, async deletarTipoDeServico(req, res) { - const response = { ...responseModel }; const serviceId = req.params.id; - // let query = ""; try { const deletaServico = await ServiceType.findByPk(serviceId); - // query = await db` - // DELETE FROM "tbTipoDeServico" WHERE "id"=${serviceId} - // RETURNING *;`; - // response.success = query.length > 0; if (deletaServico) { response.success = true; response.found = deletaServico.length; diff --git a/src/controllers/UsuarioController.js b/src/controllers/UsuarioController.js index a999db7..74276ca 100644 --- a/src/controllers/UsuarioController.js +++ b/src/controllers/UsuarioController.js @@ -3,29 +3,16 @@ import db from "../config/dbConfig.js"; import md5 from "md5"; import constants from "../constants/constants.js"; import User from "../models/usuarioModel.js"; +import Users from "../models/usuariosModel.js"; +import { responseModel } from "../helpers/responseModelHelper.js"; +import { dataFormatada } from "../helpers/dataFormatadaHelper.js"; -const responseModel = { - success: false, - found: 0, - data: [], - error: "", -}; +const response = { ...responseModel }; export default { async listaUsuarios(req, res) { - const response = { ...responseModel }; - const dataFormatada = new Intl.DateTimeFormat("pt-BR", { - year: "numeric", - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - timeZoneName: "short", - }); - try { - const findAllUsers = await User.findAll({ + const findAllUsers = await Users.findAll({ order: [ ["status", "DESC"], ["id", "ASC"], @@ -61,18 +48,7 @@ export default { }, async listaUsuario(req, res) { - const response = { ...responseModel }; let userId = req.params.id; - const dataFormatada = new Intl.DateTimeFormat("pt-BR", { - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - // weekday: 'long', - year: "numeric", - month: "2-digit", - day: "2-digit", - timeZone: "America/Sao_Paulo", - }); response.data = []; try { @@ -113,7 +89,6 @@ export default { }, async inserirUsuario(req, res) { - const response = { ...responseModel }; const dataAtual = new Date(); const { nomeFuncionario, @@ -173,7 +148,6 @@ export default { }, async atualizarUsuario(req, res) { - const response = { ...responseModel }; const dataAtual = new Date(); const userId = req.params.id; const { @@ -233,7 +207,6 @@ export default { }, async deletarUsuario(req, res) { - const response = { ...responseModel }; response.data = []; const userId = req.params.id; let query = ""; diff --git a/src/helpers/dataFormatadaHelper.js b/src/helpers/dataFormatadaHelper.js new file mode 100644 index 0000000..dec7fac --- /dev/null +++ b/src/helpers/dataFormatadaHelper.js @@ -0,0 +1,9 @@ +export const dataFormatada = new Intl.DateTimeFormat("pt-BR", { + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + timeZoneName: "short", +}); \ No newline at end of file diff --git a/src/helpers/responseModelHelper.js b/src/helpers/responseModelHelper.js new file mode 100644 index 0000000..8e74680 --- /dev/null +++ b/src/helpers/responseModelHelper.js @@ -0,0 +1,6 @@ +export const responseModel = { + success: false, + found: 0, + data: [], + error: "", +}; \ No newline at end of file diff --git a/src/models/usuarioModel.js b/src/models/usuarioModel.js index 6b812de..2cfa87a 100644 --- a/src/models/usuarioModel.js +++ b/src/models/usuarioModel.js @@ -20,6 +20,10 @@ const User = sequelize.define("tbUsuarios", { allowNull: true, unique: true, }, + senhaFuncionario: { + type: DataTypes.STRING, + allowNull: true + }, admin: { type: DataTypes.BOOLEAN, allowNull: true diff --git a/src/models/usuariosModel.js b/src/models/usuariosModel.js new file mode 100644 index 0000000..1ae7a64 --- /dev/null +++ b/src/models/usuariosModel.js @@ -0,0 +1,47 @@ +import { DataTypes, Sequelize } from "sequelize"; +import sequelize from "../config/dbConfig.js"; + +const Users = sequelize.define("tbUsuarios", { + id: { + type: DataTypes.BIGINT, + primaryKey: true, + autoIncrement: true, + }, + nomeFuncionario: { + type: DataTypes.STRING, + allowNull: true, + }, + cargoFuncionario: { + type: DataTypes.STRING, + allowNull: true, + }, + emailFuncionario: { + type: DataTypes.STRING, + allowNull: true, + unique: true, + }, + admin: { + type: DataTypes.BOOLEAN, + allowNull: true + }, + permissaoDoColaborador: { + type: DataTypes.STRING, + allowNull: true + }, + status: { + type: DataTypes.INTEGER, + allowNull: true + }, + created_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + allowNull: true, + }, + update_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + allowNull: true + } +}); + +export default Users; \ No newline at end of file From 4716e2a0548af9a2a38e3e610c24c32e8a75e06c Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Fri, 15 Mar 2024 16:45:57 -0300 Subject: [PATCH 08/36] inserido coluna app nas tabelas --- src/models/arquivosModel.js | 4 ++++ src/models/cargosModel.js | 4 ++++ src/models/planilhasModel.js | 4 ++++ src/models/provisionamentoModel.js | 4 ++++ src/models/tipoDeServicoModel.js | 4 ++++ src/models/usuarioModel.js | 4 ++++ src/models/usuariosModel.js | 4 ++++ 7 files changed, 28 insertions(+) diff --git a/src/models/arquivosModel.js b/src/models/arquivosModel.js index 43e5c60..b58a34b 100644 --- a/src/models/arquivosModel.js +++ b/src/models/arquivosModel.js @@ -15,6 +15,10 @@ const Files = sequelize.define("tbArquivos", { type: DataTypes.STRING, allowNull: false, }, + app: { + type: DataTypes.INTEGER, + allowNull: false + }, created_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), diff --git a/src/models/cargosModel.js b/src/models/cargosModel.js index 582f68d..70f2a3c 100644 --- a/src/models/cargosModel.js +++ b/src/models/cargosModel.js @@ -13,6 +13,10 @@ const Positions = sequelize.define( type: DataTypes.STRING, allowNull: true, }, + app: { + type: DataTypes.INTEGER, + allowNull: false + }, created_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), diff --git a/src/models/planilhasModel.js b/src/models/planilhasModel.js index 5705fb9..e0c2a40 100644 --- a/src/models/planilhasModel.js +++ b/src/models/planilhasModel.js @@ -19,6 +19,10 @@ const Spreadsheets = sequelize.define("tbPlanilhas", { type: DataTypes.BIGINT, allowNull: true, }, + app: { + type: DataTypes.INTEGER, + allowNull: false + }, created_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), diff --git a/src/models/provisionamentoModel.js b/src/models/provisionamentoModel.js index 4d363ad..8fb9b76 100644 --- a/src/models/provisionamentoModel.js +++ b/src/models/provisionamentoModel.js @@ -53,6 +53,10 @@ const Provisioning = sequelize.define("tbProvisionamento", { key: "id", }, }, + app: { + type: DataTypes.INTEGER, + allowNull: false + }, created_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), diff --git a/src/models/tipoDeServicoModel.js b/src/models/tipoDeServicoModel.js index 316501c..d4b9833 100644 --- a/src/models/tipoDeServicoModel.js +++ b/src/models/tipoDeServicoModel.js @@ -11,6 +11,10 @@ const ServiceType = sequelize.define("tbTipoDeServico", { type: DataTypes.STRING, allowNull: true, }, + app: { + type: DataTypes.INTEGER, + allowNull: false + }, created_at: { type: DataTypes.DATE, defaultValue: DataTypes.NOW, diff --git a/src/models/usuarioModel.js b/src/models/usuarioModel.js index 2cfa87a..fd6736d 100644 --- a/src/models/usuarioModel.js +++ b/src/models/usuarioModel.js @@ -36,6 +36,10 @@ const User = sequelize.define("tbUsuarios", { type: DataTypes.INTEGER, allowNull: true }, + app: { + type: DataTypes.INTEGER, + allowNull: false + }, created_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), diff --git a/src/models/usuariosModel.js b/src/models/usuariosModel.js index 1ae7a64..f8cf774 100644 --- a/src/models/usuariosModel.js +++ b/src/models/usuariosModel.js @@ -32,6 +32,10 @@ const Users = sequelize.define("tbUsuarios", { type: DataTypes.INTEGER, allowNull: true }, + app: { + type: DataTypes.INTEGER, + allowNull: false + }, created_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), From 572abb2aa26d0c2706ff76510993e4b77b774b01 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Fri, 15 Mar 2024 17:49:02 -0300 Subject: [PATCH 09/36] inserido model de app e estados e inserido app no token do auth --- src/controllers/AppController.js | 0 src/controllers/AuthController.js | 2 +- src/models/appModel.js | 59 ++++++++++++++++++++++++++++++ src/models/estadosModel.js | 34 +++++++++++++++++ src/models/provisionamentoModel.js | 2 +- 5 files changed, 95 insertions(+), 2 deletions(-) create mode 100644 src/controllers/AppController.js create mode 100644 src/models/appModel.js create mode 100644 src/models/estadosModel.js diff --git a/src/controllers/AppController.js b/src/controllers/AppController.js new file mode 100644 index 0000000..e69de29 diff --git a/src/controllers/AuthController.js b/src/controllers/AuthController.js index f167cd9..1871138 100644 --- a/src/controllers/AuthController.js +++ b/src/controllers/AuthController.js @@ -41,7 +41,7 @@ export default { return res.json(response); } - const token = jwt.sign({ id: resUserLogin[0].id }, SECRET, { + const token = jwt.sign({ id: resUserLogin[0].id, app:resUserLogin[0].app }, SECRET, { expiresIn: 86400000, // 1 dia para expiração do token }); response.data = resUserLogin; diff --git a/src/models/appModel.js b/src/models/appModel.js new file mode 100644 index 0000000..91cfa4f --- /dev/null +++ b/src/models/appModel.js @@ -0,0 +1,59 @@ +import { DataTypes, Sequelize } from "sequelize"; +import sequelize from "../config/dbConfig"; + +const AppsModel = sequelize.define("tbApp", { + id: { + type: DataTypes.BIGINT, + primaryKey: true, + autoIncrement: true, + }, + nomeApp: { + type: DataTypes.STRING, + allowNull: true, + }, + 'cpf/cnpj': { + type: DataTypes.STRING, + allowNull: true, + }, + enderecoApp: { + type: DataTypes.STRING, + allowNull: true, + }, + telefoneApp: { + type: DataTypes.STRING, + allowNull: true, + }, + cidadeApp: { + type: DataTypes.STRING, + allowNull: true, + }, + cepApp: { + type: DataTypes.STRING, + allowNull: true, + }, + estadoApp: { + type: DataTypes.INTEGER, + allowNull: true, + references: { + model: StatesModel, + key: "id" + }, + }, + created_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, + update: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + } +}, + { + tableName: "tbApp", + freezeTableName: true, + } +); + +export default AppsModel; diff --git a/src/models/estadosModel.js b/src/models/estadosModel.js new file mode 100644 index 0000000..cb2fe38 --- /dev/null +++ b/src/models/estadosModel.js @@ -0,0 +1,34 @@ +import { DataTypes, Sequelize } from "sequelize"; +import sequelize from "../config/dbConfig"; + +const StatesModel = sequelize.define("tbEstados", { + id: { + type: DataTypes.BIGINT, + primaryKey: true, + autoIncrement: true, + }, + estadosCompletos: { + type: DataTypes.STRING, + allowNull: false, + }, + estadosAbreviados: { + type: DataTypes.STRING, + allowNull: false, + }, + created_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, + update_at: { + type: DataTypes.DATE, + defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), + allowNull: true, + }, +}, +{ + tableName: "tbEstados", + freezeTableName: true, +}); + +export default StatesModel; \ No newline at end of file diff --git a/src/models/provisionamentoModel.js b/src/models/provisionamentoModel.js index 8fb9b76..6351496 100644 --- a/src/models/provisionamentoModel.js +++ b/src/models/provisionamentoModel.js @@ -1,4 +1,4 @@ -import { DataTypes } from "sequelize"; +import { Sequelize, DataTypes } from "sequelize"; import sequelize from "../config/dbConfig.js"; import User from "./usuarioModel"; import ServiceType from "./tipoDeServicoModel"; From a7207390aec511c0a18708d3d95daba47859fcd6 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Fri, 15 Mar 2024 21:14:37 -0300 Subject: [PATCH 10/36] alterado orm e colunas --- src/constants/constants.js | 3 +- src/controllers/AppController.js | 37 ++++++++++++++++++++++++ src/controllers/ServicosController.js | 2 +- src/controllers/UsuarioController.js | 8 ++--- src/models/{appModel.js => appsModel.js} | 10 ++++--- src/models/arquivosModel.js | 2 +- src/models/cargosModel.js | 2 +- src/models/estadosModel.js | 5 ++-- src/models/planilhasModel.js | 2 +- src/models/provisionamentoModel.js | 2 +- src/models/tipoDeServicoModel.js | 2 +- src/models/usuarioModel.js | 2 +- src/models/usuariosModel.js | 2 +- src/routes/routes.js | 2 ++ 14 files changed, 62 insertions(+), 19 deletions(-) rename src/models/{appModel.js => appsModel.js} (85%) diff --git a/src/constants/constants.js b/src/constants/constants.js index 8bf687f..8265a9d 100644 --- a/src/constants/constants.js +++ b/src/constants/constants.js @@ -37,7 +37,8 @@ export default { noProductsFound: "Nenhum Produto Encontrado!", noListsFound: "Nenhuma Lista Foi Encontrada", noCustomersFound: "Nenhum Cliente Encontrado", - noPositionsFound: "Nenhum Cargo Encontrado" + noPositionsFound: "Nenhum Cargo Encontrado", + noAppsFound: "Nenhum Aplicativo Encontrado", }, 409: { status: 409, diff --git a/src/controllers/AppController.js b/src/controllers/AppController.js index e69de29..52805d5 100644 --- a/src/controllers/AppController.js +++ b/src/controllers/AppController.js @@ -0,0 +1,37 @@ +import constants from '../constants/constants.js'; +import AppsModel from '../models/appsModel.js'; +import StatesModel from '../models/estadosModel.js'; +import { responseModel } from '../helpers/responseModelHelper.js'; + +const response = { ...responseModel }; + +export default { + async listaApps(req, res) { + response.data = []; + + const tbApps = await AppsModel.findAll({ + raw: true, + include: [{ + model: StatesModel, + required: true, + attributes: ["id", "estadosCompletos", "estadosAbreviados"], + }], + order: [['id', 'ASC']], + }).then(apps => console.table(apps)); + + try { + if (tbApps.length > 0) { + response.success = true; + response.found = tbApps.length; + response.data = tbApps; + } else { + response.error = constants['404'].noAppsFound; + } + } catch (error) { + console.error("ERROR", error); + response.error = constants['500'].errorOccurred; + return res.status(500).json(response); + } + return res.json(response); + } +} \ No newline at end of file diff --git a/src/controllers/ServicosController.js b/src/controllers/ServicosController.js index 6b3c35d..3c718cf 100644 --- a/src/controllers/ServicosController.js +++ b/src/controllers/ServicosController.js @@ -33,7 +33,7 @@ export default { try { query = await db` - INSERT INTO "tbTipoDeServico" ("tipoDeServico", "created_at", "update_at") + INSERT INTO "tbTipoDeServico" ("tipoDeServico", "created_at", "updated_at") VALUES (${tipoDeServico}, ${dataAtual}, NULL) RETURNING *;`; diff --git a/src/controllers/UsuarioController.js b/src/controllers/UsuarioController.js index 74276ca..e68440e 100644 --- a/src/controllers/UsuarioController.js +++ b/src/controllers/UsuarioController.js @@ -27,7 +27,7 @@ export default { return { ...row, created_at: dataFormatada.format(row.created_at), - update_at: dataFormatada.format(row.update_at), + updated_at: dataFormatada.format(row.updated_at), }; }); @@ -68,7 +68,7 @@ export default { return { ...row, created_at: dataFormatada.format(row.created_at), - update_at: dataFormatada.format(row.update_at), + updated_at: dataFormatada.format(row.updated_at), }; }); @@ -112,7 +112,7 @@ export default { return res.status(409).json(response); } else { query = await db` - INSERT INTO "tbUsuarios" ("nomeFuncionario", "cargoFuncionario", "emailFuncionario", "senhaFuncionario", "created_at", "admin", "permissaoDoColaborador", "update_at", "status") + INSERT INTO "tbUsuarios" ("nomeFuncionario", "cargoFuncionario", "emailFuncionario", "senhaFuncionario", "created_at", "admin", "permissaoDoColaborador", "updated_at", "status") VALUES (${nomeFuncionario}, ${cargoFuncionario}, ${emailFuncionario}, ${passwordEncrypted}, ${dataAtual}, ${ typeof admin === "boolean" ? admin : null }, ${permissaoDoColaborador}, NULL, ${parseInt(status)}) @@ -165,7 +165,7 @@ export default { try { query = await db` UPDATE "tbUsuarios" - SET "nomeFuncionario"=${nomeFuncionario}, "cargoFuncionario"=${cargoFuncionario}, "emailFuncionario"=${emailFuncionario}, "senhaFuncionario"=${passwordEncrypted}, "admin"=${admin}, "permissaoDoColaborador"=${permissaoDoColaborador}, "update_at"=${dataAtual}, "status"=${status} + SET "nomeFuncionario"=${nomeFuncionario}, "cargoFuncionario"=${cargoFuncionario}, "emailFuncionario"=${emailFuncionario}, "senhaFuncionario"=${passwordEncrypted}, "admin"=${admin}, "permissaoDoColaborador"=${permissaoDoColaborador}, "updated_at"=${dataAtual}, "status"=${status} WHERE "id"=${userId} RETURNING *;`; diff --git a/src/models/appModel.js b/src/models/appsModel.js similarity index 85% rename from src/models/appModel.js rename to src/models/appsModel.js index 91cfa4f..b15d3a3 100644 --- a/src/models/appModel.js +++ b/src/models/appsModel.js @@ -1,11 +1,13 @@ import { DataTypes, Sequelize } from "sequelize"; -import sequelize from "../config/dbConfig"; +import sequelize from "../config/dbConfig.js"; +import StatesModel from "./estadosModel.js"; const AppsModel = sequelize.define("tbApp", { id: { type: DataTypes.BIGINT, primaryKey: true, autoIncrement: true, + allowNull: false, }, nomeApp: { type: DataTypes.STRING, @@ -32,11 +34,11 @@ const AppsModel = sequelize.define("tbApp", { allowNull: true, }, estadoApp: { - type: DataTypes.INTEGER, + type: DataTypes.BIGINT, allowNull: true, references: { model: StatesModel, - key: "id" + key: "id", }, }, created_at: { @@ -44,7 +46,7 @@ const AppsModel = sequelize.define("tbApp", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - update: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/arquivosModel.js b/src/models/arquivosModel.js index b58a34b..38c0e18 100644 --- a/src/models/arquivosModel.js +++ b/src/models/arquivosModel.js @@ -24,7 +24,7 @@ const Files = sequelize.define("tbArquivos", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/cargosModel.js b/src/models/cargosModel.js index 70f2a3c..87b7efa 100644 --- a/src/models/cargosModel.js +++ b/src/models/cargosModel.js @@ -22,7 +22,7 @@ const Positions = sequelize.define( defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/estadosModel.js b/src/models/estadosModel.js index cb2fe38..d85fddf 100644 --- a/src/models/estadosModel.js +++ b/src/models/estadosModel.js @@ -1,11 +1,12 @@ import { DataTypes, Sequelize } from "sequelize"; -import sequelize from "../config/dbConfig"; +import sequelize from "../config/dbConfig.js"; const StatesModel = sequelize.define("tbEstados", { id: { type: DataTypes.BIGINT, primaryKey: true, autoIncrement: true, + allowNull: false }, estadosCompletos: { type: DataTypes.STRING, @@ -20,7 +21,7 @@ const StatesModel = sequelize.define("tbEstados", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/planilhasModel.js b/src/models/planilhasModel.js index e0c2a40..dddd353 100644 --- a/src/models/planilhasModel.js +++ b/src/models/planilhasModel.js @@ -28,7 +28,7 @@ const Spreadsheets = sequelize.define("tbPlanilhas", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/provisionamentoModel.js b/src/models/provisionamentoModel.js index 6351496..7af29a9 100644 --- a/src/models/provisionamentoModel.js +++ b/src/models/provisionamentoModel.js @@ -62,7 +62,7 @@ const Provisioning = sequelize.define("tbProvisionamento", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/tipoDeServicoModel.js b/src/models/tipoDeServicoModel.js index d4b9833..024bd79 100644 --- a/src/models/tipoDeServicoModel.js +++ b/src/models/tipoDeServicoModel.js @@ -20,7 +20,7 @@ const ServiceType = sequelize.define("tbTipoDeServico", { defaultValue: DataTypes.NOW, allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: DataTypes.NOW, allowNull: true, diff --git a/src/models/usuarioModel.js b/src/models/usuarioModel.js index fd6736d..50f2d41 100644 --- a/src/models/usuarioModel.js +++ b/src/models/usuarioModel.js @@ -45,7 +45,7 @@ const User = sequelize.define("tbUsuarios", { defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: true diff --git a/src/models/usuariosModel.js b/src/models/usuariosModel.js index f8cf774..7075ec4 100644 --- a/src/models/usuariosModel.js +++ b/src/models/usuariosModel.js @@ -41,7 +41,7 @@ const Users = sequelize.define("tbUsuarios", { defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: true diff --git a/src/routes/routes.js b/src/routes/routes.js index 6bd6ec3..3add73e 100644 --- a/src/routes/routes.js +++ b/src/routes/routes.js @@ -6,6 +6,7 @@ import ArquivosController from "../controllers/ArquivosController.js"; import verifyJWT from "../middleware/jwt.js" import ServicosController from "../controllers/ServicosController.js"; import CargoController from "../controllers/CargoController.js"; +import AppController from "../controllers/AppController.js"; const router = express.Router(); @@ -29,6 +30,7 @@ router .get("/listaServicos", verifyJWT, ServicosController.listaTipoDeServico) .get("/listaCargos", verifyJWT, CargoController.listaCargo) + .get("/listaApps", verifyJWT, AppController.listaApps) .post("/login", AuthController.login) .post("/provisionaClientes", verifyJWT, ProvisionamentoController.provisionaClientes) From c69f320bbcd294bfc6b0e85694728b8b201711d1 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 00:03:31 -0300 Subject: [PATCH 11/36] alterada resposta da rota app --- src/controllers/AppController.js | 24 ++++++++++++++---------- src/models/appsModel.js | 8 +++++--- src/models/arquivosModel.js | 2 +- src/models/cargosModel.js | 2 +- src/models/estadosModel.js | 6 +++--- src/models/oldProvModel.js | 2 +- src/models/planilhasModel.js | 4 ++-- src/models/provisionamentoModel.js | 8 ++++---- src/models/tipoDeServicoModel.js | 2 +- src/models/usuarioModel.js | 2 +- src/models/usuariosModel.js | 2 +- 11 files changed, 34 insertions(+), 28 deletions(-) diff --git a/src/controllers/AppController.js b/src/controllers/AppController.js index 52805d5..ef1688d 100644 --- a/src/controllers/AppController.js +++ b/src/controllers/AppController.js @@ -9,17 +9,19 @@ export default { async listaApps(req, res) { response.data = []; - const tbApps = await AppsModel.findAll({ - raw: true, - include: [{ - model: StatesModel, - required: true, - attributes: ["id", "estadosCompletos", "estadosAbreviados"], - }], - order: [['id', 'ASC']], - }).then(apps => console.table(apps)); - try { + const tbApps = await AppsModel.findAll({ + raw: true, + include: [{ + model: StatesModel, + required: true, + attributes: ["estadosCompleto", "estadosAbreviado"] + }], + order: [['id', 'ASC']], + }) + + console.log('result 2', tbApps) + if (tbApps.length > 0) { response.success = true; response.found = tbApps.length; @@ -32,6 +34,8 @@ export default { response.error = constants['500'].errorOccurred; return res.status(500).json(response); } + + return res.json(response); } } \ No newline at end of file diff --git a/src/models/appsModel.js b/src/models/appsModel.js index b15d3a3..3468e09 100644 --- a/src/models/appsModel.js +++ b/src/models/appsModel.js @@ -4,7 +4,7 @@ import StatesModel from "./estadosModel.js"; const AppsModel = sequelize.define("tbApp", { id: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false, @@ -34,11 +34,11 @@ const AppsModel = sequelize.define("tbApp", { allowNull: true, }, estadoApp: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, allowNull: true, references: { model: StatesModel, - key: "id", + key: 'id', }, }, created_at: { @@ -58,4 +58,6 @@ const AppsModel = sequelize.define("tbApp", { } ); +AppsModel.belongsTo(StatesModel, { foreignKey: 'estadoApp' }) + export default AppsModel; diff --git a/src/models/arquivosModel.js b/src/models/arquivosModel.js index 38c0e18..13aec89 100644 --- a/src/models/arquivosModel.js +++ b/src/models/arquivosModel.js @@ -3,7 +3,7 @@ import sequelize from "../config/dbConfig.js"; const Files = sequelize.define("tbArquivos", { id: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, diff --git a/src/models/cargosModel.js b/src/models/cargosModel.js index 87b7efa..9caefe8 100644 --- a/src/models/cargosModel.js +++ b/src/models/cargosModel.js @@ -5,7 +5,7 @@ const Positions = sequelize.define( "tbCargos", { id: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, diff --git a/src/models/estadosModel.js b/src/models/estadosModel.js index d85fddf..c8beddd 100644 --- a/src/models/estadosModel.js +++ b/src/models/estadosModel.js @@ -3,16 +3,16 @@ import sequelize from "../config/dbConfig.js"; const StatesModel = sequelize.define("tbEstados", { id: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false }, - estadosCompletos: { + estadosCompleto: { type: DataTypes.STRING, allowNull: false, }, - estadosAbreviados: { + estadosAbreviado: { type: DataTypes.STRING, allowNull: false, }, diff --git a/src/models/oldProvModel.js b/src/models/oldProvModel.js index 788eaf6..814863c 100644 --- a/src/models/oldProvModel.js +++ b/src/models/oldProvModel.js @@ -3,7 +3,7 @@ import sequelize from "../config/dbConfig.js"; const OldProv = sequelize.define("PROVISIONAMENTO", { id: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, diff --git a/src/models/planilhasModel.js b/src/models/planilhasModel.js index dddd353..84b00e5 100644 --- a/src/models/planilhasModel.js +++ b/src/models/planilhasModel.js @@ -3,7 +3,7 @@ import sequelize from "../config/dbConfig.js"; const Spreadsheets = sequelize.define("tbPlanilhas", { id: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, @@ -16,7 +16,7 @@ const Spreadsheets = sequelize.define("tbPlanilhas", { allowNull: true, }, planilhaSelecionada: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, allowNull: true, }, app: { diff --git a/src/models/provisionamentoModel.js b/src/models/provisionamentoModel.js index 7af29a9..ee8b86b 100644 --- a/src/models/provisionamentoModel.js +++ b/src/models/provisionamentoModel.js @@ -5,7 +5,7 @@ import ServiceType from "./tipoDeServicoModel"; const Provisioning = sequelize.define("tbProvisionamento", { id: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, @@ -18,7 +18,7 @@ const Provisioning = sequelize.define("tbProvisionamento", { allowNull: true, }, tecnicoRua: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, allowNull: true, references: { model: User, @@ -38,7 +38,7 @@ const Provisioning = sequelize.define("tbProvisionamento", { allowNull: true, }, tecnicoSup: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, allowNull: true, references: { model: User, @@ -46,7 +46,7 @@ const Provisioning = sequelize.define("tbProvisionamento", { }, }, tipoDeServico: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, allowNull: true, references: { model: ServiceType, diff --git a/src/models/tipoDeServicoModel.js b/src/models/tipoDeServicoModel.js index 024bd79..71089f9 100644 --- a/src/models/tipoDeServicoModel.js +++ b/src/models/tipoDeServicoModel.js @@ -3,7 +3,7 @@ import sequelize from "../config/dbConfig.js"; const ServiceType = sequelize.define("tbTipoDeServico", { id: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, diff --git a/src/models/usuarioModel.js b/src/models/usuarioModel.js index 50f2d41..febe26d 100644 --- a/src/models/usuarioModel.js +++ b/src/models/usuarioModel.js @@ -3,7 +3,7 @@ import sequelize from "../config/dbConfig.js"; const User = sequelize.define("tbUsuarios", { id: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, diff --git a/src/models/usuariosModel.js b/src/models/usuariosModel.js index 7075ec4..05fd369 100644 --- a/src/models/usuariosModel.js +++ b/src/models/usuariosModel.js @@ -3,7 +3,7 @@ import sequelize from "../config/dbConfig.js"; const Users = sequelize.define("tbUsuarios", { id: { - type: DataTypes.BIGINT, + type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, From a5590f30f50523cd6d7505a4847b0934b3febe38 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 10:14:02 -0300 Subject: [PATCH 12/36] inserido coluna where app nos controllers --- package.json | 2 +- src/constants/constants.js | 1 + src/controllers/AppController.js | 67 ++++++++++++++------------- src/controllers/ArquivosController.js | 26 +++++++++-- src/controllers/CargoController.js | 7 ++- src/controllers/ServicosController.js | 9 +++- src/controllers/UsuarioController.js | 14 ++++-- src/models/provisionamentoModel.js | 1 + 8 files changed, 80 insertions(+), 47 deletions(-) diff --git a/package.json b/package.json index d085c3a..44f8efd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "apiprovisionamento", - "version": "1.6.0", + "version": "1.6.2", "description": "", "main": "server.js", "type": "module", diff --git a/src/constants/constants.js b/src/constants/constants.js index 8265a9d..de67011 100644 --- a/src/constants/constants.js +++ b/src/constants/constants.js @@ -31,6 +31,7 @@ export default { 404: { status: 404, userNotFound: "Usuário Não Encontrado", + usersNotFound: "Nenhum Usuário Encontrado", heritageNotFound: "Patrimonio Não Encontrado", noFilesFound: "Nenhum Arquivo Encontrado!", noServiceFound: "Nenhum Serviço Encontrato", diff --git a/src/controllers/AppController.js b/src/controllers/AppController.js index ef1688d..589965c 100644 --- a/src/controllers/AppController.js +++ b/src/controllers/AppController.js @@ -1,41 +1,42 @@ -import constants from '../constants/constants.js'; -import AppsModel from '../models/appsModel.js'; -import StatesModel from '../models/estadosModel.js'; -import { responseModel } from '../helpers/responseModelHelper.js'; +import constants from "../constants/constants.js"; +import AppsModel from "../models/appsModel.js"; +import StatesModel from "../models/estadosModel.js"; +import { responseModel } from "../helpers/responseModelHelper.js"; const response = { ...responseModel }; export default { - async listaApps(req, res) { - response.data = []; + async listaApps(req, res) { + response.data = []; - try { - const tbApps = await AppsModel.findAll({ - raw: true, - include: [{ - model: StatesModel, - required: true, - attributes: ["estadosCompleto", "estadosAbreviado"] - }], - order: [['id', 'ASC']], - }) + try { + const tbApps = await AppsModel.findAll({ + raw: true, + include: [ + { + model: StatesModel, + required: true, + attributes: ["estadosCompleto", "estadosAbreviado"], + }, + ], + order: [["id", "ASC"]], + }); - console.log('result 2', tbApps) + console.log("result 2", tbApps); - if (tbApps.length > 0) { - response.success = true; - response.found = tbApps.length; - response.data = tbApps; - } else { - response.error = constants['404'].noAppsFound; - } - } catch (error) { - console.error("ERROR", error); - response.error = constants['500'].errorOccurred; - return res.status(500).json(response); - } + if (tbApps.length > 0) { + response.success = true; + response.found = tbApps.length; + response.data = tbApps; + } else { + response.error = constants["404"].noAppsFound; + } + } catch (error) { + console.error("ERROR", error); + response.error = constants["500"].errorOccurred; + return res.status(500).json(response); + } - - return res.json(response); - } -} \ No newline at end of file + return res.json(response); + }, +}; diff --git a/src/controllers/ArquivosController.js b/src/controllers/ArquivosController.js index d68e278..57741d5 100644 --- a/src/controllers/ArquivosController.js +++ b/src/controllers/ArquivosController.js @@ -8,8 +8,13 @@ const response = { ...responseModel }; export default { async listaArquivos(req, res) { response.data = []; + const { app } = req.body; - const tbArquivos = await Files.findAll(); + const tbArquivos = await Files.findAll({ + where: { + "app": app + } + }); try { if (tbArquivos.length > 0) { @@ -28,12 +33,13 @@ export default { }, async inserirArquivo(req, res) { - const { nomeArquivo, urlArquivo } = req.body; + const { nomeArquivo, urlArquivo, app } = req.body; try { const resInserirArquivo = await Files.create({ nome: nomeArquivo, url: urlArquivo, + app: app, }); if (resInserirArquivo) { @@ -58,18 +64,23 @@ export default { async atualizarArquivo(req, res) { const dataAtual = new Date(); const arqId = req.params.id; - const { nomeArquivo, urlArquivo } = req.body; + const { nomeArquivo, urlArquivo, app } = req.body; const atualizaArquivo = { nome: nomeArquivo, url: urlArquivo, + app: app }; try { const arquivo = await Files.findByPk(arqId); if (arquivo) { - await arquivo.update(atualizaArquivo); + await arquivo.update({atualizaArquivo}, { + where: { + "app": app + } + }); response.success = true; // response.found = resAtualizarArquivo.length; response.data = constants["201"].fileUpdateSuccess; @@ -87,6 +98,7 @@ export default { async deletarArquivo(req, res) { const arqId = req.params.id; + const { app } = req.body; try { const resDeletarArquivo = await Files.findByPk(arqId); @@ -95,7 +107,11 @@ export default { response.success = true; response.found = resDeletarArquivo.length; response.data = constants["200"].deletedFile; - await resDeletarArquivo.destroy(); + await resDeletarArquivo.destroy({ + where: { + "app": app + } + }); return res.status(200).json(response); } else { response.error = constants["404"].noFilesFound; diff --git a/src/controllers/CargoController.js b/src/controllers/CargoController.js index f9309a9..80a512e 100644 --- a/src/controllers/CargoController.js +++ b/src/controllers/CargoController.js @@ -6,10 +6,15 @@ const response = { ...responseModel }; export default { async listaCargo(req, res) { + const { app } = req.body; response.data = []; try { - const listaCargos = await Positions.findAll() + const listaCargos = await Positions.findAll({ + where: { + "app": app + } + }) response.success = listaCargos.length > 0; diff --git a/src/controllers/ServicosController.js b/src/controllers/ServicosController.js index 3c718cf..63fd3ea 100644 --- a/src/controllers/ServicosController.js +++ b/src/controllers/ServicosController.js @@ -7,10 +7,16 @@ const response = { ...responseModel }; export default { async listaTipoDeServico(req, res) { + const { app } = req.body; response.data = []; try { - const tbTipoDeServico = await ServiceType.findAll(); + const tbTipoDeServico = await ServiceType.findAll({ + where: { + "app": app + } + }); + response.success = tbTipoDeServico.length > 0; if (response.success) { @@ -57,7 +63,6 @@ export default { }, async atualizaTipoDeServico(req, res) { - const dataAtual = new Date(); const serviceId = req.params.id; const { tipoDeServico } = req.body; diff --git a/src/controllers/UsuarioController.js b/src/controllers/UsuarioController.js index e68440e..b558c21 100644 --- a/src/controllers/UsuarioController.js +++ b/src/controllers/UsuarioController.js @@ -11,8 +11,12 @@ const response = { ...responseModel }; export default { async listaUsuarios(req, res) { + const { app } = req.body; try { const findAllUsers = await Users.findAll({ + where: { + "app": app + }, order: [ ["status", "DESC"], ["id", "ASC"], @@ -35,9 +39,8 @@ export default { response.data = resFindAllUsersFormatado; response.found = resFindAllUsersFormatado.length; } else { - response.success = false; - response.data = []; - response.found = 0; + response.error = constants["404"].usersNotFound; + return res.status(404).json(response); } } catch (err) { console.error("error", err); @@ -49,6 +52,7 @@ export default { async listaUsuario(req, res) { let userId = req.params.id; + const { app } = req.body; response.data = []; try { @@ -80,8 +84,8 @@ export default { response.error = constants["404"].userNotFound; return res.status(404).json(response); } - } catch (err) { - console.error("ERRO:", err); + } catch (error) { + console.error("ERRO:", error); response.error = constants["500"].errorOccurred; return res.status(500).json(response); } diff --git a/src/models/provisionamentoModel.js b/src/models/provisionamentoModel.js index ee8b86b..c629d94 100644 --- a/src/models/provisionamentoModel.js +++ b/src/models/provisionamentoModel.js @@ -8,6 +8,7 @@ const Provisioning = sequelize.define("tbProvisionamento", { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, + allowNull: false, }, nomeCliente: { type: DataTypes.STRING, From 0f94d3eacc566a25ec74b40a49c805f19fcd3b12 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 10:40:12 -0300 Subject: [PATCH 13/36] alterado packageJson --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 44f8efd..f96df7c 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "main": "server.js", "type": "module", "scripts": { - "dev": "nodemon --legacy-watch server.js", + "dev": "nodemon server.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], From 388ed6339115403777f394ccbc9d16447ae87154 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 11:47:18 -0300 Subject: [PATCH 14/36] alterado cors --- src/app.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/app.js b/src/app.js index da91f45..ce4861f 100644 --- a/src/app.js +++ b/src/app.js @@ -18,7 +18,10 @@ async function connectToDatabase() { const app = express(); -app.use(cors()); +app.use(cors({ + origin: "*", + methods: "GET,POST,UPDATE,DELETE" +})); // é um recurso do Express que vai conseguir fazer interpretar o que está chegando via post ou via put // e transformar aquilo em um objeto para eu poder armazenar, visualizar e manipular. From 9626e69fae7a80d81df95a50dd11249527ee38ac Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 12:27:56 -0300 Subject: [PATCH 15/36] inserido novo modulo --- package-lock.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index 040a2a1..4addd48 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "apiprovisionamento", - "version": "1.5.0", + "version": "1.6.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "apiprovisionamento", - "version": "1.5.0", + "version": "1.6.2", "license": "ISC", "dependencies": { "body-parser": "^1.20.2", From 45ed0842cbc06cfc6d57ce30ce5343888483bd1b Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 12:38:22 -0300 Subject: [PATCH 16/36] alterado coluna update --- src/models/cargosModel.js | 2 +- src/models/tipoDeServicoModel.js | 2 +- src/models/usuariosModel.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/models/cargosModel.js b/src/models/cargosModel.js index 9caefe8..9b0ee0e 100644 --- a/src/models/cargosModel.js +++ b/src/models/cargosModel.js @@ -22,7 +22,7 @@ const Positions = sequelize.define( defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - updated_at: { + update_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/tipoDeServicoModel.js b/src/models/tipoDeServicoModel.js index 71089f9..4b0f0a7 100644 --- a/src/models/tipoDeServicoModel.js +++ b/src/models/tipoDeServicoModel.js @@ -20,7 +20,7 @@ const ServiceType = sequelize.define("tbTipoDeServico", { defaultValue: DataTypes.NOW, allowNull: true, }, - updated_at: { + update_at: { type: DataTypes.DATE, defaultValue: DataTypes.NOW, allowNull: true, diff --git a/src/models/usuariosModel.js b/src/models/usuariosModel.js index 05fd369..c9e5dad 100644 --- a/src/models/usuariosModel.js +++ b/src/models/usuariosModel.js @@ -41,7 +41,7 @@ const Users = sequelize.define("tbUsuarios", { defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: true, }, - updated_at: { + update_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: true From 2de22eeb64430be2d421a06296d8ed09156ba37d Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 12:42:53 -0300 Subject: [PATCH 17/36] removido hora do db --- src/config/dbConfig.js | 1 - 1 file changed, 1 deletion(-) diff --git a/src/config/dbConfig.js b/src/config/dbConfig.js index eb1df78..979994a 100644 --- a/src/config/dbConfig.js +++ b/src/config/dbConfig.js @@ -16,7 +16,6 @@ const sequelize = new Sequelize({ database: dbHostName, port: dbPort, define: { - timestamps: false, underscored: false } }) From 19621f619a840573647c626137d4337843fcca0f Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 12:43:53 -0300 Subject: [PATCH 18/36] inserido timestamps --- src/config/dbConfig.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/config/dbConfig.js b/src/config/dbConfig.js index 979994a..eb1df78 100644 --- a/src/config/dbConfig.js +++ b/src/config/dbConfig.js @@ -16,6 +16,7 @@ const sequelize = new Sequelize({ database: dbHostName, port: dbPort, define: { + timestamps: false, underscored: false } }) From 95b5862d0f39273b85f2ba1872d3d448339ff314 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 14:17:38 -0300 Subject: [PATCH 19/36] sequelize app --- src/controllers/AppController.js | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/src/controllers/AppController.js b/src/controllers/AppController.js index 589965c..08ae0db 100644 --- a/src/controllers/AppController.js +++ b/src/controllers/AppController.js @@ -10,17 +10,7 @@ export default { response.data = []; try { - const tbApps = await AppsModel.findAll({ - raw: true, - include: [ - { - model: StatesModel, - required: true, - attributes: ["estadosCompleto", "estadosAbreviado"], - }, - ], - order: [["id", "ASC"]], - }); + const tbApps = await AppsModel.findAll(); console.log("result 2", tbApps); From 69ff09604750102e47e5312df502ebd68efa0f36 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 14:21:16 -0300 Subject: [PATCH 20/36] join sequelize app --- src/controllers/AppController.js | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/controllers/AppController.js b/src/controllers/AppController.js index 08ae0db..589965c 100644 --- a/src/controllers/AppController.js +++ b/src/controllers/AppController.js @@ -10,7 +10,17 @@ export default { response.data = []; try { - const tbApps = await AppsModel.findAll(); + const tbApps = await AppsModel.findAll({ + raw: true, + include: [ + { + model: StatesModel, + required: true, + attributes: ["estadosCompleto", "estadosAbreviado"], + }, + ], + order: [["id", "ASC"]], + }); console.log("result 2", tbApps); From 395fffb72ceb2d6b1c50c11d822a47cca1619c8f Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 14:21:56 -0300 Subject: [PATCH 21/36] removido app --- src/routes/routes.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/routes/routes.js b/src/routes/routes.js index 3add73e..219a333 100644 --- a/src/routes/routes.js +++ b/src/routes/routes.js @@ -30,7 +30,7 @@ router .get("/listaServicos", verifyJWT, ServicosController.listaTipoDeServico) .get("/listaCargos", verifyJWT, CargoController.listaCargo) - .get("/listaApps", verifyJWT, AppController.listaApps) + // .get("/listaApps", verifyJWT, AppController.listaApps) .post("/login", AuthController.login) .post("/provisionaClientes", verifyJWT, ProvisionamentoController.provisionaClientes) From d2620a0ca8103d3a2144b618b77603ee75bc8e60 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 14:40:50 -0300 Subject: [PATCH 22/36] inserido rota apP --- src/routes/routes.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/routes/routes.js b/src/routes/routes.js index 219a333..3add73e 100644 --- a/src/routes/routes.js +++ b/src/routes/routes.js @@ -30,7 +30,7 @@ router .get("/listaServicos", verifyJWT, ServicosController.listaTipoDeServico) .get("/listaCargos", verifyJWT, CargoController.listaCargo) - // .get("/listaApps", verifyJWT, AppController.listaApps) + .get("/listaApps", verifyJWT, AppController.listaApps) .post("/login", AuthController.login) .post("/provisionaClientes", verifyJWT, ProvisionamentoController.provisionaClientes) From 90cbcbc877d3c0d0bbdc144dc8ee91e70e14767b Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 16:32:37 -0300 Subject: [PATCH 23/36] inserido dialectModule pg --- package.json | 2 +- src/config/dbConfig.js | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index f96df7c..9c6cb34 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], - "author": "", + "author": "Jean Carlos", "license": "ISC", "devDependencies": { "nodemon": "^3.0.1" diff --git a/src/config/dbConfig.js b/src/config/dbConfig.js index eb1df78..de85c1a 100644 --- a/src/config/dbConfig.js +++ b/src/config/dbConfig.js @@ -1,3 +1,4 @@ +import pg from 'pg'; import { Sequelize } from "sequelize"; import * as dotenv from "dotenv"; dotenv.config(); @@ -10,6 +11,7 @@ let dbHostName = process.env.SUPABASE_HOSTNAME; const sequelize = new Sequelize({ dialect: 'postgres', + dialectModule: pg, host: dbURL, username: dbUsername, password: dbPassword, From e9ee8bbdf751350b6a95aab30126a398cbcb8f82 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 17:12:03 -0300 Subject: [PATCH 24/36] auth --- src/controllers/AuthController.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/controllers/AuthController.js b/src/controllers/AuthController.js index 1871138..7176f67 100644 --- a/src/controllers/AuthController.js +++ b/src/controllers/AuthController.js @@ -41,7 +41,7 @@ export default { return res.json(response); } - const token = jwt.sign({ id: resUserLogin[0].id, app:resUserLogin[0].app }, SECRET, { + const token = jwt.sign({ id: resUserLogin[0].id, app: resUserLogin[0].app }, SECRET, { expiresIn: 86400000, // 1 dia para expiração do token }); response.data = resUserLogin; From 107b5c44ae7c808d13aae40a6140aefccd7bcfb5 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 17:13:35 -0300 Subject: [PATCH 25/36] update_at --- src/controllers/ServicosController.js | 2 +- src/controllers/UsuarioController.js | 8 ++++---- src/models/appsModel.js | 2 +- src/models/arquivosModel.js | 2 +- src/models/estadosModel.js | 2 +- src/models/planilhasModel.js | 2 +- src/models/provisionamentoModel.js | 2 +- src/models/usuarioModel.js | 2 +- 8 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/controllers/ServicosController.js b/src/controllers/ServicosController.js index 63fd3ea..459c232 100644 --- a/src/controllers/ServicosController.js +++ b/src/controllers/ServicosController.js @@ -39,7 +39,7 @@ export default { try { query = await db` - INSERT INTO "tbTipoDeServico" ("tipoDeServico", "created_at", "updated_at") + INSERT INTO "tbTipoDeServico" ("tipoDeServico", "created_at", "update_at") VALUES (${tipoDeServico}, ${dataAtual}, NULL) RETURNING *;`; diff --git a/src/controllers/UsuarioController.js b/src/controllers/UsuarioController.js index b558c21..2fd3158 100644 --- a/src/controllers/UsuarioController.js +++ b/src/controllers/UsuarioController.js @@ -31,7 +31,7 @@ export default { return { ...row, created_at: dataFormatada.format(row.created_at), - updated_at: dataFormatada.format(row.updated_at), + update_at: dataFormatada.format(row.update_at), }; }); @@ -72,7 +72,7 @@ export default { return { ...row, created_at: dataFormatada.format(row.created_at), - updated_at: dataFormatada.format(row.updated_at), + update_at: dataFormatada.format(row.update_at), }; }); @@ -116,7 +116,7 @@ export default { return res.status(409).json(response); } else { query = await db` - INSERT INTO "tbUsuarios" ("nomeFuncionario", "cargoFuncionario", "emailFuncionario", "senhaFuncionario", "created_at", "admin", "permissaoDoColaborador", "updated_at", "status") + INSERT INTO "tbUsuarios" ("nomeFuncionario", "cargoFuncionario", "emailFuncionario", "senhaFuncionario", "created_at", "admin", "permissaoDoColaborador", "update_at", "status") VALUES (${nomeFuncionario}, ${cargoFuncionario}, ${emailFuncionario}, ${passwordEncrypted}, ${dataAtual}, ${ typeof admin === "boolean" ? admin : null }, ${permissaoDoColaborador}, NULL, ${parseInt(status)}) @@ -169,7 +169,7 @@ export default { try { query = await db` UPDATE "tbUsuarios" - SET "nomeFuncionario"=${nomeFuncionario}, "cargoFuncionario"=${cargoFuncionario}, "emailFuncionario"=${emailFuncionario}, "senhaFuncionario"=${passwordEncrypted}, "admin"=${admin}, "permissaoDoColaborador"=${permissaoDoColaborador}, "updated_at"=${dataAtual}, "status"=${status} + SET "nomeFuncionario"=${nomeFuncionario}, "cargoFuncionario"=${cargoFuncionario}, "emailFuncionario"=${emailFuncionario}, "senhaFuncionario"=${passwordEncrypted}, "admin"=${admin}, "permissaoDoColaborador"=${permissaoDoColaborador}, "update_at"=${dataAtual}, "status"=${status} WHERE "id"=${userId} RETURNING *;`; diff --git a/src/models/appsModel.js b/src/models/appsModel.js index 3468e09..f8b83bd 100644 --- a/src/models/appsModel.js +++ b/src/models/appsModel.js @@ -46,7 +46,7 @@ const AppsModel = sequelize.define("tbApp", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - updated_at: { + update_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/arquivosModel.js b/src/models/arquivosModel.js index 13aec89..a06e199 100644 --- a/src/models/arquivosModel.js +++ b/src/models/arquivosModel.js @@ -24,7 +24,7 @@ const Files = sequelize.define("tbArquivos", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - updated_at: { + update_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/estadosModel.js b/src/models/estadosModel.js index c8beddd..d91dbc0 100644 --- a/src/models/estadosModel.js +++ b/src/models/estadosModel.js @@ -21,7 +21,7 @@ const StatesModel = sequelize.define("tbEstados", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - updated_at: { + update_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/planilhasModel.js b/src/models/planilhasModel.js index 84b00e5..2720ac5 100644 --- a/src/models/planilhasModel.js +++ b/src/models/planilhasModel.js @@ -28,7 +28,7 @@ const Spreadsheets = sequelize.define("tbPlanilhas", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - updated_at: { + update_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/provisionamentoModel.js b/src/models/provisionamentoModel.js index c629d94..c5f0c8b 100644 --- a/src/models/provisionamentoModel.js +++ b/src/models/provisionamentoModel.js @@ -63,7 +63,7 @@ const Provisioning = sequelize.define("tbProvisionamento", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - updated_at: { + update_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/usuarioModel.js b/src/models/usuarioModel.js index febe26d..6ac49cb 100644 --- a/src/models/usuarioModel.js +++ b/src/models/usuarioModel.js @@ -45,7 +45,7 @@ const User = sequelize.define("tbUsuarios", { defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: true, }, - updated_at: { + update_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: true From 647f3f6c7f32e5d002e41ac57cd1baf6e8a4ba86 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 17:22:57 -0300 Subject: [PATCH 26/36] alterado escopo para trazer usuarios --- src/controllers/UsuarioController.js | 2 +- src/routes/routes.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/controllers/UsuarioController.js b/src/controllers/UsuarioController.js index 2fd3158..8108316 100644 --- a/src/controllers/UsuarioController.js +++ b/src/controllers/UsuarioController.js @@ -11,7 +11,7 @@ const response = { ...responseModel }; export default { async listaUsuarios(req, res) { - const { app } = req.body; + const { app } = req.params.app; try { const findAllUsers = await Users.findAll({ where: { diff --git a/src/routes/routes.js b/src/routes/routes.js index 3add73e..5fa4d6b 100644 --- a/src/routes/routes.js +++ b/src/routes/routes.js @@ -15,7 +15,7 @@ router.get('/', (req, res) => { }) router - .get("/listaUsuarios", verifyJWT, UsuarioController.listaUsuarios) + .get("/listaUsuarios/:app", verifyJWT, UsuarioController.listaUsuarios) .get("/listaUsuario/:id", verifyJWT, UsuarioController.listaUsuario) .get("/listaClientes", verifyJWT, ProvisionamentoController.listaClientes) From 002bd5c6d65406f520e0223f0099badf8e73bffe Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 17:37:47 -0300 Subject: [PATCH 27/36] alterado params --- src/routes/routes.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/routes/routes.js b/src/routes/routes.js index 5fa4d6b..ac94b5e 100644 --- a/src/routes/routes.js +++ b/src/routes/routes.js @@ -15,7 +15,7 @@ router.get('/', (req, res) => { }) router - .get("/listaUsuarios/:app", verifyJWT, UsuarioController.listaUsuarios) + .get("/listaUsuarios/:id", verifyJWT, UsuarioController.listaUsuarios) .get("/listaUsuario/:id", verifyJWT, UsuarioController.listaUsuario) .get("/listaClientes", verifyJWT, ProvisionamentoController.listaClientes) From e96f65c569649310b64a799ee3b6ebbb203f762f Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 17:39:59 -0300 Subject: [PATCH 28/36] alterado params --- src/routes/routes.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/routes/routes.js b/src/routes/routes.js index ac94b5e..5fa4d6b 100644 --- a/src/routes/routes.js +++ b/src/routes/routes.js @@ -15,7 +15,7 @@ router.get('/', (req, res) => { }) router - .get("/listaUsuarios/:id", verifyJWT, UsuarioController.listaUsuarios) + .get("/listaUsuarios/:app", verifyJWT, UsuarioController.listaUsuarios) .get("/listaUsuario/:id", verifyJWT, UsuarioController.listaUsuario) .get("/listaClientes", verifyJWT, ProvisionamentoController.listaClientes) From 4d497e1563a682dfa07c63f8af123285cfda757d Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 17:43:36 -0300 Subject: [PATCH 29/36] alterado cors --- src/app.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/app.js b/src/app.js index ce4861f..da91f45 100644 --- a/src/app.js +++ b/src/app.js @@ -18,10 +18,7 @@ async function connectToDatabase() { const app = express(); -app.use(cors({ - origin: "*", - methods: "GET,POST,UPDATE,DELETE" -})); +app.use(cors()); // é um recurso do Express que vai conseguir fazer interpretar o que está chegando via post ou via put // e transformar aquilo em um objeto para eu poder armazenar, visualizar e manipular. From 8221a2a638308f9317e0f3795c7ce9b424e37510 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sat, 16 Mar 2024 17:53:25 -0300 Subject: [PATCH 30/36] alterado params dos controllers --- src/controllers/ArquivosController.js | 2 +- src/controllers/CargoController.js | 2 +- src/controllers/ServicosController.js | 2 +- src/controllers/UsuarioController.js | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/controllers/ArquivosController.js b/src/controllers/ArquivosController.js index 57741d5..f8db3ea 100644 --- a/src/controllers/ArquivosController.js +++ b/src/controllers/ArquivosController.js @@ -7,8 +7,8 @@ const response = { ...responseModel }; export default { async listaArquivos(req, res) { + let app = req.params.app; response.data = []; - const { app } = req.body; const tbArquivos = await Files.findAll({ where: { diff --git a/src/controllers/CargoController.js b/src/controllers/CargoController.js index 80a512e..37ecf60 100644 --- a/src/controllers/CargoController.js +++ b/src/controllers/CargoController.js @@ -6,7 +6,7 @@ const response = { ...responseModel }; export default { async listaCargo(req, res) { - const { app } = req.body; + let app = req.params.app; response.data = []; try { diff --git a/src/controllers/ServicosController.js b/src/controllers/ServicosController.js index 459c232..689aa00 100644 --- a/src/controllers/ServicosController.js +++ b/src/controllers/ServicosController.js @@ -7,7 +7,7 @@ const response = { ...responseModel }; export default { async listaTipoDeServico(req, res) { - const { app } = req.body; + let app = req.params.app; response.data = []; try { diff --git a/src/controllers/UsuarioController.js b/src/controllers/UsuarioController.js index 8108316..799e719 100644 --- a/src/controllers/UsuarioController.js +++ b/src/controllers/UsuarioController.js @@ -11,7 +11,7 @@ const response = { ...responseModel }; export default { async listaUsuarios(req, res) { - const { app } = req.params.app; + let app = req.params.app; try { const findAllUsers = await Users.findAll({ where: { From 213fff84a28c93c5564827fa31bc14d37131966e Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sun, 17 Mar 2024 11:06:57 -0300 Subject: [PATCH 31/36] alterada rota listaArquivos --- src/routes/routes.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/routes/routes.js b/src/routes/routes.js index 5fa4d6b..dcae802 100644 --- a/src/routes/routes.js +++ b/src/routes/routes.js @@ -26,7 +26,7 @@ router .get("/buscaPatrimonio/:id", verifyJWT, ProvisionamentoController.buscaPatrimonio) .get("/buscaTipoDeServico", verifyJWT, ProvisionamentoController.buscaTipoDeServico) - .get("/listaArquivos", verifyJWT, ArquivosController.listaArquivos) + .get("/listaArquivos/:app", verifyJWT, ArquivosController.listaArquivos) .get("/listaServicos", verifyJWT, ServicosController.listaTipoDeServico) .get("/listaCargos", verifyJWT, CargoController.listaCargo) From 002d2f81f18de814d7b4060c5ade4036eb6e0914 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sun, 17 Mar 2024 11:18:19 -0300 Subject: [PATCH 32/36] =?UTF-8?q?alterado=20order=20by=20de=20lista=20serv?= =?UTF-8?q?i=C3=A7os?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/controllers/ServicosController.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/controllers/ServicosController.js b/src/controllers/ServicosController.js index 689aa00..ef8ee3e 100644 --- a/src/controllers/ServicosController.js +++ b/src/controllers/ServicosController.js @@ -14,7 +14,10 @@ export default { const tbTipoDeServico = await ServiceType.findAll({ where: { "app": app - } + }, + order: [ + ["id", "ASC"], + ] }); response.success = tbTipoDeServico.length > 0; From aaf20a6fe6adbace5ccc8c97dc5a46f244522111 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sun, 17 Mar 2024 11:18:41 -0300 Subject: [PATCH 33/36] alterado order by lista arquivos --- src/controllers/ArquivosController.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/controllers/ArquivosController.js b/src/controllers/ArquivosController.js index f8db3ea..4bfef60 100644 --- a/src/controllers/ArquivosController.js +++ b/src/controllers/ArquivosController.js @@ -13,7 +13,10 @@ export default { const tbArquivos = await Files.findAll({ where: { "app": app - } + }, + order: [ + ["id", "ASC"], + ] }); try { From 2979dd59ccb6a3ee499454968b6fd73018b1afba Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sun, 17 Mar 2024 11:23:44 -0300 Subject: [PATCH 34/36] hotfix/cargos model e controller --- src/controllers/CargoController.js | 7 +++---- src/models/cargosModel.js | 4 ---- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/src/controllers/CargoController.js b/src/controllers/CargoController.js index 37ecf60..656a507 100644 --- a/src/controllers/CargoController.js +++ b/src/controllers/CargoController.js @@ -6,14 +6,13 @@ const response = { ...responseModel }; export default { async listaCargo(req, res) { - let app = req.params.app; response.data = []; try { const listaCargos = await Positions.findAll({ - where: { - "app": app - } + order: [ + ["id", "ASC"], + ] }) response.success = listaCargos.length > 0; diff --git a/src/models/cargosModel.js b/src/models/cargosModel.js index 9b0ee0e..aaf2ade 100644 --- a/src/models/cargosModel.js +++ b/src/models/cargosModel.js @@ -13,10 +13,6 @@ const Positions = sequelize.define( type: DataTypes.STRING, allowNull: true, }, - app: { - type: DataTypes.INTEGER, - allowNull: false - }, created_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), From fd53d71089bff105134ff1b02112f3f3068026b4 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sun, 17 Mar 2024 11:30:51 -0300 Subject: [PATCH 35/36] =?UTF-8?q?update=20rota=20lista=20servi=C3=A7os?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/routes/routes.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/routes/routes.js b/src/routes/routes.js index dcae802..c7b05fd 100644 --- a/src/routes/routes.js +++ b/src/routes/routes.js @@ -27,7 +27,7 @@ router .get("/buscaTipoDeServico", verifyJWT, ProvisionamentoController.buscaTipoDeServico) .get("/listaArquivos/:app", verifyJWT, ArquivosController.listaArquivos) - .get("/listaServicos", verifyJWT, ServicosController.listaTipoDeServico) + .get("/listaServicos/:app", verifyJWT, ServicosController.listaTipoDeServico) .get("/listaCargos", verifyJWT, CargoController.listaCargo) .get("/listaApps", verifyJWT, AppController.listaApps) From ebf50f3d4ba6e5c1c218806bdb3ed1b4c24706a9 Mon Sep 17 00:00:00 2001 From: Jean Carlos Date: Sun, 17 Mar 2024 11:57:37 -0300 Subject: [PATCH 36/36] alterado colunas update --- package.json | 2 +- src/controllers/ServicosController.js | 2 +- src/controllers/UsuarioController.js | 8 ++++---- src/models/appsModel.js | 2 +- src/models/arquivosModel.js | 2 +- src/models/cargosModel.js | 2 +- src/models/estadosModel.js | 2 +- src/models/planilhasModel.js | 2 +- src/models/provisionamentoModel.js | 2 +- src/models/tipoDeServicoModel.js | 2 +- src/models/usuarioModel.js | 2 +- src/models/usuariosModel.js | 2 +- 12 files changed, 15 insertions(+), 15 deletions(-) diff --git a/package.json b/package.json index 9c6cb34..0b1eddb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "apiprovisionamento", - "version": "1.6.2", + "version": "1.7.0", "description": "", "main": "server.js", "type": "module", diff --git a/src/controllers/ServicosController.js b/src/controllers/ServicosController.js index ef8ee3e..b16dfda 100644 --- a/src/controllers/ServicosController.js +++ b/src/controllers/ServicosController.js @@ -42,7 +42,7 @@ export default { try { query = await db` - INSERT INTO "tbTipoDeServico" ("tipoDeServico", "created_at", "update_at") + INSERT INTO "tbTipoDeServico" ("tipoDeServico", "created_at", "updated_at") VALUES (${tipoDeServico}, ${dataAtual}, NULL) RETURNING *;`; diff --git a/src/controllers/UsuarioController.js b/src/controllers/UsuarioController.js index 799e719..36c4fc0 100644 --- a/src/controllers/UsuarioController.js +++ b/src/controllers/UsuarioController.js @@ -31,7 +31,7 @@ export default { return { ...row, created_at: dataFormatada.format(row.created_at), - update_at: dataFormatada.format(row.update_at), + updated_at: dataFormatada.format(row.updated_at), }; }); @@ -72,7 +72,7 @@ export default { return { ...row, created_at: dataFormatada.format(row.created_at), - update_at: dataFormatada.format(row.update_at), + updated_at: dataFormatada.format(row.updated_at), }; }); @@ -116,7 +116,7 @@ export default { return res.status(409).json(response); } else { query = await db` - INSERT INTO "tbUsuarios" ("nomeFuncionario", "cargoFuncionario", "emailFuncionario", "senhaFuncionario", "created_at", "admin", "permissaoDoColaborador", "update_at", "status") + INSERT INTO "tbUsuarios" ("nomeFuncionario", "cargoFuncionario", "emailFuncionario", "senhaFuncionario", "created_at", "admin", "permissaoDoColaborador", "updated_at", "status") VALUES (${nomeFuncionario}, ${cargoFuncionario}, ${emailFuncionario}, ${passwordEncrypted}, ${dataAtual}, ${ typeof admin === "boolean" ? admin : null }, ${permissaoDoColaborador}, NULL, ${parseInt(status)}) @@ -169,7 +169,7 @@ export default { try { query = await db` UPDATE "tbUsuarios" - SET "nomeFuncionario"=${nomeFuncionario}, "cargoFuncionario"=${cargoFuncionario}, "emailFuncionario"=${emailFuncionario}, "senhaFuncionario"=${passwordEncrypted}, "admin"=${admin}, "permissaoDoColaborador"=${permissaoDoColaborador}, "update_at"=${dataAtual}, "status"=${status} + SET "nomeFuncionario"=${nomeFuncionario}, "cargoFuncionario"=${cargoFuncionario}, "emailFuncionario"=${emailFuncionario}, "senhaFuncionario"=${passwordEncrypted}, "admin"=${admin}, "permissaoDoColaborador"=${permissaoDoColaborador}, "updated_at"=${dataAtual}, "status"=${status} WHERE "id"=${userId} RETURNING *;`; diff --git a/src/models/appsModel.js b/src/models/appsModel.js index f8b83bd..3468e09 100644 --- a/src/models/appsModel.js +++ b/src/models/appsModel.js @@ -46,7 +46,7 @@ const AppsModel = sequelize.define("tbApp", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/arquivosModel.js b/src/models/arquivosModel.js index a06e199..13aec89 100644 --- a/src/models/arquivosModel.js +++ b/src/models/arquivosModel.js @@ -24,7 +24,7 @@ const Files = sequelize.define("tbArquivos", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/cargosModel.js b/src/models/cargosModel.js index aaf2ade..b593f02 100644 --- a/src/models/cargosModel.js +++ b/src/models/cargosModel.js @@ -18,7 +18,7 @@ const Positions = sequelize.define( defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/estadosModel.js b/src/models/estadosModel.js index d91dbc0..c8beddd 100644 --- a/src/models/estadosModel.js +++ b/src/models/estadosModel.js @@ -21,7 +21,7 @@ const StatesModel = sequelize.define("tbEstados", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/planilhasModel.js b/src/models/planilhasModel.js index 2720ac5..84b00e5 100644 --- a/src/models/planilhasModel.js +++ b/src/models/planilhasModel.js @@ -28,7 +28,7 @@ const Spreadsheets = sequelize.define("tbPlanilhas", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/provisionamentoModel.js b/src/models/provisionamentoModel.js index c5f0c8b..c629d94 100644 --- a/src/models/provisionamentoModel.js +++ b/src/models/provisionamentoModel.js @@ -63,7 +63,7 @@ const Provisioning = sequelize.define("tbProvisionamento", { defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal("CURRENT_TIMESTAMP"), allowNull: true, diff --git a/src/models/tipoDeServicoModel.js b/src/models/tipoDeServicoModel.js index 4b0f0a7..71089f9 100644 --- a/src/models/tipoDeServicoModel.js +++ b/src/models/tipoDeServicoModel.js @@ -20,7 +20,7 @@ const ServiceType = sequelize.define("tbTipoDeServico", { defaultValue: DataTypes.NOW, allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: DataTypes.NOW, allowNull: true, diff --git a/src/models/usuarioModel.js b/src/models/usuarioModel.js index 6ac49cb..febe26d 100644 --- a/src/models/usuarioModel.js +++ b/src/models/usuarioModel.js @@ -45,7 +45,7 @@ const User = sequelize.define("tbUsuarios", { defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: true diff --git a/src/models/usuariosModel.js b/src/models/usuariosModel.js index c9e5dad..05fd369 100644 --- a/src/models/usuariosModel.js +++ b/src/models/usuariosModel.js @@ -41,7 +41,7 @@ const Users = sequelize.define("tbUsuarios", { defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: true, }, - update_at: { + updated_at: { type: DataTypes.DATE, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), allowNull: true