Ajuste conexao oracle & postgres

This commit is contained in:
unknown
2025-03-28 17:03:25 -03:00
parent d2ffb266db
commit b98b219e52
28 changed files with 916 additions and 1383 deletions

14
.env Normal file
View File

@@ -0,0 +1,14 @@
ORACLE_HOST=10.1.1.241
ORACLE_CONNECT_STRING= (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 10.1.1.241)(PORT = 1521)))(CONNECT_DATA = (SERVICE_NAME = WINT)))
ORACLE_PORT=1521
ORACLE_SERVICE=WINT
ORACLE_USER=SEVEN
ORACLE_PASSWORD=USR54SEV
POSTGRES_HOST=10.1.1.222
POSTGRES_PORT=5432
POSTGRES_USER=ti
POSTGRES_PASSWORD=ti
POSTGRES_DB=ksdb

262
package-lock.json generated
View File

@@ -61,8 +61,8 @@
"prettier": "^2.1.2", "prettier": "^2.1.2",
"supertest": "^6.0.0", "supertest": "^6.0.0",
"ts-jest": "^26.4.3", "ts-jest": "^26.4.3",
"ts-loader": "^8.0.8", "ts-loader": "^9.5.2",
"ts-node": "^9.0.0", "ts-node": "^10.9.2",
"tsconfig-paths": "^3.9.0", "tsconfig-paths": "^3.9.0",
"typescript": "^5.8.2" "typescript": "^5.8.2"
} }
@@ -780,6 +780,30 @@
"node": ">=0.1.90" "node": ">=0.1.90"
} }
}, },
"node_modules/@cspotcode/source-map-support": {
"version": "0.8.1",
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
"integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/trace-mapping": "0.3.9"
},
"engines": {
"node": ">=12"
}
},
"node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": {
"version": "0.3.9",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
"integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.0.3",
"@jridgewell/sourcemap-codec": "^1.4.10"
}
},
"node_modules/@inquirer/checkbox": { "node_modules/@inquirer/checkbox": {
"version": "4.1.4", "version": "4.1.4",
"resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-4.1.4.tgz", "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-4.1.4.tgz",
@@ -1571,6 +1595,7 @@
"resolved": "https://registry.npmjs.org/@nestjs/cli/-/cli-11.0.5.tgz", "resolved": "https://registry.npmjs.org/@nestjs/cli/-/cli-11.0.5.tgz",
"integrity": "sha512-ab/d8Ple+dMSQ4pC7RSNjhntpT8gFQQE8y/F/ilaplp7zPGpuxbayRtYbsA/wc1UkJHORDckrqFc8Jh8mrTq2A==", "integrity": "sha512-ab/d8Ple+dMSQ4pC7RSNjhntpT8gFQQE8y/F/ilaplp7zPGpuxbayRtYbsA/wc1UkJHORDckrqFc8Jh8mrTq2A==",
"dev": true, "dev": true,
"license": "MIT",
"dependencies": { "dependencies": {
"@angular-devkit/core": "19.1.8", "@angular-devkit/core": "19.1.8",
"@angular-devkit/schematics": "19.1.8", "@angular-devkit/schematics": "19.1.8",
@@ -2411,6 +2436,34 @@
"node": ">= 6" "node": ">= 6"
} }
}, },
"node_modules/@tsconfig/node10": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz",
"integrity": "sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==",
"dev": true,
"license": "MIT"
},
"node_modules/@tsconfig/node12": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz",
"integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==",
"dev": true,
"license": "MIT"
},
"node_modules/@tsconfig/node14": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz",
"integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==",
"dev": true,
"license": "MIT"
},
"node_modules/@tsconfig/node16": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz",
"integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/babel__core": { "node_modules/@types/babel__core": {
"version": "7.20.5", "version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@@ -3455,15 +3508,6 @@
} }
] ]
}, },
"node_modules/big.js": {
"version": "5.2.2",
"resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz",
"integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==",
"dev": true,
"engines": {
"node": "*"
}
},
"node_modules/binary-extensions": { "node_modules/binary-extensions": {
"version": "2.3.0", "version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
@@ -4799,15 +4843,6 @@
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==" "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="
}, },
"node_modules/emojis-list": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-3.0.0.tgz",
"integrity": "sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==",
"dev": true,
"engines": {
"node": ">= 4"
}
},
"node_modules/encodeurl": { "node_modules/encodeurl": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
@@ -4847,18 +4882,6 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/errno": {
"version": "0.1.8",
"resolved": "https://registry.npmjs.org/errno/-/errno-0.1.8.tgz",
"integrity": "sha512-dJ6oBr5SQ1VSd9qkk7ByRgb/1SH4JZjCHSW/mr63/QcXO9zLVxvJ6Oy13nio03rxpSnVDDjFor75SjVeZWPW/A==",
"dev": true,
"dependencies": {
"prr": "~1.0.1"
},
"bin": {
"errno": "cli.js"
}
},
"node_modules/error-ex": { "node_modules/error-ex": {
"version": "1.3.2", "version": "1.3.2",
"resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz",
@@ -7832,32 +7855,6 @@
"node": ">=6.11.5" "node": ">=6.11.5"
} }
}, },
"node_modules/loader-utils": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.4.tgz",
"integrity": "sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==",
"dev": true,
"dependencies": {
"big.js": "^5.2.2",
"emojis-list": "^3.0.0",
"json5": "^2.1.2"
},
"engines": {
"node": ">=8.9.0"
}
},
"node_modules/loader-utils/node_modules/json5": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
"integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
"dev": true,
"bin": {
"json5": "lib/cli.js"
},
"engines": {
"node": ">=6"
}
},
"node_modules/locate-path": { "node_modules/locate-path": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
@@ -8047,55 +8044,6 @@
"node": ">= 4.0.0" "node": ">= 4.0.0"
} }
}, },
"node_modules/memory-fs": {
"version": "0.5.0",
"resolved": "https://registry.npmjs.org/memory-fs/-/memory-fs-0.5.0.tgz",
"integrity": "sha512-jA0rdU5KoQMC0e6ppoNRtpp6vjFq6+NY7r8hywnC7V+1Xj/MtHwGIbB1QaK/dunyjWteJzmkpd7ooeWg10T7GA==",
"dev": true,
"dependencies": {
"errno": "^0.1.3",
"readable-stream": "^2.0.1"
},
"engines": {
"node": ">=4.3.0 <5.0.0 || >=5.10"
}
},
"node_modules/memory-fs/node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
"dev": true
},
"node_modules/memory-fs/node_modules/readable-stream": {
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
"dev": true,
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"node_modules/memory-fs/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"dev": true
},
"node_modules/memory-fs/node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"dev": true,
"dependencies": {
"safe-buffer": "~5.1.0"
}
},
"node_modules/merge-descriptors": { "node_modules/merge-descriptors": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
@@ -9118,12 +9066,6 @@
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
}, },
"node_modules/prr": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz",
"integrity": "sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw==",
"dev": true
},
"node_modules/psl": { "node_modules/psl": {
"version": "1.15.0", "version": "1.15.0",
"resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz", "resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz",
@@ -10803,15 +10745,6 @@
"integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
"dev": true "dev": true
}, },
"node_modules/tapable": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/tapable/-/tapable-1.1.3.tgz",
"integrity": "sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA==",
"dev": true,
"engines": {
"node": ">=6"
}
},
"node_modules/terminal-link": { "node_modules/terminal-link": {
"version": "2.1.1", "version": "2.1.1",
"resolved": "https://registry.npmjs.org/terminal-link/-/terminal-link-2.1.1.tgz", "resolved": "https://registry.npmjs.org/terminal-link/-/terminal-link-2.1.1.tgz",
@@ -11157,63 +11090,91 @@
} }
}, },
"node_modules/ts-loader": { "node_modules/ts-loader": {
"version": "8.4.0", "version": "9.5.2",
"resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-8.4.0.tgz", "resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-9.5.2.tgz",
"integrity": "sha512-6nFY3IZ2//mrPc+ImY3hNWx1vCHyEhl6V+wLmL4CZcm6g1CqX7UKrkc6y0i4FwcfOhxyMPCfaEvh20f4r9GNpw==", "integrity": "sha512-Qo4piXvOTWcMGIgRiuFa6nHNm+54HbYaZCKqc9eeZCLRy3XqafQgwX2F7mofrbJG3g7EEb+lkiR+z2Lic2s3Zw==",
"dev": true, "dev": true,
"license": "MIT",
"dependencies": { "dependencies": {
"chalk": "^4.1.0", "chalk": "^4.1.0",
"enhanced-resolve": "^4.0.0", "enhanced-resolve": "^5.0.0",
"loader-utils": "^2.0.0",
"micromatch": "^4.0.0", "micromatch": "^4.0.0",
"semver": "^7.3.4" "semver": "^7.3.4",
"source-map": "^0.7.4"
}, },
"engines": { "engines": {
"node": ">=10.0.0" "node": ">=12.0.0"
}, },
"peerDependencies": { "peerDependencies": {
"typescript": "*", "typescript": "*",
"webpack": "*" "webpack": "^5.0.0"
} }
}, },
"node_modules/ts-loader/node_modules/enhanced-resolve": { "node_modules/ts-loader/node_modules/source-map": {
"version": "4.5.0", "version": "0.7.4",
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-4.5.0.tgz", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.4.tgz",
"integrity": "sha512-Nv9m36S/vxpsI+Hc4/ZGRs0n9mXqSWGGq49zxb/cJfPAQMbUtttJAlNPS4AQzaBdw/pKskw5bMbekT/Y7W/Wlg==", "integrity": "sha512-l3BikUxvPOcn5E74dZiq5BGsTb5yEwhaTSzccU6t4sDOH8NWJCstKO5QT2CvtFoK6F0saL7p9xHAqHOlCPJygA==",
"dev": true, "dev": true,
"dependencies": { "license": "BSD-3-Clause",
"graceful-fs": "^4.1.2",
"memory-fs": "^0.5.0",
"tapable": "^1.0.0"
},
"engines": { "engines": {
"node": ">=6.9.0" "node": ">= 8"
} }
}, },
"node_modules/ts-node": { "node_modules/ts-node": {
"version": "9.1.1", "version": "10.9.2",
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-9.1.1.tgz", "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz",
"integrity": "sha512-hPlt7ZACERQGf03M253ytLY3dHbGNGrAq9qIHWUY9XHYl1z7wYngSr3OQ5xmui8o2AaxsONxIzjafLUiWBo1Fg==", "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==",
"dev": true, "dev": true,
"license": "MIT",
"dependencies": { "dependencies": {
"@cspotcode/source-map-support": "^0.8.0",
"@tsconfig/node10": "^1.0.7",
"@tsconfig/node12": "^1.0.7",
"@tsconfig/node14": "^1.0.0",
"@tsconfig/node16": "^1.0.2",
"acorn": "^8.4.1",
"acorn-walk": "^8.1.1",
"arg": "^4.1.0", "arg": "^4.1.0",
"create-require": "^1.1.0", "create-require": "^1.1.0",
"diff": "^4.0.1", "diff": "^4.0.1",
"make-error": "^1.1.1", "make-error": "^1.1.1",
"source-map-support": "^0.5.17", "v8-compile-cache-lib": "^3.0.1",
"yn": "3.1.1" "yn": "3.1.1"
}, },
"bin": { "bin": {
"ts-node": "dist/bin.js", "ts-node": "dist/bin.js",
"ts-node-cwd": "dist/bin-cwd.js",
"ts-node-esm": "dist/bin-esm.js",
"ts-node-script": "dist/bin-script.js", "ts-node-script": "dist/bin-script.js",
"ts-node-transpile-only": "dist/bin-transpile.js", "ts-node-transpile-only": "dist/bin-transpile.js",
"ts-script": "dist/bin-script-deprecated.js" "ts-script": "dist/bin-script-deprecated.js"
}, },
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": { "peerDependencies": {
"@swc/core": ">=1.2.50",
"@swc/wasm": ">=1.2.50",
"@types/node": "*",
"typescript": ">=2.7" "typescript": ">=2.7"
},
"peerDependenciesMeta": {
"@swc/core": {
"optional": true
},
"@swc/wasm": {
"optional": true
}
}
},
"node_modules/ts-node/node_modules/acorn-walk": {
"version": "8.3.4",
"resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz",
"integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==",
"dev": true,
"license": "MIT",
"dependencies": {
"acorn": "^8.11.0"
},
"engines": {
"node": ">=0.4.0"
} }
}, },
"node_modules/tsconfig-paths": { "node_modules/tsconfig-paths": {
@@ -11783,6 +11744,13 @@
"uuid": "dist/bin/uuid" "uuid": "dist/bin/uuid"
} }
}, },
"node_modules/v8-compile-cache-lib": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
"integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==",
"dev": true,
"license": "MIT"
},
"node_modules/v8-to-istanbul": { "node_modules/v8-to-istanbul": {
"version": "7.1.2", "version": "7.1.2",
"resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-7.1.2.tgz", "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-7.1.2.tgz",

View File

@@ -72,8 +72,8 @@
"prettier": "^2.1.2", "prettier": "^2.1.2",
"supertest": "^6.0.0", "supertest": "^6.0.0",
"ts-jest": "^26.4.3", "ts-jest": "^26.4.3",
"ts-loader": "^8.0.8", "ts-loader": "^9.5.2",
"ts-node": "^9.0.0", "ts-node": "^10.9.2",
"tsconfig-paths": "^3.9.0", "tsconfig-paths": "^3.9.0",
"typescript": "^5.8.2" "typescript": "^5.8.2"
}, },

View File

@@ -1,13 +1,10 @@
import { BaseModule } from './core/services/base.module'; import { Module } from '@nestjs/common';
import { BaseService } from './core/services/base.service'; import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { createOracleConfig } from './core/configs/typeorm.oracle.config';
import { createPostgresConfig } from './core/configs/typeorm.postgres.config';
import { LogisticModule } from './logistic/logistic.module'; import { LogisticModule } from './logistic/logistic.module';
import { OrdersPaymentModule } from './orders-payment/orders-payment.module'; import { OrdersPaymentModule } from './orders-payment/orders-payment.module';
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable prettier/prettier */
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { typeOrmConfig, typeOrmPgConfig } from './core/configs/typeorm.config';
import { ProductsModule } from './products/products.module'; import { ProductsModule } from './products/products.module';
import { AuthModule } from './auth/auth/auth.module'; import { AuthModule } from './auth/auth/auth.module';
import { DataConsultModule } from './data-consult/data-consult.module'; import { DataConsultModule } from './data-consult/data-consult.module';
@@ -18,13 +15,22 @@ import { ReasonTableModule } from './crm/reason-table/reason-table.module';
import { NegotiationsModule } from './crm/negotiations/negotiations.module'; import { NegotiationsModule } from './crm/negotiations/negotiations.module';
import { HttpModule } from '@nestjs/axios'; import { HttpModule } from '@nestjs/axios';
import { LogisticController } from './logistic/logistic.controller'; import { LogisticController } from './logistic/logistic.controller';
import { CacheModule } from './core/configs/cache/redis.module';
import { LogisticService } from './logistic/logistic.service'; import { LogisticService } from './logistic/logistic.service';
import { LoggerModule } from './Log/logger.module'; import { LoggerModule } from './Log/logger.module';
@Module({ @Module({
imports: [ imports: [
BaseModule, ConfigModule.forRoot({ isGlobal: true }), // necessário para ConfigService
TypeOrmModule.forRootAsync({
name: 'oracle',
inject: [ConfigService],
useFactory: createOracleConfig,
}),
TypeOrmModule.forRootAsync({
name: 'postgres',
inject: [ConfigService],
useFactory: createPostgresConfig,
}),
LogisticModule, LogisticModule,
OrdersPaymentModule, OrdersPaymentModule,
HttpModule, HttpModule,
@@ -36,14 +42,8 @@ import { LoggerModule } from './Log/logger.module';
ProductsModule, ProductsModule,
AuthModule, AuthModule,
OrdersModule, OrdersModule,
TypeOrmModule.forRoot(typeOrmConfig),
TypeOrmModule.forRoot(typeOrmPgConfig),
CacheModule,
], ],
controllers: [ controllers: [OcorrencesController, LogisticController],
OcorrencesController, LogisticController,], providers: [ LogisticService],
providers: [
BaseService, LogisticService,],
}) })
export class AppModule { } export class AppModule {}

View File

@@ -9,10 +9,10 @@ import {
} from '@nestjs/common'; } from '@nestjs/common';
import { AuthService } from './auth.service'; import { AuthService } from './auth.service';
import { UsersService } from '../users/users.service'; import { UsersService } from '../users/users.service';
import { UserModel } from '../../core/models/user.model'; import { UserModel } from 'src/core/models/user.model';
import { ResultModel } from '../../core/models/result.model'; import { ResultModel } from 'src/core/models/result.model';
import { ResetPasswordModel } from '../../core/models/reset-password.model'; import { ResetPasswordModel } from 'src/core/models/reset-password.model';
import { ChangePasswordModel } from '../../core/models/change-password.model'; import { ChangePasswordModel } from 'src/core/models/change-password.model';
@Controller('api/v1/auth') @Controller('api/v1/auth')
export class AuthController { export class AuthController {

View File

@@ -0,0 +1,4 @@
export class AuthRequestDto {
userName: string;
password: string;
}

View File

@@ -0,0 +1,6 @@
export class ChangePasswordModel {
id: string;
currentPassword: string;
newPassword: string;
}

View File

@@ -0,0 +1,5 @@
export class ResetPasswordModel {
document: string;
email: string;
}

View File

@@ -0,0 +1,10 @@
export interface UserModel {
id: string;
name: string;
sellerId: string;
storeId: string;
email: string;
username: string;
dataDesligamento: Date | null;
situacao: string;
}

View File

@@ -1,18 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from './users.service';
describe('UsersService', () => {
let service: UsersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UsersService],
}).compile();
service = module.get<UsersService>(UsersService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@@ -1,17 +1,16 @@
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
import md5 = require('md5'); import md5 = require('md5');
import { Guid } from "guid-typescript"; import { Guid } from "guid-typescript";
import { typeOrmConfig } from '../../core/configs/typeorm.config'; import { createOracleConfig } from '../../core/configs/typeorm.oracle.config';
import { UserModel } from '../../core/models/user.model'; import { ConfigService } from '@nestjs/config';
@Injectable() @Injectable()
export class UsersService { export class UsersService {
constructor(private readonly configService: ConfigService) {}
async authenticate(user: any): Promise<any> { async authenticate(user: any): Promise<any> {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -51,7 +50,7 @@ export class UsersService {
} }
async resetPassword(user: any): Promise<any> { async resetPassword(user: any): Promise<any> {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -105,7 +104,7 @@ export class UsersService {
async changePassword(user: any): Promise<any> { async changePassword(user: any): Promise<any> {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();

View File

@@ -1,22 +1,16 @@
/* eslint-disable prettier/prettier */ import { registerAs } from '@nestjs/config';
import { DataSourceOptions } from 'typeorm/data-source';
export const typeOrmConfig: DataSourceOptions = { export const databaseConfig = registerAs('database', () => ({
type: 'oracle', oracle: {
connectString: '(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 10.1.1.241)(PORT = 1521)))(CONNECT_DATA = (SERVICE_NAME = WINT)))', connectString: `(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = ${process.env.ORACLE_HOST})(PORT = ${process.env.ORACLE_PORT})))(CONNECT_DATA = (SERVICE_NAME = ${process.env.ORACLE_SERVICE})))`,
username: 'SEVEN', username: process.env.ORACLE_USER,
password: 'USR54SEV', password: process.env.ORACLE_PASSWORD,
synchronize: false, },
logging: false, postgres: {
entities: [__dirname + '/../**/*.entity.{js,ts}'], host: process.env.POSTGRES_HOST,
}; port: parseInt(process.env.POSTGRES_PORT || '5432', 10),
username: process.env.POSTGRES_USER,
export const typeOrmPgConfig: DataSourceOptions = { password: process.env.POSTGRES_PASSWORD,
type: 'postgres', database: process.env.POSTGRES_DB,
host: '10.1.1.222', },
port: 5432, }));
username: 'ti',
password: 'ti',
database: 'ksdb',
synchronize: true,
}

View File

@@ -0,0 +1,14 @@
import { DataSourceOptions } from 'typeorm';
import { ConfigService } from '@nestjs/config';
export function createOracleConfig(config: ConfigService): DataSourceOptions {
return {
type: 'oracle',
connectString: config.get('ORACLE_CONNECT_STRING'),
username: config.get('ORACLE_USER'),
password: config.get('ORACLE_PASSWORD'),
synchronize: false,
logging: false,
entities: [__dirname + '/../**/*.entity.{ts,js}'],
};
}

View File

@@ -0,0 +1,15 @@
import { DataSourceOptions } from 'typeorm';
import { ConfigService } from '@nestjs/config';
export function createPostgresConfig(config: ConfigService): DataSourceOptions {
return {
type: 'postgres',
host: config.get('POSTGRES_HOST'),
port: config.get('POSTGRES_PORT'),
username: config.get('POSTGRES_USER'),
password: config.get('POSTGRES_PASSWORD'),
database: config.get('POSTGRES_DB'),
synchronize: true,
entities: [__dirname + '/../**/*.entity.{ts,js}'],
};
}

View File

@@ -1,101 +0,0 @@
import { DropAction } from './../../../node_modules/aws-sdk/clients/mailmanager.d';
/*
https://docs.nestjs.com/controllers#controllers
*/
import {
Body,
Controller,
Get,
HttpException,
HttpStatus,
Post,
Query,
Req,
UseInterceptors,
UploadedFile,
} from '@nestjs/common';
import { BaseService } from './base.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';
import * as fs from 'fs';
@Controller('api/v1/base')
export class BaseController {
constructor(public readonly baseService: BaseService) {}
// @UseGuards(JwtAuthGuard)
@Get('execute-view')
/* @ApiOperation({
summary: 'Executa uma view com ou sem parâmetros',
})
@ApiResponse({
status: 200,
description: 'Dados retornados com sucesso.',
})
@ApiResponse({
status: 400,
description: 'O nome da view é obrigatório.',
})
@ApiResponse({
status: 500,
description: 'Erro ao executar a view.',
})*/
async executeView(
@Query('viewName') viewName: string,
@Query() params: Record<string, any>,
) {
if (!viewName) {
throw new HttpException(
'O nome da view é obrigatório.',
HttpStatus.BAD_REQUEST,
);
}
try {
return await this.baseService.executeView(viewName, params);
} catch (error) {
throw new HttpException(
`Erro ao executar a view: ${error.message}`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
@Post('send-image')
@UseInterceptors(
FileInterceptor('file', {
storage: diskStorage({
// Pasta onde os arquivos serão salvos; certifique-se que essa pasta exista ou crie-a automaticamente
destination: './uploads',
filename: (req, file, callback) => {
// Gera um nome único para o arquivo
const uniqueSuffix =
Date.now() + '-' + Math.round(Math.random() * 1e9);
const fileExtName = extname(file.originalname);
callback(null, `${file.fieldname}-${uniqueSuffix}${fileExtName}`);
},
}),
// Opcional: definir limites (ex.: tamanho máximo do arquivo)
limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
}),
)
async sendImage(
@UploadedFile() file: Express.Multer.File,
@Body('licensePlate') licensePlate: string,
) {
if (!file) {
throw new HttpException('Nenhum arquivo enviado', HttpStatus.BAD_REQUEST);
}
// Aqui você pode processar o arquivo (ex.: enviar para o S3) ou armazená-lo no disco mesmo.
// Neste exemplo, retornamos a URL do arquivo salvo localmente.
this.baseService.sendImages('./uploads/' + file.filename);
fs.unlink('./uploads/' + file.filename, () => {});
return {
success: true,
message: 'Upload realizado com sucesso',
url: `https://jur-saidaretornoveiculo.s3.sa-east-1.amazonaws.com/${file.filename}`,
licensePlate,
};
}
}

View File

@@ -1,14 +0,0 @@
import { BaseController } from './base.controller';
/*
https://docs.nestjs.com/modules
*/
import { Module } from '@nestjs/common';
import { BaseService } from './base.service';
@Module({
imports: [],
controllers: [BaseController],
providers: [BaseService],
})
export class BaseModule {}

View File

@@ -1,331 +0,0 @@
import {
Inject,
Injectable,
InternalServerErrorException,
} from '@nestjs/common';
import { DataSource } from 'typeorm';
import { typeOrmConfig } from '../configs/typeorm.config';
import { S3 } from 'aws-sdk';
import * as fs from 'fs';
@Injectable()
export class BaseService {
constructor() {}
async findAll(table: string) {
const dataSource = new DataSource(typeOrmConfig);
await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const [rows] = await queryRunner.query(`SELECT * FROM ${table}`);
return rows;
} catch (error) {
this.handleDatabaseError(
error,
`Erro ao buscar todos os registros da tabela ${table}`,
);
} finally {
queryRunner.release();
dataSource.destroy();
}
}
async findOne(table: string, id: any) {
const dataSource = new DataSource(typeOrmConfig);
await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const [rows] = await queryRunner.query(
`SELECT * FROM ${table} WHERE id = '${id}'`,
);
return rows[0];
} catch (error) {
this.handleDatabaseError(
error,
`Erro ao buscar o registro com ID ${id} na tabela ${table}`,
);
} finally {
queryRunner.release();
dataSource.destroy();
}
}
async create(table: string, data: any) {
const dataSource = new DataSource(typeOrmConfig);
await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const columns = Object.keys(data)
.map((key) => `${key}`)
.join(', ');
const values = Object.values(data);
const placeholders = values.map(() => '?').join(', ');
const query = `INSERT INTO ${table} (${columns}) VALUES (${placeholders})`;
const [result] = await queryRunner.query(query, values);
return result;
} catch (error) {
this.handleDatabaseError(
error,
`Erro ao criar um registro na tabela ${table}`,
);
} finally {
queryRunner.release();
dataSource.destroy();
}
}
async update(table: string, where: any, data: any) {
const dataSource = new DataSource(typeOrmConfig);
await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const [result] = await queryRunner.query(
`UPDATE ${table} SET ${data} WHERE ${where}`,
);
return result;
} catch (error) {
this.handleDatabaseError(
error,
`Erro ao atualizar o registro com ${where} na tabela ${table}`,
);
} finally {
queryRunner.release();
dataSource.destroy();
}
}
async delete(table: string, where: any) {
const dataSource = new DataSource(typeOrmConfig);
await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const [result] = await queryRunner.query(
`DELETE FROM ${table} WHERE ${where}`,
);
return result;
} catch (error) {
this.handleDatabaseError(
error,
`Erro ao deletar o registro com ID ${where} na tabela ${table}`,
);
} finally {
queryRunner.release();
dataSource.destroy();
}
}
async query(queryString: string, params: any[]): Promise<any[]> {
const dataSource = new DataSource(typeOrmConfig);
await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const [rows] = await queryRunner.query(queryString, params);
return rows as any[];
} catch (error) {
this.handleDatabaseError(
error,
`Erro ao executar a consulta SQL personalizada`,
);
} finally {
queryRunner.release();
dataSource.destroy();
}
}
async executeView(viewName: string, params: Record<string, any>) {
const dataSource = new DataSource(typeOrmConfig);
await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
// Valida se o nome da view foi fornecido
if (!viewName) {
throw new Error('O nome da view é obrigatório.');
}
console.log(`Iniciando execução da view: ${viewName}`);
console.log('Parâmetros recebidos:', params);
const conditions: string[] = [];
const values: any[] = [];
// Remove o parâmetro viewName dos parâmetros antes de processar
const filteredParams = { ...params };
delete filteredParams.viewName;
// Adiciona as condições baseadas nos parâmetros fornecidos
if (filteredParams && Object.keys(filteredParams).length > 0) {
console.log('Adicionando condições para os parâmetros fornecidos...');
for (const [key, value] of Object.entries(filteredParams)) {
// Verifica se a chave e o valor são válidos
if (value !== undefined && value !== null && value !== '') {
console.log(`Parâmetro válido: ${key} = '${value}'`);
conditions.push(`${key} = '${value}'`); // Adiciona aspas para evitar problemas de SQL injection
values.push(value);
} else {
console.warn(`Parâmetro ignorado: ${key} = '${value}'`);
}
}
} else {
console.log('Nenhum parâmetro válido foi fornecido.');
}
// Monta a cláusula WHERE somente se houver condições
const whereClause =
conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
const query = `SELECT * FROM ${viewName} ${whereClause}`;
console.log(`Consulta SQL montada: ${query}`);
console.log(`{Valores para a consulta:, ${values}`);
// Executa a consulta
const rows = await queryRunner.query(query);
console.log(
`Consulta executada com sucesso.Linhas retornadas: ${JSON.stringify(
rows,
)}`,
);
return rows;
} catch (error) {
console.error(`Erro ao executar a view ${viewName}: `, error.message);
this.handleDatabaseError(
error,
`Erro ao executar a view ${viewName} com parâmetros.`,
);
} finally {
await queryRunner.release();
await dataSource.destroy();
}
}
async executeProcedure(procedureName: string, params: Record<string, any>) {
const dataSource = new DataSource(typeOrmConfig);
await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const placeholders = Object.keys(params)
.map(() => '?')
.join(', ');
const values = Object.values(params);
const query = `EXECUTE IMMEDIATE ${procedureName}(${placeholders})`;
// Log da query e dos valores
console.log('Query executada:', query);
console.log('Valores:', values);
const [result] = await queryRunner.query(query, values);
// Verifica e converte campos que contenham JSON strings para objetos
const parsedResult = Array.isArray(result)
? result.map((row) => {
const parsedRow = { ...row };
for (const [key, value] of Object.entries(parsedRow)) {
try {
// Tenta converter strings JSON para objetos
if (
typeof value === 'string' &&
value.trim().startsWith('{') &&
value.trim().endsWith('}')
) {
parsedRow[key] = JSON.parse(value);
}
} catch (error) {
// Ignora se a conversão falhar
console.warn(
`Campo ${key} não é um JSON válido.Mantendo como string.`,
);
}
}
return parsedRow;
})
: result;
// Retorna os valores e o resultado
return {
message: 'Procedure executada com sucesso.',
executedQuery: query,
values: values,
result: parsedResult,
};
} catch (error) {
this.handleDatabaseError(
error,
`Erro ao executar a procedure ${procedureName} com parâmetros.`,
);
}
}
private handleDatabaseError(error: any, message: string): never {
console.error(message, error); // Log detalhado do erro
throw new InternalServerErrorException({
message,
sqlMessage: error.sqlMessage || error.message,
sqlState: error.sqlState,
});
}
async sendImages(file: string) {
// for (const file of files) {
// const file = 'C:\\Temp\\brasil_2.jpg'
if (file.endsWith('.jpg')) {
const fileName = file; //directoryImages + '\\' + file;
fs.readFile(fileName, (err, data) => {
if (err) throw err;
if (err) {
console.log(`WRITE ERROR: ${err}`);
} else {
this.uploadS3(
data,
'jur-saidaretornoveiculo',
file.replace('./uploads/', ''),
);
}
});
}
//}
}
async uploadS3(file, bucket, name) {
const s3 = this.getS3();
const params = {
Bucket: bucket,
Key: String(name),
Body: file,
};
return new Promise((resolve, reject) => {
s3.upload(params, (err, data) => {
if (err) {
console.log(JSON.stringify(err));
reject(err.message);
}
resolve(data);
});
});
}
getS3() {
return new S3({
accessKeyId: 'AKIAVHJOO6W765ZT2PNI', //process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: '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', // process.env.AWS_SECRET_ACCESS_KEY,
});
}
}

View File

@@ -34,10 +34,9 @@ export class DataConsultController {
} }
@Get('products/:filter') @Get('products/:filter')
@ApiOperation({ summary: 'Filtra produtos pelo parâmetro fornecido' }) @ApiOperation({ summary: 'Busca produtos filtrados' })
@ApiParam({ name: 'filter', description: 'Filtro de busca para produtos' }) @ApiParam({ name: 'filter', description: 'Filtro de busca' })
async products(@Param('filter') filter: string) { async products(@Param('filter') filter: string) {
return this.dataConsultService.products(filter); return this.dataConsultService.products(filter);
} }
} }

View File

@@ -2,11 +2,11 @@ import { Module } from '@nestjs/common';
import { DataConsultService } from './data-consult.service'; import { DataConsultService } from './data-consult.service';
import { DataConsultController } from './data-consult.controller'; import { DataConsultController } from './data-consult.controller';
import { DataConsultRepository } from './data-consult.repository'; import { DataConsultRepository } from './data-consult.repository';
import { CacheModule } from '../core/configs/cache/redis.module';
import { LoggerModule } from 'src/Log/logger.module'; import { LoggerModule } from 'src/Log/logger.module';
import { ConfigModule } from '@nestjs/config';
@Module({ @Module({
imports: [CacheModule,LoggerModule], imports: [LoggerModule, ConfigModule],
controllers: [DataConsultController], controllers: [DataConsultController],
providers: [ providers: [
DataConsultService, DataConsultService,

View File

@@ -1,18 +1,19 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
import { typeOrmConfig } from '../core/configs/typeorm.config'; import { createOracleConfig } from '../core/configs/typeorm.oracle.config';
import { StoreDto } from './dto/store.dto'; import { StoreDto } from './dto/store.dto';
import { SellerDto } from './dto/seller.dto'; import { SellerDto } from './dto/seller.dto';
import { BillingDto } from './dto/billing.dto'; import { BillingDto } from './dto/billing.dto';
import { CustomerDto } from './dto/customer.dto'; import { CustomerDto } from './dto/customer.dto';
import { ProductDto } from './dto/product.dto'; import { ProductDto } from './dto/product.dto';
import { ConfigService } from '@nestjs/config';
@Injectable() @Injectable()
export class DataConsultRepository { export class DataConsultRepository {
private readonly dataSource: DataSource; private readonly dataSource: DataSource;
constructor() { constructor(private readonly configService: ConfigService) {
this.dataSource = new DataSource(typeOrmConfig); this.dataSource = new DataSource(createOracleConfig(configService));
this.dataSource.initialize(); this.dataSource.initialize();
} }
@@ -63,39 +64,47 @@ export class DataConsultRepository {
} }
async findCustomers(filter: string): Promise<CustomerDto[]> { async findCustomers(filter: string): Promise<CustomerDto[]> {
if (!filter || typeof filter !== 'string') return [];
const cleanedNumeric = filter.replace(/[^\d]/g, '');
const likeFilter = filter.toUpperCase().replace('@', '%') + '%';
const queries = [ const queries = [
// Busca por código (apenas números)
{ {
sql: ` sql: `
SELECT PCCLIENT.CODCLI as "id", SELECT PCCLIENT.CODCLI as "id",
PCCLIENT.CODCLI || ' - ' || PCCLIENT.CLIENTE || PCCLIENT.CODCLI || ' - ' || PCCLIENT.CLIENTE ||
' ( ' || REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '') || ' )' as "name" ' ( ' || REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '') || ' )' as "name"
FROM PCCLIENT FROM PCCLIENT
WHERE PCCLIENT.CODCLI = REGEXP_REPLACE(?, '[^0-9]', '') WHERE PCCLIENT.CODCLI = :1
ORDER BY PCCLIENT.CLIENTE ORDER BY PCCLIENT.CLIENTE
`, `,
params: [filter], params: [cleanedNumeric],
}, },
// Busca por CNPJ/CPF limpo
{ {
sql: ` sql: `
SELECT PCCLIENT.CODCLI as "id", SELECT PCCLIENT.CODCLI as "id",
PCCLIENT.CODCLI || ' - ' || PCCLIENT.CLIENTE || PCCLIENT.CODCLI || ' - ' || PCCLIENT.CLIENTE ||
' ( ' || REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '') || ' )' as "name" ' ( ' || REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '') || ' )' as "name"
FROM PCCLIENT FROM PCCLIENT
WHERE REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '') = REGEXP_REPLACE(?, '[^0-9]', '') WHERE REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '') = :1
ORDER BY PCCLIENT.CLIENTE ORDER BY PCCLIENT.CLIENTE
`, `,
params: [filter], params: [cleanedNumeric],
}, },
// Busca por nome do cliente
{ {
sql: ` sql: `
SELECT PCCLIENT.CODCLI as "id", SELECT PCCLIENT.CODCLI as "id",
PCCLIENT.CODCLI || ' - ' || PCCLIENT.CLIENTE || PCCLIENT.CODCLI || ' - ' || PCCLIENT.CLIENTE ||
' ( ' || REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '') || ' )' as "name" ' ( ' || REGEXP_REPLACE(PCCLIENT.CGCENT, '[^0-9]', '') || ' )' as "name"
FROM PCCLIENT FROM PCCLIENT
WHERE PCCLIENT.CLIENTE LIKE ? WHERE UPPER(PCCLIENT.CLIENTE) LIKE :1
ORDER BY PCCLIENT.CLIENTE ORDER BY PCCLIENT.CLIENTE
`, `,
params: [filter.toUpperCase().replace('@', '%') + '%'], params: [likeFilter],
}, },
]; ];
@@ -109,10 +118,10 @@ export class DataConsultRepository {
return []; return [];
} }
async findProducts(filter: string): Promise<ProductDto[]> { async findProducts(filter: string): Promise<ProductDto[]> {
const cleanFilter = filter.replace(/[^\d]/g, ''); const cleanedFilter = filter.replace(/[^\d]/g, ''); // apenas números
const likeFilter = filter + '%'; const likeFilter = filter + '%';
const codAux = filter.replace(/[^\d]/g, '');
const queries = [ const queries = [
{ {
@@ -124,7 +133,7 @@ export class DataConsultRepository {
WHERE PCPRODUT.CODPROD = ? WHERE PCPRODUT.CODPROD = ?
ORDER BY PCPRODUT.DESCRICAO ORDER BY PCPRODUT.DESCRICAO
`, `,
params: [cleanFilter], params: [cleanedFilter],
}, },
{ {
sql: ` sql: `
@@ -135,7 +144,7 @@ export class DataConsultRepository {
WHERE PCPRODUT.CODAUXILIAR = ? WHERE PCPRODUT.CODAUXILIAR = ?
ORDER BY PCPRODUT.DESCRICAO ORDER BY PCPRODUT.DESCRICAO
`, `,
params: [codAux], params: [cleanedFilter],
}, },
{ {
sql: ` sql: `

View File

@@ -1,6 +1,4 @@
import { Inject, Injectable } from '@nestjs/common'; import { Injectable, HttpException, HttpStatus, Inject } from '@nestjs/common';
import { IRedisClient } from '../core/configs/cache/IRedisClient';
import { RedisClientToken } from '../core/configs/cache/redis-client.adapter.provider';
import { DataConsultRepository } from './data-consult.repository'; import { DataConsultRepository } from './data-consult.repository';
import { StoreDto } from './dto/store.dto'; import { StoreDto } from './dto/store.dto';
import { SellerDto } from './dto/seller.dto'; import { SellerDto } from './dto/seller.dto';
@@ -9,119 +7,73 @@ import { CustomerDto } from './dto/customer.dto';
import { ProductDto } from './dto/product.dto'; import { ProductDto } from './dto/product.dto';
import { ILogger } from '../Log/ILogger'; import { ILogger } from '../Log/ILogger';
const DEFAULT_CACHE_TTL = 100;
@Injectable() @Injectable()
export class DataConsultService { export class DataConsultService {
constructor( constructor(
private readonly repository: DataConsultRepository, private readonly repository: DataConsultRepository,
@Inject(RedisClientToken)
private readonly redisClient: IRedisClient,
@Inject('LoggerService') @Inject('LoggerService')
private readonly logger: ILogger private readonly logger: ILogger
) {} ) {}
/** /**
* Método genérico para lidar com lógica de cache * Obter todas as lojas
* @param cacheKey - A chave a ser usada para cache
* @param fetchFn - Função para buscar dados se não estiverem no cache
* @param ttl - Tempo de vida em segundos para o cache
* @returns Os dados em cache ou recentemente buscados
*/
private async getCachedData<T>(
cacheKey: string,
fetchFn: () => Promise<T>,
ttl: number = DEFAULT_CACHE_TTL
): Promise<T> {
try {
this.logger.log(`Tentando obter dados em cache para a chave: ${cacheKey}`);
const cached = await this.redisClient.get<T>(cacheKey);
if (cached) {
this.logger.log(`Cache encontrado para a chave: ${cacheKey}`);
return cached;
}
this.logger.log(`Cache não encontrado para a chave: ${cacheKey}, buscando na origem`);
const result = await fetchFn();
try {
await this.redisClient.set<T>(cacheKey, result, ttl);
this.logger.log(`Dados armazenados em cache com sucesso para a chave: ${cacheKey}`);
} catch (cacheError) {
this.logger.warn(`Falha ao armazenar dados em cache para a chave: ${cacheKey}`);
this.logger.error('Detalhes do erro de cache:', cacheError instanceof Error ? cacheError.stack : '');
}
return result;
} catch (error) {
this.logger.error(
`Erro no método getCachedData para a chave ${cacheKey}:`,
error instanceof Error ? error.stack : ''
);
return fetchFn();
}
}
/**
* Obter todas as lojas com cache
* @returns Array de StoreDto * @returns Array de StoreDto
*/ */
async stores(): Promise<StoreDto[]> { async stores(): Promise<StoreDto[]> {
this.logger.log('Buscando todas as lojas'); this.logger.log('Buscando todas as lojas');
return this.getCachedData<StoreDto[]>( return this.repository.findStores();
'data-consult:stores',
() => this.repository.findStores()
);
} }
/** /**
* Obter todos os vendedores com cache * Obter todos os vendedores
* @returns Array de SellerDto * @returns Array de SellerDto
*/ */
async sellers(): Promise<SellerDto[]> { async sellers(): Promise<SellerDto[]> {
this.logger.log('Buscando todos os vendedores'); this.logger.log('Buscando todos os vendedores');
return this.getCachedData<SellerDto[]>( return this.repository.findSellers();
'data-consult:sellers',
() => this.repository.findSellers()
);
} }
/** /**
* Obter todos os faturamentos com cache * Obter todos os faturamentos
* @returns Array de BillingDto * @returns Array de BillingDto
*/ */
async billings(): Promise<BillingDto[]> { async billings(): Promise<BillingDto[]> {
this.logger.log('Buscando todos os faturamentos'); this.logger.log('Buscando todos os faturamentos');
return this.getCachedData<BillingDto[]>( return this.repository.findBillings();
'data-consult:billings',
() => this.repository.findBillings()
);
} }
/** /**
* Obter clientes filtrados por termo de pesquisa com cache * Obter clientes filtrados por termo de pesquisa
* @param filter - Termo de pesquisa para filtrar clientes * @param filter - Termo de pesquisa para filtrar clientes
* @returns Array de CustomerDto * @returns Array de CustomerDto
*/ */
async customers(filter: string): Promise<CustomerDto[]> { async customers(filter: string): Promise<CustomerDto[]> {
this.logger.log(`Buscando clientes com filtro: ${filter}`); this.logger.log(`Buscando clientes com filtro: ${filter}`);
return this.getCachedData<CustomerDto[]>( return this.repository.findCustomers(filter);
`data-consult:customers:${filter}`,
() => this.repository.findCustomers(filter)
);
} }
/** /**
* Obter produtos filtrados por termo de pesquisa com cache * Obter produtos filtrados por termo de pesquisa
* @param filter - Termo de pesquisa para filtrar produtos * @param filter - Termo de pesquisa para filtrar produtos
* @returns Array de ProductDto * @returns Array de ProductDto
*/ */
async products(filter: string): Promise<ProductDto[]> { async products(filter: string): Promise<ProductDto[]> {
this.logger.log(`Buscando produtos com filtro: ${filter}`); this.logger.log(`Buscando produtos com filtro: ${filter}`);
return this.getCachedData<ProductDto[]>(
`data-consult:products:${filter}`, try {
() => this.repository.findProducts(filter) const result = await this.repository.findProducts(filter);
this.logger.log(`Produtos encontrados: ${result.length}`);
return result;
} catch (error) {
this.logger.error(
`Erro ao buscar produtos com filtro "${filter}"`,
error instanceof Error ? error.stack : ''
);
throw new HttpException(
'Erro ao buscar produtos. Tente novamente mais tarde.',
HttpStatus.INTERNAL_SERVER_ERROR
); );
} }
}
} }

View File

@@ -1,14 +1,17 @@
import { Get, HttpException, HttpStatus, Injectable, Query, UseGuards } from '@nestjs/common'; import { Get, HttpException, HttpStatus, Injectable, Query, UseGuards } from '@nestjs/common';
import { typeOrmConfig, typeOrmPgConfig } from '../core/configs/typeorm.config'; import { createOracleConfig } from '../core/configs/typeorm.oracle.config';
import { createPostgresConfig } from '../core/configs/typeorm.postgres.config';
import { CarOutDelivery } from '../core/models/car-out-delivery.model'; import { CarOutDelivery } from '../core/models/car-out-delivery.model';
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
import { CarInDelivery } from '../core/models/car-in-delivery.model'; import { CarInDelivery } from '../core/models/car-in-delivery.model';
import { ConfigService } from '@nestjs/config';
@Injectable() @Injectable()
export class LogisticService { export class LogisticService {
constructor(private readonly configService: ConfigService) {}
async getExpedicao() { async getExpedicao() {
const dataSource = new DataSource(typeOrmPgConfig); const dataSource = new DataSource(createPostgresConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -95,7 +98,7 @@ export class LogisticService {
} }
async getDeliveries(placa: string) { async getDeliveries(placa: string) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createPostgresConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -139,7 +142,7 @@ export class LogisticService {
} }
async getStatusCar(placa: string) { async getStatusCar(placa: string) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createPostgresConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -163,7 +166,7 @@ export class LogisticService {
} }
async getEmployee() { async getEmployee() {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createPostgresConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -186,7 +189,7 @@ export class LogisticService {
async createCarOut(data: CarOutDelivery) { async createCarOut(data: CarOutDelivery) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createPostgresConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -261,7 +264,7 @@ export class LogisticService {
async createCarIn(data: CarInDelivery) { async createCarIn(data: CarInDelivery) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createPostgresConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();

View File

@@ -23,6 +23,6 @@ async function bootstrap() {
const document = SwaggerModule.createDocument(app, config); const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document); SwaggerModule.setup('docs', app, document);
await app.listen(9002); await app.listen(9009);
} }
bootstrap(); bootstrap();

View File

@@ -6,14 +6,16 @@ https://docs.nestjs.com/providers#services
*/ */
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { typeOrmConfig } from '../core/configs/typeorm.config'; import { createOracleConfig } from '../core/configs/typeorm.oracle.config';
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
import { ConfigService } from '@nestjs/config';
@Injectable() @Injectable()
export class OrdersPaymentService { export class OrdersPaymentService {
constructor(private readonly configService: ConfigService) {}
async findOrders(storeId: string, orderId: number) { async findOrders(storeId: string, orderId: number) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -58,7 +60,7 @@ export class OrdersPaymentService {
} }
async findPayments(orderId: number) { async findPayments(orderId: number) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -90,7 +92,7 @@ export class OrdersPaymentService {
} }
async createPayment(payment: any) { async createPayment(payment: any) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -116,7 +118,7 @@ export class OrdersPaymentService {
async createInvoice(data: any) { async createInvoice(data: any) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();

View File

@@ -5,14 +5,16 @@ https://docs.nestjs.com/providers#services
*/ */
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { typeOrmConfig } from '../core/configs/typeorm.config'; import { createOracleConfig } from '../core/configs/typeorm.oracle.config';
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
import { ConfigService } from '@nestjs/config';
@Injectable() @Injectable()
export class OrdersService { export class OrdersService {
constructor(private readonly configService: ConfigService) {}
async findOrders(query) { async findOrders(query) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -228,7 +230,7 @@ export class OrdersService {
} }
async findInvoice(chavenfe: string) { async findInvoice(chavenfe: string) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -289,7 +291,7 @@ export class OrdersService {
async getItens(orderId: string) { async getItens(orderId: string) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -333,7 +335,7 @@ export class OrdersService {
} }
async getCutItens(orderId: string) { async getCutItens(orderId: string) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -360,7 +362,7 @@ export class OrdersService {
} }
async getOrderDelivery(orderId: string){ async getOrderDelivery(orderId: string){
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -421,7 +423,7 @@ export class OrdersService {
async getTransfer(orderId: number) { async getTransfer(orderId: number) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -454,7 +456,7 @@ export class OrdersService {
} }
async getStatusOrder(orderId: number) { async getStatusOrder(orderId: number) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -602,7 +604,7 @@ export class OrdersService {
async createInvoiceCheck(invoice: any) { async createInvoiceCheck(invoice: any) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();

View File

@@ -6,15 +6,16 @@ https://docs.nestjs.com/providers#services
*/ */
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { typeOrmConfig } from '../core/configs/typeorm.config'; import { createOracleConfig } from '../core/configs/typeorm.oracle.config';
import { ExposedProduct } from '../core/models/exposed-product.model'; import { ExposedProduct } from '../core/models/exposed-product.model';
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
import { ConfigService } from '@nestjs/config';
@Injectable() @Injectable()
export class ProductsService { export class ProductsService {
constructor(private readonly configService: ConfigService) {}
async productsValidation(storeId: string, filtro: string): Promise<any> { async productsValidation(storeId: string, filtro: string): Promise<any> {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -76,7 +77,7 @@ export class ProductsService {
} }
async exposedProduct(product: ExposedProduct) { async exposedProduct(product: ExposedProduct) {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();
@@ -97,7 +98,7 @@ export class ProductsService {
} }
async getProductsEcommerce() { async getProductsEcommerce() {
const dataSource = new DataSource(typeOrmConfig); const dataSource = new DataSource(createOracleConfig(this.configService));
await dataSource.initialize(); await dataSource.initialize();
const queryRunner = dataSource.createQueryRunner(); const queryRunner = dataSource.createQueryRunner();
await queryRunner.connect(); await queryRunner.connect();