@seniorsistemas/hcm-clocking-event-rule-nodejs 0.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/copilot-instructions.md +11 -0
- package/.github/workflows/release.yaml +10 -0
- package/.gitlab-ci.yml +68 -0
- package/CHANGELOG.md +274 -0
- package/README.doc.md +658 -0
- package/README.md +117 -0
- package/assets/favicon.ico +0 -0
- package/catalog-info.yaml +19 -0
- package/jest.config.js +17 -0
- package/package.json +48 -0
- package/prompt.md +15 -0
- package/run_build_win.bat +1 -0
- package/run_link.bat +3 -0
- package/run_test.bat +1 -0
- package/sonar-project.properties +21 -0
- package/src/data/changes/changes.ts +92 -0
- package/src/data/context/context.ts +251 -0
- package/src/data/context/contextReference.ts +376 -0
- package/src/data/contract/contract.ts +272 -0
- package/src/data/dataset/database.ts +130 -0
- package/src/data/dataset/dataset.ts +275 -0
- package/src/data/definition/timeEvaluationSituationDefinitionHistory.ts +1425 -0
- package/src/data/employee/employee.ts +434 -0
- package/src/data/foundation/companyBranch.ts +66 -0
- package/src/data/foundation/costCenter.ts +47 -0
- package/src/data/foundation/employer.ts +35 -0
- package/src/data/foundation/employmentRelationship.ts +63 -0
- package/src/data/foundation/holiday.ts +84 -0
- package/src/data/foundation/holidayGroup.ts +47 -0
- package/src/data/foundation/jobPosition.ts +73 -0
- package/src/data/foundation/person.ts +35 -0
- package/src/data/foundation/situation.ts +301 -0
- package/src/data/foundation/syndicate.ts +244 -0
- package/src/data/foundation/workschedule.ts +688 -0
- package/src/data/foundation/workshift.ts +647 -0
- package/src/data/foundation/workshiftBase.ts +113 -0
- package/src/data/histories/companyBranchHistory.ts +128 -0
- package/src/data/histories/costCenterHistory.ts +114 -0
- package/src/data/histories/employmentRelationshipHistory.ts +116 -0
- package/src/data/histories/histories.ts +419 -0
- package/src/data/histories/jobPositionHistory.ts +117 -0
- package/src/data/histories/leaveHistory.ts +227 -0
- package/src/data/histories/timeEvaluationHistory.ts +191 -0
- package/src/data/histories/workshiftHistory.ts +66 -0
- package/src/data/hourBank/hourBank.ts +43 -0
- package/src/data/hourBank/hourBankAccount.ts +77 -0
- package/src/data/log/log.ts +38 -0
- package/src/data/schedules/bridge.ts +84 -0
- package/src/data/schedules/compensation.ts +332 -0
- package/src/data/schedules/overtimeAuthorization.ts +174 -0
- package/src/data/schedules/readiness.ts +150 -0
- package/src/data/schedules/schedules.ts +398 -0
- package/src/data/schedules/workscheduleChange.ts +91 -0
- package/src/data/schedules/workshiftChange.ts +76 -0
- package/src/data/timeEvaluation/adjustmentReason.ts +46 -0
- package/src/data/timeEvaluation/clockingEvent.ts +198 -0
- package/src/data/timeEvaluation/estimatedHours.ts +245 -0
- package/src/data/timeEvaluation/interval.ts +568 -0
- package/src/data/timeEvaluation/separatedHours.ts +134 -0
- package/src/data/timeEvaluation/timeEvaluation.ts +1540 -0
- package/src/data/timeEvaluation/timeEvaluationSituation.ts +154 -0
- package/src/data/user/user.ts +44 -0
- package/src/index.ts +60 -0
- package/src/test/builder/bridgeBuilder.builder.ts +28 -0
- package/src/test/builder/clockingEvent.builder.ts +49 -0
- package/src/test/builder/companyBranchHistoryBuilder.ts +29 -0
- package/src/test/builder/compensation.builder.ts +84 -0
- package/src/test/builder/contextReference.builder.ts +69 -0
- package/src/test/builder/costCenterHistoryBuilder.ts +29 -0
- package/src/test/builder/database.builder.ts +21 -0
- package/src/test/builder/datasetBuilder.ts +111 -0
- package/src/test/builder/dateIntervalBuilder.ts +25 -0
- package/src/test/builder/employee.builder.ts +91 -0
- package/src/test/builder/employmentRelationshipBuilder.ts +35 -0
- package/src/test/builder/employmentRelationshipHistoryBuilder.ts +29 -0
- package/src/test/builder/historiesBuilder.ts +56 -0
- package/src/test/builder/holiday.builder.ts +44 -0
- package/src/test/builder/hourBankAccountBuilder.ts +77 -0
- package/src/test/builder/hourBankBuilder.ts +32 -0
- package/src/test/builder/interval.builder.ts +113 -0
- package/src/test/builder/jobPositionHistoryBuilder.ts +29 -0
- package/src/test/builder/overtimeAuthorization.builder.ts +42 -0
- package/src/test/builder/readinessBuilder.builder.ts +57 -0
- package/src/test/builder/schedules.builder.ts +126 -0
- package/src/test/builder/situation.builder.ts +59 -0
- package/src/test/builder/syndicate.builder.ts +96 -0
- package/src/test/builder/syndicateHistoryBuilder.ts +33 -0
- package/src/test/builder/timeEvaluation.builder.ts +138 -0
- package/src/test/builder/timeEvaluationHistory.builder.ts +49 -0
- package/src/test/builder/timeEvaluationSituation.builder.ts +34 -0
- package/src/test/builder/workschedule.builder.ts +96 -0
- package/src/test/builder/workshift.builder.ts +179 -0
- package/src/test/builder/workshiftBuilder.ts +55 -0
- package/src/test/data/clockingEvent.spec.ts +56 -0
- package/src/test/data/context.spec.ts +176 -0
- package/src/test/data/currentUser.spec.ts +11 -0
- package/src/test/data/dataset.spec.ts +144 -0
- package/src/test/data/employee/employee.spec.ts +20 -0
- package/src/test/data/employmentRelationship/employmentRelationship.spec.ts +48 -0
- package/src/test/data/estimatedHours/estimatedHours.spec.ts +96 -0
- package/src/test/data/histories/costCenterHistory.spec.ts +32 -0
- package/src/test/data/histories/histories.spec.ts +306 -0
- package/src/test/data/holyday.spec.ts +89 -0
- package/src/test/data/hourBank/hourBank.spec.ts +48 -0
- package/src/test/data/hourBank/hourBankAccount.spec.ts +32 -0
- package/src/test/data/schedules/bridge.spec.ts +13 -0
- package/src/test/data/schedules/compesation.spect.ts +89 -0
- package/src/test/data/schedules/overtimeAuthorization.spec.ts +52 -0
- package/src/test/data/schedules/readiness.spec.ts +64 -0
- package/src/test/data/schedules/schedules.spec.ts +134 -0
- package/src/test/data/schedules/workscheduleChange.spec.ts +21 -0
- package/src/test/data/syndicate/syndicate.spec.ts +51 -0
- package/src/test/data/timeEvaluation.spec.ts +1057 -0
- package/src/test/data/timeEvaluationDefinition.spec.ts +144 -0
- package/src/test/data/workschedule/workschedule.spec.ts +194 -0
- package/src/test/data/workshift/workshift.spec.ts +79 -0
- package/src/test/utils/date.utils.spec.ts +198 -0
- package/src/test/utils/dateIntervalUtils.spec.ts +210 -0
- package/src/test/utils/object.utils.spec.ts +83 -0
- package/src/utils/dateIntervalUtils.ts +284 -0
- package/src/utils/dateUtils.ts +456 -0
- package/src/utils/decompressGzipLambda.ts +15 -0
- package/src/utils/object.utils.ts +156 -0
- package/trivy/vulnerabilities_scan.json +1160 -0
- package/tsconfig.json +32 -0
- package/tsconfig.spec.json +21 -0
- package/tslint.json +92 -0
- package/typedoc.json +22 -0
package/README.md
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# hcm-clocking-event-rule-nodejs
|
|
2
|
+
|
|
3
|
+
## Descrição
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
Uma biblioteca de utilitários para implementação de regras no Ponto X, desenvolvida em Node.js/TypeScript.
|
|
9
|
+
|
|
10
|
+
## Principais artefatos
|
|
11
|
+
|
|
12
|
+
O projeto exporta diversas entidades e utilitários, incluindo:
|
|
13
|
+
|
|
14
|
+
- Contextos, contratos e colaboradores (`Context`, `Contract`, `EmploymentRelationship`, etc)
|
|
15
|
+
- Informações completas do dia como horários, escalas, feriados, etc (`Workshift`, `Holiday`, etc)
|
|
16
|
+
- Utilitários de data e objeto (`DateUtils`, `ObjectUtils`)
|
|
17
|
+
- Históricos e programações
|
|
18
|
+
- Situações, escalas, feriados, logs, etc.
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
## Estrutura do Projeto
|
|
22
|
+
|
|
23
|
+
- `src/` — Código-fonte principal
|
|
24
|
+
- `src/data/` — Entidades de domínio
|
|
25
|
+
- `src/utils/` — Utilitários
|
|
26
|
+
- `src/test/` — Testes automatizados e builders
|
|
27
|
+
|
|
28
|
+
## Documentação
|
|
29
|
+
|
|
30
|
+
As informações sobre as entidades e utilitários estão documentadas diretamente no código, a documentação em formato html será gerada automaticamente e disponibilizada no arquivo docs.zip após a execução do comando de build.
|
|
31
|
+
|
|
32
|
+
Após a instalação da biblioteca, você pode acessar a documentação descompactando o arquivo de documentação localizado em: `/<lamda>/node_modules/hcm-clocking-event-rule-nodejs/docs.zip`.
|
|
33
|
+
|
|
34
|
+
## Instalação
|
|
35
|
+
Para instalar a biblioteca, execute o seguinte comando:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npm install hcm-clocking-event-rule-nodejs
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Uso
|
|
42
|
+
Para utilizar a biblioteca, importe os módulos necessários no seu projeto Node.js/Javascript. Por exemplo:
|
|
43
|
+
|
|
44
|
+
Exemplo: Lamda em Node.js
|
|
45
|
+
|
|
46
|
+
```javascript
|
|
47
|
+
const { Context } = require('hcm-clocking-event-rule-nodejs');
|
|
48
|
+
|
|
49
|
+
exports.handler = async (event) => {
|
|
50
|
+
return sendRes(200, event);
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const sendRes = (status, event) => {
|
|
54
|
+
|
|
55
|
+
const { Context, TimeEvaluationRule } = require('hcm-clocking-event-rule-nodejs');
|
|
56
|
+
// Cria uma nova instância do contexto com o evento recebido
|
|
57
|
+
let context = new Context(event);
|
|
58
|
+
try{
|
|
59
|
+
// Executa a regra de apuração
|
|
60
|
+
const rule = new TimeEvaluationRule(context);
|
|
61
|
+
rule.execute();
|
|
62
|
+
} catch (error) {
|
|
63
|
+
context.logError(`Erro: ${error.message}, stack: ${error.stack}`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Obtém o resultado do corpo do contexto
|
|
67
|
+
const result = context.getBodyResult();
|
|
68
|
+
var response = {
|
|
69
|
+
statusCode: status,
|
|
70
|
+
headers: {
|
|
71
|
+
"Content-Type": "application/json"
|
|
72
|
+
},
|
|
73
|
+
body: result
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Exemplo: TimeEvaluationRule.js
|
|
79
|
+
```javascript
|
|
80
|
+
const { DateUtils, DateIntervalUtils, DateInterval } = require('hcm-clocking-event-rule-nodejs');
|
|
81
|
+
|
|
82
|
+
class TimeEvaluationRule {
|
|
83
|
+
constructor(context) {
|
|
84
|
+
this.context = context;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
execute() {
|
|
88
|
+
try{
|
|
89
|
+
//Iterar sobre os contratos do contexto e executar alguma lógica
|
|
90
|
+
this.context.contracts.forEach((contract) => {
|
|
91
|
+
//Iterar sobre as apurações do contrato do colaborador
|
|
92
|
+
contract.timeEvaluation.forEach((timeEvaluation) => {
|
|
93
|
+
try{
|
|
94
|
+
this.timeEvaluation(timeEvaluation, contract);
|
|
95
|
+
} catch (error) {
|
|
96
|
+
timeEvaluation.invalidate(`Erro: ${error.message}, stack: ${error.stack}`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
} catch (error) {
|
|
102
|
+
this.context.logError(`Erro: ${error.message}, stack: ${error.stack}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Método para processar as apurações.
|
|
108
|
+
* @param {TimeEvaluation} timeEvaluation - Apuração
|
|
109
|
+
* @param {Contract} contract - O contrato do colaborador
|
|
110
|
+
*/
|
|
111
|
+
timeEvaluation(timeEvaluation, contract){
|
|
112
|
+
// Implementar a lógica de customização....
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
```
|
|
Binary file
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
apiVersion: backstage.io/v1alpha1
|
|
2
|
+
|
|
3
|
+
kind: Component
|
|
4
|
+
|
|
5
|
+
metadata:
|
|
6
|
+
annotations:
|
|
7
|
+
grafana/tag-selector: gestao-pessoas-hcm-clocking-event-rule-nodejs
|
|
8
|
+
sonarqube.org/project-key: gestao-pessoas-hcm-clocking-event-rule-nodejs
|
|
9
|
+
argocd/app-name: hcm-clocking-event-rule-nodejs-prod-hcm
|
|
10
|
+
description: ''
|
|
11
|
+
links:
|
|
12
|
+
- title: Documentação
|
|
13
|
+
url: https://wiki.senior.com.br/
|
|
14
|
+
name: hcm-clocking-event-rule-nodejs
|
|
15
|
+
|
|
16
|
+
spec:
|
|
17
|
+
lifecycle: production
|
|
18
|
+
owner: gestao-pessoas
|
|
19
|
+
type: service
|
package/jest.config.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
const { pathsToModuleNameMapper } = require('ts-jest');
|
|
2
|
+
const { compilerOptions } = require('./tsconfig.json');
|
|
3
|
+
|
|
4
|
+
module.exports = {
|
|
5
|
+
preset: 'ts-jest',
|
|
6
|
+
testEnvironment: 'node',
|
|
7
|
+
testMatch: ['**/test/**/?(*.)+(spec|test).[jt]s?(x)'],
|
|
8
|
+
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
|
|
9
|
+
collectCoverage: true,
|
|
10
|
+
coverageDirectory: 'coverage',
|
|
11
|
+
coverageReporters: ['html','json', 'lcov', 'text', 'clover', 'text-summary'],
|
|
12
|
+
testPathIgnorePatterns: ['/node_modules/', '/dist/'],
|
|
13
|
+
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths || {}, {
|
|
14
|
+
prefix: '<rootDir>/',
|
|
15
|
+
}),
|
|
16
|
+
moduleDirectories: ['node_modules', 'src']
|
|
17
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@seniorsistemas/hcm-clocking-event-rule-nodejs",
|
|
3
|
+
"version": "0.35.0",
|
|
4
|
+
"description": "Uma biblioteca de utilitários implementação de regra no pontoX",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"types": "index.d.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"build": "tsc && tsc-alias && npm run copy-extras && npm run docs",
|
|
9
|
+
"build:win": "tsc && tsc-alias && npm run copy-extras:win",
|
|
10
|
+
"docs": "typedoc && zip -r dist/docs.zip docs",
|
|
11
|
+
"docs:win": "typedoc",
|
|
12
|
+
"test": "cross-env TZ=UTC jest --coverage",
|
|
13
|
+
"test:dev": "cross-env TZ=UTC jest",
|
|
14
|
+
"test:coverage": "cross-env TZ=UTC jest --coverage",
|
|
15
|
+
"coverage": "cross-env TZ=UTC jest --coverage",
|
|
16
|
+
"copy-extras": "cp package.json dist && cp README.md dist",
|
|
17
|
+
"copy-extras:win": "copy package.json dist && copy README.md dist"
|
|
18
|
+
},
|
|
19
|
+
"devDependencies": {
|
|
20
|
+
"@types/jest": "^30.0.0",
|
|
21
|
+
"@types/node": "^22.0.0",
|
|
22
|
+
"@types/winston": "^2.4.4",
|
|
23
|
+
"cross-env": "^7.0.3",
|
|
24
|
+
"jest": "^29.7.0",
|
|
25
|
+
"ts-jest": "^29.2.6",
|
|
26
|
+
"tsc-alias": "^1.8.13",
|
|
27
|
+
"typedoc": "^0.28.5",
|
|
28
|
+
"typescript": "^5.8.3"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"type": "commonjs",
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"find-up": "5.0.0",
|
|
36
|
+
"winston": "^3.17.0"
|
|
37
|
+
},
|
|
38
|
+
"keywords": [
|
|
39
|
+
"Gestão do Ponto X",
|
|
40
|
+
"Customização",
|
|
41
|
+
"Regra de customização",
|
|
42
|
+
"Controle de ponto",
|
|
43
|
+
"nodejs",
|
|
44
|
+
"typescript",
|
|
45
|
+
"Senior HCM",
|
|
46
|
+
"Senior Sistemas"
|
|
47
|
+
]
|
|
48
|
+
}
|
package/prompt.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Lista de prompts do projeto
|
|
2
|
+
|
|
3
|
+
## Gerar uma classe baseado no json
|
|
4
|
+
- nome deve ser jobPosition
|
|
5
|
+
- o construtor deve receber uma interface com o nome jobPositionParams, deve ser gerado no mesmo arquivo
|
|
6
|
+
- os métodos deve ser privados e readonly, com o prefixo _
|
|
7
|
+
- gerar gets para todos os metodos
|
|
8
|
+
- adicionar no path src\data\histories
|
|
9
|
+
- documentar os métodos e atributos em protuguês
|
|
10
|
+
{
|
|
11
|
+
"key": "1_1",
|
|
12
|
+
"code": 1,
|
|
13
|
+
"structureCode": 1
|
|
14
|
+
},
|
|
15
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
npm run build:win --prod
|
package/run_link.bat
ADDED
package/run_test.bat
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
npm run test
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
sonar.projectKey=gestao-pessoas-hcm-clocking-event-rule-nodejs
|
|
2
|
+
sonar.projectName=hcm-clocking-event-rule-nodejs
|
|
3
|
+
sonar.projectVersion=1.0
|
|
4
|
+
sonar.sourceEncoding=UTF-8
|
|
5
|
+
|
|
6
|
+
sonar.sources=src
|
|
7
|
+
sonar.language=ts
|
|
8
|
+
sonar.exclusions=**/node_modules/**,**/*.spec.ts,**/src/app/**,**/test/**
|
|
9
|
+
|
|
10
|
+
sonar.tests=src
|
|
11
|
+
sonar.test.inclusions=**/*.spec.ts
|
|
12
|
+
sonar.typescript.lcov.reportPaths=coverage/lcov.info
|
|
13
|
+
sonar.javascript.lcov.reportPaths=coverage/lcov.info
|
|
14
|
+
#sonar.coverage.exclusions=src/*,**/*.js,**/*environment*.ts,**/*module.ts,**/*routing.ts,**/*enum.ts,**/*.d.ts
|
|
15
|
+
sonar.coverage.exclusions=**/*.spec.ts
|
|
16
|
+
sonar.clover.reportPath=coverage/clover.xml
|
|
17
|
+
|
|
18
|
+
sonar.ts.tslint.configPath=tslint.json
|
|
19
|
+
|
|
20
|
+
sonar.host.url=http://sonar.senior.com.br/
|
|
21
|
+
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hidden
|
|
3
|
+
*/
|
|
4
|
+
export class Changes {
|
|
5
|
+
public changesItems: ChangesItems[] = [];
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Enumeração dos tipos de mudanças.
|
|
10
|
+
* Representa os diferentes tipos de mudanças que podem ocorrer no sistema, como situações, pendências, erros, logs e metadados.
|
|
11
|
+
* @hidden
|
|
12
|
+
*/
|
|
13
|
+
export enum ChangesType {
|
|
14
|
+
SITUATION = "SITUATION",
|
|
15
|
+
PENDENCY = "PENDENCY",
|
|
16
|
+
ERROR = "ERROR",
|
|
17
|
+
LOG = "LOG",
|
|
18
|
+
METADATA = "METADATA"
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Parameters for ChangesItems.
|
|
22
|
+
* @hidden
|
|
23
|
+
*/
|
|
24
|
+
export interface ChangesItemsParams {
|
|
25
|
+
contractId: string | null;
|
|
26
|
+
type: ChangesType;
|
|
27
|
+
timeEvaluationDate: string | null;
|
|
28
|
+
key: string | null;
|
|
29
|
+
value: string;
|
|
30
|
+
sequence: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @hidden
|
|
36
|
+
* Representa os itens de mudanças no sistema, como situações, pendências, erros, logs e metadados.
|
|
37
|
+
*/
|
|
38
|
+
export class ChangesItems {
|
|
39
|
+
private readonly contractId: string | null;
|
|
40
|
+
private readonly type: ChangesType;
|
|
41
|
+
private readonly timeEvaluationDate: string | null;
|
|
42
|
+
private readonly key: string | null;
|
|
43
|
+
private readonly value: string;
|
|
44
|
+
private readonly sequence: number;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @hidden
|
|
48
|
+
*/
|
|
49
|
+
constructor(params: ChangesItemsParams) {
|
|
50
|
+
this.contractId = params.contractId;
|
|
51
|
+
this.type = params.type;
|
|
52
|
+
this.timeEvaluationDate = params.timeEvaluationDate;
|
|
53
|
+
this.key = params.key;
|
|
54
|
+
this.value = params.value;
|
|
55
|
+
this.sequence = params.sequence;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
getContractId(): string | null {
|
|
59
|
+
return this.contractId;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
getType(): ChangesType {
|
|
63
|
+
return this.type;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
getTimeEvaluationDate(): string | null {
|
|
67
|
+
return this.timeEvaluationDate;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
getKey(): string | null {
|
|
71
|
+
return this.key;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
getValue(): string {
|
|
75
|
+
return this.value;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
getSequence(): number {
|
|
79
|
+
return this.sequence;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
getChangesItems(): ChangesItemsParams {
|
|
83
|
+
return {
|
|
84
|
+
contractId: this.contractId,
|
|
85
|
+
type: this.type,
|
|
86
|
+
timeEvaluationDate: this.timeEvaluationDate,
|
|
87
|
+
key: this.key,
|
|
88
|
+
value: this.value,
|
|
89
|
+
sequence: this.sequence,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { Changes } from "./../changes/changes";
|
|
2
|
+
import { Dataset } from "./../dataset/dataset";
|
|
3
|
+
import { Contract } from "./../contract/contract";
|
|
4
|
+
import { decompressGzipSync } from "src/utils/decompressGzipLambda";
|
|
5
|
+
import { createLogger, format, transports } from "winston";
|
|
6
|
+
|
|
7
|
+
const logger = createLogger({
|
|
8
|
+
level: "debug",
|
|
9
|
+
format: format.json(),
|
|
10
|
+
transports: [new transports.Console()],
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Contexto de execução do processo de apuração.
|
|
15
|
+
* Representa o ambiente onde a apuração é realizada, contendo informações sobre a apuração, datas de início e fim, contratos envolvidos, usuário atual, logs de processo, etc.
|
|
16
|
+
*
|
|
17
|
+
*/
|
|
18
|
+
export class Context {
|
|
19
|
+
|
|
20
|
+
private _dataset: Dataset;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Construtor da classe Context.
|
|
24
|
+
* A partir do contexto pode ser acessado os contratos e apurações no cenário de regra.
|
|
25
|
+
* A estrutura das classes é um contexto que possui vários contratos de apuração, cada contrato pertence a um colaborador.
|
|
26
|
+
* Dentro do contrato podem ser encontradas as apurações, que devem ser iteradas para customizar as mudanças das situações.
|
|
27
|
+
*
|
|
28
|
+
* Ex.:
|
|
29
|
+
* ```javascript
|
|
30
|
+
* let context = new Context(event);
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* @param event Evento enviado para a função Lambda.
|
|
34
|
+
*/
|
|
35
|
+
public constructor(event: any) {
|
|
36
|
+
try {
|
|
37
|
+
if (event.body) {
|
|
38
|
+
const body: string = this.getBody(event);
|
|
39
|
+
|
|
40
|
+
const pDataset = JSON.parse(body);
|
|
41
|
+
|
|
42
|
+
this.build(pDataset.input);
|
|
43
|
+
} else {
|
|
44
|
+
this.createEmpty();
|
|
45
|
+
}
|
|
46
|
+
} catch (error) {
|
|
47
|
+
this.createEmpty();
|
|
48
|
+
let message = "";
|
|
49
|
+
let stack = "";
|
|
50
|
+
if (error instanceof Error) {
|
|
51
|
+
message = error.message;
|
|
52
|
+
stack = error.stack ?? "";
|
|
53
|
+
} else if (typeof error === "string") {
|
|
54
|
+
message = error;
|
|
55
|
+
} else {
|
|
56
|
+
message = JSON.stringify(error);
|
|
57
|
+
}
|
|
58
|
+
this.logError(`Erro: ${message}, stack: ${stack}`);
|
|
59
|
+
logger.error(`Erro: ${message}, stack: ${stack}`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private getBody(event: any) {
|
|
64
|
+
const contentEncoding = event.headers && (event.headers['Content-Encoding'] || event.headers['content-encoding']);
|
|
65
|
+
let body: string;
|
|
66
|
+
|
|
67
|
+
if (contentEncoding === 'gzip') {
|
|
68
|
+
try {
|
|
69
|
+
const compressedPayload = event.isBase64Encoded
|
|
70
|
+
? Buffer.from(event.body, 'base64')
|
|
71
|
+
: Buffer.from(event.body, 'utf-8');
|
|
72
|
+
body = decompressGzipSync(compressedPayload);
|
|
73
|
+
} catch (decompressError) {
|
|
74
|
+
// Se falhar ao descomprimir, tenta tratar como texto normal
|
|
75
|
+
// prevendo uma mundança de comportamento quando entrar invocação direta de lambda.
|
|
76
|
+
body = event.body;
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
body = event.body;
|
|
80
|
+
}
|
|
81
|
+
return body;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
private createEmpty() {
|
|
85
|
+
const dataset = Dataset.empty();
|
|
86
|
+
this.build(dataset);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
static empty() {
|
|
90
|
+
return new Context({});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Todas as classes que possuirem métodos precisam ser reintanciadas, pois ao converter os dados para json os métodos perdem a referência.
|
|
95
|
+
*
|
|
96
|
+
* @param pDataset
|
|
97
|
+
*/
|
|
98
|
+
private build(pDataset: Dataset) {
|
|
99
|
+
this._dataset = pDataset;
|
|
100
|
+
const datasetParams = {
|
|
101
|
+
batchId: this._dataset.batchId,
|
|
102
|
+
startDate: this._dataset.startDate,
|
|
103
|
+
endDate: this._dataset.endDate,
|
|
104
|
+
contracts: this._dataset.contracts,
|
|
105
|
+
database: this._dataset.database,
|
|
106
|
+
currentUser: this._dataset.currentUser
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
this._dataset = new Dataset(datasetParams);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* ID do lote de apuração, identificador do conjunto de colaboradores que estão sendo processados.
|
|
114
|
+
* Este ID é utilizado para agrupar os contratos e apurações que pertencem ao mesmo lote de processamento.
|
|
115
|
+
*/
|
|
116
|
+
get batchId(): string {
|
|
117
|
+
return this._dataset.batchId;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Data inicial da apuração, do qual foi o perído de cálculo de apuração.
|
|
122
|
+
*
|
|
123
|
+
* @example
|
|
124
|
+
* ```javascript
|
|
125
|
+
* let startDate = context.startDate;
|
|
126
|
+
* context.logInfo(`Data inicial da apuração: ${startDate.toISOString()}`);
|
|
127
|
+
* ```
|
|
128
|
+
* @returns Data inicial da apuração.
|
|
129
|
+
*/
|
|
130
|
+
get startDate(): Date {
|
|
131
|
+
return this._dataset.startDate;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Data final da apuração, do qual foi o perído de cálculo de apuração.
|
|
136
|
+
*
|
|
137
|
+
* @example
|
|
138
|
+
* ```javascript
|
|
139
|
+
* let endDate = context.endDate;
|
|
140
|
+
* context.logInfo(`Data final da apuração: ${endDate.toISOString()}`);
|
|
141
|
+
* ```
|
|
142
|
+
* @returns Data final da apuração.
|
|
143
|
+
*/
|
|
144
|
+
get endDate(): Date {
|
|
145
|
+
return this._dataset.endDate;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Processa as mudanças que ocorreram na customização das apurações.
|
|
150
|
+
* Tipos: Situação, Pendência, Erro, Log e Metadados.
|
|
151
|
+
*
|
|
152
|
+
* @example
|
|
153
|
+
* ```javascript
|
|
154
|
+
* let changes = context.processChanges();
|
|
155
|
+
* context.logInfo(`Mudanças processadas: ${JSON.stringify(changes)}`);
|
|
156
|
+
* ```
|
|
157
|
+
*
|
|
158
|
+
* @returns Retorna as mudanças que ocorreram na customização para serem enviados ao cálculo de apuração.
|
|
159
|
+
*/
|
|
160
|
+
processChanges(): Changes {
|
|
161
|
+
return this._dataset.processChanges();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Lista os contratos que foram calculados na apuração.
|
|
166
|
+
* O contrato de admissão representa um colaborador que foi calculado.
|
|
167
|
+
* Uma apuração pode conter vários contratos, cada contrato representa um colaborador.
|
|
168
|
+
*
|
|
169
|
+
* @example
|
|
170
|
+
* ```javascript
|
|
171
|
+
* let contracts = context.contracts;
|
|
172
|
+
* for (const contract of contracts) {
|
|
173
|
+
* context.logInfo(`Contrato: ${contract.id}, Colaborador: ${contract.employee.name}`);
|
|
174
|
+
* }
|
|
175
|
+
* ```
|
|
176
|
+
*/
|
|
177
|
+
get contracts(): Contract[] {
|
|
178
|
+
return this._dataset.contracts;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Retorna o usuário corrente que está executando o processo de apuração.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* ```javascript
|
|
186
|
+
* let currentUser = context.currentUser;
|
|
187
|
+
* context.logInfo(`Usuário corrente: ${currentUser.name}, ID: ${currentUser.id}`);
|
|
188
|
+
* ```
|
|
189
|
+
*
|
|
190
|
+
*/
|
|
191
|
+
get currentUser() {
|
|
192
|
+
return this._dataset.currentUser;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Cria um registro no log com o tipo INFO no processo de apuração.
|
|
197
|
+
*
|
|
198
|
+
* @example
|
|
199
|
+
* ```javascript
|
|
200
|
+
* context.logInfo("Início do processamento de apuração.");
|
|
201
|
+
* ```
|
|
202
|
+
*
|
|
203
|
+
* @param message Mensagem do info.
|
|
204
|
+
*/
|
|
205
|
+
public logInfo(message: string) {
|
|
206
|
+
this._dataset.logInfo(message);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Cria um registro log do tipo WARNING no processo de apuração.
|
|
211
|
+
*
|
|
212
|
+
* @example
|
|
213
|
+
* ```javascript
|
|
214
|
+
* context.logWarning("Aviso: Verifique a configuração do contrato.");
|
|
215
|
+
* ```
|
|
216
|
+
*
|
|
217
|
+
* @param message Mensagem do warning.
|
|
218
|
+
*/
|
|
219
|
+
public logWarning(message: string) {
|
|
220
|
+
this._dataset.logWarning(message);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Cria um log do tipo ERRO no processo de apuração.
|
|
225
|
+
*
|
|
226
|
+
* @example
|
|
227
|
+
* ```javascript
|
|
228
|
+
* context.logError("Erro ao processar o contrato: " + contract.id);
|
|
229
|
+
* ```
|
|
230
|
+
*
|
|
231
|
+
* @param message Mensagem do erro.
|
|
232
|
+
*/
|
|
233
|
+
public logError(message: string) {
|
|
234
|
+
this._dataset.logError(message);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Retorna o resultado do processamento em formato JSON convertido para string, para ser adicionado no body da requisão de resposta da Lamdba.
|
|
239
|
+
*
|
|
240
|
+
* @example
|
|
241
|
+
* ```javascript
|
|
242
|
+
* let result = context.getBodyResult();
|
|
243
|
+
* ```
|
|
244
|
+
*
|
|
245
|
+
* @returns String JSON com o resultado do processamento.
|
|
246
|
+
*/
|
|
247
|
+
getBodyResult(): string {
|
|
248
|
+
const changes = this._dataset.processChanges();
|
|
249
|
+
return JSON.stringify({ "version": this._dataset.getProjectVersionSync(), "result": changes });
|
|
250
|
+
}
|
|
251
|
+
}
|