This commit is contained in:
Felipe Batista 2025-01-27 17:44:27 -03:00
commit 47e7f75720
238 changed files with 36425 additions and 0 deletions

24
.eslintrc.js Normal file
View File

@ -0,0 +1,24 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
],
root: true,
env: {
node: true,
jest: true,
},
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

35
.gitignore vendored Normal file
View File

@ -0,0 +1,35 @@
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

75
README.md Normal file
View File

@ -0,0 +1,75 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" alt="Nest Logo" /></a>
</p>
[travis-image]: https://api.travis-ci.org/nestjs/nest.svg?branch=master
[travis-url]: https://travis-ci.org/nestjs/nest
[linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux
[linux-url]: https://travis-ci.org/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="blank">Node.js</a> framework for building efficient and scalable server-side applications, heavily inspired by <a href="https://angular.io" target="blank">Angular</a>.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore"><img src="https://img.shields.io/npm/dm/@nestjs/core.svg" alt="NPM Downloads" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://api.travis-ci.org/nestjs/nest.svg?branch=master" alt="Travis" /></a>
<a href="https://travis-ci.org/nestjs/nest"><img src="https://img.shields.io/travis/nestjs/nest/master.svg?label=linux" alt="Linux" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#5" alt="Coverage" /></a>
<a href="https://gitter.im/nestjs/nestjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=body_badge"><img src="https://badges.gitter.im/nestjs/nestjs.svg" alt="Gitter" /></a>
<a href="https://opencollective.com/nest#backer"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec"><img src="https://img.shields.io/badge/Donate-PayPal-dc3d53.svg"/></a>
<a href="https://twitter.com/nestframework"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Installation
```bash
$ npm install
```
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).

View File

@ -0,0 +1,55 @@
CERTIFICADO PARA DESENVOLVIMENTO
-----BEGIN CERTIFICATE-----
MIIEFTCCAv2gAwIBAgIUbexM37zIhdxNpGtug6DDveiB1OIwDQYJKoZIhvcNAQEL
BQAwgagxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH
Ew1TYW4gRnJhbmNpc2NvMRkwFwYDVQQKExBDbG91ZGZsYXJlLCBJbmMuMRswGQYD
VQQLExJ3d3cuY2xvdWRmbGFyZS5jb20xNDAyBgNVBAMTK01hbmFnZWQgQ0EgNjIz
Y2ExZTBlOTBmOTExODYyMzNiZWY5YjgyNzQ1MDMwHhcNMjMwMTE5MjIwNjAwWhcN
MzMwMTE2MjIwNjAwWjAiMQswCQYDVQQGEwJVUzETMBEGA1UEAxMKQ2xvdWRmbGFy
ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALu92p81Ko0xqfHyBiOA
iGsL1H2TeBZOtgKAmCe8VN2n46qW28DCafEQazNBxt7foshXDhTVG5v3YHxejI/4
08vNwRmLKt70v7DmvVKQeSNULElqfQsnxdraSET4ifAQmKJwOCCCReDcczDKM5Vw
+7UHkhe6XsW3vksjPwXKjFKahuqh7ElcygF6BPn+5Dt7hTxO/46KToR38kwZhM4V
PY36/VO3TbVjYon/2zFFZN2CwHQgTTN0n/0T3vx43ro2xb5JpwmLH/2eXLumrhPt
UBfdlG5wtvdMtbHqA3cHJ1V6KlO5RoQ9+KxRF+vVnznJ9ezxV62yJ3APx0SFl2Ol
LksCAwEAAaOBuzCBuDATBgNVHSUEDDAKBggrBgEFBQcDAjAMBgNVHRMBAf8EAjAA
MB0GA1UdDgQWBBTwH+TXvR3mDFGcrPUuLqtSFY07dzAfBgNVHSMEGDAWgBTtBVpV
QSpTHII2bTGykCpX4D47YDBTBgNVHR8ETDBKMEigRqBEhkJodHRwOi8vY3JsLmNs
b3VkZmxhcmUuY29tLzVjMGQwODU4LTdkZTItNDI3Yi04ZjBkLWI3ZDEwNzBmYzJi
OS5jcmwwDQYJKoZIhvcNAQELBQADggEBAJvkt9PbJp00sFSXKUgrSIDfT2F0f0Ki
3xonEOETCJUf6WeoWggC9XFISnHt+T9yPUEffCpvd+uFc253rzEhkmUN78ZuWddc
2MTrkFybLL77g0xN6pdreq1o3KWCTUzF90b7sqPbgGsoR/QRuJw/UJlsw0ZzJCKB
UF0RGm5SYRtNefRETtxE/Zg1xK9dmvryXznSiVyzrLu+rWUmwtKuBXp8u0VPb4i5
S1pfILuOccJSkbQV2qBEYb4MOS3jUb73/LWwZXJqVF+yLGrWxjrMmg1FAe3X9mdb
XEbe8Def0xGNh87vqpi3aYTGJeOlgRMwJtseKkAWeg8k1v9Zbg5bDyk=
-----END CERTIFICATE-----
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC7vdqfNSqNManx
8gYjgIhrC9R9k3gWTrYCgJgnvFTdp+OqltvAwmnxEGszQcbe36LIVw4U1Rub92B8
XoyP+NPLzcEZiyre9L+w5r1SkHkjVCxJan0LJ8Xa2khE+InwEJiicDgggkXg3HMw
yjOVcPu1B5IXul7Ft75LIz8FyoxSmobqoexJXMoBegT5/uQ7e4U8Tv+Oik6Ed/JM
GYTOFT2N+v1Tt021Y2KJ/9sxRWTdgsB0IE0zdJ/9E978eN66NsW+SacJix/9nly7
pq4T7VAX3ZRucLb3TLWx6gN3BydVeipTuUaEPfisURfr1Z85yfXs8VetsidwD8dE
hZdjpS5LAgMBAAECggEADx6lIrlHagOb6i5RrD5Hvkc/n7VmsHU6V00/88NJGmjQ
/wYTQJznp1BpMcGUYJKmK3hHXAolpRPxI1MCAv5JIFq7uHDqzPXtEjQi/yk/eEbp
Iih/VYyodI2r0FIr2becc0iSXJvhQNDAPieqq9hjjRrE+0A5Lbc0jhySkMbVMjm4
KDWhvWO67BpiFRQXMKMM+VpJ7v63Z3XTAbEE00p+799I3S2EEfZo3pAaMlJ0QQev
6tN+Gsvqmxe5764r7Y6zMEEtJrcMMx/OBIrdaDB77/AtCuWZZUvyU9kRg0LMvRDQ
+gSCcoum4XnlzbQI8ldUNkdddzXhAKXqH5599IzY4QKBgQD0/g629+EQjKSgFxb0
1HpMm4pYNU6fyVFIoZ36kcyz0X6XlxI8ZJil8iB0jgjGSX2ujvC3ChpF242XKnC3
iTBZOCl9YcCwmV9kSvjeOn5OCEShkHXnZ413kt7lld4K/kI03Pd2QbWhkpqrr92g
aM2Q+HEXRTxQwyoaHdkCmEaaMwKBgQDELUnftYXMSKHf6qh63MJIa6T3m43T4D6y
nTEDk1S/8ez8dmTJ8bPNha9xYoB++qfM/uvUt3di0AXkIGhnCO5UhFygZYaVUBGE
HNKUbiZYFczlhnLj/IXuGdWZpM6zYuGGKDTwBt5pq8Q7jm6aTKff+nBa3OZbEEjH
jzecssmziQKBgCoiM1emQ8+70Ggz8F/E1w+rxFwtNstmLROHsAqy3niic9oQQjOe
vV30yT4iW0H2y6WksaNZGnGfM7emteHqtyTw8rm8gQ4eIni2KBzYBHbZFyyOEqjs
dzj0Sl9Dqf9MAQjkY66z2E/kTbNvOHdo7sma4KA26QuetPPu5C59D89fAoGAZ6F0
8NQ3Rd7ohBy1u5F6oD8c+iAWH+LJvBkFl1nw3ySxh/wS6grgbKU+NKtQLcPDeKsB
cXEpg+1X71afUC6Ll+ID/EclfSK63gtLwlUdtFJv1p/beUwgg9Lp3ywMdP67G9+J
d3Jpc3DlTIDFNIVh+ROW3qjqlxhXGfQx8HkRy+ECgYAhvnnhd4P5hGZz4bq8/K7f
7ZcA1n+KSbqVlGwnyQengo4ITDdzrmDg+A5ThJhyBMo0KOCzgDQEyCrZ2BKJgRCs
AUSjfnqp68PSt4x7QEHnqwOVZi9CdriGYEv9ytelGIBXYrkoWCCHnCdp5SfeQLbV
kGEVeKv7JveS3C6gDNo9uA==
-----END PRIVATE KEY-----

28
certificado/appsoluti.key Normal file
View File

@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC7vdqfNSqNManx
8gYjgIhrC9R9k3gWTrYCgJgnvFTdp+OqltvAwmnxEGszQcbe36LIVw4U1Rub92B8
XoyP+NPLzcEZiyre9L+w5r1SkHkjVCxJan0LJ8Xa2khE+InwEJiicDgggkXg3HMw
yjOVcPu1B5IXul7Ft75LIz8FyoxSmobqoexJXMoBegT5/uQ7e4U8Tv+Oik6Ed/JM
GYTOFT2N+v1Tt021Y2KJ/9sxRWTdgsB0IE0zdJ/9E978eN66NsW+SacJix/9nly7
pq4T7VAX3ZRucLb3TLWx6gN3BydVeipTuUaEPfisURfr1Z85yfXs8VetsidwD8dE
hZdjpS5LAgMBAAECggEADx6lIrlHagOb6i5RrD5Hvkc/n7VmsHU6V00/88NJGmjQ
/wYTQJznp1BpMcGUYJKmK3hHXAolpRPxI1MCAv5JIFq7uHDqzPXtEjQi/yk/eEbp
Iih/VYyodI2r0FIr2becc0iSXJvhQNDAPieqq9hjjRrE+0A5Lbc0jhySkMbVMjm4
KDWhvWO67BpiFRQXMKMM+VpJ7v63Z3XTAbEE00p+799I3S2EEfZo3pAaMlJ0QQev
6tN+Gsvqmxe5764r7Y6zMEEtJrcMMx/OBIrdaDB77/AtCuWZZUvyU9kRg0LMvRDQ
+gSCcoum4XnlzbQI8ldUNkdddzXhAKXqH5599IzY4QKBgQD0/g629+EQjKSgFxb0
1HpMm4pYNU6fyVFIoZ36kcyz0X6XlxI8ZJil8iB0jgjGSX2ujvC3ChpF242XKnC3
iTBZOCl9YcCwmV9kSvjeOn5OCEShkHXnZ413kt7lld4K/kI03Pd2QbWhkpqrr92g
aM2Q+HEXRTxQwyoaHdkCmEaaMwKBgQDELUnftYXMSKHf6qh63MJIa6T3m43T4D6y
nTEDk1S/8ez8dmTJ8bPNha9xYoB++qfM/uvUt3di0AXkIGhnCO5UhFygZYaVUBGE
HNKUbiZYFczlhnLj/IXuGdWZpM6zYuGGKDTwBt5pq8Q7jm6aTKff+nBa3OZbEEjH
jzecssmziQKBgCoiM1emQ8+70Ggz8F/E1w+rxFwtNstmLROHsAqy3niic9oQQjOe
vV30yT4iW0H2y6WksaNZGnGfM7emteHqtyTw8rm8gQ4eIni2KBzYBHbZFyyOEqjs
dzj0Sl9Dqf9MAQjkY66z2E/kTbNvOHdo7sma4KA26QuetPPu5C59D89fAoGAZ6F0
8NQ3Rd7ohBy1u5F6oD8c+iAWH+LJvBkFl1nw3ySxh/wS6grgbKU+NKtQLcPDeKsB
cXEpg+1X71afUC6Ll+ID/EclfSK63gtLwlUdtFJv1p/beUwgg9Lp3ywMdP67G9+J
d3Jpc3DlTIDFNIVh+ROW3qjqlxhXGfQx8HkRy+ECgYAhvnnhd4P5hGZz4bq8/K7f
7ZcA1n+KSbqVlGwnyQengo4ITDdzrmDg+A5ThJhyBMo0KOCzgDQEyCrZ2BKJgRCs
AUSjfnqp68PSt4x7QEHnqwOVZi9CdriGYEv9ytelGIBXYrkoWCCHnCdp5SfeQLbV
kGEVeKv7JveS3C6gDNo9uA==
-----END PRIVATE KEY-----

24
certificado/appsoluti.pem Normal file
View File

@ -0,0 +1,24 @@
-----BEGIN CERTIFICATE-----
MIIEFTCCAv2gAwIBAgIUbexM37zIhdxNpGtug6DDveiB1OIwDQYJKoZIhvcNAQEL
BQAwgagxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH
Ew1TYW4gRnJhbmNpc2NvMRkwFwYDVQQKExBDbG91ZGZsYXJlLCBJbmMuMRswGQYD
VQQLExJ3d3cuY2xvdWRmbGFyZS5jb20xNDAyBgNVBAMTK01hbmFnZWQgQ0EgNjIz
Y2ExZTBlOTBmOTExODYyMzNiZWY5YjgyNzQ1MDMwHhcNMjMwMTE5MjIwNjAwWhcN
MzMwMTE2MjIwNjAwWjAiMQswCQYDVQQGEwJVUzETMBEGA1UEAxMKQ2xvdWRmbGFy
ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALu92p81Ko0xqfHyBiOA
iGsL1H2TeBZOtgKAmCe8VN2n46qW28DCafEQazNBxt7foshXDhTVG5v3YHxejI/4
08vNwRmLKt70v7DmvVKQeSNULElqfQsnxdraSET4ifAQmKJwOCCCReDcczDKM5Vw
+7UHkhe6XsW3vksjPwXKjFKahuqh7ElcygF6BPn+5Dt7hTxO/46KToR38kwZhM4V
PY36/VO3TbVjYon/2zFFZN2CwHQgTTN0n/0T3vx43ro2xb5JpwmLH/2eXLumrhPt
UBfdlG5wtvdMtbHqA3cHJ1V6KlO5RoQ9+KxRF+vVnznJ9ezxV62yJ3APx0SFl2Ol
LksCAwEAAaOBuzCBuDATBgNVHSUEDDAKBggrBgEFBQcDAjAMBgNVHRMBAf8EAjAA
MB0GA1UdDgQWBBTwH+TXvR3mDFGcrPUuLqtSFY07dzAfBgNVHSMEGDAWgBTtBVpV
QSpTHII2bTGykCpX4D47YDBTBgNVHR8ETDBKMEigRqBEhkJodHRwOi8vY3JsLmNs
b3VkZmxhcmUuY29tLzVjMGQwODU4LTdkZTItNDI3Yi04ZjBkLWI3ZDEwNzBmYzJi
OS5jcmwwDQYJKoZIhvcNAQELBQADggEBAJvkt9PbJp00sFSXKUgrSIDfT2F0f0Ki
3xonEOETCJUf6WeoWggC9XFISnHt+T9yPUEffCpvd+uFc253rzEhkmUN78ZuWddc
2MTrkFybLL77g0xN6pdreq1o3KWCTUzF90b7sqPbgGsoR/QRuJw/UJlsw0ZzJCKB
UF0RGm5SYRtNefRETtxE/Zg1xK9dmvryXznSiVyzrLu+rWUmwtKuBXp8u0VPb4i5
S1pfILuOccJSkbQV2qBEYb4MOS3jUb73/LWwZXJqVF+yLGrWxjrMmg1FAe3X9mdb
XEbe8Def0xGNh87vqpi3aYTGJeOlgRMwJtseKkAWeg8k1v9Zbg5bDyk=
-----END CERTIFICATE-----

Binary file not shown.

15
nest-cli.json Normal file
View File

@ -0,0 +1,15 @@
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"plugins": [
{
"name": "@nestjs/swagger",
"options": {
"classValidatorShim": false,
"introspectComments": true
}
}
]
}
}

10534
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

92
package.json Normal file
View File

@ -0,0 +1,92 @@
{
"name": "venda_web",
"version": "2023.5.1",
"description": "",
"author": "",
"private": true,
"license": "JURUNENSE HOME CENTER",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^7.0.0",
"@nestjs/config": "^0.5.0",
"@nestjs/core": "^7.0.0",
"@nestjs/jwt": "^7.1.0",
"@nestjs/passport": "^7.1.0",
"@nestjs/platform-express": "^7.0.0",
"@nestjs/swagger": "^4.8.2",
"@nestjs/typeorm": "^7.1.0",
"cache-manager": "^3.4.0",
"compression": "^1.7.4",
"crc": "^4.3.2",
"fs": "0.0.1-security",
"guid-typescript": "^1.0.9",
"md5": "^2.3.0",
"md5-typescript": "^1.0.5",
"mindee": "^3.7.3",
"node-geocoder": "^4.2.0",
"odata-v4-typeorm": "^0.1.1",
"oracledb": "^4.2.0",
"passport": "^0.4.1",
"passport-http-bearer": "^1.0.1",
"passport-jwt": "^4.0.0",
"pdf-lib": "^1.17.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.8.0",
"stimulsoft-reports-js": "^2021.1.1",
"swagger-ui-express": "^4.6.3",
"typeorm": "^0.2.25",
"uuid": "^8.3.2"
},
"devDependencies": {
"@nestjs/cli": "^7.0.0",
"@nestjs/schematics": "^7.0.0",
"@nestjs/testing": "^7.0.0",
"@types/express": "^4.17.3",
"@types/jest": "25.1.4",
"@types/md5": "^2.3.0",
"@types/node": "^13.13.12",
"@types/supertest": "^2.0.8",
"@typescript-eslint/eslint-plugin": "^2.23.0",
"@typescript-eslint/parser": "^2.23.0",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.10.0",
"eslint-plugin-import": "^2.20.1",
"jest": "^25.1.0",
"prettier": "^1.19.1",
"supertest": "^4.0.2",
"ts-jest": "25.2.1",
"ts-loader": "^6.2.1",
"ts-node": "^8.6.2",
"tsconfig-paths": "^3.9.0",
"typescript": "^3.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

View File

@ -0,0 +1,8 @@
select '@Column({ name: '''||column_name||''' })'||CHR(13)||
LOWER(column_name)||': '||
case when user_tab_columns.data_type = 'NUMBER' then 'number;'
when user_tab_columns.data_type = 'DATE' then 'Date;'
else 'string;' END ||CHR(13)
FROM USER_TAB_COLUMNS
WHERE TABLE_NAME = 'PCPEDITEMP'
order by user_tab_columns.column_id;

View File

@ -0,0 +1,8 @@
CREATE TABLE ESTPROTOCOLOENTREGA (
NUMPED NUMBER(10),
NUMNOTA NUMBER(10),
DTENTREGA DATE,
CPFRECEBEDOR VARCHAR2(20),
NOMERECEBEDOR VARCHAR2(100),
URL_IMAGEMPROTOCOLO VARCHAR2(200),
CONSTRAINT ESTPROTOCOLOENTREGA_PK PRIMARY KEY ( NUMPED ) );

25
scripts/estshopping.sql Normal file
View File

@ -0,0 +1,25 @@
CREATE TABLE ESTSHOPPING (
ID VARCHAR2(100),
IDCART VARCHAR2(100),
CODPROD NUMBER(6),
QT NUMBER(22,6),
PVENDA NUMBER(22,6),
DTINCLUSAO DATE,
DTCANCEL DATE,
CODFUNC NUMBER(10),
CONSTRAINT ESTSHOPPING_PK PRIMARY KEY ( ID )
);
ALTER TABLE ESTSHOPPING ADD DATAVENDA DATE;
ALTER TABLE ESTSHOPPING ADD NUMPED NUMBER(10);
ALTER TABLE ESTSHOPPING ADD NOMEECOMMERCE VARCHAR2(200);
ALTER TABLE ESTSHOPPING ADD URLIMAGEM VARCHAR2(200);
ALTER TABLE ESTSHOPPING ADD TIPOPRODUTO VARCHAR2(1);
ALTER TABLE ESTSHOPPING ADD CODFILIALRETIRA VARCHAR2(2);
ALTER TABLE ESTSHOPPING ADD TIPOENTREGA VARCHAR2(2);
ALTER TABLE ESTSHOPPING ADD CODUSUR NUMBER(6);
--ALTER TABLE ESTSHOPPING ADD CODPLPAG NUMBER(4);
--ALTER TABLE ESTSHOPPING ADD CODCOB VARCHAR2(4);

10
scripts/estusuario.sql Normal file
View File

@ -0,0 +1,10 @@
CREATE TABLE estusuario
(idusuario NUMBER(10,0) ,
nome VARCHAR2(100 BYTE) NOT NULL,
email VARCHAR2(100 BYTE) NOT NULL,
senha VARCHAR2(100 BYTE) NOT NULL,
tipo VARCHAR2(20 BYTE) NOT NULL,
matricula NUMBER(8,0),
bloqueado CHAR(1 BYTE) DEFAULT 'N');
CREATE SEQUENCE ESSUSUARIO;

16
scripts/estvenda.sql Normal file
View File

@ -0,0 +1,16 @@
CREATE TABLE ESTVENDA (
ID VARCHAR2(100),
IDSHOPPING VARCHAR2(100),
CODCLI NUMBER(6),
CODUSUR NUMBER(6),
CODENDCLI NUMBER(10),
CODPLPAG NUMBER(6),
CODCOB VARCHAR2(4),
VLFRETE NUMBER(22,6),
OBSERVACAO1 VARCHAR2(80),
OBSERVACAO2 VARCHAR2(80),
OBSERVACAO3 VARCHAR2(80),
OBSERVACAOENTREGA1 VARCHAR2(80),
OBSERVACAOENTREGA2 VARCHAR2(80),
OBSERVACAOENTREGA3 VARCHAR2(80),
CONSTRAINT PK_OBSERVACAOENTREGA PRIMARY KEY (ID));

3
src/.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"js/ts.implicitProjectConfig.experimentalDecorators": true
}

View File

@ -0,0 +1,48 @@
/*
https://docs.nestjs.com/controllers#controllers
*/
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { AccessControlService } from './access-control.service';
import { ApiExcludeEndpoint } from '@nestjs/swagger';
@Controller('api/v1/access-control')
export class AccessControlController {
constructor(
private readonly accessControlService: AccessControlService
){}
@Get('modules/:id')
@ApiExcludeEndpoint()
async getModules(@Param('id') id: number) {
return this.accessControlService.getAccessModule(id);
}
@Get('permissionUser/:id')
@ApiExcludeEndpoint()
async getPermissionsUser(@Param('id') id: number) {
return this.accessControlService.getPermissionsUser(id);
}
@Get('pages/:userId/:moduleId')
@ApiExcludeEndpoint()
async getPagesUser(@Param('userId') userId: number, @Param('moduleId') moduleId: number) {
return this.accessControlService.getPagesUser(moduleId, userId);
}
@Get('actions/:userId/:moduleId')
@ApiExcludeEndpoint()
async getActionUser(@Param('userId') userId: number, @Param('moduleId') moduleId: number
) {
return this.accessControlService.getActionsUser(moduleId, userId);
}
@Post('permissionUser/:id')
@ApiExcludeEndpoint()
async updatePermission(@Param('id') userId: number, @Body() data
) {
return this.accessControlService.updatePermissionUser(userId, data);
}
}

View File

@ -0,0 +1,16 @@
import { AccessControlService } from './access-control.service';
import { AccessControlController } from './access-control.controller';
/*
https://docs.nestjs.com/modules
*/
import { Module } from '@nestjs/common';
@Module({
imports: [],
controllers: [
AccessControlController,],
providers: [
AccessControlService,],
})
export class AccessControlModule { }

View File

@ -0,0 +1,261 @@
/*
https://docs.nestjs.com/providers#services
*/
import { Injectable } from '@nestjs/common';
import { connectionOptions } from 'src/configs/typeorm.config';
import { Connection } from 'typeorm';
import { IndexActions } from '../../domain/models/index-action.model';
@Injectable()
export class AccessControlService {
async getAccessModule(id: number) {
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = 'SELECT ESTACESSOMODULO.CODMODULO as "moduleId" ' +
' ,ESTACESSOMODULO.CODUSUARIO as "userId" ' +
` ,NVL(ESTACESSOMODULO.ACESSO, 'S') as "access" ` +
' FROM ESTACESSOMODULO ' +
' WHERE ESTACESSOMODULO.CODUSUARIO = :1';
const modules = await queryRunner
.query(sql, [id]);
return modules;
} finally {
await queryRunner.release();
await connection.close();
}
}
async getPagesUser(moduleId: number, userId: number) {
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = 'SELECT ESTACESSOATIVIDADE.CODMODULO as "moduleId" ' +
' ,ESTACESSOATIVIDADE.CODPROCESSO as "processId" ' +
' ,ESTACESSOATIVIDADE.CODATIVIDADE as "pageId" ' +
' ,ESTACESSOATIVIDADE.codusuario as "userId" ' +
' ,ESTACESSOATIVIDADE.ACESSO as "access" ' +
' FROM ESTACESSOATIVIDADE ' +
' WHERE ESTACESSOATIVIDADE.CODMODULO = :CODMODULO ' +
' AND ESTACESSOATIVIDADE.CODUSUARIO = :CODUSUARIO ';
const pages = await queryRunner
.query(sql, [moduleId, userId]);
return pages;
} finally {
await queryRunner.release();
await connection.close();
}
}
async getActionsUser(moduleId: number, userId: number) {
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = `SELECT ESTACESSOATIVIDADEACAO.CODMODULO as "moduleId"
,ESTACESSOATIVIDADEACAO.CODPROCESSO as "processId"
,ESTACESSOATIVIDADEACAO.CODATIVIDADE as "pageId"
,ESTACESSOATIVIDADEACAO.CODACAO as "actionId"
,ESTACESSOATIVIDADEACAO.codusuario as "userId"
,ESTACESSOATIVIDADEACAO.ACESSO as "access"
FROM ESTACESSOATIVIDADEACAO
WHERE ESTACESSOATIVIDADEACAO.CODMODULO = :CODMODULO
AND ESTACESSOATIVIDADEACAO.CODUSUARIO = :CODUSUARIO`;
const actions = await queryRunner
.query(sql, [moduleId, userId]);
return actions;
} finally {
await queryRunner.release();
await connection.close();
}
}
async getPermissionsUser(userId: number) {
const sqlModules = `SELECT ESTMODULO.codmodulo as "id"
,ESTMODULO.descricao as "text"
,${userId} as "userId"
,NVL(( SELECT ESTACESSOMODULO.ACESSO
FROM ESTACESSOMODULO
WHERE ESTACESSOMODULO.CODMODULO = ESTMODULO.CODMODULO
AND ESTACESSOMODULO.CODUSUARIO = ${userId} AND ROWNUM = 1),'N') as "allow"
FROM ESTMODULO`;
const sqlAtividade = `SELECT ESTATIVIDADE.codmodulo as "moduloId"
,ESTATIVIDADE.CODPROCESSO as "processId"
,ESTATIVIDADE.CODATIVIDADE as "id"
,ESTATIVIDADE.descricao as "text"
,NVL(( SELECT ESTACESSOATIVIDADE.ACESSO
FROM ESTACESSOATIVIDADE
WHERE ESTACESSOATIVIDADE.CODMODULO = ESTATIVIDADE.CODMODULO
AND ESTACESSOATIVIDADE.CODPROCESSO = ESTATIVIDADE.codprocesso
AND ESTACESSOATIVIDADE.CODATIVIDADE = ESTATIVIDADE.CODATIVIDADE
AND ESTACESSOATIVIDADE.CODUSUARIO = ${userId} AND ROWNUM = 1),'N') as "allow"
FROM ESTATIVIDADE`;
const sqlAction = `SELECT estatividadeacao.codmodulo as "moduloId"
,estatividadeacao.CODPROCESSO as "processId"
,estatividadeacao.CODATIVIDADE as "atividadeId"
,estatividadeacao.CODACAO as "Id"
,estatividadeacao.descricao as "text"
,NVL(( SELECT ESTACESSOATIVIDADEACAO.ACESSO
FROM ESTACESSOATIVIDADEACAO
WHERE ESTACESSOATIVIDADEACAO.CODMODULO = estatividadeacao.CODMODULO
AND ESTACESSOATIVIDADEACAO.CODPROCESSO = estatividadeacao.codprocesso
AND ESTACESSOATIVIDADEACAO.CODATIVIDADE = estatividadeacao.CODATIVIDADE
AND ESTACESSOATIVIDADEACAO.CODACAO = estatividadeacao.CODACAO
AND ESTACESSOATIVIDADEACAO.CODUSUARIO = ${userId} AND ROWNUM = 1),'N') as "allow"
FROM estatividadeacao`;
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const modules = await queryRunner.query(sqlModules);
const atividades = await queryRunner.query(sqlAtividade);
const actions = await queryRunner.query(sqlAction);
console.log("acoes:" + JSON.stringify(actions));
console.log("atividaes:" + JSON.stringify(atividades));
const arrayAtividade = [];
atividades.map((atividade) => {
const data = {
...atividade, items: [...actions.filter((a) => a.moduloId == atividade.moduloId
&& a.processId == atividade.processId &&
a.atividadeId == atividade.id)]
}
arrayAtividade.push(data);
});
console.log("atividade acao: " + JSON.stringify(arrayAtividade));
const arrayModules = [];
modules.map((module) => {
const data = {
...module, items: [...arrayAtividade.filter((a) => a.moduloId == module.id)]
}
arrayModules.push(data);
});
return arrayModules;
} finally {
await queryRunner.release();
await connection.close();
}
}
async updatePermissionUser(userId: number, data: any) {
console.log(JSON.stringify(data));
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const sqlDeletePermissionUser = `BEGIN
DELETE FROM ESTACESSOMODULO WHERE CODUSUARIO = ${userId};
DELETE FROM ESTACESSOATIVIDADE WHERE CODUSUARIO = ${userId};
DELETE FROM ESTACESSOATIVIDADEACAO WHERE CODUSUARIO = ${userId};
END;
`;
await queryRunner.query(sqlDeletePermissionUser);
for (const action of data.actions) {
const sqlCreatePermissionAction = `BEGIN
UPDATE ESTACESSOATIVIDADEACAO SET
ACESSO = 'S'
WHERE CODMODULO = ${action.moduloId} AND CODPROCESSO = ${action.processId}
AND CODATIVIDADE = ${action.atividadeId} AND CODACAO = ${action.Id} AND CODUSUARIO = ${userId};
IF SQL%ROWCOUNT = 0 THEN
INSERT INTO ESTACESSOATIVIDADEACAO ( CODMODULO, CODPROCESSO, CODATIVIDADE, CODACAO, CODUSUARIO, ACESSO )
VALUES ( ${action.moduloId}, ${action.processId}, ${action.atividadeId}, ${action.Id}, ${userId},'S');
END IF;
UPDATE ESTACESSOATIVIDADE SET
ACESSO = 'S'
WHERE CODMODULO = ${action.moduloId} AND CODPROCESSO = ${action.processId}
AND CODATIVIDADE = ${action.atividadeId} AND CODUSUARIO = ${userId};
IF SQL%ROWCOUNT = 0 THEN
INSERT INTO ESTACESSOATIVIDADE ( CODMODULO, CODPROCESSO, CODATIVIDADE, CODUSUARIO, ACESSO )
VALUES ( ${action.moduloId}, ${action.processId}, ${action.atividadeId}, ${userId},'S');
END IF;
UPDATE ESTACESSOMODULO SET
ACESSO = 'S'
WHERE CODMODULO = ${action.moduloId} AND CODUSUARIO = ${userId};
IF SQL%ROWCOUNT = 0 THEN
INSERT INTO ESTACESSOMODULO ( CODMODULO, CODUSUARIO, ACESSO )
VALUES ( ${action.moduloId}, ${userId}, 'S');
END IF;
END; `
await queryRunner.query(sqlCreatePermissionAction);
}
for (const atividade of data.atividades) {
const sqlCreatePermissionAtividade = `BEGIN
UPDATE ESTACESSOATIVIDADE SET
ACESSO = 'S'
WHERE CODMODULO = ${atividade.moduloId} AND CODPROCESSO = ${atividade.processId}
AND CODATIVIDADE = ${atividade.id} AND CODUSUARIO = ${userId};
IF SQL%ROWCOUNT = 0 THEN
INSERT INTO ESTACESSOATIVIDADE ( CODMODULO, CODPROCESSO, CODATIVIDADE, CODUSUARIO, ACESSO )
VALUES ( ${atividade.moduloId}, ${atividade.processId}, ${atividade.id}, ${userId},'S');
END IF;
UPDATE ESTACESSOMODULO SET
ACESSO = 'S'
WHERE CODMODULO = ${atividade.moduloId} AND CODUSUARIO = ${userId};
IF SQL%ROWCOUNT = 0 THEN
INSERT INTO ESTACESSOMODULO ( CODMODULO, CODUSUARIO, ACESSO )
VALUES ( ${atividade.moduloId}, ${userId},'S');
END IF;
END; `;
await queryRunner.query(sqlCreatePermissionAtividade);
}
await queryRunner.commitTransaction();
} catch (err) {
await queryRunner.rollbackTransaction();
console.log(err);
} finally {
await queryRunner.release();
await connection.close();
}
}
}

10
src/Auth/auth.module.ts Normal file
View File

@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
@Module({
imports: [],
controllers: [],
providers: [],
})
export class AuthModule { }

View File

@ -0,0 +1,132 @@
import { ResultModel } from '../../domain/models/result.model';
import { UserModel } from '../../domain/models/user.model';
import { RoleInterceptor } from '../interceptors/role.interceptor';
import { JwtAuthGuard } from '../guards/auth.guard';
import { AuthService } from '../services/auth.service';
import { UserService } from '../services/user.service';
import { Body, Controller, Get, HttpException, HttpStatus, Param, Post, Req, UseGuards, UseInterceptors } from "@nestjs/common";
import { Guid } from 'guid-typescript';
import { ResetPasswordModel } from 'src/domain/models/reset-password.model';
import { ChangePasswordModel } from 'src/domain/models/change-password.model';
import { CreateUserModel } from 'src/domain/models/create-user.model';
import { ApiExcludeEndpoint, ApiTags } from '@nestjs/swagger';
@ApiTags('Autenticação')
@Controller('api/v1/auth')
export class UserController {
constructor(private authService: AuthService,
private userService: UserService) { }
/**
* Realiza a autenticação do usuário para acesso a vendaweb.
* @@example { email: "exemplo@exemplo.com", password: "123456"}
*/
@Get('users')
async getUsers() {
return this.userService.findAll();
}
@Post('login')
async login(@Body() model: UserModel): Promise<any> {
const userDb = await this.userService.authenticate(model);
if (!userDb)
throw new HttpException(new ResultModel(false, 'Usuário ou senha inválidos.', null, null), HttpStatus.UNAUTHORIZED);
if (userDb.blocked == "S")
throw new HttpException(new ResultModel(false, 'Usuário inativo.', null, null), HttpStatus.UNAUTHORIZED);
if (model.application == "SALE" && userDb.seller == 0)
throw new HttpException(new ResultModel(false, 'Usuário sem vendedor informado .', null, null), HttpStatus.UNAUTHORIZED);
if (model.application == "SALE" && (userDb.codigoFilial == null || userDb.codigoFilial == ''))
throw new HttpException(new ResultModel(false, 'Usuário sem filial informada.', null, null), HttpStatus.UNAUTHORIZED);
const token = await this.authService.createToken(userDb.username, userDb.email, '', [userDb.sectorId, userDb.sectorManagerId]);
return new ResultModel(true, null, {
"id": userDb.id, "username": userDb.userName, "email": userDb.email,
"store": userDb.codigoFilial, "name": userDb.nomeFilial, "seller": userDb.seller,
"deliveryTime": userDb.deliveryTime, "supervisorId": userDb.supervisorId, "token": token
}, null);
}
@Post('create')
async createUser(@Body() model: CreateUserModel): Promise<any> {
const result = await this.userService.create(model);
console.log(result);
return result;
/*if (!userDb)
throw new HttpException(new ResultModel(false, 'Usuário ou senha inválidos.', null, null), HttpStatus.UNAUTHORIZED);
if (userDb.blocked == "S")
throw new HttpException(new ResultModel(false, 'Usuário inativo.', null, null), HttpStatus.UNAUTHORIZED);
const token = await this.authService.createToken(userDb.username, userDb.email, '', [userDb.role, model.application]);
return new ResultModel(true, null, {"username": userDb.username, "email": userDb.email, "token": token}, null);*/
}
@Post('reset-password')
async resetPassword(@Body() model: ResetPasswordModel): Promise<any> {
try {
//TODO: Enviar email com a senha
const password = Guid.create.toString().substring(0, 8).replace('-', '');
await this.userService.update(model.email, password);
return new ResultModel(true, 'Uma nova senha foi enviada para seu e-mail.', null, null);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível restaurar sua senha', null, null), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Post('change-password')
@UseGuards(JwtAuthGuard)
async changePassword(@Req() request, @Body() model: ChangePasswordModel): Promise<any> {
try {
//TODO: Encriptar senha
//TODO: Validar usuario
await this.userService.update(request.user.email, model.newPassword);
return new ResultModel(true, 'Sua senha foi alterada com sucesso', null, null);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível alterar sua senha', null, null), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Get('discount-user/:id')
async discountAuthorization(@Param('id') id: number): Promise<any> {
const user = await this.userService.discountUser(id);
console.log(user);
return new ResultModel(true, null, user, null);
}
@Post('refresh')
@UseGuards(JwtAuthGuard)
async refreshToken(@Req() request): Promise<any> {
const token = await this.authService.createToken(request.user.username, request.user.email, request.user.image, request.user.roles);
return new ResultModel(true, null, token, null);
}
@Post('authenticate')
@ApiExcludeEndpoint()
async authenticate(@Body() model: UserModel): Promise<any> {
const userDb = await this.userService.authenticate(model);
console.log(userDb);
if (!userDb)
throw new HttpException(new ResultModel(false, 'Usuário ou senha inválidos.', null, null), HttpStatus.UNAUTHORIZED);
if (userDb.blocked == "S")
throw new HttpException(new ResultModel(false, 'Usuário inativo.', null, null), HttpStatus.UNAUTHORIZED);
return new ResultModel(true, null, {
"id": userDb.id, "username": userDb.userName, "email": userDb.email,
"store": userDb.codigoFilial, "seller": userDb.seller, "discountPercent": userDb.discountPercent,
"sectorId": userDb.sectorId, "sectorManagerId": userDb.sectorManagerId
}, null);
}
@Get('')
@UseGuards(JwtAuthGuard)
@UseInterceptors(new RoleInterceptor(['admin']))
findAll() {
return [];
}
}

View File

@ -0,0 +1,17 @@
import { AuthGuard } from '@nestjs/passport';
import { ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
@Injectable()
export class JwtAuthGuard extends AuthGuard() {
canActivate(context: ExecutionContext) {
return super.canActivate(context);
}
handleRequest(err: any, user: any, info: any) {
if (err || !user) {
throw err || new UnauthorizedException();
}
return user;
}
}

View File

@ -0,0 +1,32 @@
import { HttpStatus } from '@nestjs/common';
import { ResultModel } from './../../domain/models/result.model';
import { HttpException } from '@nestjs/common';
import { JwtPayload } from './../interfaces/jwt-payload.interface';
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class RoleInterceptor implements NestInterceptor {
constructor(private roles: string[]){}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const payload: JwtPayload = context.switchToHttp().getRequest().user;
console.log(payload);
let hasRole = false;
payload.roles.forEach((role) => {
if (this.roles.includes(role))
hasRole = true;
});
if (!hasRole) {
throw new HttpException(
new ResultModel(false, 'Acesso não autorizado', null, null),
HttpStatus.FORBIDDEN
)
}
return next
.handle();
}
}

View File

@ -0,0 +1,8 @@
export interface JwtPayload {
username: string;
email: string;
image: string;
sectorId: string;
sectorManagerId: string;
roles: string[];
}

View File

@ -0,0 +1,24 @@
import { Injectable } from '@nestjs/common';
import { JwtPayload } from './../interfaces/jwt-payload.interface';
import { JwtService, JwtSignOptions } from "@nestjs/jwt";
import { UserService } from './user.service';
@Injectable()
export class AuthService {
constructor(
private readonly accountService: UserService,
private readonly jwtService: JwtService,
){}
async createToken(username: string, email: string, image: string, roles: string[]) {
const user: JwtPayload = { username: username, email: email, image: image, sectorId: roles[0], sectorManagerId: roles[1], roles: [], }
const options: JwtSignOptions = {expiresIn: "1h"};
return this.jwtService.sign(user, options);
}
async validateUser(payload: JwtPayload): Promise<any> {
//return await this.accountService.findOneByUsername(payload.username);
return payload;
}
}

View File

@ -0,0 +1,197 @@
import { UserModel } from '../../domain/models/user.model';
import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import { User } from 'src/domain/entity/tables/estusuario.enity';
import { Connection, getConnection } from 'typeorm';
import md5 = require('md5');
import { CreateUserModel } from 'src/domain/models/create-user.model';
import { Pcempr } from '../../domain/entity/tables/pcempr.entity';
import { connectionOptions } from 'src/configs/typeorm.config';
@Injectable()
export class UserService {
async create(data: CreateUserModel): Promise<User> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const user = await queryRunner.manager
.getRepository(User)
.createQueryBuilder('estusuario')
.where("\"estusuario\".email = :email", { email: data.email })
.getOne();
if (user != null) {
throw new HttpException("Já existe um usuário cadastrado no sistema com este email", HttpStatus.BAD_REQUEST);
}
} catch (err) {
throw err;
} finally {
await queryRunner.release();
}
const newUser = new User();
newUser.username = data.userName;
newUser.password = md5(data.password).toUpperCase();
newUser.email = data.email;
newUser.role = data.application;
newUser.blocked = "N";
newUser.registration = data.registration;
await getConnection()
.createQueryBuilder()
.insert()
.into(User)
.values(newUser)
.execute();
return newUser;
}
async findAll() {
const sqlUsers = `SELECT PCEMPR.MATRICULA as "userId"
,PCEMPR.NOME||' ('||PCEMPR.MATRICULA||')' as "name"
,PCEMPR.USUARIOBD as "userBD"
,PCEMPR.CODFILIAL as "storeId"
,PCEMPR.FUNCAO as "function"
,PCSETOR.DESCRICAO as "sector"
FROM PCEMPR, PCSETOR
WHERE PCEMPR.CODSETOR = PCSETOR.CODSETOR
AND PCEMPR.DTDEMISSAO IS NULL
ORDER BY PCEMPR.NOME`;
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
return await queryRunner.query(sqlUsers);
} finally {
await queryRunner.release();
}
}
async authenticate(user: UserModel): Promise<any> {
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = 'SELECT PCEMPR.matricula as \"id\" ' +
' ,PCEMPR.usuariobd as \"userName\" ' +
' ,PCEMPR.codfilial as \"codigoFilial\" ' +
' ,PCFILIAL.fantasia as \"nomeFilial\" ' +
' ,PCEMPR.codusur as \"seller\" ' +
' ,NVL(PCEMPR.percdesc,0) as \"discountPercent\" ' +
' ,NVL(PCEMPR.codsetor,0) as \"sectorId\" ' +
' ,NVL(PCPARAMFILIAL.valor,0) as \"sectorManagerId\" ' +
' ,( SELECT PCUSUARI.CODSUPERVISOR FROM PCUSUARI WHERE PCUSUARI.CODUSUR = PCEMPR.CODUSUR ) as \"supervisorId\" ' +
' ,( SELECT NVL(P.valor,0) FROM PCPARAMFILIAL P WHERE P.CODFILIAL = \'99\' AND ' +
' P.NOME = \'CON_PRAZOENTREGA\' ) as \"deliveryTime\" ' +
' FROM PCEMPR, PCFILIAL, PCPARAMFILIAL ' +
' WHERE PCEMPR.CODFILIAL = PCFILIAL.CODIGO (+)' +
' AND PCPARAMFILIAL.CODFILIAL = \'99\' ' +
' AND PCPARAMFILIAL.NOME = \'CON_CODSETORGERENTELOJA\' ' +
' AND PCEMPR.EMAIL = :username AND PCEMPR.SENHABD = CRYPT(:password, USUARIOBD)';
const users = await queryRunner.manager
.query(sql, [user.email, user.password]);
if (users.length == 0) {
return null;
}
// const sqlDiasUteis = 'SELECT ( mv_prox_diautil( (TRUNC(SYSDATE) + :1) + COUNT(1), :2 ) - TRUNC(SYSDATE) ) as "days" ' +
// ' FROM MVDIASUTEIS ' +
// ' WHERE MVDIASUTEIS.CODFILIAL = :3 ' +
// ` AND MVDIASUTEIS.diaentrega = 'N' ` +
// ` AND MVDIASUTEIS.data BETWEEN TRUNC(SYSDATE) AND TRUNC(SYSDATE) + :4 `;
// const sqlDiasUteis = `SELECT CASE WHEN mv_prox_diautil(TRUNC(SYSDATE), :1) > TRUNC(SYSDATE) THEN
// ( ( mv_prox_diautil((mv_prox_diautil(TRUNC(SYSDATE), :2) + :3) + COUNT(1), :4 ) - (mv_prox_diautil(TRUNC(SYSDATE), :5)) ) - 1 )
// ELSE ( mv_prox_diautil((mv_prox_diautil(TRUNC(SYSDATE), :6) + :7) + COUNT(1), :8 ) - (mv_prox_diautil(TRUNC(SYSDATE), :9)) ) END as "days"
// FROM MVDIASUTEIS
// WHERE MVDIASUTEIS.CODFILIAL = :10
// AND MVDIASUTEIS.diaentrega = 'N'
// AND MVDIASUTEIS.data BETWEEN mv_prox_diautil(TRUNC(SYSDATE), :11) AND mv_prox_diautil(TRUNC(SYSDATE), :12) + :13`;
// const deliveryDays = await queryRunner.manager
// .query(sqlDiasUteis, ['6',
// '6', Number.parseInt(users[0].deliveryTime), '6', '6',
// '6', Number.parseInt(users[0].deliveryTime), '6', '6',
// '6',
// '6', '6', Number.parseInt(users[0].deliveryTime)
// ]);
const sqlDiasEntrega = `SELECT ( MAX(MVDIASUTEIS.DATA) - TRUNC(SYSDATE) ) as "days"
FROM MVDIASUTEIS
WHERE MVDIASUTEIS.data BETWEEN TRUNC(SYSDATE)
AND TRUNC(SYSDATE) + :dias`;
const sqlDiasSemEntrega = `SELECT GREATEST(COUNT(1) - 1,0) as "daysNoDelivery"
FROM MVDIASUTEIS
WHERE MVDIASUTEIS.data BETWEEN TRUNC(SYSDATE)
AND TRUNC(SYSDATE) + :dias
AND MVDIASUTEIS.DIAENTREGA = 'N'`;
const deliveryDays2 = await queryRunner.manager
.query(sqlDiasEntrega, [Number.parseInt(users[0].deliveryTime)]);
const noDeliveryDays = await queryRunner.manager
.query(sqlDiasSemEntrega, [Number.parseInt(users[0].deliveryTime)]);
const days = Number.parseInt(deliveryDays2[0].days) +
( noDeliveryDays.length > 0 ? Number.parseInt(noDeliveryDays[0].daysNoDelivery) : 0 );
const userDb = users[0];
console.log(userDb);
if (!isNaN(days)) {
userDb.deliveryTime = days; // deliveryDays[0].days;
}
console.log(days);
console.log(userDb);
return userDb;
} finally {
await queryRunner.release();
await connection.close();
}
}
async discountUser(userId: number): Promise<any> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
return await queryRunner.manager
.getRepository(Pcempr)
.createQueryBuilder('pcempr')
.select("NVL(\"pcempr\".percdesc,0) as \"discountUser\"")
.where("MATRICULA = :userId", { userId })
.getRawOne(); //...authUser,
} finally {
await queryRunner.release();
}
}
async update(email: string, newPassword: string) {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
return await queryRunner.manager
.createQueryBuilder()
.update(User)
.set({ password: newPassword })
.where("EMAIL = :email", { email })
.execute();
} finally {
await queryRunner.release();
}
}
}

View File

@ -0,0 +1,24 @@
import { JwtPayload } from './../interfaces/jwt-payload.interface';
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { AuthService } from "../services/auth.service";
import { ExtractJwt, Strategy } from 'passport-jwt';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService){
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKeyProvider: '4557C0D7-DFB0-40DA-BF83-91A75103F7A9', //secretOrKey
})
}
async validate(payload: JwtPayload) {
const user = await this.authService.validateUser(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}

View File

@ -0,0 +1,22 @@
import { ResultModel } from './../domain/models/result.model';
import { Contract } from './../contracts/contract';
import { CallHandler, ExecutionContext, HttpException, HttpStatus, NestInterceptor } from "@nestjs/common";
import { Observable } from "rxjs";
export class ValidadorInterceptor implements NestInterceptor {
constructor(public contract: Contract){}
intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> {
const body = context.switchToHttp().getRequest().body;
const valid = this.contract.validade(body);
if (!valid) {
throw new HttpException(new ResultModel(false, 'Ops, algo saiu errado!', null, this.contract.errors), HttpStatus.BAD_REQUEST);
}
return next.handle();
}
}

View File

@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

14
src/app.controller.ts Normal file
View File

@ -0,0 +1,14 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { ApiExcludeEndpoint } from '@nestjs/swagger';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
@ApiExcludeEndpoint()
getHello(): string {
return this.appService.getHello();
}
}

101
src/app.module.ts Normal file
View File

@ -0,0 +1,101 @@
import { DashboardModule } from './sales/dashboard/dashboard.module';
import { MindeeModule } from './payment/mindee.module';
import { GoogleModule } from './google/google.module';
import { CepModule } from './sales/cep/cep.module';
import { AccessControlModule } from './Auth/access-control/access-control.module';
import { TintometricoModule } from './sales/tintometrico/tintometrico.module';
import { PartnerRangeModule } from './partner-range/partner-range.module';
import { SellerModule } from './seller/seller.module';
import { PartnerCategoryModule } from './partner-category/partner-category.module';
import { PartnerModule } from './partner/partner.module';
import { PreOrderModule } from './sales/pre-order/pre-order.module';
import { OrderModule } from './sales/order/order.module';
import { MessagesModule } from './backoffice/messages/messages.module';
import { CustomerModule } from './sales/customer/customer.module';
import { AddressCustomerModule } from './sales/address-customer/address-customer.module';
import { ProductService } from './backoffice/product/product.service';
import { ProductController } from './backoffice/product/product.controller';
import { BackofficeModule } from './backoffice/backoffice.module';
import { ShoppingModule } from './sales/shopping/shopping.module';
import { ListsModule } from './backoffice/lists/lists.module';
import { SalesModule } from './sales/sales/sales.module';
import { DeliveryModule } from './delivery/delivery.module';
import { ReportsController } from './schedules/report/report.controller';
import { ReportService } from './schedules/report/report.service';
import { ProductTypeModule } from './backoffice/product-type/product-type.module';
import { CestModule } from './backoffice/cest/cest.module';
import { NcmModule } from './backoffice/ncm/ncm.module';
import { CategoryModule } from './backoffice/category/category.module';
import { SectionModule } from './backoffice/section/section.module';
import { DepartmentModule } from './backoffice/department/department.module';
import { AuthModule } from './Auth/auth.module';
import { MeasureProductModule } from './backoffice/measureproduct/measureproduct.module';
import { HttpModule, MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { typeOrmConfig } from './configs/typeorm.config';
import { Connection } from 'typeorm';
import { DictionaryModule } from './backoffice/dictionary/dictionary.module';
import { ConfigModule } from '@nestjs/config/dist/config.module';
@Module({
imports: [
DashboardModule,
MindeeModule,
GoogleModule,
CepModule,
AccessControlModule,
TintometricoModule,
PartnerRangeModule,
SellerModule,
PartnerCategoryModule,
PartnerModule,
PreOrderModule,
OrderModule,
MessagesModule,
CustomerModule,
TypeOrmModule.forRoot(typeOrmConfig),
ConfigModule.forRoot({ envFilePath: ['.env', '.env.development.local', '.env.development'], isGlobal: true }),
AuthModule,
DictionaryModule,
MeasureProductModule,
DepartmentModule,
SectionModule,
CategoryModule,
NcmModule,
CestModule,
ProductTypeModule,
SalesModule,
ListsModule,
AddressCustomerModule,
BackofficeModule,
ShoppingModule,
ListsModule,
SalesModule,
DeliveryModule,
ProductTypeModule,
CestModule,
NcmModule,
CategoryModule,
DepartmentModule,
HttpModule,
PartnerCategoryModule,
SellerModule
],
controllers: [
ProductController,
ReportsController,
AppController],
providers: [
ProductService,
ReportService, AppService],
})
export class AppModule implements NestModule {
constructor(private connection: Connection) { }
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
configure(consumer: MiddlewareConsumer) { }
}

8
src/app.service.ts Normal file
View File

@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { ProductController } from './product/product.controller';
import { ProductService } from './product/product.service';
@Module({
imports: [],
controllers: [ProductController],
providers: [ProductService],
})
export class BackofficeModule {}

View File

@ -0,0 +1,24 @@
import { CategoryService } from './category.service';
import { Controller, Get, HttpException, HttpStatus, Param } from '@nestjs/common';
import { ApiExcludeEndpoint, ApiTags } from '@nestjs/swagger';
import { ResultModel } from 'src/domain/models/result.model';
@ApiTags('BackOffice')
@Controller('v1/category')
export class CategoryController {
constructor(private readonly categoryService: CategoryService){}
@Get(':idSecion')
@ApiExcludeEndpoint()
async getSection(@Param('idSecion') idSection: number) {
try {
const result = await this.categoryService.find(idSection);
return new ResultModel(true, null, result, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar lista de departamentos', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@ -0,0 +1,15 @@
import { Pccategoria } from '../../domain/entity/tables/pccategoria.entity';
import { CategoryService } from './category.service';
import { CategoryController } from './category.controller';
import { CacheModule, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [CacheModule.register(),
TypeOrmModule.forFeature([Pccategoria])],
controllers: [
CategoryController,],
providers: [
CategoryService,],
})
export class CategoryModule { }

View File

@ -0,0 +1,22 @@
import { Pccategoria } from '../../domain/entity/tables/pccategoria.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
@Injectable()
export class CategoryService {
constructor(@InjectRepository(Pccategoria)
private categoryRespository: Repository<Pccategoria>) { }
async find(idSecion: number): Promise<Pccategoria[]> {
return await this.categoryRespository
.createQueryBuilder('pccategoria')
.select('"pccategoria".codcategoria', 'codigoCategoria')
.addSelect('concat(concat("pccategoria".codcategoria, \'-\'),"pccategoria".categoria)', 'descricaoCategoria')
//.addSelect('concat(concat("pccategoria".codcategoria, \'-\'),"pccategoria".categoria)', 'descricaoCategoria')
.where("codsec = :codsec", { codsec: idSecion })
.getRawMany();
}
}

View File

@ -0,0 +1,38 @@
import { ApiExcludeEndpoint, ApiTags } from '@nestjs/swagger';
import { ResultModel } from './../../domain/models/result.model';
import { CestService } from './cest.service';
import { Controller, Get, HttpException, HttpStatus, Param, Req } from '@nestjs/common';
@ApiTags('BackOffice')
@Controller('v1/cest')
export class CestController {
constructor(private readonly cestService: CestService){}
@Get()
@ApiExcludeEndpoint()
async getAll(@Req() req) {
try {
if (req.query['query'])
{
const result = await this.cestService.findByDescription(req.query['query']);
return new ResultModel(true, null, result, []);
}
return new ResultModel(false, 'Para pesquisar os Cest é necessário informar pelo menos 3 caracteres.', null, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar lista de dicionários', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Get(':ncm')
@ApiExcludeEndpoint()
async GetbyNcm(@Param('ncm') ncm: string) {
try {
const result = await this.cestService.findByNcm(ncm);
return new ResultModel(true, null, result, null);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar lista de CESTs', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@ -0,0 +1,15 @@
import { Pccest } from '../../domain/entity/tables/pccest.entity';
import { CestController } from './cest.controller';
import { CestService } from './cest.service';
import { CacheModule, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [CacheModule.register(),
TypeOrmModule.forFeature([Pccest])],
controllers: [
CestController,],
providers: [
CestService,],
})
export class CestModule { }

View File

@ -0,0 +1,35 @@
import { Pccest } from '../../domain/entity/tables/pccest.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
@Injectable()
export class CestService {
constructor(@InjectRepository(Pccest)
private cestRepository: Repository<Pccest>) { }
async find(): Promise<Pccest[]> {
return await this.cestRepository
.createQueryBuilder('pccest')
.getMany()
}
async findByDescription(descricaoCest: string): Promise<Pccest[]> {
return await this.cestRepository
.createQueryBuilder('pccest')
.select('"pccest".codigo', 'codigo')
.addSelect('concat(concat(\"pccest\".codcest, \'-\'), substr(\"pccest\".descricaocest,1,80))', 'descricaoCest')
.andWhere("concat(concat(\"pccest\".codcest, \'-\'), substr(\"pccest\".descricaocest,1,80)) like '%'||UPPER(:descricaoCest)||'%'", {descricaoCest})
.getRawMany();
}
async findByNcm(codigoNcm: string): Promise<Pccest[]> {
return await this.cestRepository
.createQueryBuilder('pccest')
.where('ncm = :codigoncm', { codigoncm: codigoNcm })
.getMany()
}
}

View File

@ -0,0 +1,35 @@
import { DepartmentService } from './department.service';
import { CacheInterceptor, Controller, Get, HttpException, HttpStatus, UseInterceptors } from '@nestjs/common';
import { ApiExcludeEndpoint, ApiTags } from '@nestjs/swagger';
import { ResultModel } from 'src/domain/models/result.model';
@ApiTags('BackOffice')
@Controller('api/v1/department')
export class DepartmentController {
constructor(private readonly departmentService: DepartmentService){}
@Get()
@UseInterceptors(CacheInterceptor)
@ApiExcludeEndpoint()
async getAll() {
try {
const departments = await this.departmentService.findAll();
return new ResultModel(true, null, departments, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar lista de departamentos', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Get('all')
@UseInterceptors(CacheInterceptor)
async get() {
try {
const departments = await this.departmentService.findDepartments();
return new ResultModel(true, null, departments, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar lista de departamentos', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@ -0,0 +1,14 @@
import { Pcdepto } from '../../domain/entity/tables/pcdepto.entity';
import { DepartmentService } from './department.service';
import { DepartmentController } from './department.controller';
import { CacheModule, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [ CacheModule.register(),
TypeOrmModule.forFeature([Pcdepto])],
controllers: [DepartmentController,],
providers: [DepartmentService,],
})
export class DepartmentModule { }

View File

@ -0,0 +1,47 @@
import { Pcdepto } from 'src/domain/entity/tables/pcdepto.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getConnection, Repository } from 'typeorm';
import { Esvdepartamento } from 'src/domain/entity/views/esvdepartamento.entity';
@Injectable()
export class DepartmentService {
constructor( @InjectRepository(Pcdepto)
private departmentRepository: Repository<Pcdepto>){}
async findAll(): Promise<Pcdepto[]> {
return await this.departmentRepository
.createQueryBuilder('pcdepto')
.leftJoinAndSelect("pcdepto.secoes", "secoes")
.leftJoinAndSelect("pcsecao.categoria", "categoria")
.select('"pcdepto".codepto', 'codigoDepartamento')
.addSelect('concat(concat("pcdepto".codepto, \' - \'),"pcdepto".descricao)', 'descricaoDepartamento')
// .addSelect('concat(concat(concat("pcdepto".descricao, \' (\'),"pcdepto".codepto),\')\')', 'descricaoDepartamento')
.where('codepto <> 9999')
.getRawMany();
}
async findDepartments() {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const departments = await queryRunner.manager
.getRepository(Esvdepartamento)
.createQueryBuilder('esvdepartamento')
.innerJoinAndSelect('esvdepartamento.secoes', 'secoes')
.innerJoinAndSelect('secoes.categorias', 'itens')
.where('\"esvdepartamento\".codepto <> 9999')
.orderBy("\"esvdepartamento\".DESCRICAO")
.getMany();
return departments;
} catch (error) {
console.log(error);
throw error;
} finally {
await queryRunner.release();
}
}
}

View File

@ -0,0 +1,64 @@
import { ResultModel } from '../../domain/models/result.model';
import { CreateDictionaryContract } from '../../contracts/dictionary.contract';
import { ValidadorInterceptor } from '../../Interceptors/validador.interceptor';
import { DictionaryModel } from '../../domain/models/dictionary.model';
import { DictionaryService } from './dictionary.service';
import { Controller, Get, Param, Put, Body, Post, Delete, UseInterceptors, HttpException, HttpStatus, CacheInterceptor, Req } from "@nestjs/common";
import { ApiExcludeEndpoint, ApiTags } from '@nestjs/swagger';
@ApiTags('BackOffice')
@Controller('v1/dictionary')
export class DictionaryController {
constructor(
private readonly dictionaryService: DictionaryService
){}
@Get()
@UseInterceptors(CacheInterceptor)
@ApiExcludeEndpoint()
async getAll(@Req() req) {
try {
if (req.query['query'])
{
const result = await this.dictionaryService.findByDescription(req.query['query']);
return new ResultModel(true, null, result, []);
}
const dictionaries = await this.dictionaryService.findAll();
return new ResultModel(true, null, dictionaries, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar lista de dicionários', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Get(':id')
async get(@Param('id') id: number) {
try {
const dictionary = await this.dictionaryService.find(id);
return new ResultModel(true, null, dictionary, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar dicionário.', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Put(':id')
async put(@Param('id') id: number, @Body() dados: DictionaryModel) {
try {
await this.dictionaryService.update(id, dados);
return new ResultModel(true, null, dados, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível atualizar dicionário.', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Post()
@UseInterceptors(new ValidadorInterceptor(new CreateDictionaryContract()))
async post(@Body() dados: DictionaryModel) {
return await this.dictionaryService.create(dados);
}
@Delete(':id')
async delete(@Param('id') id: number) {
return await this.dictionaryService.delete(id);
}
}

View File

@ -0,0 +1,30 @@
import { User } from '../../domain/entity/tables/estusuario.enity';
import { TypeOrmModule } from '@nestjs/typeorm';
import { DictionaryController } from './dictionary.controller';
import { CacheModule, Module } from "@nestjs/common";
import { DictionaryService } from './dictionary.service';
import { EstAbreviatura } from 'src/domain/entity/tables/estabreviatura.entity';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from '../../Auth/strategies/jwt-strategy';
import { AuthService } from '../../Auth/services/auth.service';
import { UserController } from 'src/Auth/controllers/user.controller';
import { UserService } from 'src/Auth/services/user.service';
@Module({
imports: [CacheModule.register(),
PassportModule.register({
defaultStrategy: 'jwt'
}),
JwtModule.register({
secretOrPrivateKey: '4557C0D7-DFB0-40DA-BF83-91A75103F7A9',
signOptions: {
expiresIn: 3600,
}
}),TypeOrmModule.forFeature([EstAbreviatura, User])],
controllers: [UserController, DictionaryController],
providers: [DictionaryService, UserService, AuthService, JwtStrategy],
})
export class DictionaryModule {}

View File

@ -0,0 +1,84 @@
import { ResultModel } from '../../domain/models/result.model';
import { DictionaryModel } from '../../domain/models/dictionary.model';
import { EstAbreviatura } from 'src/domain/entity/tables/estabreviatura.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getConnection } from 'typeorm';
import { NumberUtils } from 'src/utils/number.utils';
@Injectable()
export class DictionaryService {
constructor(
@InjectRepository(EstAbreviatura)
private dictionaryRepository: Repository<EstAbreviatura>
) { }
async findAll(): Promise<EstAbreviatura[]> {
return await this.dictionaryRepository.find();
}
async findByDescription(description: string): Promise<EstAbreviatura[]> {
return await this.dictionaryRepository
.createQueryBuilder("estabreviatura")
.where("PALAVRA LIKE UPPER(:description)||'%'", { description }
).getMany();
}
async find(id: number): Promise<EstAbreviatura> {
return await this.dictionaryRepository.createQueryBuilder("estabreviatura").where(
"ID = :id", { id: id }
).getOne();
}
async update(id: number, dados: DictionaryModel) {
return await this.dictionaryRepository
.createQueryBuilder()
.update(EstAbreviatura)
.set({ abreviatura: dados.nick, palavra: dados.word })
.where("ID = :id", { id })
.execute();
}
async delete(id: number) {
return await getConnection()
.createQueryBuilder()
.delete()
.from(EstAbreviatura)
.where("ID = :id", { id })
.execute();
}
async create(dados: DictionaryModel) {
try
{
const id = NumberUtils.getNewId(9999, 1);
const newDictionary = new EstAbreviatura();
newDictionary.id = id;
newDictionary.abreviatura = dados.nick;
newDictionary.palavra = dados.word;
await getConnection()
.createQueryBuilder()
.insert()
.into(EstAbreviatura)
.values(newDictionary)
.execute();
return newDictionary;
} catch ( erro ) {
return new ResultModel(true, "Ops! Houve um erro ao criar o Dicionário.", null, erro);
}
}
}

View File

@ -0,0 +1,97 @@
import { Controller, Get, Param } from '@nestjs/common';
import { ListsService } from './lists.service';
import { ApiParam, ApiTags } from '@nestjs/swagger';
@ApiTags('BackOffice')
@Controller('api/v1/lists')
export class ListsController {
constructor(private readonly listsServices: ListsService) { }
/**
* Consulta todas filiais cadastradas
*/
@Get('store')
async getAll() {
return this.listsServices.GetStoreAll();
}
/**
* Consulta filiais autorizadas para o usuário
*/
@Get('store/user/:id')
async getByUser(@Param('id') id: number) {
return this.listsServices.GetStoreByUser(id);
}
/**
* Consulta tabela de checkouts da filial informada
*/
@Get('checkout/:store')
@ApiParam({name: 'Código da filial',})
async getCheckout(@Param('store') idStore: string) {
return this.listsServices.GetCheckout(idStore);
}
/**
* Consulta lista de funcionários para a filial informada nos parâmetros
*/
@Get('user/:store')
async getUser(@Param('store') idStore: string) {
return this.listsServices.GetUser(idStore);
}
/**
* Consulta tabela de plano de pagamento para pedido de venda
*/
@Get('paymentplan/:billindid')
async getPaymentPlan(@Param('billindid') billingId: string) {
return this.listsServices.GetPaymentPlan(billingId);
}
/**
* Consulta tabela de cobrança para pedido de venda
*/
@Get('billing/:customerid')
async getBillingByCustomer(@Param('customerid') customerId: number) {
return this.listsServices.GetBilling(customerId);
}
/**
* Consulta cadastro de parceiros
*/
@Get('partners')
async getPartners() {
return this.listsServices.GetPartners();
}
/**
* Consulta praças para o cadastro de cliente / endereços
*/
@Get('places')
async getPlaces() {
return this.listsServices.GetPlaces();
}
/**
* Consulta praças para o cadastro de cliente / endereços para retira em loja (CODPRINCIPAL = 1004)
*/
@Get('store-places')
async getStorePlaces() {
return this.listsServices.GetStorePlaces();
}
/**
* Consulta ramos de atividade do cliente
*/
@Get('ramo')
async getRamo() {
return this.listsServices.GetRamo();
}
@Get('supervisores')
async getSupervisores() {
return this.listsServices.getSupervisores();
}
}

View File

@ -0,0 +1,12 @@
import { ListsService } from './lists.service';
import { ListsController } from './lists.controller';
import { Module } from '@nestjs/common';
@Module({
imports: [],
controllers: [
ListsController,],
providers: [
ListsService,],
})
export class ListsModule { }

View File

@ -0,0 +1,302 @@
import { Injectable } from '@nestjs/common';
import { Checkout } from 'src/domain/entity/tables/pccaixa.entity';
import { Connection } from 'typeorm';
import { Store } from '../../domain/entity/tables/pcfilial.entity';
import { Pcempr } from '../../domain/entity/tables/pcempr.entity';
import { connectionOptions } from 'src/configs/typeorm.config';
@Injectable()
export class ListsService {
async GetStoreAll(): Promise<Store[]> {
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = `SELECT PCFILIAL.CODIGO as "id", ` +
` PCFILIAL.RAZAOSOCIAL as "name", ` +
` PCFILIAL.CODIGO|| ' - '|| PCFILIAL.FANTASIA as "shortName" ` +
` FROM PCFILIAL ` +
` WHERE PCFILIAL.CODIGO <> '99' ` +
` ORDER BY PCFILIAL.CODIGO `;
const stores = await queryRunner.query(sql);
return stores as Store[];
} catch (error) {
console.log(error);
throw error;
} finally {
await queryRunner.release();
await connection.close();
}
}
async GetStoreByUser(idUser: number): Promise<Store[]> {
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
const sql = `SELECT PCFILIAL.CODIGO as "id", ` +
` PCFILIAL.RAZAOSOCIAL as "name", ` +
` PCFILIAL.CODIGO|| ' - '|| PCFILIAL.FANTASIA as "shortName" ` +
` FROM PCFILIAL `;
const whereByUser = " WHERE PCFILIAL.CODIGO <> '99' AND " +
" ((PCFILIAL.CODIGO IN ( SELECT PCLIB.CODIGOA FROM PCLIB WHERE PCLIB.CODTABELA = 1 AND PCLIB.CODFUNC = :iduser )) OR " +
" (EXISTS(SELECT PCLIB.CODIGOA FROM PCLIB WHERE PCLIB.CODTABELA = 1 AND PCLIB.CODFUNC = :iduser AND PCLIB.CODIGOA = '99')) ) ";
const orderBy = ` ORDER BY PCFILIAL.CODIGO`
try {
const stores = await queryRunner.query(sql + whereByUser + orderBy, [idUser]);
return stores as Store[];
} catch (error) {
console.log(error);
throw error;
} finally {
await queryRunner.release();
await connection.close();
}
}
async GetCheckout(idStore: string): Promise<Checkout[]> {
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const checkouts = await queryRunner.manager
.getRepository(Checkout)
.createQueryBuilder('pccaixa')
.where("\"pccaixa\".CODFILIAL = :idStore", {idStore: idStore})
.orderBy("\"pccaixa\".NUMCAIXA")
.getMany();
return checkouts;
} catch (error) {
console.log(error);
throw error;
} finally {
await queryRunner.release();
await connection.close();
}
}
async GetUser(idStore: string): Promise<Pcempr[]> {
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const checkouts = await queryRunner.manager
.getRepository(Pcempr)
.createQueryBuilder('pcempr')
.select("\"pcempr\".matricula as \"id\", \"pcempr\".nome as \"name\", \"pcempr\".email as \"email\", \"pcempr\".usuariobd as \"smallName\"")
.where("\"pcempr\".CODFILIAL = :idStore", {idStore: idStore})
.orderBy("\"pcempr\".NOME")
.getRawMany();
return checkouts;
} catch (error) {
console.log(error);
throw error;
} finally {
await queryRunner.release();
await connection.close();
}
}
async GetPaymentPlan(billingId: string){
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = ' SELECT PCPLPAG.CODPLPAG as "codplpag", PCPLPAG.DESCRICAO as "descricao", ' +
' NVL(PCPLPAG.NUMDIAS,0) as "numdias" ' +
' FROM PCPLPAG ' +
' WHERE EXISTS(SELECT PCCOBPLPAG.CODCOB FROM PCCOBPLPAG ' +
' WHERE PCCOBPLPAG.CODPLPAG = PCPLPAG.CODPLPAG ' +
' AND PCCOBPLPAG.CODCOB = :CODCOB ) '
' ORDER BY PCPAG.DESCRICAO ';
const paymentPlans = await queryRunner.query(sql, [billingId]);
return paymentPlans;
} catch (error) {
throw error;
} finally {
await queryRunner.release();
await connection.close();
}
}
async GetBilling(clienteId: number){
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = ' SELECT PCCOB.CODCOB as "codcob", PCCOB.CODCOB ||\' - \'||PCCOB.COBRANCA as "cobranca" ' +
' FROM PCCOB ' +
' WHERE NVL(PCCOB.enviacobrancafv, \'N\') = \'S\' ' +
' AND ( ( NOT EXISTS(SELECT PCCOBCLI.CODCOB FROM PCCOBCLI WHERE PCCOBCLI.CODCLI = :CODCLI ) AND ' +
' ( PCCOB.NIVELVENDA <= ( SELECT C.NIVELVENDA FROM PCCLIENT, PCCOB C ' +
' WHERE PCCLIENT.CODCLI = :CODCLI AND PCCLIENT.CODCOB = C.CODCOB ) ) ) OR ' +
' EXISTS(SELECT PCCOBCLI.CODCOB FROM PCCOBCLI WHERE PCCOBCLI.CODCLI = :CODCLI AND PCCOBCLI.CODCOB = PCCOB.CODCOB ) ) ' +
' ORDER BY PCCOB.CODCOB';
const billings = await queryRunner.query(sql, [clienteId]);
return billings;
} catch (error) {
throw error;
} finally {
await queryRunner.release();
await connection.close();
}
}
async GetPartners(){
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = ' SELECT ESTPARCEIRO.ID as "id" ' +
' ,REGEXP_REPLACE(ESTPARCEIRO.CPF, \'[^0-9]\',\'\') || \' - \' ||ESTPARCEIRO.NOME as "name" ' +
' FROM ESTPARCEIRO ' +
' WHERE 1 = 1 ';
const partners = await queryRunner.manager
.query(sql);
return partners;
} catch (error) {
throw error;
} finally {
await queryRunner.release();
await connection.close();
}
}
async GetPreCustomer(idCart: string){
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = ' select CPF as "document" '+
' ,NOME as "name" ' +
' ,TELEFONE as "phone" ' +
' ,IDCART as "idCart" ' +
' from estvendaprecliente ' +
' where IDCART = :idcart ';
console.log(idCart);
const preCustomer = await queryRunner
.query(sql, [idCart]);
console.log(JSON.stringify(preCustomer));
return preCustomer[0];
} catch (error) {
throw error;
} finally {
await queryRunner.release();
await connection.close();
}
}
async GetPlaces(){
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = ' SELECT PCPRACA.CODPRACA as "id" ' +
' ,PCPRACA.PRACA as "name" ' +
' FROM PCPRACA ' +
' WHERE 1 = 1';
const places = await queryRunner.manager
.query(sql);
return places;
} catch (error) {
throw error;
} finally {
await queryRunner.release();
await connection.close();
}
}
async GetStorePlaces(){
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = ' SELECT PCPRACA.CODPRACA as "id" ' +
' ,PCPRACA.PRACA as "name" ' +
' FROM PCPRACA ' +
' WHERE PCPRACA.CODPRACAPRINCIPAL = 1004';
const places = await queryRunner.manager
.query(sql);
return places;
} catch (error) {
throw error;
} finally {
await queryRunner.release();
await connection.close();
}
}
async GetRamo(){
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = ' SELECT PCATIVI.CODATIV as "id" ' +
' ,PCATIVI.RAMO as "name" ' +
' FROM PCATIVI ' +
' WHERE 1 = 1 ' +
' ORDER BY PCATIVI.RAMO';
const ramos = await queryRunner.manager
.query(sql);
return ramos;
} catch (error) {
throw error;
} finally {
await queryRunner.release();
await connection.close();
}
}
async GetStates(state: string){
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = ' SELECT PCESTADO.ESTADO as "name" FROM PCESTADO' +
' WHERE PCESTADO.UF = :1';
const states = await queryRunner.manager
.query(sql, [state]);
return states[0].name;
} catch (error) {
throw error;
} finally {
await queryRunner.release();
await connection.close();
}
}
async getSupervisores(){
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const sql = `SELECT PCSUPERV.CODSUPERVISOR as "supervisorId"
,PCSUPERV.NOME as "name"
FROM PCSUPERV
WHERE PCSUPERV.dtdemissao IS NULL`;
const supervisores = await queryRunner.manager
.query(sql);
return supervisores;
} catch (error) {
throw error;
} finally {
await queryRunner.release();
await connection.close();
}
}
}

View File

@ -0,0 +1,61 @@
import { MeasureProductModel } from '../../domain/models/measureproduct.model';
import { Controller, Get, Param, Put, Body, Post, Delete, HttpException, HttpStatus, Req } from "@nestjs/common";
import { MeasureProductService } from './measureproduct.service';
import { ResultModel } from 'src/domain/models/result.model';
import { ApiExcludeEndpoint, ApiTags } from '@nestjs/swagger';
@ApiTags('BackOffice')
@Controller('v1/measure')
export class MeasureProductController {
constructor(
private measureProductService: MeasureProductService
){}
@Get()
@ApiExcludeEndpoint()
async getAll(@Req() req) {
try {
if (req.query['query'] || req.query['query'] !== '')
{
const result = await this.measureProductService.findByDescription(req.query['query']);
return new ResultModel(true, null, result, []);
}
const result = await this.measureProductService.findAll();
return new ResultModel(true, null, result, []);
} catch (error) {
console.log(error);
throw new HttpException(new ResultModel(false, 'Não foi possível consultar lista de medidas de produto.', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Get(':id')
@ApiExcludeEndpoint()
async get(@Param('id') id) {
try {
const result =await this.measureProductService.find(id);
return new ResultModel(true, null, result, []);
} catch (error) {
console.log(error);
throw new HttpException(new ResultModel(false, 'Não foi possível consultar lista de medidas de produto.', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Put(':id')
@ApiExcludeEndpoint()
async put(@Param('id') id: number, @Body() body: MeasureProductModel) {
return await this.measureProductService.update(id, body);
}
@Post()
@ApiExcludeEndpoint()
async post(@Body() body: MeasureProductModel) {
return await this.measureProductService.create(body);
}
@Delete(':id')
@ApiExcludeEndpoint()
async delete(@Param('id') id: number) {
return await this.measureProductService.delete(id);
}
}

View File

@ -0,0 +1,30 @@
import { TypeOrmModule } from '@nestjs/typeorm';
import { Module } from "@nestjs/common";
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { MeasureProductController } from './measureproduct.controller';
import { MeasureProductService } from './measureproduct.service';
import { Estmedidaproduto } from 'src/domain/entity/tables/estmedidaproduto.entity';
import { AuthService } from 'src/Auth/services/auth.service';
import { JwtStrategy } from 'src/Auth/strategies/jwt-strategy';
import { UserService } from 'src/Auth/services/user.service';
import { User } from 'src/domain/entity/tables/estusuario.enity';
@Module({
imports: [PassportModule.register({
defaultStrategy: 'jwt'
}),
JwtModule.register({
secretOrPrivateKey: '4557C0D7-DFB0-40DA-BF83-91A75103F7A9',
signOptions: {
expiresIn: 3600,
}
}),
TypeOrmModule.forFeature([Estmedidaproduto, User])],
controllers: [MeasureProductController],
providers: [MeasureProductService, UserService, AuthService, JwtStrategy],
})
export class MeasureProductModule {}

View File

@ -0,0 +1,85 @@
import { NumberUtils } from '../../utils/number.utils';
import { MeasureProductModel } from '../../domain/models/measureproduct.model';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Estmedidaproduto } from 'src/domain/entity/tables/estmedidaproduto.entity';
import { Repository } from 'typeorm';
@Injectable()
export class MeasureProductService {
constructor(
@InjectRepository(Estmedidaproduto)
private measureProductRepository: Repository<Estmedidaproduto>
) { }
async findAll(): Promise<Estmedidaproduto[]> {
return await this.measureProductRepository.find();
}
async findByDescription(description: string): Promise<Estmedidaproduto[]> {
return await this.measureProductRepository.createQueryBuilder("ESTMEDIDAPRODUTO").where(
"DESCRICAO LIKE :description||'%'", { description }
).getMany();
}
async find(id: number): Promise<Estmedidaproduto> {
return await this.measureProductRepository.createQueryBuilder("ESTMEDIDAPRODUTO").where(
"IDMEDIDAPRODUTO = :IDMEDIDAPRODUTO", { IDMEDIDAPRODUTO: id }
).getOne();
}
async update(id: number, dados: MeasureProductModel): Promise<boolean> {
await this.measureProductRepository
.createQueryBuilder()
.update('Estmedidaproduto')
.set({ descricao: dados.descricao, abreviatura: dados.abreviatura, quantidade: dados.quantidade, nivel: dados.nivel })
.where("IDMEDIDAPRODUTO = :IDMEDIDAPRODUTO", { IDMEDIDAPRODUTO: id })
.execute();
return Promise.resolve(true);
}
async delete(id: number): Promise<boolean> {
await this.measureProductRepository
.createQueryBuilder()
.delete()
.from('Estmedidaproduto')
.where("IDMEDIDAPRODUTO = :IDMEDIDAPRODUTO", { IDMEDIDAPRODUTO: id })
.execute();
return Promise.resolve(true);
}
async create(dados: MeasureProductModel) {
try
{
const id = NumberUtils.getNewId(999999, 1);
const newEstmedidaproduto = new Estmedidaproduto();
newEstmedidaproduto.idmedidaproduto = id;
newEstmedidaproduto.abreviatura = dados.abreviatura;
newEstmedidaproduto.descricao = dados.descricao;
newEstmedidaproduto.nivel = dados.nivel;
newEstmedidaproduto.quantidade = dados.quantidade;
await this.measureProductRepository
.createQueryBuilder()
.insert()
.into('Estmedidaproduto')
.values(newEstmedidaproduto)
.execute();
return Promise.resolve(true);
} catch( error ) {
console.log(error);
return Promise.resolve(false);
}
}
}

View File

@ -0,0 +1,15 @@
/*
https://docs.nestjs.com/modules
*/
import { HttpModule, Module } from '@nestjs/common';
import { WhatsappController } from './whatsapp/whatsapp.controller';
import { WhatsappService } from './whatsapp/whatsapp.service';
@Module({
imports: [HttpModule],
controllers: [WhatsappController],
providers: [WhatsappService,
],
})
export class MessagesModule {}

View File

@ -0,0 +1,42 @@
/*
https://docs.nestjs.com/controllers#controllers
*/
import { Body, Controller, HttpException, HttpStatus, Post } from '@nestjs/common';
import { IndexActions } from 'src/domain/models/index-action.model';
import { ResultModel } from 'src/domain/models/result.model';
import { MessageWhatsApp } from '../../../domain/models/message-whatsapp.model';
import { WhatsappService } from './whatsapp.service';
import { ApiExcludeEndpoint } from '@nestjs/swagger';
@Controller('api/v1/message/whatsapp')
export class WhatsappController {
constructor(private readonly whatsappService: WhatsappService){}
@Post('send')
@ApiExcludeEndpoint()
async sendMessage(@Body() message: MessageWhatsApp){
try{
const result = await this.whatsappService.sendMessage(message);
console.log(result);
return result;
} catch(err){
throw new HttpException(new ResultModel(false, 'Não foi possível enviar mensagem para o clientes.', {}, err),
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Post('action')
@ApiExcludeEndpoint()
async createActionIndex(@Body() action: IndexActions){
try{
const result = await this.whatsappService.createActionIndex(action);
console.log(result);
return result;
} catch(err){
throw new HttpException(new ResultModel(false, 'Não foi possível criar pesquisa no INDEX para este cliente.', {}, err),
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@ -0,0 +1,58 @@
import { HttpException, HttpService, HttpStatus, Injectable } from '@nestjs/common';
import { IndexActions, } from 'src/domain/models/index-action.model';
import { MessageWhatsApp } from '../../../domain/models/message-whatsapp.model';
@Injectable()
export class WhatsappService {
constructor(private readonly httpService: HttpService) {}
async sendMessage(message: MessageWhatsApp ) {
// var fs = require('fs');
//'Key ' + 'emFwanVydTppY0NtdXlFc3NvYmpqTkVLSFEwbw=='
const url = `https://takebroadcast.cs.blip.ai/api/v1/Notification`;
try {
const response = await this.httpService
.post(url,
JSON.stringify(message),
{
headers: {
'accept': 'application/json',
'content-type': 'application/json',
'accesskey': 'aWNDbXV5RXNzb2Jqak5FS0hRMG8=',
'identifier': 'zapjuru'
}
})
.toPromise();
return response.data;
} catch (e) {
console.log(e);
throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
}
}
async createActionIndex(action: IndexActions) {
const url = `https://indecx.com/v2/actions/185E2H/invites`;
try {
const response = await this.httpService
.post(url,
JSON.stringify(action),
{
headers: {
'accept': 'application/json',
'content-type': 'application/json',
'company-key': '$2b$10$rlMclOiWPwGgKavwPDFvCOYlDWujMi.h7BGizTxHPVjkn62VCgreO',
}
})
.toPromise();
return response.data;
} catch (e) {
console.log(e);
throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
}
}
}

View File

@ -0,0 +1,52 @@
import { NcmService } from './ncm.service';
import { Controller, Get, HttpException, HttpStatus, Param, Req } from '@nestjs/common';
import { ApiExcludeEndpoint, ApiTags } from '@nestjs/swagger';
import { ResultModel } from 'src/domain/models/result.model';
@ApiTags('BackOffice')
@Controller('v1/ncm')
export class NcmController {
constructor(private readonly ncmService: NcmService ){}
@Get()
@ApiExcludeEndpoint()
async getAll(@Req() req) {
try {
if (req.query['query'])
{
const result = await this.ncmService.findByDescription(req.query['query']);
return new ResultModel(true, null, result, []);
}
return new ResultModel(false, 'Para pesquisar os NCMs é necessário informar pelo menos 3 caracteres.', null, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar lista de dicionários', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/*
@Get()
async findAll() {
try {
const ncms = await this.ncmService.findAll();
return new ResultModel(true, null, ncms, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar lista de NCMs', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}*/
@Get(":ncm")
@ApiExcludeEndpoint()
async findByNcm(@Param("ncm") ncm: string, @Req() req) {
console.log(req.query);
try {
const result = await this.ncmService.find(ncm);
return new ResultModel(true, null, result, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar lista de NCMs', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@ -0,0 +1,15 @@
import { Pcncm } from '../../domain/entity/tables/pcncm.entity';
import { NcmController } from './ncm.controller';
import { NcmService } from './ncm.service';
import { CacheModule, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [CacheModule.register(),
TypeOrmModule.forFeature([Pcncm])],
controllers: [
NcmController,],
providers: [
NcmService,],
})
export class NcmModule { }

View File

@ -0,0 +1,39 @@
import { Pcncm } from '../../domain/entity/tables/pcncm.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
@Injectable()
export class NcmService {
constructor(@InjectRepository(Pcncm)
private ncmRepository: Repository<Pcncm>){}
async findAll(): Promise<Pcncm[]> {
return await this.ncmRepository
.createQueryBuilder('pcncm')
.select('"pcncm".codncmex', 'codigoNcmEx')
.addSelect('concat(concat("pcncm".codncmex, \' - \'),SUBSTR("pcncm".descricao,1,100))', 'descricaoNcm')
.where('dtexclusao is null')
.getRawMany();
}
async findByDescription(description: string): Promise<Pcncm[]> {
return await this.ncmRepository
.createQueryBuilder('pcncm')
.select('"pcncm".codncmex', 'codigoNcmEx')
.addSelect('concat(concat("pcncm".codncmex, \' - \'),SUBSTR("pcncm".descricao,1,100))', 'descricaoNcm')
.where('dtexclusao is null')
.andWhere("descricao like UPPER(:description)||'%'", {description})
.getRawMany();
}
async find(ncm: string): Promise<Pcncm[]> {
return await this.ncmRepository
.createQueryBuilder('pcncm')
.where("dtexclusao is null and codncm like :ncm||'%'", { ncm })
.getRawMany();
}
}

View File

@ -0,0 +1,81 @@
import { ProductTypeModel } from './../../domain/models/product-type.model';
import { Body, Delete, Param, Post } from '@nestjs/common';
import { ResultModel } from './../../domain/models/result.model';
import { ProductTypeService } from './product-type.service';
import { CacheInterceptor, Controller, Get, HttpException, HttpStatus, Put, Req, UseInterceptors } from '@nestjs/common';
import { ApiExcludeEndpoint, ApiTags } from '@nestjs/swagger';
@ApiTags('BackOffice')
@Controller('v1/product-type')
export class ProductTypeController {
constructor( private readonly productTypeService: ProductTypeService){}
@Get()
@UseInterceptors(CacheInterceptor)
@ApiExcludeEndpoint()
async getAll(@Req() req) {
try {
if (req.query['query'])
{
const result = await this.productTypeService.findByType(req.query['query']);
return new ResultModel(true, null, result, []);
}
const typeProducts = await this.productTypeService.findAll();
return new ResultModel(true, null, typeProducts, []);
} catch (error) {
console.log(error);
throw new HttpException(new ResultModel(false, 'Não foi possível consultar lista de tipos de produto.', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Get(':id')
@UseInterceptors(CacheInterceptor)
@ApiExcludeEndpoint()
async getOne(@Param('id') id: number ) {
try {
const data = await this.productTypeService.findById(id);
console.log(data);
return new ResultModel(true, null, data, []);
} catch (error) {
console.log(error);
throw new HttpException(new ResultModel(false, 'Não foi possível consultar tipo de produto.', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Put(':id')
async update(@Param('id') id: number, @Body() dados: ProductTypeModel) {
try {
await this.productTypeService.update(id, dados);
return new ResultModel(true, null, dados, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível atualizar tipo do produto.', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Post()
@ApiExcludeEndpoint()
//TODO: @UseInterceptors(new ValidadorInterceptor(new CreateDictionaryContract()))
async post(@Body() dados: ProductTypeModel) {
try {
const newProductType = await await this.productTypeService.create(dados);
return new ResultModel(true, null, newProductType, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível incluir tipo do produto.', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Delete(':id')
@ApiExcludeEndpoint()
async delete(@Param('id') id: number) {
try {
const result = await this.productTypeService.delete(id);
return new ResultModel(true, 'Tipo do produto excluído com sucesso!', null, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível excluir tipo do produto.', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@ -0,0 +1,15 @@
import { Esttipoproduto } from '../../domain/entity/tables/esttipoproduto.entity';
import { ProductTypeController } from './product-type.controller';
import { ProductTypeService } from './product-type.service';
import { CacheModule, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [CacheModule.register(),
TypeOrmModule.forFeature([Esttipoproduto])],
controllers: [
ProductTypeController,],
providers: [
ProductTypeService,],
})
export class ProductTypeModule { }

View File

@ -0,0 +1,165 @@
import { ProductTypeModel } from './../../domain/models/product-type.model';
import { Esttipoproduto } from '../../domain/entity/tables/esttipoproduto.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getConnection, Repository } from 'typeorm';
import { NumberUtils } from 'src/utils/number.utils';
import { ResultModel } from 'src/domain/models/result.model';
@Injectable()
export class ProductTypeService {
constructor(
@InjectRepository(Esttipoproduto)
private productTypeRepository: Repository<Esttipoproduto>
) { }
async findAll(): Promise<Esttipoproduto[]> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
return await queryRunner.manager
.getRepository(Esttipoproduto)
.createQueryBuilder('esttipoproduto')
.select(['"esttipoproduto".idtipoproduto as "id"'
, '"esttipoproduto".tipoproduto as "tipoProduto"'
, '"esttipoproduto".siglaproduto as "siglaProduto"'
, '"esttipoproduto".ncm as "ncm"'
, '"esttipoproduto".codepto as "codigoDepartamento"'
, '"esttipoproduto".codsec as "codigoSecao"'
, '"esttipoproduto".codcategoria as "codigoCategoria"'
, '"esttipoproduto".cest as "codigoCest"'
, 'concat(concat("departamento".codepto, \'-\'),"departamento".descricao) as "departamentoDescricao"'
, 'concat(concat("secao".codsec, \'-\'),"secao".descricao) as "secaoDescricao"'
, 'concat(concat("categoria".codcategoria, \'-\'),"categoria".categoria) as "categoriaDescricao"'
, '"registrocest".descricaocest as "cestDescricao"'])
.innerJoin("esttipoproduto.departamento", "departamento")
.innerJoin("esttipoproduto.secao", "secao")
.innerJoin("esttipoproduto.categoria", "categoria", '"esttipoproduto".codsec = "categoria".codsec')
.innerJoin("esttipoproduto.registrocest", "registrocest")
.getRawMany();
}
async findByType(description: string): Promise<Esttipoproduto[]> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
const descriptionType = description + '%';
return await queryRunner.manager
.getRepository(Esttipoproduto)
.createQueryBuilder('esttipoproduto')
.select(['"esttipoproduto".idtipoproduto as "id"'
, '"esttipoproduto".tipoproduto as "tipoProduto"'
, '"esttipoproduto".siglaproduto as "siglaProduto"'
, '"esttipoproduto".ncm as "ncm"'
, '"esttipoproduto".codepto as "codigoDepartamento"'
, '"esttipoproduto".codsec as "codigoSecao"'
, '"esttipoproduto".codcategoria as "codigoCategoria"'
, '"esttipoproduto".cest as "codigoCest"'
, 'concat(concat("departamento".codepto, \'-\'),"departamento".descricao) as "departamentoDescricao"'
, 'concat(concat("secao".codsec, \'-\'),"secao".descricao) as "secaoDescricao"'
, 'concat(concat("categoria".codcategoria, \'-\'),"categoria".categoria) as "categoriaDescricao"'
, '"registrocest".descricaocest as "cestDescricao"'])
.innerJoin("esttipoproduto.departamento", "departamento")
.innerJoin("esttipoproduto.secao", "secao")
.innerJoin("esttipoproduto.categoria", "categoria", '"esttipoproduto".codsec = "categoria".codsec')
.innerJoin("esttipoproduto.registrocest", "registrocest")
.where('"esttipoproduto".tipoproduto like :type', { type: descriptionType })
.getRawMany();
}
async findById(id: number): Promise<Esttipoproduto> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
try{
return await queryRunner.manager
.getRepository(Esttipoproduto)
.createQueryBuilder('esttipoproduto')
.select(['"esttipoproduto".idtipoproduto as "id"'
, '"esttipoproduto".tipoproduto as "tipoProduto"'
, '"esttipoproduto".siglaproduto as "siglaProduto"'
, '"esttipoproduto".ncm as "ncm"'
, '"esttipoproduto".codepto as "codigoDepartamento"'
, '"esttipoproduto".codsec as "codigoSecao"'
, '"esttipoproduto".codcategoria as "codigoCategoria"'
, '"esttipoproduto".cest as "codigoCest"'
, 'concat(concat("departamento".codepto, \'-\'),"departamento".descricao) as "departamentoDescricao"'
, 'concat(concat("secao".codsec, \'-\'),"secao".descricao) as "secaoDescricao"'
, 'concat(concat("categoria".codcategoria, \'-\'),"categoria".categoria) as "categoriaDescricao"'
, 'concat(concat(\"registrocest\".codcest, \'-\'), substr(\"registrocest\".descricaocest,1,80)) as "cestDescricao"'
, 'concat(concat("registroNcm".codncmex, \' - \'),SUBSTR("registroNcm".descricao,1,100)) as "ncmDescricao"'])
.innerJoin("esttipoproduto.departamento", "departamento")
.innerJoin("esttipoproduto.secao", "secao")
.innerJoin("esttipoproduto.categoria", "categoria", '"esttipoproduto".codsec = "categoria".codsec')
.innerJoin("esttipoproduto.registrocest", "registrocest")
.innerJoin("esttipoproduto.registroNcm", "registroNcm")
.where('"esttipoproduto".idtipoproduto = :id', { id })
.getRawOne();
} catch (error) {
console.log(error)
}
}
async update(id: number, dados: ProductTypeModel) {
return await this.productTypeRepository
.createQueryBuilder()
.update(Esttipoproduto)
.set({ tipoProduto: dados.type, ncm: dados.ncm, codigoDepartamento: dados.idDepartment, codigoSecao: dados.idSection,
codigoCategoria: dados.idCategory, sigla: dados.sigla, cest: dados.idCest })
.where("ID = :id", { id })
.execute();
}
async delete(id: number) {
return await getConnection()
.createQueryBuilder()
.delete()
.from(Esttipoproduto)
.where("ID = :id", { id })
.execute();
}
async create(dados: ProductTypeModel) {
try
{
const id = NumberUtils.getNewId(9999, 1);
const newProductType = new Esttipoproduto();
newProductType.idTipoProduto = id;
newProductType.tipoProduto = dados.type;
newProductType.ncm = dados.ncm;
newProductType.sigla = dados.sigla;
newProductType.codigoDepartamento = dados.idDepartment;
newProductType.codigoSecao = dados.idSection;
newProductType.codigoCategoria = dados.idCategory;
newProductType.cest = dados.idCest;
await getConnection()
.createQueryBuilder()
.insert()
.into(Esttipoproduto)
.values(newProductType)
.execute();
return newProductType;
} catch ( erro ) {
console.log(erro);
return new ResultModel(true, "Ops! Houve um erro ao criar o Dicionário.", null, erro);
}
}
}

View File

@ -0,0 +1,34 @@
import { Body, Controller, Get, HttpException, HttpStatus, Param, Post } from '@nestjs/common';
import { ProductService } from './product.service';
import { ApiExcludeEndpoint, ApiTags } from '@nestjs/swagger';
@ApiTags('BackOffice')
@Controller('api/v1/product')
export class ProductController {
constructor (private readonly productService: ProductService){}
@Get(':id')
@ApiExcludeEndpoint()
getProduct(@Param('id') id: number){
try {
return this.productService.getProduct(id);
}
catch(error){
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
}
}
@Post('exposeded')
@ApiExcludeEndpoint()
createExposedProduct(@Body() data: any){
try {
return this.productService.createExposededProduct(data);
}
catch(error){
throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
}
}
}

View File

@ -0,0 +1,48 @@
import { Injectable } from '@nestjs/common';
import { connectionOptions } from 'src/configs/typeorm.config';
import { Product } from 'src/domain/entity/tables/pcprodut.entity';
import { Connection, getConnection } from 'typeorm';
@Injectable()
export class ProductService {
async getProduct(id: number) {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const product = await queryRunner.manager
.getRepository(Product)
.createQueryBuilder('pcprodut')
.innerJoinAndSelect('pcprodut.brand', 'brand')
.where("\"pcprodut\".codprod = :id", { id: id })
.getOne();
return product;
} catch (error) {
console.log(error);
throw error;
} finally {
await queryRunner.release();
}
}
async createExposededProduct(data: any) {
const connection = new Connection(connectionOptions);
await connection.connect();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const sqlInsert = `INSERT INTO ESTPRODUTOEXPOSICAO ( CODFILIAL, DATA, CODAUXILIAR )
VALUES ( '4', TRUNC(SYSDATE), ${data.codigoean})`;
await queryRunner.query(sqlInsert);
await queryRunner.commitTransaction();
} catch (err) {
await queryRunner.commitTransaction();
console.log(err);
} finally {
await queryRunner.release();
await connection.close();
}
}
}

View File

@ -0,0 +1,24 @@
import { SectionService } from './section.service';
import { CacheInterceptor, Controller, Get, HttpException, HttpStatus, Param, UseInterceptors } from '@nestjs/common';
import { ApiExcludeEndpoint, ApiTags } from '@nestjs/swagger';
import { ResultModel } from 'src/domain/models/result.model';
@ApiTags('BackOffice')
@Controller('v1/section')
export class SectionController {
constructor(private readonly sectionService: SectionService){}
@Get(':idDepartment')
@UseInterceptors(CacheInterceptor)
@ApiExcludeEndpoint()
async getAll(@Param('idDepartment') idDepartment: number) {
try {
const sections = await this.sectionService.find(idDepartment);
return new ResultModel(true, null, sections, []);
} catch (error) {
throw new HttpException(new ResultModel(false, 'Não foi possível consultar lista de seções', {}, error), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@ -0,0 +1,14 @@
import { CacheModule, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Pcsecao } from 'src/domain/entity/tables/pcsecao.entity';
import { SectionController } from './section.controller';
import { SectionService } from './section.service';
@Module({
imports: [ CacheModule.register(),
TypeOrmModule.forFeature([Pcsecao])],
controllers: [SectionController,],
providers: [SectionService,],
})
export class SectionModule { }

View File

@ -0,0 +1,22 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Pcsecao } from 'src/domain/entity/tables/pcsecao.entity';
import { Repository } from 'typeorm';
@Injectable()
export class SectionService {
constructor( @InjectRepository(Pcsecao)
private sectionRepository: Repository<Pcsecao>){}
async find(idDepartment: number): Promise<Pcsecao[]> {
return await this.sectionRepository
.createQueryBuilder('pcsecao')
.select('"pcsecao".codsec', 'codigoSecao')
.addSelect('concat(concat("pcsecao".codsec, \'-\'),"pcsecao".descricao)', 'descricaoSecao')
//.addSelect('concat(concat(concat("pcsecao".descricao, \' (\'),"pcsecao".codsec),\')\')', 'descricaoSecao')
.where("codepto = :codepto", {codepto: idDepartment})
.getRawMany();
}
}

View File

@ -0,0 +1,32 @@
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { ConnectionOptions } from 'typeorm';
export const typeOrmConfig: TypeOrmModuleOptions = {
type: "oracle",
// host: "192.168.100.40",
// username: "LIVIA",
// password: "LIVIA",
host: "10.1.1.241",
username: "SEVEN",
password: "USR54SEV",
// username: "API",
// password: "E05H5KIEQV3YKDJR",
port: 1521,
sid: "WINT",
synchronize: false,
logging: false,
entities: [__dirname + '/../**/*.entity.{js,ts}'],
autoLoadEntities: true,
};
export const connectionOptions: ConnectionOptions = {
type: "oracle",
host: "10.1.1.241",
username: "SEVEN",
password: "USR54SEV",
port: 1521,
sid: "WINT",
synchronize: false,
logging: false,
entities: [__dirname + '/../**/*.entity.{js,ts}'],
}

View File

@ -0,0 +1,4 @@
export interface Contract {
errors: any[],
validade(model: any): boolean,
}

View File

@ -0,0 +1,19 @@
import { Injectable } from '@nestjs/common';
import { Flunt } from 'src/utils/flunt';
import { DictionaryModel } from './../domain/models/dictionary.model';
import { Contract } from './contract';
@Injectable()
export class CreateDictionaryContract implements Contract {
errors: any[];
validade(model: DictionaryModel): boolean {
const flunt = new Flunt();
flunt.isRequired(model.nick, "Informe a abreviatura do dicionário.");
flunt.hasMinLen(model.word, 5, "Nome do dicionário deve conter no mínimo 5 caracteres.");
this.errors = flunt.errors;
return flunt.errors.length == 0;
}
}

View File

@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { ShippingController } from './services/shipping.controller';
import { ShippingService } from './services/shipping.service';
import { OrdersController } from './orders/orders.controller';
import { OrdersService } from './orders/orders.service';
import { DeliveryOrderController } from './order/delivery-order.controller';
import { DeliveryOrderService } from './order/delivery-order.service';
@Module({
imports: [],
controllers: [ShippingController, OrdersController,
DeliveryOrderController],
providers: [ShippingService, OrdersService, DeliveryOrderService],
})
export class DeliveryModule {}

View File

@ -0,0 +1,47 @@
/*
https://docs.nestjs.com/controllers#controllers
*/
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { DeliveryOrderModel } from 'src/domain/models/delivery-order.model';
import { ImageOrderModel } from 'src/domain/models/image-order.model';
import { PaymentModel } from 'src/domain/models/payment.model';
import { DeliveryOrderService } from './delivery-order.service';
import { ApiExcludeEndpoint } from '@nestjs/swagger';
@Controller('api/v1/deliveryorder')
export class DeliveryOrderController {
constructor(private readonly deliveryOrderSevive: DeliveryOrderService){}
@Get('protocolo/:shipmentId/:customerId')
@ApiExcludeEndpoint()
async getdeliveryByCustomer(@Param("shipmentId") shipmentId: number, @Param("customerId") customerId: number) {
return await this.deliveryOrderSevive.getDataDelivery(shipmentId, customerId);
}
@Post('protocolo')
@ApiExcludeEndpoint()
async createOrReplaceDeliveryByCustomer(@Body() data: DeliveryOrderModel) {
return await this.deliveryOrderSevive.createOrReplaceDeliveryOrder(data);
}
@Get('images/:shipmentId/:orderId')
@ApiExcludeEndpoint()
async getImagesOrder(@Param("shipmentId") shipmentId: number, @Param("orderId") orderId: number) {
return await this.deliveryOrderSevive.getImageOrder(shipmentId, orderId);
}
@Post('image')
@ApiExcludeEndpoint()
async crateImageOrder(@Body() data: ImageOrderModel) {
return await this.deliveryOrderSevive.createImageOrder(data);
}
@ApiExcludeEndpoint()
@Post('payment')
async createPayment(@Body() data: PaymentModel) {
return await this.deliveryOrderSevive.createPayment(data);
}
}

View File

@ -0,0 +1,227 @@
/*
https://docs.nestjs.com/providers#services
*/
import { Injectable } from '@nestjs/common';
import { Estprotocoloentrega } from 'src/domain/entity/tables/estprotocolo.entity';
import { DeliveryOrderModel } from 'src/domain/models/delivery-order.model';
import { ImageOrderModel } from 'src/domain/models/image-order.model';
import { PaymentModel } from 'src/domain/models/payment.model';
import { ResultModel } from 'src/domain/models/result.model';
import { getConnection } from 'typeorm';
import { Estimagemnota } from '../../domain/entity/tables/estimagemnota.entity';
import { Estpagamento } from '../../domain/entity/tables/estpagamento.entity';
@Injectable()
export class DeliveryOrderService {
async getDataDelivery(shipmentId: number, customerId: number): Promise<any> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const result = await queryRunner.manager
.getRepository(Estprotocoloentrega)
.createQueryBuilder('estprotocoloentrega')
.where('numcar = :numcar and codcli = :codcli', { numcar: shipmentId, codcli: customerId})
.getOne();
return result; //new ResultModel(true, 'Registro localizado com sucesso!', result, {});
} catch (error) {
console.log(error);
return new ResultModel(false,
'Erro ao atualizar dados de entrega.',
null,
error);
} finally {
await queryRunner.release();
}
}
async createOrReplaceDeliveryOrder(data: DeliveryOrderModel): Promise<any> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
console.log(data);
try {
const updateDelivery = await queryRunner.manager
.getRepository(Estprotocoloentrega)
.createQueryBuilder('estprotocoloentrega')
.where('numcar = :numcar and codcli = :codcli',
{ numcar: data.numeroCarregamento, codcli: data.codigoCliente})
.getOne();
if ( updateDelivery ) {
await queryRunner.manager
.createQueryBuilder()
.update(Estprotocoloentrega)
.set({
dataEntrega: data.dataEntrega,
cpfRecebedor: data.cpfRecebedor,
nomeRecebedor: data.nomeRecebedor,
urlImagemProtocolo: data.urlImagemProtocolo,
latitude: data.latitude,
longitude: data.longitude,
})
.where('numcar = :numcar and codcli = :codcli', { numcar: data.numeroCarregamento, codcli: data.codigoCliente})
.execute()
} else {
await queryRunner.manager
.createQueryBuilder()
.insert()
.into(Estprotocoloentrega)
.values(data)
.execute()
}
await queryRunner.commitTransaction();
return new ResultModel(true, 'Registro atualizado com sucesso!', data, {});
} catch (error) {
await queryRunner.rollbackTransaction();
console.log(error);
return new ResultModel(false,
'Erro ao atualizar dados de entrega.',
null,
error);
} finally {
await queryRunner.release();
}
}
async getImageOrder(shipmentId: number, orderId: number): Promise<any> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const result = await queryRunner.manager
.getRepository(Estimagemnota)
.createQueryBuilder('estimagemnota')
.select(["numnota as \"numeroNota\"", "numped as \"numeroPedido\", numcar as \"numeroCarregamento\""])
.addSelect(["tipo as \"tipo\", data as \"data\", url as \"url\", latitude as \"latitude\", longitude as \"longitude\" "])
.where('numcar = :numcar and numped = :numped ', { numcar: shipmentId, numped: orderId})
.getRawMany();
return result;
} catch (error) {
console.log(error);
return new ResultModel(false,
'Erro ao atualizar imagens da nota fiscal.',
null,
error);
} finally {
await queryRunner.release();
}
}
async createImageOrder(dataImage: ImageOrderModel): Promise<any> {
console.log(dataImage);
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
//const dateDelivery = '2022-04-14T17:52:00';
//dataImage.data = dateDelivery;
//console.log(dataImage);
await queryRunner.manager
.createQueryBuilder()
.insert()
.into(Estimagemnota)
.values(dataImage)
.execute()
await queryRunner.commitTransaction();
return new ResultModel(true, 'Imagens incluídas com sucesso!', dataImage, {});
} catch (error) {
await queryRunner.rollbackTransaction();
console.log(error);
return new ResultModel(false,
'Erro ao incluir imagens da nota fiscal.',
null,
error);
} finally {
await queryRunner.release();
}
}
async createPayment(payment: PaymentModel): Promise<any> {
console.log(payment);
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
let cobranca = 'PAGV';
switch (payment.formaPagto){
case 'credit_card_parcelado':
cobranca = 'PAGP';
break;
case 'debit_card':
cobranca = 'PAGD';
break;
case 'credit_card':
cobranca = 'PAGV';
break;
default:
cobranca = 'DH';
break;
};
await queryRunner.manager
.createQueryBuilder()
.insert()
.into(Estpagamento)
.values({
orderId: payment.orderId,
dataPagamento: payment.dataPagamento,
codigoAutorizacao: payment.idTransacao,
codigoResposta: '00',
dataRequisicao: payment.dataPagamento,
dataServidor: payment.dataPagamento,
estAcquirer: 'pagseguro',
idTransacao: payment.codigoAutorizacao,
nsu: payment.nsu,
parcelas: payment.parcelas,
valor: payment.valor / 100,
nomeBandeira: 'pagseguro',
formaPagto: payment.formaPagto,
codigoFuncionario: null,
cobranca: cobranca
})
.execute()
await queryRunner.commitTransaction();
return new ResultModel(true, 'Pagamento incluído com sucesso!', {}, {});
} catch (error) {
await queryRunner.rollbackTransaction();
console.log(error);
return new ResultModel(false,
'Erro ao pagamento para carrgamento / cliente.',
null,
error);
} finally {
await queryRunner.release();
}
}
}

View File

@ -0,0 +1,22 @@
import { Controller, Get, Param } from '@nestjs/common';
import { OrdersService } from './orders.service';
import { ApiExcludeEndpoint } from '@nestjs/swagger';
@Controller('api/v1/orders')
export class OrdersController {
constructor(private ordersService: OrdersService){}
@Get('customer/:id')
@ApiExcludeEndpoint()
async getdeliveryByCustomer(@Param("id") id: number) {
return await this.ordersService.GetOrdersByCustomer(id);
}
@Get('payments/:id')
@ApiExcludeEndpoint()
async getPayments(@Param("id") id: number) {
return await this.ordersService.GetPayments(id);
}
}

View File

@ -0,0 +1,127 @@
import { Injectable } from '@nestjs/common';
import { Pcpedc } from 'src/domain/entity/tables/pcpedc.entity';
import { Pcpedi } from 'src/domain/entity/tables/pcpedi.entity';
import { ResultModel } from 'src/domain/models/result.model';
import { getConnection } from 'typeorm';
import { Estpagamento } from '../../domain/entity/tables/estpagamento.entity';
@Injectable()
export class OrdersService {
async GetOrdersByCustomer(id: number): Promise<any> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const user = { matricula: 154969 }; //await this.GetUser(queryRunner); 2854
if (user == null) {
return new ResultModel(false, 'Não foi possível localizar notas para este usuário',
null,
'Não foi localizado motorista para este usuário.');
}
const orders = await queryRunner.manager
.getRepository(Pcpedc)
.createQueryBuilder('pcpedc')
.innerJoinAndSelect('pcpedc.pcclient', 'pcclient')
.innerJoinAndSelect('pcpedc.pccarreg', 'pccarreg',
'pccarreg.codmotorista = :matricula ', //AND pccarreg.dtfecha is null',
{ matricula: user.matricula })
.leftJoinAndSelect('pcpedc.pcclientendent', 'pcclientendent')
.innerJoinAndSelect("pcpedc.pcplpag", "pcplpag")
.select(['pcpedc.numcar as "numeroCarga"',
'NVL(pcpedc.numnota, pcpedc.numcupom) as "numeroNota"',
'pcpedc.dtfat as "dataEmissao"',
'pcpedc.numped as "numeroPedido"',
'TRUNC(pcpedc.vlatend * 100) as "valorNota"',
'pcpedc.codcli as "codigoCliente"',
'pcclient.cliente as "nomeCliente"',
'NVL(pcclientendent.enderent, pcclient.enderent) as "endereco"',
'NVL(pcclientendent.numeroent, pcclient.numeroent) as "numero"',
'NVL(pcclientendent.bairroent, pcclient.bairroent) as "bairro"',
'NVL(pcclientendent.complementoent, pcclient.complementoent) as "complemento"',
'NVL(pcclientendent.municent, pcclient.municent) as "cidade"',
'NVL(pcclientendent.estent, pcclient.estent) as "estado"',
'NVL(pcclientendent.cepent, pcclient.cepent) as "cep"',
'pcclient.pontorefer as "pontoReferencia"',
'pcpedc.codendentcli as "codigoEnderecoEntrega"',
'pcclientendent.telent as "telefoneEntrega"',
'pcclient.telent as "telefoneCliente"',
'pcclient.telcelent as "celularCliente"',
'pcplpag.descricao as "planoPagamento"',
'NVL(\"pcplpag\".NUMPARCELAS,0) as "numeroParcelas"',
'NVL((select sum(trunc(pccrecli.valor*100)) from pccrecli where pccrecli.numtransvendadesc = \"pcpedc\".numtransvenda),0) as "valorCreditos"',
'NVL((select sum(trunc(pcestcom.vldevolucao*100)) from pcestcom where pcestcom.numtransvenda = \"pcpedc\".numtransvenda),0) as "valorDevolucoes"',
'NVL((select sum(trunc(estpagamento.valor*100)) from estpagamento where estpagamento.numorca = \"pcpedc\".numped),0) as "valorRecebimentos"',
'NVL((select count(1) from estimagemnota where estimagemnota.numped = \"pcpedc\".numped and estimagemnota.tipo = \'P\'),0) as "notaComImagens"',
'NVL((select count(1) from estimagemnota where estimagemnota.numped = \"pcpedc\".numped and estimagemnota.tipo = \'C\'),0) as "notaComProtocolo"',
'NVL((select count(1) from estprotocoloentrega where estprotocoloentrega.numcar = \"pcpedc\".numcar and estprotocoloentrega.codcli = pcpedc.codcli),0) as "notaComDadosRecebedor"',
])
.addSelect(subQuery => {
return subQuery
.select('count(distinct item.codfilialretira)', 'lojas')
.from(Pcpedi, 'item')
.where('item.numped = pcpedc.numped and item.codfilialretira <> pcpedc.codfilial')
}, 'lojas')
.where("pcpedc.posicao = 'F'")
.andWhere("pcpedc.codcli = :codcli", { codcli: id })
.getRawMany();
return orders;
} catch (error) {
console.log(error);
return new ResultModel(false,
'Erro ao consultar notas fiscais.',
null,
error);
} finally {
await queryRunner.release();
}
}
async GetPayments(id: number) {
// const user = await this.GetUser(queryRunner);
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
const payments = await queryRunner.manager
.getRepository(Estpagamento)
.createQueryBuilder('estpagamento')
.select(['\"estpagamento\".numorca as "orderId"',
'TRUNC(\"estpagamento\".valor * 100) as "valor"',
'\"estpagamento\".nsu as "nsu"',
'\"estpagamento\".dtpagamento as "dataPagamento"',
'\"estpagamento\".codautorizacao as "codigoAutorizacao"',
'\"estpagamento\".idtransacao as "idTransacao"',
'\"estpagamento\".parcelas as "parcelas"',
'\"estpagamento\".formapagto as "formaPagto"',
])
.innerJoin('estpagamento.pedido', 'pcpedc')
.innerJoin('pcpedc.pcclient', 'pcclient')
//.innerJoin('pcpedc.pccarreg', 'pccarreg',
// 'pccarreg.codmotorista1 = :matricula ', //AND pccarreg.dtfecha is null',
// { matricula: user.matricula })
.where('\"pcpedc\".codcli = :id', { id })
.getRawMany()
return payments;
} catch (error) {
console.log(error);
return new ResultModel(false,
'Erro ao consultar pagamentos.',
null,
error);
} finally {
await queryRunner.release();
}
}
}

View File

@ -0,0 +1,29 @@
import { Controller, Get, Param } from '@nestjs/common';
import { ShippingService } from './shipping.service';
import { ApiExcludeEndpoint } from '@nestjs/swagger';
@Controller('api/v1/shipping')
export class ShippingController {
constructor(private shippingService: ShippingService){}
@Get('customer')
@ApiExcludeEndpoint()
async getdeliveryByCustomer() {
return await this.shippingService.GetShippingsByCustomer();
}
@Get('collect/shop')
@ApiExcludeEndpoint()
async getCollectbyShop() {
return await this.shippingService.GetCollectByShop();
}
@Get('collect/customer/:id')
@ApiExcludeEndpoint()
async getCollectbyCustomer(@Param('id') id: string) {
return await this.shippingService.GetCollectByCustomer(id);
}
}

View File

@ -0,0 +1,161 @@
import { Injectable } from '@nestjs/common';
import { Esventregasporcliente } from 'src/domain/entity/views/esventregasporcliente.entity';
import { Connection, getConnection } from 'typeorm';
import { ResultModel } from '../../domain/models/result.model';
import { Esvretiralojascliente } from '../../domain/entity/views/esventregaslojascliente.entity';
import { EsvRetiraLojas } from '../../domain/entity/views/esvretiralojas.entity';
@Injectable()
export class ShippingService {
constructor(private connection: Connection) { }
async GetShippingsByCustomer(): Promise<any> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
/*const user = await this.GetUser(queryRunner);
if (user == null) {
return new ResultModel(false, 'Não foi possível localizar entregas para este usuário',
null,
'Não foi localizado motorista para este usuário.');
}*/
const deliveries = await queryRunner.manager
.getRepository(Esventregasporcliente)
.createQueryBuilder('ESVENTREGASPORCLIENTE')
.select(['cliente as "nomeCliente"'
, 'cgcent as "cnpj_cpf"'
, 'email as "email"'
, 'endereco as "endereco"'
, 'numero as "numero"'
, 'bairro as "bairro"'
, 'complemento as "complemento"'
, 'cidade as "cidade"'
, 'estado as "uf"'
, 'cep as "cep"'
, 'qtpedidos as "quantidadePedidos"'
, 'qtlojas as "quantidaeLojas"'
, 'entrega_concluida as "entregaConcluida"'
, 'telefone as "telefoneCliente"'
, 'celular as "celularCliente"'
, 'codcli as "codigoCliente"'])
.where("email = 'eduardoestevao.gyn@gmail.com'")
.getRawMany();
return deliveries;
} catch (error) {
console.log(error);
return new ResultModel(false, 'Não foi possível consultar as entregas por cliente.',
null,
error);
} finally {
await queryRunner.release();
}
}
async GetCollectByShop(): Promise<any> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
/*const user = await this.GetUser(queryRunner);
if (user == null) {
return new ResultModel(false, 'Não foi possível localizar entregas para este usuário',
null,
'Não foi localizado motorista para este usuário.');
}*/
const deliveries = await queryRunner.manager
.getRepository(EsvRetiraLojas)
.createQueryBuilder('ESVRETIRALOJAS')
.select(['codigo as "codigoLoja"'
, 'razaosocial as "razaoSocial"'
, 'quantidadepedidos as "quantidadePedidos"'
])
.where("email = 'eduardoestevao.gyn@gmail.com'")
.getRawMany();
return deliveries;
} catch (error) {
console.log(error);
return new ResultModel(false, 'Não foi possível consultar as coletas por loja.',
null,
error);
} finally {
await queryRunner.release();
}
}
async GetCollectByCustomer(id: string): Promise<any> {
const connection = getConnection();
const queryRunner = connection.createQueryRunner();
await queryRunner.connect();
try {
/*const user = await this.GetUser(queryRunner);
if (user == null) {
return new ResultModel(false, 'Não foi possível localizar entregas para este usuário',
null,
'Não foi localizado motorista para este usuário.');
}*/
const deliveries = await queryRunner.manager
.getRepository(Esvretiralojascliente)
.createQueryBuilder('ESVRETIRALOJASCLIENTE')
.select([
'codfilial as "codigoFilial"'
,'numped as "numeroPedido"'
,'numnota as "numeroNota"'
,'dtfat as "dataFaturamento"'
,'datapedido as "dataPedido"'
,'codcli as "codigoCliente"'
,'cliente as "nomeCliente"'
,'codfilialretira as "codigoLoja"'
,'razaosocial as "nomeLoja"'
,'qtitens as "quantidadeItens"'
,'quantidade as "quantidade"'
])
.where("email = 'eduardoestevao.gyn@gmail.com'")
.andWhere("codfilial = :codfilial", {codfilial: id})
.getRawMany();
return deliveries;
} catch (error) {
console.log(error);
return new ResultModel(false, 'Não foi possível consultar as coletas por cliente.',
null,
error);
} finally {
await queryRunner.release();
}
}
}

View File

@ -0,0 +1,50 @@
CREATE OR REPLACE VIEW ESVPRODUTOSVENDA
AS
SELECT ROWNUM SEQ, PCPRODUT.CODPROD, PCPRODUT.DESCRICAO, PCPRODUT.NOMEECOMMERCE, PCPRODUT.CODFAB,
PCPRODUT.CODAUXILIAR, CASE WHEN PCPRODUT.TIPOPRODUTO = 'S' THEN 'SHOWROOM'
WHEN PCPRODUT.TIPOPRODUTO = 'A' THEN 'AUTOSSERVICO'
ELSE 'NÃO DEFINIDO' END TIPOPRODUTO,
PCPRODUT.DADOSTECNICOS, PCPRODUT.INFORMACOESTECNICAS, PCPRODUT.URLIMAGEM,
PCPRODUT.ENVIAECOMMERCE, PCPRODUT.CODMARCA CODIGOMARCA, PCMARCA.MARCA NOMEMARCA,
PCPRODUT.CODEPTO CODIGODEPARTAMENTO, PCDEPTO.DESCRICAO NOMEDEPARTAMENTO,
PCPRODUT.CODSEC CODIGOSECAO, PCSECAO.DESCRICAO NOMESECAO,
PCPRODUT.CODCATEGORIA CODIGOCATEGORIA, PCCATEGORIA.CATEGORIA NOMECATEGORIA,
PCPRODUT.CODFORNEC, PCFORNEC.FORNECEDOR NOMEFORNECEDOR, PCPRODFILIAL.CLASSEESTOQUE,
PCPRODFILIAL.CLASSEVENDA, PCPRODFILIAL.CODFILIAL CODIGOFILIAL
FROM PCPRODUT, PCDEPTO, PCSECAO, PCCATEGORIA, PCMARCA, PCFORNEC, PCPRODFILIAL
WHERE PCPRODUT.DTEXCLUSAO IS NULL
AND NVL(PCPRODUT.OBS,'X') <> 'PV'
AND PCPRODUT.CODEPTO = PCDEPTO.CODEPTO
AND PCPRODUT.CODSEC = PCSECAO.CODSEC
AND PCPRODUT.CODPROD = PCPRODFILIAL.CODPROD
AND PCPRODUT.CODSEC = PCCATEGORIA.CODSEC (+)
AND PCPRODUT.CODCATEGORIA = PCCATEGORIA.CODCATEGORIA (+)
AND PCPRODUT.CODFORNEC = PCFORNEC.CODFORNEC (+)
AND PCPRODUT.CODMARCA = PCMARCA.CODMARCA (+) ;
CREATE OR REPLACE VIEW ESVPRECOVENDA
AS
SELECT PCTABPR.NUMREGIAO NUMEROREGIAO
,PCTABPR.CODPROD
,PCTABPR.PVENDA1 PRECOVENDA
,( SELECT PCPRECOPROM.PRECOFIXO
FROM PCPRECOPROM
WHERE PCPRECOPROM.NUMREGIAO = PCTABPR.NUMREGIAO
AND PCPRECOPROM.CODPROD = PCTABPR.CODPROD
AND TRUNC(SYSDATE) BETWEEN PCPRECOPROM.DTINICIOVIGENCIA AND PCPRECOPROM.DTFIMVIGENCIA ) PRECOOFERTA
FROM PCTABPR
WHERE PCTABPR.PVENDA > 0
AND NVL(PCTABPR.EXCLUIDO, 'N') = 'N';
CREATE OR REPLACE VIEW ESVESTOQUEVENDA
AS
SELECT PCEST.CODFILIAL, PCEST.CODPROD,
( NVL(PCEST.QTESTGER,0) - NVL(PCEST.QTRESERV,0) - NVL(PCEST.QTBLOQUEADA,0) - NVL(PCEST.QTPENDENTE,0) ) QUANTIDADEESTOQUEDISPONIVEL,
( SELECT MIN(PCPEDIDO.dtprevent) FROM PCITEM, PCPEDIDO
WHERE PCITEM.NUMPED = PCPEDIDO.NUMPED
AND ( PCITEM.QTPEDIDA - NVL(PCITEM.QTENTREGUE,0) ) > 0
AND PCITEM.CODPROD = PCEST.CODPROD ) DATAPREVISAOENTREGA
FROM PCEST
WHERE PCEST.CODFILIAL <> '99';

View File

@ -0,0 +1,15 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity("ESTABREVIATURA")
export class EstAbreviatura {
@PrimaryColumn({ name: 'ID' })
id: number;
@Column({ name: 'ABREVIATURA' })
abreviatura: string;
@Column({ name: 'PALAVRA' })
palavra: string;
}

View File

@ -0,0 +1,33 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity('ESTAVISOESTOQUE')
export class Estavisoestoque {
@PrimaryColumn({name: 'ID'})
id: number;
@Column({name: 'DTINCLUSAO'})
createDate: Date;
@Column({name: 'CODUSUR'})
codusur: number;
@Column({name: 'CPFCNPJ'})
cpf: string;
@Column({name: 'NOME'})
name: string;
@Column({name: 'CELULAR'})
cellPhone: string;
@Column({name: 'EMAIL'})
email: string;
@Column({name: 'CODPROD'})
codprod: number;
@Column({name: 'OBSERVACAO'})
obs: string;
}

View File

@ -0,0 +1,10 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity('ESTCATEGORIACLIENTE')
export class Estcategoriacliente {
@PrimaryColumn({name: 'ID'})
id: number;
@Column({name: 'DESCRICAO'})
name: string;
}

View File

@ -0,0 +1,18 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity('ESTCATEGORIAPARCEIRO')
export class Estcategoriaparceiro {
@PrimaryColumn({name: 'ID'})
id: number;
@Column({name: 'TIPO'})
tipo: string;
@Column({name: 'DESCRICAO'})
descricao: string;
@Column({name: 'TIPOPAGTO'})
tipopagto: string;
}

View File

@ -0,0 +1,33 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity('ESTFAIXAPARCEIRO')
export class Estfaixaparceiro {
@PrimaryColumn({name: 'ID'})
id: number;
@Column({name: 'TIPO'})
tipo: string;
@Column({name: 'FAIXAINI'})
faixaIni: number;
@Column({name: 'FAIXAFIM'})
faixaFim: number;
@Column({name: 'PERCCOMISSAO'})
percComissao: number;
@Column({name: 'DTCADASTRO'})
dtCadastro: Date;
@Column({name: 'CODFUNCCAD'})
codfunccad: number;
@Column({name: 'DTALTERACAO'})
dtAlteracao: Date;
@Column({name: 'CODFUNCALT'})
codfuncalt: number;
}

View File

@ -0,0 +1,30 @@
import { Column, Entity, PrimaryColumn } from 'typeorm';
@Entity('ESTIMAGEMNOTA')
export class Estimagemnota {
@PrimaryColumn({name: 'NUMPED'})
numeroPedido: number;
@Column({name: 'NUMNOTA'})
numeroNota: number;
@Column({name: 'NUMCAR'})
numeroCarregamento: number;
@Column({name: 'DATA'})
data: Date;
@Column({name: 'TIPO'})
tipo: string;
@Column({name: 'URL'})
url: string;
@Column({name: 'LATITUDE'})
latitude: number;
@Column({name: 'LONGITUDE'})
longitude: number;
}

View File

@ -0,0 +1,21 @@
import { PrimaryColumn, Column, Entity } from "typeorm";
@Entity("ESTMEDIDAPRODUTO")
export class Estmedidaproduto {
@PrimaryColumn({name: 'IDMEDIDAPRODUTO'})
idmedidaproduto: number;
@Column({name: 'DESCRICAO'})
descricao: string;
@Column({name: 'ABREVIATURA'})
abreviatura: string;
@Column({name: 'QUANTIDADE'})
quantidade: number;
@Column({name: 'NIVEL'})
nivel: number;
}

View File

@ -0,0 +1,56 @@
import { Column, Entity, JoinColumn, ManyToOne, PrimaryColumn } from "typeorm";
import { Pcpedc } from "./pcpedc.entity";
@Entity('ESTPAGAMENTO')
export class Estpagamento {
@PrimaryColumn({ name: 'NUMORCA' })
orderId: number;
@PrimaryColumn({ name: 'DTPAGAMENTO' })
dataPagamento: Date;
@Column({ name: 'CODAUTORIZACAO' })
codigoAutorizacao: string;
@Column({ name: 'CODRESPOSTA' })
codigoResposta: string;
@Column({ name: 'DTREQUISICAO' })
dataRequisicao: Date;
@Column({ name: 'DTSERVIDOR' })
dataServidor: Date;
@Column({ name: 'ESTACQUIRER' })
estAcquirer: string;
@Column({ name: 'IDTRANSACAO' })
idTransacao: string;
@Column({ name: 'NSU' })
nsu: string;
@Column({ name: 'PARCELAS' })
parcelas: number;
@Column({ name: 'VALOR' })
valor: number;
@Column({ name: 'NOMEBANDEIRA' })
nomeBandeira: string;
@Column({ name: 'FORMAPAGTO' })
formaPagto: string;
@Column({ name: 'CODFUNC' })
codigoFuncionario: number;
@Column({ name: 'CODCOB' })
cobranca: string;
@ManyToOne(() => Pcpedc, pcpedc => pcpedc.pagamentos)
@JoinColumn({ name: 'NUMORCA' })
pedido: Pcpedc;
}

View File

@ -0,0 +1,108 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity('ESTPARCEIRO')
export class Estparceiro {
@PrimaryColumn({ name: 'ID'})
public id: number;
@Column({name: 'TIPO'})
public tipo: string;
@Column({name: 'CPF'})
public cpf: string;
@Column({name: 'NOME'})
public nome: string;
@Column({name: 'RG'})
public rg: string;
@Column({name: 'ORGAOEXP'})
public orgaoexp: string;
@Column({name: 'REGPROFISSIONAL'})
public regprofissional: string;
@Column({name: 'CEP'})
public cep: string;
@Column({name: 'CODIBGE'})
public codibge: string;
@Column({name: 'ENDERECO'})
public endereco: string;
@Column({name: 'NUMERO'})
public numero: string;
@Column({name: 'COMPLEMENTO'})
public complemento: string;
@Column({name: 'BAIRRO'})
public bairro: string;
@Column({name: 'CIDADE'})
public cidade: string;
@Column({name: 'ESTADO'})
public estado: string;
@Column({name: 'TELEFONE'})
public telefone: string;
@Column({name: 'EMAIL'})
public email: string;
@Column({name: 'CHAVEPIX'})
public chavepix: string;
@Column({name: 'BANCO'})
public banco: string;
@Column({name: 'AGENCIA'})
public agencia: string;
@Column({name: 'CONTA'})
public conta: string;
@Column({name: 'CODUSUR'})
public codusur: number;
@Column({name: 'CODUSURPARCEIRO'})
public codusurparceiro: number;
@Column({name: 'COMPRADORPJ'})
public compradorPj: string;
@Column({name: 'CODCLI'})
public codcli: number;
@Column({name: 'CODCATEGORIA'})
public codcategoria: number;
@Column({name: 'CODPRACA'})
public codpraca: number;
@Column({name: 'OBSERVACAO'})
public observacao: string;
@Column({name: 'OBSERVACAO2'})
public observacao2: string;
@Column({name: 'PERCCOMISSAO'})
public perccomissao: number;
@Column({name: 'CODFUNCCADASTRO'})
public codfunccadastro: number;
@Column({name: 'DTCADASTRO'})
public dtcadastro: Date;
@Column({name: 'CODFUNCALTERACAO'})
public codfuncalteracao: number;
@Column({name: 'DTALTERACAO'})
public dtalteracao: Date;
}

View File

@ -0,0 +1,63 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity('ESTPREVENDAC')
export class Shopping {
@PrimaryColumn({ name: 'ID' })
id: string;
@Column({ name: 'CODFILIAL' })
store: string;
@Column({ name: 'DATA' })
data: Date;
@Column({ name: 'CODUSUR' })
codusur: number;
@Column({ name: 'CODCLI' })
codcli: number;
@Column({ name: 'CODENDENTCLI' })
codendentcli: number;
@Column({ name: 'CODPLPAG' })
codplpag: number;
@Column({ name: 'CODCOB' })
codcob: string;
@Column({ name: 'VLPEDIDO' })
vlpedido: number;
@Column({ name: 'VLTABELA' })
vltabela: number;
@Column({ name: 'VLDESCONTO' })
vldesconto: number;
@Column({name: 'VLCUSTOFIN'})
vlcustofin: number;
@Column({ name: 'CODFUNCAUTOR' })
codfuncautor: number;
@Column({ name: 'VLTAXAENTREGA', type: "decimal", precision: 10, scale: 2, default: 0 })
vltaxaentrega: number;
@Column({ name: 'NUMORCA' })
numorca: number;
@Column({ name: 'NUMPED' })
numped: number;
@Column({ name: 'TOTPESO' })
totpeso: number;
@Column({ name: 'CODFORNECFRETE' })
codfornecfrete: number;
@Column({ name: 'CODTABELAFRETE' })
codtabelafrete: number;
}

View File

@ -0,0 +1,117 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity("ESTPREVENDAI")
export class ShoppingItens {
@PrimaryColumn({name: 'ID'})
id: string;
@Column({name: 'IDCART'})
idCart: string;
@Column({name: 'NUMSEQ'})
numSeq: number;
@Column({name: 'CODPROD'})
idProduct: number;
@Column({name: 'CODAUXILIAR'})
ean: number;
@Column({name: 'QT'})
quantity: number;
@Column({name: 'PTABELA'})
listPrice: number;
@Column({name: 'PERCDESC'})
discount: number;
@Column({name: 'VLDESCONTO'})
discountValue: number;
@Column({name: 'PVENDA'})
price: number;
@Column({name: 'VLCUSTOFIN'})
cost: number;
@Column({name: 'DTINCLUSAO', select: false})
createDate: Date;
@Column({name: 'CODFUNC', select: false})
idUser: Date;
@Column({name: 'DTCANCEL', select: false})
cancelDate: Date;
@Column({name: 'DATAVENDA', select: false})
orderDate: Date;
@Column({name: 'NUMPED', select: false})
orderId: number;
@Column({name: 'NOMEECOMMERCE'})
description: string;
@Column({name: 'URLIMAGEM'})
image: string;
@Column({name: 'TIPOPRODUTO'})
productType: string;
@Column({name: 'TIPOENTREGA'})
deliveryType: string;
@Column({name: 'CODFILIALRETIRA'})
stockStore: string;
@Column({name: 'CODUSUR'})
seller: number;
@Column({name: 'PRECOPROMOCAO'})
promotion: number;
@Column({name: 'CODFUNCDESC'})
userDiscount: number;
@Column({name: 'MULTIPLO'})
mutiple: number;
@Column({name: 'DESCRICAOAUXILIAR'})
auxDescription: string;
@Column({name: 'DESCRICAO'})
smallDescription: string;
@Column({name: 'MARCA'})
brand: string;
@Column({name: 'PERCACRESCIMO'})
percentUpQuantity: number;
@Column({name: 'QTACRESCIMO'})
upQuantity: number;
@Column({name: 'BASETINTOMETRICO'})
base: string;
@Column({name: 'LETRATINTOMETRICO'})
letter: string;
@Column({name: 'LINHATINTOMETRICO'})
line: string;
@Column({name: 'CORTINTOMETRICO'})
color: string;
@Column({name: 'LITRAGEM'})
can: number;
@Column({name: 'AMBIENTE'})
environment: string;
@Column({name: 'PRODUTOCOMPREJUNTO'})
productTogether: string;
}

View File

@ -0,0 +1,30 @@
import { Column, Entity, PrimaryColumn } from 'typeorm';
@Entity("ESTPROTOCOLOENTREGA")
export class Estprotocoloentrega {
@PrimaryColumn({name: 'NUMCAR'})
numeroCarregamento: number;
@Column({name: 'CODCLI'})
codigoCliente: number;
@Column({name: 'DTENTREGA'})
dataEntrega: Date;
@Column({name: 'CPFRECEBEDOR'})
cpfRecebedor: string;
@Column({name: 'NOMERECEBEDOR'})
nomeRecebedor: string;
@Column({name: 'URL_IMAGEMPROTOCOLO'})
urlImagemProtocolo: string;
@Column({name: 'LATITUDE'})
latitude: number;
@Column({name: 'LONGITUDE'})
longitude: number;
}

View File

@ -0,0 +1,58 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity('ESTRUPTURA')
export class Estruptura {
@PrimaryColumn({name: 'ID'})
id: number;
@Column({name: 'DATA'})
date: Date;
@Column({name: 'CODFILIAL'})
store: string;
@Column({name: 'CODCLI'})
customerId: number;
@Column({name: 'CPF_CNPJ'})
document: string;
@Column({name: 'NOME'})
name: string;
@Column({name: 'CELULAR'})
cellPhone: string;
@Column({name: 'EMAIL'})
email: string;
@Column({name: 'CODUSUR'})
sellerId: number;
@Column({name: 'CODPROD'})
productId: number;
@Column({name: 'QT'})
quantity: number;
}
/* --Script criação tabela
CREATE TABLE ESTRUPTURA (
ID NUMBER(10),
DATA DATE,
CODFILIAL VARCHAR2(2),
CODCLI NUMBER(6),
CPF_CNPJ VARCHAR2(20),
NOME VARCHAR2(100),
CELULAR VARCHAR2(20),
EMAIL VARCHAR2(100),
CODUSUR NUMBER(6),
CODPROD NUMBER(6),
QT NUMBER(22,6) );
CREATE SEQUENCE ESSRUPTURA;
*/

View File

@ -0,0 +1,14 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity('ESTSUBCATEGORIACLIENTE')
export class Estsubcategoriacliente {
@PrimaryColumn({name: 'ID'})
id: number;
@Column({name: 'CATEGORIAID'})
categoryId: number;
@Column({name: 'DESCRICAO'})
name: string;
}

View File

@ -0,0 +1,56 @@
import { Pccest } from './pccest.entity';
import { Pccategoria } from './pccategoria.entity';
import { Pcdepto } from 'src/domain/entity/tables/pcdepto.entity';
import { PrimaryColumn, Entity, Column, ManyToOne, JoinColumn } from "typeorm";
import { Pcncm } from './pcncm.entity';
import { Pcsecao } from './pcsecao.entity';
@Entity("ESTTIPOPRODUTO")
export class Esttipoproduto {
@PrimaryColumn({name: 'IDTIPOPRODUTO'})
idTipoProduto: number;
@Column({name: 'NCM'})
ncm: string;
@ManyToOne(() => Pcncm, itemNcm => itemNcm.tiposProduto)
@JoinColumn({ name: 'NCM' })
registroNcm: Pcncm;
@Column({name: 'TIPOPRODUTO'})
tipoProduto: string;
@Column({name: 'SIGLAPRODUTO'})
sigla: string;
@Column({name: 'CODEPTO'})
codigoDepartamento: number;
@Column({name: 'CODSEC'})
codigoSecao: number;
@Column({name: 'CODCATEGORIA'})
codigoCategoria: number;
@Column({name: 'CEST'})
cest: number;
@ManyToOne(() => Pcdepto, departamento => departamento.tiposProduto)
@JoinColumn({ name: 'CODEPTO' })
departamento: Pcdepto;
@ManyToOne(() => Pcsecao, secao => secao.tiposProduto)
@JoinColumn({ name: 'CODSEC' })
secao: Pcsecao;
@ManyToOne(() => Pccategoria, categoria => categoria.tiposProduto)
@JoinColumn({ name: 'CODCATEGORIA' })
categoria: Pccategoria;
@ManyToOne(() => Pccest, itemCest => itemCest.tiposProduto)
@JoinColumn({ name: 'CEST' })
registrocest: Pccest;
}

View File

@ -0,0 +1,27 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity('ESTUSUARIO')
export class User {
@PrimaryColumn({name: 'IDUSUARIO'})
id: number;
@Column({name: 'NOME'})
username: string;
@Column({name: 'EMAIL'})
email: string;
@Column({name: 'SENHA', select: false})
password: string;
@Column({name: 'TIPO'})
role: string;
@Column({name: 'BLOQUEADO'})
blocked: string;
@Column({name: 'MATRICULA'})
registration: string;
}

View File

@ -0,0 +1,44 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity('ESTVENDA')
export class Sale {
@PrimaryColumn({ name: 'ID' })
id: string;
@Column({ name: 'CODCLI' })
codcli: number;
@Column({ name: 'CODUSUR' })
codusur: number;
@Column({ name: 'CODENDCLI' })
codendcli: number;
@Column({ name: 'CODPLPAG' })
codplpag: number;
@Column({ name: 'CODCOB' })
codcob: string;
@Column({ name: 'OBSERVACAO1' })
observacao1: string;
@Column({ name: 'OBSERVACAO2' })
observacao2: string;
@Column({ name: 'OBSERVACAO3' })
observacao3: string;
@Column({ name: 'OBSERVACAOENTREGA1' })
observacaoentrega1: string;
@Column({ name: 'OBSERVACAOENTREGA2' })
observacaoentrega2: string;
@Column({ name: 'OBSERVACAOENTREGA3' })
observacaoentrega3: string;
@Column({ name: 'VLFRETE' })
vlfrete: number;
}

View File

@ -0,0 +1,27 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity('ESTVENDAPRECLIENTE')
export class Estvendaprecliente {
@PrimaryColumn({ name: 'ID'})
id: number;
@Column({ name: 'IDCART'})
idcart: string;
@Column({ name: 'CPF'})
cpf: string;
@Column({ name: 'NOME'})
nome: string;
@Column({ name: 'TELEFONE'})
telefone: string;
@Column({ name: 'CODUSUR'})
codusur: number;
@Column({ name: 'DTCADASTRO'})
dtcadastro: Date;
}

View File

@ -0,0 +1,15 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity("PCCAIXA")
export class Checkout {
@PrimaryColumn({name: "NUMCAIXA"})
id: number;
@Column({name: "DESCRICAO"})
description: string;
@Column({name: "NUMSERIEEQUIP"})
serialNumber: string;
}

View File

@ -0,0 +1,421 @@
import { Pcpedc } from './pcpedc.entity';
import { Pcempr } from './pcempr.entity';
import { Entity, Column, PrimaryColumn, OneToMany, OneToOne, JoinColumn } from "typeorm";
import { Pcnfsaid } from "./pcnfsaid.entity";
@Entity('PCCARREG')
export class Pccarreg {
@PrimaryColumn({ name: 'NUMCAR' })
numcar: number;
@Column({ name: 'DTSAIDA' })
dtsaida: Date;
@Column({ name: 'CODMOTORISTA' })
codmotorista: number;
@Column({ name: 'CODVEICULO' })
codveiculo: number;
@Column({ name: 'TOTPESO' })
totpeso: number;
@Column({ name: 'TOTVOLUME' })
totvolume: number;
@Column({ name: 'VLTOTAL' })
vltotal: number;
@Column({ name: 'DTFECHA' })
dtfecha: Date;
@Column({ name: 'DESTINO' })
destino: string;
@Column({ name: 'NUMNOTAS' })
numnotas: number;
@Column({ name: 'CODCAIXA' })
codcaixa: number;
@Column({ name: 'PERCOM' })
percom: number;
@Column({ name: 'NUMENT' })
nument: number;
@Column({ name: 'NUMCID' })
numcid: number;
@Column({ name: 'PREVCHEG' })
prevcheg: Date;
@Column({ name: 'DTRETORNO' })
dtretorno: Date;
@Column({ name: 'CODCONF' })
codconf: number;
@Column({ name: 'DT_CANCEL' })
dt_cancel: Date;
@Column({ name: 'DATAMON' })
datamon: Date;
@Column({ name: 'CODFUNCMON' })
codfuncmon: number;
@Column({ name: 'DATAMAPA' })
datamapa: Date;
@Column({ name: 'CODFUNCMAPA' })
codfuncmapa: number;
@Column({ name: 'NUMVIASMAPA' })
numviasmapa: number;
@Column({ name: 'DTCAIXA' })
dtcaixa: Date;
@Column({ name: 'DTFAT' })
dtfat: Date;
@Column({ name: 'CODFUNCFAT' })
codfuncfat: number;
@Column({ name: 'CODFUNCCANCEL' })
codfunccancel: number;
@Column({ name: 'DATACONF' })
dataconf: Date;
@Column({ name: 'QTITENS' })
qtitens: number;
@Column({ name: 'OBSFATUR' })
obsfatur: string;
@Column({ name: 'TIPOCARGA' })
tipocarga: string;
@Column({ name: 'KMINICIAL' })
kminicial: number;
@Column({ name: 'KMFINAL' })
kmfinal: number;
@Column({ name: 'DTSAIDAVEICULO' })
dtsaidaveiculo: Date;
@Column({ name: 'CODROTAPRINC' })
codrotaprinc: number;
@Column({ name: 'NUMDIARIAS' })
numdiarias: number;
@Column({ name: 'CODFUNCAJUD' })
codfuncajud: number;
@Column({ name: 'PAGCOMMOTMIN' })
pagcommotmin: string;
@Column({ name: 'VLVALERETENCAO' })
vlvaleretencao: number;
@Column({ name: 'HORAFECHA' })
horafecha: number;
@Column({ name: 'MINUTOFECHA' })
minutofecha: number;
@Column({ name: 'NUMCAROL' })
numcarol: number;
@Column({ name: 'CONHECFRETE' })
conhecfrete: string;
@Column({ name: 'NUMCAROPERLOG' })
numcaroperlog: number;
@Column({ name: 'DTFECHACOMISSMOT' })
dtfechacomissmot: Date;
@Column({ name: 'QTCOMBUSTIVEL' })
qtcombustivel: number;
@Column({ name: 'BALCAOBAIXADO' })
balcaobaixado: string;
@Column({ name: 'OBSDESTINO' })
obsdestino: string;
@Column({ name: 'VLFRETE' })
vlfrete: number;
@Column({ name: 'ABASTECIDO' })
abastecido: string;
@Column({ name: 'MAPAGERADOWMS' })
mapageradowms: string;
@Column({ name: 'CONHECGERADO' })
conhecgerado: string;
@Column({ name: 'MAPAGERADOWMSPAL' })
mapageradowmspal: string;
@Column({ name: 'VLCOMBUSTIVEL' })
vlcombustivel: number;
@Column({ name: 'NUMCARWMS' })
numcarwms: number;
@Column({ name: 'QTCAIXAS' })
qtcaixas: number;
@Column({ name: 'HORAMON' })
horamon: number;
@Column({ name: 'MINUTOMON' })
minutomon: number;
@Column({ name: 'DTINICIOCHECKOUT' })
dtiniciocheckout: Date;
@Column({ name: 'DTFIMCHECKOUT' })
dtfimcheckout: Date;
@Column({ name: 'DATAHORAMAPA' })
datahoramapa: Date;
@Column({ name: 'NUMCARBROKER' })
numcarbroker: number;
@Column({ name: 'PERCOMTERC' })
percomterc: number;
@Column({ name: 'PERCOMAJUD' })
percomajud: number;
@Column({ name: 'TIPOCOMISSAO' })
tipocomissao: string;
@Column({ name: 'NUMLANCDIARIA' })
numlancdiaria: number;
@Column({ name: 'CARGASECUNDARIA' })
cargasecundaria: string;
@Column({ name: 'LACRE' })
lacre: string;
@Column({ name: 'VLDIARIA' })
vldiaria: number;
@Column({ name: 'VLDESPAJUDANTE' })
vldespajudante: number;
@Column({ name: 'DATACONFFIM' })
dataconffim: Date;
@Column({ name: 'DTINICIALPEND' })
dtinicialpend: Date;
@Column({ name: 'DTFINALPEND' })
dtfinalpend: Date;
@Column({ name: 'FROTA_PESO' })
frota_peso: number;
@Column({ name: 'CODMOTTRANSBORDO' })
codmottransbordo: number;
@Column({ name: 'CODAJUDTRANSBORDO' })
codajudtransbordo: number;
@Column({ name: 'LANCTOCPAGARFECHCOMISS414' })
lanctocpagarfechcomiss414: string;
@Column({ name: 'DTFECHACOMMOTTRANSB' })
dtfechacommottransb: Date;
@Column({ name: 'DTFECHACOMAJUDTRANSB' })
dtfechacomajudtransb: Date;
@Column({ name: 'DTFECHACOMAJUD' })
dtfechacomajud: Date;
@Column({ name: 'CODFUNCMAPACARAGRUPADO' })
codfuncmapacaragrupado: number;
@Column({ name: 'DATAHORAMAPACARAGRUPADO' })
datahoramapacaragrupado: Date;
@Column({ name: 'NUMCARAGRUPADO' })
numcaragrupado: number;
@Column({ name: 'NUMVIASCARAGRUPADO' })
numviascaragrupado: number;
@Column({ name: 'CODMOTORISTACARAGRUPADO' })
codmotoristacaragrupado: number;
@Column({ name: 'CODVEICULCARAGRUPADO' })
codveiculcaragrupado: number;
@Column({ name: 'DATACARAGRUPADO' })
datacaragrupado: Date;
@Column({ name: 'TRANSFERENCIA' })
transferencia: string;
@Column({ name: 'SEGURADA' })
segurada: string;
@Column({ name: 'CODFILIALSAIDA' })
codfilialsaida: string;
@Column({ name: 'OBSDESTINOAGRUP' })
obsdestinoagrup: string;
@Column({ name: 'DESTINOAGRUP' })
destinoagrup: string;
@Column({ name: 'OBSACERTO' })
obsacerto: string;
@Column({ name: 'VLFIXO' })
vlfixo: number;
@Column({ name: 'VLPED' })
vlped: number;
@Column({ name: 'PERGRIS' })
pergris: number;
@Column({ name: 'VALORKG' })
valorkg: number;
@Column({ name: 'LANCARDESPDESCFINAUTOMATIC' })
lancardespdescfinautomatic: string;
@Column({ name: 'CODFUNCCONF' })
codfuncconf: number;
@Column({ name: 'CODFUNCSAIDACAR' })
codfuncsaidacar: number;
@Column({ name: 'CODFUNCRETORNOCAR' })
codfuncretornocar: number;
@Column({ name: 'SEGUNDOMON' })
segundomon: number;
@Column({ name: 'SEGUNDOSFECHA' })
segundosfecha: number;
@Column({ name: 'NUMONUCARGA' })
numonucarga: string;
@Column({ name: 'NOMEAPROPRIADOCARGA' })
nomeapropriadocarga: string;
@Column({ name: 'DIVISAOCARGA' })
divisaocarga: string;
@Column({ name: 'GRUPOEMBCARGA' })
grupoembcarga: string;
@Column({ name: 'QTDTOTALPRODCARGA' })
qtdtotalprodcarga: string;
@Column({ name: 'PONTOFUGORCARGA' })
pontofugorcarga: string;
@Column({ name: 'CODVEICULO1' })
codveiculo1: number;
@Column({ name: 'CODVEICULO2' })
codveiculo2: number;
@Column({ name: 'CODFUNCAJUD2' })
codfuncajud2: number;
@Column({ name: 'CODFUNCAJUD3' })
codfuncajud3: number;
@Column({ name: 'GEOVOLUMETOTAL' })
geovolumetotal: number;
@Column({ name: 'DTEXPORTACAO' })
dtexportacao: Date;
@Column({ name: 'OBSEXPORTACAO' })
obsexportacao: string;
@Column({ name: 'IDINTEGRACAOMYFROTA' })
idintegracaomyfrota: string;
@Column({ name: 'CODTIPOVEICULO' })
codtipoveiculo: number;
@Column({ name: 'CODPERFILVEICULO' })
codperfilveiculo: number;
@Column({ name: 'TIPOCALCULOCOMISSAOFRETISTA' })
tipocalculocomissaofretista: string;
@Column({ name: 'CODFUNTIPOCALCCOMISSAOFRETISTA' })
codfuntipocalccomissaofretista: number;
@Column({ name: 'LIBERA_RETAGUARDA' })
libera_retaguarda: string;
@Column({ name: 'CODFUNCLIBEROURET' })
codfuncliberouret: number;
@Column({ name: 'DATALIBEROURET' })
dataliberouret: Date;
@Column({ name: 'NUMCARMANIFCONCLUIDOFV' })
numcarmanifconcluidofv: string;
@Column({ name: 'CODFUNCFECHA' })
codfuncfecha: number;
@Column({ name: 'OBSFRETE' })
obsfrete: string;
@Column({ name: 'LANCIMPPRIMPARC' })
lancimpprimparc: string;
@Column({ name: 'NUMONDA' })
numonda: number;
@Column({ name: 'ORDEMSEP' })
ordemsep: number;
@Column({ name: 'ORDEMCONF' })
ordemconf: number;
@Column({ name: 'IDSOFITVIEW' })
idsofitview: string;
@Column({ name: 'ULTIMASITUACAOCFAT' })
ultimasituacaocfat: string;
@Column({ name: 'DATAULTIMASITUACAOCFAT' })
dataultimasituacaocfat: Date;
@OneToMany(type => Pcnfsaid, notas => notas.pccarreg)
notas: Pcnfsaid[];
@OneToMany(type => Pcpedc, pedidos => pedidos.pccarreg)
pedidos: Pcnfsaid[];
@OneToOne(type => Pcempr)
@JoinColumn({ name: 'CODMOTORISTA' })
motorista: Pcempr;
}

View File

@ -0,0 +1,25 @@
import { Column, Entity, JoinColumn, ManyToOne, OneToMany, PrimaryColumn } from "typeorm";
import { Esttipoproduto } from './esttipoproduto.entity';
import { Pcsecao } from './pcsecao.entity';
@Entity("PCCATEGORIA")
export class Pccategoria {
@PrimaryColumn({name: "CODSEC"})
codigoSecao: number;
@PrimaryColumn({name: "CODCATEGORIA"})
codigoCategoria: number;
@Column({name: "CATEGORIA"})
descricao: string;
@ManyToOne(() => Pcsecao, secao => secao.categorias)
@JoinColumn({name: 'CODSEC'})
secao: Pcsecao;
@OneToMany(() => Esttipoproduto, tipoProduto => tipoProduto.categoria)
tiposProduto: Esttipoproduto[];
}

View File

@ -0,0 +1,22 @@
import { Column, Entity, OneToMany, PrimaryColumn } from "typeorm";
import { Esttipoproduto } from "./esttipoproduto.entity";
@Entity("PCCEST")
export class Pccest {
@PrimaryColumn({name: "CODIGO"})
codigo: number;
@Column({name: "CODCEST"})
codigoCest: string;
@Column({name: "DESCRICAOCEST"})
descricao: string;
@Column({name: "NCM"})
codigoNcm: string;
@OneToMany(() => Esttipoproduto, tipoProduto => tipoProduto.registrocest)
tiposProduto: Esttipoproduto[];
}

View File

@ -0,0 +1,38 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity('PCCIDADE')
export class Pccidade {
@PrimaryColumn({ name: 'CODCIDADE' })
codcidade: number;
@Column({ name: 'NOMECIDADE' })
nomecidade: string;
@Column({ name: 'CODIBGE' })
codibge: number;
@Column({ name: 'UF' })
uf: string;
@Column({ name: 'POPULACAO' })
populacao: number;
@Column({ name: 'CODMUNESTADUAL' })
codmunestadual: number;
@Column({ name: 'UTILIZAFRETETRANSP' })
utilizafretetransp: string;
@Column({ name: 'CODMUNSIAFI' })
codmunsiafi: number;
@Column({ name: 'DTMXSALTER' })
dtmxsalter: Date;
@Column({ name: 'LATITUDE' })
latitude: string;
@Column({ name: 'LONGITUDE' })
longitude: string;
}

Some files were not shown because too many files have changed in this diff Show More