mirror of
https://github.com/dadosfera/maestro.git
synced 2026-09-03 05:04:49 +00:00
Compare commits
113
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
051fb6e4dd | ||
|
|
e3099aa2b2 | ||
|
|
12c61d9b5d | ||
|
|
99c2a9ecf5 | ||
|
|
c0f75d241f | ||
|
|
1e0fb78dff | ||
|
|
b70d37423d | ||
|
|
4ddd5edcfd | ||
|
|
3bcbba9581 | ||
|
|
67d47a9642 | ||
|
|
6f9c967c96 | ||
|
|
b8bdc5beea | ||
|
|
269f70b309 | ||
|
|
93f452ae05 | ||
|
|
e39378229f | ||
|
|
61a4f724ef | ||
|
|
38a9e21f5f | ||
|
|
1a2153d62f | ||
|
|
d25bfd147c | ||
|
|
d4ba45fd03 | ||
|
|
82f1035a5e | ||
|
|
6c57bac235 | ||
|
|
cf8eed35a3 | ||
|
|
55fc85c544 | ||
|
|
72ed637640 | ||
|
|
890364f597 | ||
|
|
30eec733b2 | ||
|
|
30a41ba144 | ||
|
|
2dc032e7e7 | ||
|
|
7f5981731f | ||
|
|
66309c7bbe | ||
|
|
15048eaf8a | ||
|
|
0e169a3cbc | ||
|
|
b5d933eaf3 | ||
|
|
6fa9bf861a | ||
|
|
9a217dff57 | ||
|
|
e08734c97f | ||
|
|
cd4382c1ff | ||
|
|
54b75ce11b | ||
|
|
0e038d0b12 | ||
|
|
85234fe0dd | ||
|
|
c97a02cb17 | ||
|
|
878ec977b8 | ||
|
|
8006867bc2 | ||
|
|
784b0ef090 | ||
|
|
b736cddf07 | ||
|
|
3d6328fb0b | ||
|
|
4246c7495e | ||
|
|
3d40746ccb | ||
|
|
3ab2f8f27d | ||
|
|
b44d23552c | ||
|
|
8e63757738 | ||
|
|
3b84409003 | ||
|
|
0ce3822300 | ||
|
|
a2c7ce00db | ||
|
|
121e30ce45 | ||
|
|
85c8a4937d | ||
|
|
53920f2f3f | ||
|
|
8c34914806 | ||
|
|
1881d07c4a | ||
|
|
3b8310fdca | ||
|
|
52bda8ebe2 | ||
|
|
275a53dbd1 | ||
|
|
9cefdb226d | ||
|
|
007f3911ff | ||
|
|
8ac0a8a79f | ||
|
|
285de97375 | ||
|
|
e2a7d2b92b | ||
|
|
da23ad76db | ||
|
|
55b0961b82 | ||
|
|
d3c5c0fa63 | ||
|
|
5dbc644d1d | ||
|
|
8eddb9e1bf | ||
|
|
76485f929d | ||
|
|
8e0182aa50 | ||
|
|
a18bdccc09 | ||
|
|
b27298501d | ||
|
|
33ebc91826 | ||
|
|
6948156693 | ||
|
|
0aaa4384c3 | ||
|
|
1f9d0c29ec | ||
|
|
039c652b28 | ||
|
|
653d4f53b5 | ||
|
|
31f8c2c1a6 | ||
|
|
8b93d4e97b | ||
|
|
adeb022818 | ||
|
|
e326cab44d | ||
|
|
61109f8ae9 | ||
|
|
3f8dc5cabe | ||
|
|
7f5d157739 | ||
|
|
bce73fb11f | ||
|
|
9473e65deb | ||
|
|
77b9acd2d0 | ||
|
|
e99306adba | ||
|
|
96b947ebdc | ||
|
|
6f7436f33f | ||
|
|
865140e681 | ||
|
|
c4a664572a | ||
|
|
7a10f88113 | ||
|
|
466f8fb8cc | ||
|
|
5989822263 | ||
|
|
64a3e2652e | ||
|
|
ea44a1cbb6 | ||
|
|
fc9c0b0991 | ||
|
|
a4b5a44e44 | ||
|
|
d99a6aa322 | ||
|
|
3f910f851a | ||
|
|
bd231382eb | ||
|
|
9c1979e17a | ||
|
|
fcf7fb054e | ||
|
|
288aaeabc0 | ||
|
|
918c3d7416 | ||
|
|
e7f410831f |
@@ -0,0 +1,12 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
.git
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
.DS_Store
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
coverage
|
||||||
|
.nyc_output
|
||||||
|
*.tgz
|
||||||
|
!protospack.tgz
|
||||||
+2
-1
@@ -1,4 +1,5 @@
|
|||||||
FROM node:18.17-alpine AS base_image
|
FROM node:20-alpine AS base_image
|
||||||
|
RUN npm install -g npm@latest
|
||||||
|
|
||||||
FROM base_image AS build_base
|
FROM base_image AS build_base
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
FROM node:22-alpine AS base_image
|
||||||
|
RUN npm install -g npm@latest
|
||||||
|
|
||||||
|
FROM base_image AS build_base
|
||||||
|
WORKDIR /app
|
||||||
|
RUN apk update
|
||||||
|
RUN apk add --no-cache \
|
||||||
|
aws-cli \
|
||||||
|
chromium \
|
||||||
|
nss \
|
||||||
|
freetype \
|
||||||
|
harfbuzz \
|
||||||
|
ca-certificates \
|
||||||
|
ttf-freefont
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true \
|
||||||
|
PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
|
||||||
|
|
||||||
|
|
||||||
|
# Local build with secrets
|
||||||
|
FROM build_base AS build
|
||||||
|
RUN --mount=type=secret,id=aws,target=/root/.aws/credentials \
|
||||||
|
aws codeartifact login --tool npm --namespace @dadosfera --repository dadosfera-npm --domain dadosfera --domain-owner 611330257153 --region us-east-1
|
||||||
|
RUN npm ci
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
|
||||||
|
FROM base_image
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=build /app/dist ./dist
|
||||||
|
COPY --from=build /app/node_modules ./node_modules
|
||||||
|
COPY --from=build /app/package*.json ./
|
||||||
|
RUN apk update
|
||||||
|
RUN apk add --no-cache \
|
||||||
|
chromium \
|
||||||
|
nss \
|
||||||
|
freetype \
|
||||||
|
harfbuzz \
|
||||||
|
ca-certificates \
|
||||||
|
ttf-freefont
|
||||||
|
|
||||||
|
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true \
|
||||||
|
PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
|
||||||
|
|
||||||
|
ENTRYPOINT ["npm", "run", "start:prod"]
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
# Maestro
|
# Maestro
|
||||||
|
|
||||||
|
|
||||||
Maestro é a API principal da Dadosfera. É responsável pela comunicação do Frontend com nossos microsserviços.
|
Maestro é a API principal da Dadosfera. É responsável pela comunicação do Frontend com nossos microsserviços.
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
|
|||||||
@@ -48,6 +48,9 @@ spec:
|
|||||||
{{- toYaml .Values.resources | nindent 12 }}
|
{{- toYaml .Values.resources | nindent 12 }}
|
||||||
{{- end }}
|
{{- end }}
|
||||||
env:
|
env:
|
||||||
|
# Auth Provider Configuration (cognito or keycloak)
|
||||||
|
- name: AUTH_PROVIDER
|
||||||
|
value: {{ .Values.maestro.auth_provider | default "cognito" | quote }}
|
||||||
- name: AWS_IDENTITY_POOL_ID
|
- name: AWS_IDENTITY_POOL_ID
|
||||||
value: {{ .Values.maestro.aws_identity_pool_id }}
|
value: {{ .Values.maestro.aws_identity_pool_id }}
|
||||||
- name: AWS_REGION
|
- name: AWS_REGION
|
||||||
@@ -108,6 +111,8 @@ spec:
|
|||||||
value: "{{ .Values.maestro.redis_tls }}"
|
value: "{{ .Values.maestro.redis_tls }}"
|
||||||
- name: PLATFORM_API_URL
|
- name: PLATFORM_API_URL
|
||||||
value: {{ .Values.maestro.platform_api_url }}
|
value: {{ .Values.maestro.platform_api_url }}
|
||||||
|
- name: STORAGE_EXPLORER_API_URL
|
||||||
|
value: {{ .Values.maestro.storage_explorer_api_url | quote }}
|
||||||
- name: JWT_PRIVATE_KEY
|
- name: JWT_PRIVATE_KEY
|
||||||
valueFrom:
|
valueFrom:
|
||||||
secretKeyRef:
|
secretKeyRef:
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ maestro:
|
|||||||
cookie_secret: "ff7bc13823edb2ae50d248e5780bddc9d4b31c36"
|
cookie_secret: "ff7bc13823edb2ae50d248e5780bddc9d4b31c36"
|
||||||
redis_database: "1"
|
redis_database: "1"
|
||||||
platform_api_url: https://xs2hkhq07k.execute-api.us-east-1.amazonaws.com
|
platform_api_url: https://xs2hkhq07k.execute-api.us-east-1.amazonaws.com
|
||||||
|
storage_explorer_api_url: "http://storage-explorer-{customer}.data-apps.svc.cluster.local:8000/api"
|
||||||
|
|
||||||
hostname: maestro.stg.dadosfera.ai
|
hostname: maestro.stg.dadosfera.ai
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,9 @@ resources:
|
|||||||
cpu: 2000m
|
cpu: 2000m
|
||||||
memory: 2Gi
|
memory: 2Gi
|
||||||
maestro:
|
maestro:
|
||||||
|
# Auth provider: "cognito" (default) or "keycloak"
|
||||||
|
# Note: maestro doesn't connect to Keycloak directly, only duc does
|
||||||
|
auth_provider: "cognito"
|
||||||
aws_identity_pool_id: "us-east-1_Mrezsw9Sn"
|
aws_identity_pool_id: "us-east-1_Mrezsw9Sn"
|
||||||
duc_url: duc.dadosfera.ai
|
duc_url: duc.dadosfera.ai
|
||||||
in_factory_url: in-factory.dadosfera.ai
|
in_factory_url: in-factory.dadosfera.ai
|
||||||
@@ -44,6 +47,7 @@ maestro:
|
|||||||
open_customer_id: f239718a-a271-4ef9-ae7e-02a2f0f3aa6e
|
open_customer_id: f239718a-a271-4ef9-ae7e-02a2f0f3aa6e
|
||||||
open_group_id: 401573bb-334f-44b2-b30e-88d4cea31ae9
|
open_group_id: 401573bb-334f-44b2-b30e-88d4cea31ae9
|
||||||
platform_api_url: https://oz8v2zid1e.execute-api.us-east-1.amazonaws.com
|
platform_api_url: https://oz8v2zid1e.execute-api.us-east-1.amazonaws.com
|
||||||
|
storage_explorer_api_url: "https://storage-explorer-{customer}.dadosfera.ai/api"
|
||||||
dedicated_proxy: ""
|
dedicated_proxy: ""
|
||||||
restricted_ip: ""
|
restricted_ip: ""
|
||||||
redis_host: "aaapzppmlyamkocqwstpo7zvopczyyiyuy6xzm2g6c5k4mq3a66be4a-0.redis.sa-saopaulo-1.oci.oraclecloud.com"
|
redis_host: "aaapzppmlyamkocqwstpo7zvopczyyiyuy6xzm2g6c5k4mq3a66be4a-0.redis.sa-saopaulo-1.oci.oraclecloud.com"
|
||||||
|
|||||||
+2066
-1138
File diff suppressed because it is too large
Load Diff
Generated
+2110
-2969
File diff suppressed because it is too large
Load Diff
+10
-4
@@ -30,12 +30,12 @@
|
|||||||
"@aws-crypto/sha256-js": "^5.2.0",
|
"@aws-crypto/sha256-js": "^5.2.0",
|
||||||
"@aws-sdk/client-dynamodb": "^3.414.0",
|
"@aws-sdk/client-dynamodb": "^3.414.0",
|
||||||
"@aws-sdk/client-secrets-manager": "^3.414.0",
|
"@aws-sdk/client-secrets-manager": "^3.414.0",
|
||||||
"@aws-sdk/lib-dynamodb": "^3.414.0",
|
|
||||||
"@aws-sdk/credential-provider-node": "^3.940.0",
|
"@aws-sdk/credential-provider-node": "^3.940.0",
|
||||||
|
"@aws-sdk/lib-dynamodb": "^3.414.0",
|
||||||
"@aws-sdk/signature-v4": "^3.370.0",
|
"@aws-sdk/signature-v4": "^3.370.0",
|
||||||
"@dadosfera/dadosfera-logs": "^1.0.0-beta.4",
|
"@dadosfera/dadosfera-logs": "^1.0.0-beta.4",
|
||||||
"@dadosfera/protospack": "2.5.3",
|
"@dadosfera/protospack": "2.5.3",
|
||||||
"@dadosfera/protospack-v2": "3.38.0-beta.16",
|
"@dadosfera/protospack-v2": "3.38.0-beta.28",
|
||||||
"@grpc/grpc-js": "^1.9.3",
|
"@grpc/grpc-js": "^1.9.3",
|
||||||
"@grpc/proto-loader": "^0.7.9",
|
"@grpc/proto-loader": "^0.7.9",
|
||||||
"@nestjs/cli": "^9.5.0",
|
"@nestjs/cli": "^9.5.0",
|
||||||
@@ -49,7 +49,7 @@
|
|||||||
"@nestjs/schematics": "^9.2.0",
|
"@nestjs/schematics": "^9.2.0",
|
||||||
"@nestjs/swagger": "^6.3.0",
|
"@nestjs/swagger": "^6.3.0",
|
||||||
"@nestjs/testing": "^9.4.3",
|
"@nestjs/testing": "^9.4.3",
|
||||||
"axios": "^0.27.2",
|
"axios": "^0.30.2",
|
||||||
"cache-manager": "^5.1.4",
|
"cache-manager": "^5.1.4",
|
||||||
"cache-manager-ioredis-yet": "^1.1.0",
|
"cache-manager-ioredis-yet": "^1.1.0",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
@@ -80,7 +80,13 @@
|
|||||||
"swagger-ui-express": "^4.6.3"
|
"swagger-ui-express": "^4.6.3"
|
||||||
},
|
},
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"multer": "1.4.5-lts.1"
|
"multer": "2.0.2",
|
||||||
|
"form-data": "^4.0.4",
|
||||||
|
"body-parser": "^1.20.3",
|
||||||
|
"cross-spawn": "^7.0.5",
|
||||||
|
"glob": "^10.5.0",
|
||||||
|
"path-to-regexp": "^3.3.0",
|
||||||
|
"semver": "^7.5.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/cache-manager": "^4.0.6",
|
"@types/cache-manager": "^4.0.6",
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ import { AssignModule } from './modules/assign/assign.module';
|
|||||||
import { ShareMetadataModule } from './modules/share-metadata/share-metadata.module';
|
import { ShareMetadataModule } from './modules/share-metadata/share-metadata.module';
|
||||||
import { ApiKeyModule } from './modules/api-key/api-key.module';
|
import { ApiKeyModule } from './modules/api-key/api-key.module';
|
||||||
import { PlatformApiModule } from './modules/platform-api/platform-api.module';
|
import { PlatformApiModule } from './modules/platform-api/platform-api.module';
|
||||||
|
import { StorageExplorerModule } from './modules/storage-explorer/storage-explorer.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
providers: [
|
providers: [
|
||||||
@@ -75,6 +76,7 @@ import { PlatformApiModule } from './modules/platform-api/platform-api.module';
|
|||||||
IdentityProviderModule,
|
IdentityProviderModule,
|
||||||
NetworkPolicyModule,
|
NetworkPolicyModule,
|
||||||
PlatformApiModule,
|
PlatformApiModule,
|
||||||
|
StorageExplorerModule,
|
||||||
//Always leave HealthModule last, so it is on the bottom of swagger
|
//Always leave HealthModule last, so it is on the bottom of swagger
|
||||||
HealthModule,
|
HealthModule,
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -668,6 +668,35 @@ export const PERMISSIONS_GROUPS = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
STORAGE_EXPLORER: {
|
||||||
|
title: {
|
||||||
|
'pt-br': 'Storage Explorer',
|
||||||
|
'en-us': 'Storage Explorer',
|
||||||
|
'es-es': 'Storage Explorer',
|
||||||
|
},
|
||||||
|
permissions: {
|
||||||
|
READ: {
|
||||||
|
seqid: 51,
|
||||||
|
claim: 'storage-explorer:read',
|
||||||
|
usage: PermissionUsages.PUBLIC,
|
||||||
|
name: {
|
||||||
|
'pt-br': 'Ler dados do Storage Explorer',
|
||||||
|
'en-us': 'Read Storage Explorer data',
|
||||||
|
'es-es': 'Leer datos del Storage Explorer',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
WRITE: {
|
||||||
|
seqid: 52,
|
||||||
|
claim: 'storage-explorer:write',
|
||||||
|
usage: PermissionUsages.PUBLIC,
|
||||||
|
name: {
|
||||||
|
'pt-br': 'Escrever dados no Storage Explorer',
|
||||||
|
'en-us': 'Write Storage Explorer data',
|
||||||
|
'es-es': 'Escribir datos en Storage Explorer',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
};
|
};
|
||||||
export interface DadosferaModule {
|
export interface DadosferaModule {
|
||||||
name: string;
|
name: string;
|
||||||
|
|||||||
@@ -111,3 +111,4 @@ function configureSwagger(app: INestApplication) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
bootstrap();
|
bootstrap();
|
||||||
|
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ import jwt, { JwtPayload } from 'jsonwebtoken';
|
|||||||
import { LanguageEnum } from 'src/utils/languages.enum';
|
import { LanguageEnum } from 'src/utils/languages.enum';
|
||||||
import { Language } from 'src/decorators/language.decorator';
|
import { Language } from 'src/decorators/language.decorator';
|
||||||
import { ApiInternalOnlyEndpoint } from 'src/decorators/swagger.decorator';
|
import { ApiInternalOnlyEndpoint } from 'src/decorators/swagger.decorator';
|
||||||
|
import { ApiKeyService } from 'src/modules/api-key/api-key.service';
|
||||||
|
|
||||||
type CookiesValues = {
|
type CookiesValues = {
|
||||||
accessToken?: string;
|
accessToken?: string;
|
||||||
@@ -74,6 +75,7 @@ export class AuthController {
|
|||||||
@Inject(DadosferaLogger)
|
@Inject(DadosferaLogger)
|
||||||
dadosferaLogger: DadosferaLogger,
|
dadosferaLogger: DadosferaLogger,
|
||||||
private authClient: AuthClientService,
|
private authClient: AuthClientService,
|
||||||
|
private apiKeyService: ApiKeyService,
|
||||||
) {
|
) {
|
||||||
this.logger = dadosferaLogger.logger;
|
this.logger = dadosferaLogger.logger;
|
||||||
|
|
||||||
@@ -190,13 +192,14 @@ export class AuthController {
|
|||||||
) {
|
) {
|
||||||
this.logger.info('/auth - change-password');
|
this.logger.info('/auth - change-password');
|
||||||
|
|
||||||
const { oldPassword, newPassword } = body;
|
const { oldPassword, newPassword, totpCode } = body;
|
||||||
const { authorization: accessToken } = headers;
|
const { authorization: accessToken } = headers;
|
||||||
|
|
||||||
return this.authClient.changePassword({
|
return this.authClient.changePassword({
|
||||||
accessToken,
|
accessToken,
|
||||||
oldPassword,
|
oldPassword,
|
||||||
newPassword,
|
newPassword,
|
||||||
|
totpCode,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -214,7 +217,8 @@ export class AuthController {
|
|||||||
|
|
||||||
const { username } = body;
|
const { username } = body;
|
||||||
|
|
||||||
return this.authClient.resetPassword({ username }, metadata);
|
await this.authClient.resetPassword({ username }, metadata);
|
||||||
|
return { authProvider: process.env.AUTH_PROVIDER || 'cognito' };
|
||||||
}
|
}
|
||||||
|
|
||||||
@ApiInternalOnlyEndpoint()
|
@ApiInternalOnlyEndpoint()
|
||||||
@@ -474,12 +478,32 @@ export class AuthController {
|
|||||||
@Get('me')
|
@Get('me')
|
||||||
async getMe(@Req() req: Request, @Res() res: Response) {
|
async getMe(@Req() req: Request, @Res() res: Response) {
|
||||||
this.logger.info('GET /auth/me ')
|
this.logger.info('GET /auth/me ')
|
||||||
|
this.logger.info(JSON.stringify(req.headers));
|
||||||
|
|
||||||
|
// Check for API key header first
|
||||||
|
const apiKey = req.get('X-Api-key');
|
||||||
|
if (apiKey) {
|
||||||
|
this.logger.info('Authenticating via X-Api-key header');
|
||||||
|
const { api_key } = await this.apiKeyService.get(apiKey);
|
||||||
|
|
||||||
|
const userDto = {
|
||||||
|
id: api_key.user_id,
|
||||||
|
name: api_key.username,
|
||||||
|
customer: {
|
||||||
|
id: api_key.customer_id,
|
||||||
|
name: api_key.customer_name,
|
||||||
|
tier: api_key.customer_tier,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return res.status(200).json(userDto);
|
||||||
|
}
|
||||||
|
|
||||||
// Get token and headers
|
// Get token and headers
|
||||||
const accessToken = req.cookies['ddf-auth'];
|
const accessToken = req.cookies['ddf-auth'];
|
||||||
const refreshToken = req.cookies['ddf-refresh-auth'];
|
const refreshToken = req.cookies['ddf-refresh-auth'];
|
||||||
const userId = req.cookies['ddf-user-id'];
|
const userId = req.cookies['ddf-user-id'];
|
||||||
const resourceHost = req.headers["host"]
|
const resourceHost = req.headers["x-original-url"] as string || "" ;
|
||||||
|
|
||||||
const hasUserSession = Boolean(accessToken) && Boolean(userId);
|
const hasUserSession = Boolean(accessToken) && Boolean(userId);
|
||||||
this.logger.info('Has User Session: ' + hasUserSession);
|
this.logger.info('Has User Session: ' + hasUserSession);
|
||||||
|
|||||||
@@ -8,10 +8,11 @@ import { AuthClientService } from './auth.service';
|
|||||||
import { DucClient } from '../duc/client.config';
|
import { DucClient } from '../duc/client.config';
|
||||||
import { GoogleLoginStrategy } from './passport-strategies/google-strategy';
|
import { GoogleLoginStrategy } from './passport-strategies/google-strategy';
|
||||||
import { getOauthSecrets } from 'src/utils/OauthSecrets';
|
import { getOauthSecrets } from 'src/utils/OauthSecrets';
|
||||||
|
import { ApiKeyModule } from '../api-key/api-key.module';
|
||||||
const client = new DucClient();
|
const client = new DucClient();
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ClientsModule.register([client.providerOptions])],
|
imports: [ClientsModule.register([client.providerOptions]), ApiKeyModule],
|
||||||
controllers: [AuthController],
|
controllers: [AuthController],
|
||||||
providers: [
|
providers: [
|
||||||
AuthClientService,
|
AuthClientService,
|
||||||
|
|||||||
@@ -143,6 +143,7 @@ export class AuthClientService implements OnModuleInit {
|
|||||||
accessToken,
|
accessToken,
|
||||||
oldPassword,
|
oldPassword,
|
||||||
newPassword,
|
newPassword,
|
||||||
|
totpCode,
|
||||||
}: AuthChangePasswordRequest) {
|
}: AuthChangePasswordRequest) {
|
||||||
this.logger.info('ChangePassword');
|
this.logger.info('ChangePassword');
|
||||||
|
|
||||||
@@ -151,6 +152,7 @@ export class AuthClientService implements OnModuleInit {
|
|||||||
accessToken,
|
accessToken,
|
||||||
oldPassword,
|
oldPassword,
|
||||||
newPassword,
|
newPassword,
|
||||||
|
totpCode,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ import {
|
|||||||
import { TypeParser } from 'src/utils/FileParser/parser-types';
|
import { TypeParser } from 'src/utils/FileParser/parser-types';
|
||||||
import { ParserBuilder } from 'src/utils/FileParser/parser.builder';
|
import { ParserBuilder } from 'src/utils/FileParser/parser.builder';
|
||||||
|
|
||||||
|
|
||||||
class CatalogService implements OnModuleInit {
|
class CatalogService implements OnModuleInit {
|
||||||
catalogReadService: ReadService.CatalogReadServices;
|
catalogReadService: ReadService.CatalogReadServices;
|
||||||
catalogWriteService: WriteService.CatalogWriteServices;
|
catalogWriteService: WriteService.CatalogWriteServices;
|
||||||
@@ -58,7 +57,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
this.logger = dadosferaLogger.logger;
|
this.logger = dadosferaLogger.logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
onModuleInit() {
|
onModuleInit() {
|
||||||
this.catalogReadService =
|
this.catalogReadService =
|
||||||
this.grpcClient.getService<ReadService.CatalogReadServices>(
|
this.grpcClient.getService<ReadService.CatalogReadServices>(
|
||||||
@@ -74,81 +72,65 @@ class CatalogService implements OnModuleInit {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
_getNimbusUrl(body) {
|
_getNimbusUrl(body) {
|
||||||
this.logger.debug(`Body: ${JSON.stringify(body)}`);
|
this.logger.debug(`Body: ${JSON.stringify(body)}`);
|
||||||
const customer = body.info.customer.toLowerCase();
|
const customer = body.info.customer.toLowerCase();
|
||||||
|
|
||||||
|
|
||||||
if (process.env.ENV === 'prd') {
|
if (process.env.ENV === 'prd') {
|
||||||
return `https://nimbus-${customer}.dadosfera.ai`;
|
return `https://nimbus-${customer}.dadosfera.ai`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return `https://nimbus-${customer}.${process.env.ENV.replace(
|
return `https://nimbus-${customer}.${process.env.ENV.replace(
|
||||||
'local',
|
'local',
|
||||||
'stg',
|
'stg',
|
||||||
)}.dadosfera.ai`;
|
)}.dadosfera.ai`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async getPiiReporter(metadata: Metadata, type: TypeParser) {
|
async getPiiReporter(metadata: Metadata, type: TypeParser) {
|
||||||
this.logger.info('getPiiReporter: ' + type)
|
this.logger.info('getPiiReporter: ' + type);
|
||||||
try {
|
try {
|
||||||
const {
|
const { data } = await lastValueFrom(
|
||||||
data
|
this.catalogWriteService.GetPiiReporter({}, metadata),
|
||||||
} = await lastValueFrom(
|
);
|
||||||
this.catalogWriteService.GetPiiReporter({}, metadata)
|
this.logger.info('Finish grpc call');
|
||||||
)
|
|
||||||
this.logger.info("Finish grpc call")
|
|
||||||
|
|
||||||
|
|
||||||
const parser = ParserBuilder.build<PiiMetadata>(type);
|
const parser = ParserBuilder.build<PiiMetadata>(type);
|
||||||
|
|
||||||
|
this.logger.info('parser file to: ' + type);
|
||||||
this.logger.info('parser file to: ' + type)
|
const file = await parser.parse(data);
|
||||||
const file = await parser.parse(data)
|
this.logger.info('finish parser');
|
||||||
this.logger.info('finish parser')
|
|
||||||
const mimeTypes: Record<TypeParser, string> = {
|
const mimeTypes: Record<TypeParser, string> = {
|
||||||
'csv': 'text/csv',
|
csv: 'text/csv',
|
||||||
'html': 'text/html',
|
html: 'text/html',
|
||||||
'pdf': 'application/pdf'
|
pdf: 'application/pdf',
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||||
const filename = `relatorio-pii-${timestamp}.${type}`;
|
const filename = `relatorio-pii-${timestamp}.${type}`;
|
||||||
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
file,
|
file,
|
||||||
filename: filename,
|
filename: filename,
|
||||||
type: mimeTypes[type]
|
type: mimeTypes[type],
|
||||||
}
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(error.message);
|
this.logger.error(error.message);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async createDataAsset(data: Messages.CreateDataAssetRequest, metadata) {
|
async createDataAsset(data: Messages.CreateDataAssetRequest, metadata) {
|
||||||
this.logger.info('CatalogService - Manage Data assets permissions');
|
this.logger.info('CatalogService - Manage Data assets permissions');
|
||||||
if (!data.embed) data.embed = undefined;
|
if (!data.embed) data.embed = undefined;
|
||||||
|
|
||||||
|
|
||||||
return lastValueFrom(
|
return lastValueFrom(
|
||||||
this.catalogWriteService.CreateDataAsset(data, metadata),
|
this.catalogWriteService.CreateDataAsset(data, metadata),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async managePermissions(data: Messages.ManagePermissionRequest, metadata) {
|
async managePermissions(data: Messages.ManagePermissionRequest, metadata) {
|
||||||
this.logger.info('CatalogService - Manage Data assets permissions');
|
this.logger.info('CatalogService - Manage Data assets permissions');
|
||||||
|
|
||||||
|
|
||||||
return lastValueFrom(
|
return lastValueFrom(
|
||||||
this.catalogWriteService.ManagePermission(data, metadata),
|
this.catalogWriteService.ManagePermission(data, metadata),
|
||||||
).catch((err) => {
|
).catch((err) => {
|
||||||
@@ -159,11 +141,9 @@ class CatalogService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async revokePermissions(data: Messages.RevokePermissionRequest, metadata) {
|
async revokePermissions(data: Messages.RevokePermissionRequest, metadata) {
|
||||||
this.logger.info('CatalogService - Manage Data assets permissions');
|
this.logger.info('CatalogService - Manage Data assets permissions');
|
||||||
|
|
||||||
|
|
||||||
return lastValueFrom(
|
return lastValueFrom(
|
||||||
this.catalogWriteService.RevokePermission(data, metadata),
|
this.catalogWriteService.RevokePermission(data, metadata),
|
||||||
).catch((err) => {
|
).catch((err) => {
|
||||||
@@ -174,11 +154,9 @@ class CatalogService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async commentOnDataAsset(data: Messages.MakeACommentRequest, metadata) {
|
async commentOnDataAsset(data: Messages.MakeACommentRequest, metadata) {
|
||||||
this.logger.info('CatalogService - Manage Data assets permissions');
|
this.logger.info('CatalogService - Manage Data assets permissions');
|
||||||
|
|
||||||
|
|
||||||
return lastValueFrom(
|
return lastValueFrom(
|
||||||
this.catalogWriteService.MakeAComment(data, metadata),
|
this.catalogWriteService.MakeAComment(data, metadata),
|
||||||
).catch((err) => {
|
).catch((err) => {
|
||||||
@@ -189,11 +167,9 @@ class CatalogService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async deleteComment(data: Messages.UpdateACommentRequest, metadata) {
|
async deleteComment(data: Messages.UpdateACommentRequest, metadata) {
|
||||||
this.logger.info('CatalogService - Manage Data assets permissions');
|
this.logger.info('CatalogService - Manage Data assets permissions');
|
||||||
|
|
||||||
|
|
||||||
return lastValueFrom(
|
return lastValueFrom(
|
||||||
this.catalogWriteService.UpdateAComment(data, metadata),
|
this.catalogWriteService.UpdateAComment(data, metadata),
|
||||||
).catch((err) => {
|
).catch((err) => {
|
||||||
@@ -204,11 +180,9 @@ class CatalogService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async deleteDataAsset(data: Messages.DeleteDataAssetRequest, metadata) {
|
async deleteDataAsset(data: Messages.DeleteDataAssetRequest, metadata) {
|
||||||
this.logger.info('CatalogService - Manage Data assets permissions');
|
this.logger.info('CatalogService - Manage Data assets permissions');
|
||||||
|
|
||||||
|
|
||||||
return lastValueFrom(
|
return lastValueFrom(
|
||||||
this.catalogWriteService.DeleteDataAsset(data, metadata),
|
this.catalogWriteService.DeleteDataAsset(data, metadata),
|
||||||
).catch((err) => {
|
).catch((err) => {
|
||||||
@@ -219,30 +193,114 @@ class CatalogService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async getUserRolesIds(userId: string) {
|
async getUserRolesIds(userId: string) {
|
||||||
const result = await this.userService.findOneById(userId).catch(() => null);
|
const result = await this.userService.findOneById(userId).catch(() => null);
|
||||||
|
|
||||||
|
|
||||||
if (result) {
|
if (result) {
|
||||||
return result.user.roles.map((role) => role.id);
|
return result.user.roles.map((role) => role.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async searchDataAssets(
|
async searchDataAssets(
|
||||||
query: Record<string, any>,
|
query: Record<string, any>,
|
||||||
metadata: Metadata,
|
metadata: Metadata,
|
||||||
customer_id: string,
|
customer_id: string,
|
||||||
) {
|
) {
|
||||||
this.logger.info('CatalogService - searchDataAssets');
|
this.logger.info('CatalogService - searchDataAssets', { query });
|
||||||
|
|
||||||
|
|
||||||
const { search, page, size, sort_by, order, ...filters } = query;
|
const { search, page, size, sort_by, order, ...filters } = query;
|
||||||
|
|
||||||
|
this.logger.debug('Extracted filters:', { filters });
|
||||||
|
|
||||||
|
console.log('MAESTRO VAI CHAMAR PI-FACTORY COM (ANTES AJUSTE):', {
|
||||||
|
search,
|
||||||
|
page,
|
||||||
|
size,
|
||||||
|
sort_by,
|
||||||
|
order,
|
||||||
|
filters,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (
|
||||||
|
filters.manually !== undefined &&
|
||||||
|
filters.manually !== null &&
|
||||||
|
filters.manually !== ''
|
||||||
|
) {
|
||||||
|
filters.manually = Number(filters.manually); // 1 ou 0
|
||||||
|
} else {
|
||||||
|
delete filters.manually;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('MAESTRO VAI CHAMAR PI-FACTORY COM (DEPOIS AJUSTE):', {
|
||||||
|
search,
|
||||||
|
page,
|
||||||
|
size,
|
||||||
|
sort_by,
|
||||||
|
order,
|
||||||
|
filters,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (filters.owner) {
|
||||||
|
const { users: customer_users } =
|
||||||
|
await this.userService.findAllUsersByCustomerId(customer_id);
|
||||||
|
|
||||||
|
this.logger.info('Available users in database count:', {
|
||||||
|
count: customer_users.length,
|
||||||
|
});
|
||||||
|
this.logger.info('First 5 users:', {
|
||||||
|
users: customer_users
|
||||||
|
.slice(0, 5)
|
||||||
|
.map((u) => ({ id: u.id, email: u.email, name: u.name })),
|
||||||
|
});
|
||||||
|
|
||||||
|
const ownerValues = Array.isArray(filters.owner)
|
||||||
|
? filters.owner
|
||||||
|
: typeof filters.owner === 'string' && filters.owner.includes(',')
|
||||||
|
? filters.owner.split(',').map((o: string) => o.trim())
|
||||||
|
: [filters.owner];
|
||||||
|
|
||||||
|
this.logger.info('Owner values to convert:', {
|
||||||
|
ownerValues,
|
||||||
|
ownerFiltersOriginal: filters.owner,
|
||||||
|
});
|
||||||
|
|
||||||
|
const ownerIds = ownerValues
|
||||||
|
.map((ownerValue: string) => {
|
||||||
|
const normalizedOwner = ownerValue.replace(/\s/g, '+');
|
||||||
|
const user = customer_users.find((u) => {
|
||||||
|
const isIdMatch = u.id === ownerValue;
|
||||||
|
const isEmailMatch =
|
||||||
|
u.email === ownerValue || u.email === normalizedOwner;
|
||||||
|
const isNameMatch =
|
||||||
|
u.name === ownerValue || u.name === normalizedOwner;
|
||||||
|
this.logger.info('Comparing:', {
|
||||||
|
userId: u.id,
|
||||||
|
userEmail: u.email,
|
||||||
|
userName: u.name,
|
||||||
|
filterValue: ownerValue,
|
||||||
|
normalizedFilter: normalizedOwner,
|
||||||
|
idMatch: isIdMatch,
|
||||||
|
emailMatch: isEmailMatch,
|
||||||
|
nameMatch: isNameMatch,
|
||||||
|
});
|
||||||
|
return isIdMatch || isEmailMatch || isNameMatch;
|
||||||
|
});
|
||||||
|
this.logger.info('Looking for owner result:', {
|
||||||
|
ownerValue,
|
||||||
|
found: !!user,
|
||||||
|
userId: user?.id,
|
||||||
|
});
|
||||||
|
return user?.id || ownerValue;
|
||||||
|
})
|
||||||
|
.filter((id: string) => id);
|
||||||
|
|
||||||
|
if (ownerIds.length > 0) {
|
||||||
|
filters.owner = ownerIds;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const { data_assets, total } = await lastValueFrom(
|
const { data_assets, total } = await lastValueFrom(
|
||||||
this.catalogReadService.GetAllDataAssets(
|
this.catalogReadService.GetAllDataAssets(
|
||||||
{
|
{
|
||||||
@@ -257,20 +315,18 @@ class CatalogService implements OnModuleInit {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
console.log('MAESTRO RECEBEU RESPOSTA DO PI-FACTORY');
|
||||||
|
|
||||||
const result = JSON.parse(data_assets);
|
const result = JSON.parse(data_assets);
|
||||||
|
|
||||||
|
|
||||||
const response = await this.getAssetsUsersAndRoles(
|
const response = await this.getAssetsUsersAndRoles(
|
||||||
result.data_assets,
|
result.data_assets,
|
||||||
customer_id,
|
customer_id,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
return { data_assets: response, total };
|
return { data_assets: response, total };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async downloadAssets(
|
async downloadAssets(
|
||||||
query: Record<string, any>,
|
query: Record<string, any>,
|
||||||
metadata: Metadata,
|
metadata: Metadata,
|
||||||
@@ -278,33 +334,27 @@ class CatalogService implements OnModuleInit {
|
|||||||
) {
|
) {
|
||||||
const data = await this.searchDataAssets(query, metadata, customer_id);
|
const data = await this.searchDataAssets(query, metadata, customer_id);
|
||||||
|
|
||||||
|
const formatData = data.data_assets.map((asset) => ({
|
||||||
const formatData = data.data_assets.map(asset => ({
|
|
||||||
id: asset.id,
|
id: asset.id,
|
||||||
display_name: asset.display_name,
|
display_name: asset.display_name,
|
||||||
data_asset_type: asset.data_asset_type,
|
data_asset_type: asset.data_asset_type,
|
||||||
created_at: asset.created_at,
|
created_at: asset.created_at,
|
||||||
tags: '[' + asset.tags.join(', ') + ']'
|
tags: '[' + asset.tags.join(', ') + ']',
|
||||||
}))
|
}));
|
||||||
|
|
||||||
|
|
||||||
const parser = ParserBuilder.build<AssetReporter>('csv');
|
const parser = ParserBuilder.build<AssetReporter>('csv');
|
||||||
|
|
||||||
|
|
||||||
const file = await parser.parse(formatData);
|
const file = await parser.parse(formatData);
|
||||||
|
|
||||||
|
|
||||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||||
const filename = `dadosfera_assets_${timestamp}.csv`;
|
const filename = `dadosfera_assets_${timestamp}.csv`;
|
||||||
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
file,
|
file,
|
||||||
filename
|
filename,
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async getOneDataAsset(data: {
|
async getOneDataAsset(data: {
|
||||||
id: string;
|
id: string;
|
||||||
customer_id: string;
|
customer_id: string;
|
||||||
@@ -325,11 +375,9 @@ class CatalogService implements OnModuleInit {
|
|||||||
};
|
};
|
||||||
asset = await this.getAssetsUsersAndRoles([asset], customer_id);
|
asset = await this.getAssetsUsersAndRoles([asset], customer_id);
|
||||||
|
|
||||||
|
|
||||||
return { data_asset: asset[0] };
|
return { data_asset: asset[0] };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async getOneDataAssetByPipelineAndObject(data: {
|
async getOneDataAssetByPipelineAndObject(data: {
|
||||||
customer_id: string;
|
customer_id: string;
|
||||||
pipeline: string;
|
pipeline: string;
|
||||||
@@ -351,11 +399,9 @@ class CatalogService implements OnModuleInit {
|
|||||||
};
|
};
|
||||||
asset = await this.getAssetsUsersAndRoles([asset], customer_id);
|
asset = await this.getAssetsUsersAndRoles([asset], customer_id);
|
||||||
|
|
||||||
|
|
||||||
return { data_asset: asset[0] };
|
return { data_asset: asset[0] };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async updateOneDataAsset(data: {
|
async updateOneDataAsset(data: {
|
||||||
data_asset_id: string;
|
data_asset_id: string;
|
||||||
customer_id: string;
|
customer_id: string;
|
||||||
@@ -364,7 +410,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
}) {
|
}) {
|
||||||
const { body, customer_id, data_asset_id, metadata } = data;
|
const { body, customer_id, data_asset_id, metadata } = data;
|
||||||
|
|
||||||
|
|
||||||
const { data_asset } = await lastValueFrom(
|
const { data_asset } = await lastValueFrom(
|
||||||
this.catalogWriteService.UpdateDataAsset(
|
this.catalogWriteService.UpdateDataAsset(
|
||||||
{ id: data_asset_id, changes: JSON.stringify(body) },
|
{ id: data_asset_id, changes: JSON.stringify(body) },
|
||||||
@@ -379,7 +424,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
};
|
};
|
||||||
asset = await this.getAssetsUsersAndRoles([asset], customer_id);
|
asset = await this.getAssetsUsersAndRoles([asset], customer_id);
|
||||||
|
|
||||||
|
|
||||||
return { data_asset: asset[0] };
|
return { data_asset: asset[0] };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -392,7 +436,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
return docs;
|
return docs;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async getDatasetPreview(id: string, metadata: Metadata) {
|
async getDatasetPreview(id: string, metadata: Metadata) {
|
||||||
const { preview } = await lastValueFrom(
|
const { preview } = await lastValueFrom(
|
||||||
this.catalogReadService.GetDatasetPreview(
|
this.catalogReadService.GetDatasetPreview(
|
||||||
@@ -404,7 +447,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async getDatasetColumnsMetadata(id: string, metadata: Metadata) {
|
async getDatasetColumnsMetadata(id: string, metadata: Metadata) {
|
||||||
const { columns_metadata } = await lastValueFrom(
|
const { columns_metadata } = await lastValueFrom(
|
||||||
this.catalogReadService.GetDatasetColumnsMetadata(
|
this.catalogReadService.GetDatasetColumnsMetadata(
|
||||||
@@ -434,7 +476,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private async createDataDocsViaGrpc(body: CreateDataDocsDTO, metadata: Metadata) {
|
private async createDataDocsViaGrpc(body: CreateDataDocsDTO, metadata: Metadata) {
|
||||||
this.logger.info('Creating data docs via gRPC for other asset types');
|
this.logger.info('Creating data docs via gRPC for other asset types');
|
||||||
try {
|
try {
|
||||||
@@ -449,7 +490,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
);
|
);
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error('Error creating data asset docs:', error);
|
this.logger.error('Error creating data asset docs:', error);
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
@@ -462,7 +502,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
async findAllTags(data, metadata) {
|
async findAllTags(data, metadata) {
|
||||||
this.logger.info('CatalogService - findAllCustomerTags');
|
this.logger.info('CatalogService - findAllCustomerTags');
|
||||||
|
|
||||||
|
|
||||||
const response = await lastValueFrom(
|
const response = await lastValueFrom(
|
||||||
this.catalogReadService.GetCustomerTags(data, metadata),
|
this.catalogReadService.GetCustomerTags(data, metadata),
|
||||||
)
|
)
|
||||||
@@ -475,9 +514,9 @@ class CatalogService implements OnModuleInit {
|
|||||||
throw new Error(err);
|
throw new Error(err);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getAssetsUsersAndRoles(data_assets: Array<any>, customer_id: string) {
|
async getAssetsUsersAndRoles(data_assets: Array<any>, customer_id: string) {
|
||||||
const { users: customer_users } =
|
const { users: customer_users } =
|
||||||
await this.userService.findAllUsersByCustomerId(customer_id);
|
await this.userService.findAllUsersByCustomerId(customer_id);
|
||||||
@@ -490,17 +529,15 @@ class CatalogService implements OnModuleInit {
|
|||||||
(u) => u.id === data_asset.owner,
|
(u) => u.id === data_asset.owner,
|
||||||
)?.email;
|
)?.email;
|
||||||
|
|
||||||
|
|
||||||
const roles = [];
|
const roles = [];
|
||||||
const users = [];
|
const users = [];
|
||||||
const data_asset_roles = data_asset?.roles || []
|
const data_asset_roles = data_asset?.roles || [];
|
||||||
for (const role_id of data_asset_roles) {
|
for (const role_id of data_asset_roles) {
|
||||||
const role = customer_roles.find((r) => r.id === role_id);
|
const role = customer_roles.find((r) => r.id === role_id);
|
||||||
if (role) roles.push({ id: role.id, name: role.name });
|
if (role) roles.push({ id: role.id, name: role.name });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const data_asset_users = data_asset?.users || [];
|
||||||
const data_asset_users = data_asset?.users || []
|
|
||||||
for (const user_id of data_asset_users) {
|
for (const user_id of data_asset_users) {
|
||||||
const user = customer_users.find((r) => r.id === user_id);
|
const user = customer_users.find((r) => r.id === user_id);
|
||||||
if (user) users.push({ id: user.id, email: user.email });
|
if (user) users.push({ id: user.id, email: user.email });
|
||||||
@@ -514,7 +551,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async triggerCatalog(data: TriggerCatalogReq, metadata: Metadata) {
|
async triggerCatalog(data: TriggerCatalogReq, metadata: Metadata) {
|
||||||
const { session } = await lastValueFrom(
|
const { session } = await lastValueFrom(
|
||||||
this.catalogWriteService.TriggerDatasetCataloging(data, metadata),
|
this.catalogWriteService.TriggerDatasetCataloging(data, metadata),
|
||||||
@@ -528,7 +564,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async addRlsRule(data: AddRlsRuleRequest, metadata: Metadata) {
|
async addRlsRule(data: AddRlsRuleRequest, metadata: Metadata) {
|
||||||
const res = await lastValueFrom(
|
const res = await lastValueFrom(
|
||||||
this.catalogWriteService.AddRlsRule(data, metadata),
|
this.catalogWriteService.AddRlsRule(data, metadata),
|
||||||
@@ -536,7 +571,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async removeRlsRule(id: number, metadata: Metadata) {
|
async removeRlsRule(id: number, metadata: Metadata) {
|
||||||
const res = await lastValueFrom(
|
const res = await lastValueFrom(
|
||||||
this.catalogWriteService.RemoveRlsRule({ id }, metadata),
|
this.catalogWriteService.RemoveRlsRule({ id }, metadata),
|
||||||
@@ -544,14 +578,12 @@ class CatalogService implements OnModuleInit {
|
|||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async batchRemoveRlsRule(
|
async batchRemoveRlsRule(
|
||||||
query: BatchRemoveRlsRulesRequest,
|
query: BatchRemoveRlsRulesRequest,
|
||||||
metadata: Metadata,
|
metadata: Metadata,
|
||||||
) {
|
) {
|
||||||
const { id_rls, nimbus_dashboard_id } = query;
|
const { id_rls, nimbus_dashboard_id } = query;
|
||||||
|
|
||||||
|
|
||||||
if (id_rls && nimbus_dashboard_id) {
|
if (id_rls && nimbus_dashboard_id) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
"You can't delete using both parameters. Choose either 'id_rls' or 'nimbus_dashboard_id'",
|
"You can't delete using both parameters. Choose either 'id_rls' or 'nimbus_dashboard_id'",
|
||||||
@@ -572,7 +604,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
return 'OK';
|
return 'OK';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async getRlsRules(data: GetRlsRulesRequest, metadata: Metadata) {
|
async getRlsRules(data: GetRlsRulesRequest, metadata: Metadata) {
|
||||||
const res = await lastValueFrom(
|
const res = await lastValueFrom(
|
||||||
this.catalogReadService.GetRlsRules(data, metadata),
|
this.catalogReadService.GetRlsRules(data, metadata),
|
||||||
@@ -580,7 +611,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
return res.rls_rules;
|
return res.rls_rules;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async getOneRlsRule(id: number, metadata: Metadata) {
|
async getOneRlsRule(id: number, metadata: Metadata) {
|
||||||
const res = await lastValueFrom(
|
const res = await lastValueFrom(
|
||||||
this.catalogReadService.GetOneRlsRule({ id }, metadata),
|
this.catalogReadService.GetOneRlsRule({ id }, metadata),
|
||||||
@@ -588,7 +618,6 @@ class CatalogService implements OnModuleInit {
|
|||||||
return res.rls_rule;
|
return res.rls_rule;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async getNimbusDashboards(
|
async getNimbusDashboards(
|
||||||
data: GetNimbusDashboardsRequest,
|
data: GetNimbusDashboardsRequest,
|
||||||
metadata: Metadata,
|
metadata: Metadata,
|
||||||
@@ -599,88 +628,99 @@ class CatalogService implements OnModuleInit {
|
|||||||
return res.dashboards;
|
return res.dashboards;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async createTableMetadata(body: any): Promise<number> {
|
async createTableMetadata(body: any): Promise<number> {
|
||||||
const nimbusUrl = this._getNimbusUrl(body);
|
const nimbusUrl = this._getNimbusUrl(body);
|
||||||
this.logger.info(`Nimbus URL: ${nimbusUrl}`, {...body.logMetadata});
|
this.logger.info(`Nimbus URL: ${nimbusUrl}`, { ...body.logMetadata });
|
||||||
|
|
||||||
|
|
||||||
const endpoint = `${nimbusUrl}/api/catalog/table-metadata/`;
|
const endpoint = `${nimbusUrl}/api/catalog/table-metadata/`;
|
||||||
|
|
||||||
|
this.logger.info(
|
||||||
this.logger.info(`Creating table metadata for table ${body.table_metadata.table_name}`, {...body.logMetadata});
|
`Creating table metadata for table ${body.table_metadata.table_name}`,
|
||||||
this.logger.info(`Using endpoint: ${endpoint}`, {...body.logMetadata});
|
{ ...body.logMetadata },
|
||||||
this.logger.debug(`Payload: ${JSON.stringify(body.table_metadata)}`, {...body.logMetadata});
|
);
|
||||||
|
this.logger.info(`Using endpoint: ${endpoint}`, { ...body.logMetadata });
|
||||||
|
this.logger.debug(`Payload: ${JSON.stringify(body.table_metadata)}`, {
|
||||||
|
...body.logMetadata,
|
||||||
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { data, status } = await axios.post(endpoint, {...body.table_metadata});
|
const { data, status } = await axios.post(endpoint, {
|
||||||
|
...body.table_metadata,
|
||||||
|
});
|
||||||
|
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
`Table metadata created successfully with status ${status} for table ${body.table_metadata.table_name}`,
|
`Table metadata created successfully with status ${status} for table ${body.table_metadata.table_name}`,
|
||||||
{...body.logMetadata},
|
{ ...body.logMetadata },
|
||||||
);
|
);
|
||||||
return data.id;
|
return data.id;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
`Failed to create table metadata for table ${body.table_metadata.table_name} failed with status ${
|
`Failed to create table metadata for table ${body.table_metadata.table_name} failed with status ${
|
||||||
error.response?.status
|
error.response?.status
|
||||||
} because of ${JSON.stringify(error.response?.data) || error.message}`, {...body.logMetadata});
|
} because of ${JSON.stringify(error.response?.data) || error.message}`,
|
||||||
|
{ ...body.logMetadata },
|
||||||
|
);
|
||||||
throw new Error(error.response?.data?.message || error.message);
|
throw new Error(error.response?.data?.message || error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async createColumnMetadata(body: any): Promise<number[]> {
|
async createColumnMetadata(body: any): Promise<number[]> {
|
||||||
const nimbusUrl = this._getNimbusUrl(body);
|
const nimbusUrl = this._getNimbusUrl(body);
|
||||||
this.logger.info(`Nimbus URL: ${nimbusUrl}`, body.logMetadata);
|
this.logger.info(`Nimbus URL: ${nimbusUrl}`, body.logMetadata);
|
||||||
const endpoint = `${nimbusUrl}/api/catalog/column-metadata/`;
|
const endpoint = `${nimbusUrl}/api/catalog/column-metadata/`;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
this.logger.info(`Creating column metadata for table ${body.column_metadata.table_name}`, {...body.logMetadata});
|
this.logger.info(
|
||||||
this.logger.info(`Using endpoint: ${endpoint}`, {...body.logMetadata});
|
`Creating column metadata for table ${body.column_metadata.table_name}`,
|
||||||
this.logger.debug(`Payload: ${JSON.stringify(body.column_metadata)}`, {...body.logMetadata});
|
{ ...body.logMetadata },
|
||||||
const { data, status } = await axios.post(endpoint, body.column_metadata);
|
);
|
||||||
|
this.logger.info(`Using endpoint: ${endpoint}`, { ...body.logMetadata });
|
||||||
|
this.logger.debug(
|
||||||
|
`Payload: ${JSON.stringify(body.column_metadata)}`,
|
||||||
|
{ ...body.logMetadata },
|
||||||
|
);
|
||||||
|
const { data, status } = await axios.post(
|
||||||
|
endpoint,
|
||||||
|
body.column_metadata,
|
||||||
|
);
|
||||||
|
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
`Column metadata created successfully with status ${status} for table ${body.column_metadata.table_name}`,
|
`Column metadata created successfully with status ${status} for table ${body.column_metadata.table_name}`,
|
||||||
{...body.logMetadata},
|
{ ...body.logMetadata },
|
||||||
);
|
);
|
||||||
return data.map((column) => column.id);
|
return data.map((column) => column.id);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
`Failed to create column metadata failed with status for table ${body.column_metadata.table_name} ${
|
`Failed to create column metadata failed with status for table ${body.column_metadata.table_name} ${
|
||||||
error.response?.status
|
error.response?.status
|
||||||
} because of ${error.response?.data || error.message}`, {...body.logMetadata});
|
} because of ${error.response?.data || error.message}`,
|
||||||
|
{ ...body.logMetadata },
|
||||||
|
);
|
||||||
throw new Error(error.response?.data?.message || error.message);
|
throw new Error(error.response?.data?.message || error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async createDataPreview(body: any): Promise<number> {
|
async createDataPreview(body: any): Promise<number> {
|
||||||
const nimbusUrl = this._getNimbusUrl(body);
|
const nimbusUrl = this._getNimbusUrl(body);
|
||||||
this.logger.info(`Nimbus URL: ${nimbusUrl}`, {...body.logMetadata});
|
this.logger.info(`Nimbus URL: ${nimbusUrl}`, { ...body.logMetadata });
|
||||||
const endpoint = `${nimbusUrl}/api/catalog/data-preview/`;
|
const endpoint = `${nimbusUrl}/api/catalog/data-preview/`;
|
||||||
|
|
||||||
|
this.logger.info(
|
||||||
this.logger.info(`Creating data preview for table ${body.data_preview.table_name}`, {...body.logMetadata});
|
`Creating data preview for table ${body.data_preview.table_name}`,
|
||||||
this.logger.info(`Using endpoint: ${endpoint}`, {...body.logMetadata});
|
{ ...body.logMetadata },
|
||||||
this.logger.debug(`Payload: ${JSON.stringify(body.data_preview)}`, {...body.logMetadata});
|
);
|
||||||
|
this.logger.info(`Using endpoint: ${endpoint}`, { ...body.logMetadata });
|
||||||
|
this.logger.debug(
|
||||||
|
`Payload: ${JSON.stringify(body.data_preview)}`,
|
||||||
|
{ ...body.logMetadata },
|
||||||
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { data, status } = await axios.post(endpoint, body.data_preview);
|
const { data, status } = await axios.post(endpoint, body.data_preview);
|
||||||
|
|
||||||
|
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
`Data preview created successfully with status ${status} for table ${body.data_preview.table_name}`,
|
`Data preview created successfully with status ${status} for table ${body.data_preview.table_name}`,
|
||||||
{...body.logMetadata},
|
{ ...body.logMetadata },
|
||||||
);
|
);
|
||||||
return data.id;
|
return data.id;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -688,17 +728,73 @@ class CatalogService implements OnModuleInit {
|
|||||||
`Failed to create data preview for table ${body.data_preview.table_name} failed with status ${
|
`Failed to create data preview for table ${body.data_preview.table_name} failed with status ${
|
||||||
error.response?.status
|
error.response?.status
|
||||||
} because of ${error.response?.data || error.message}`,
|
} because of ${error.response?.data || error.message}`,
|
||||||
{...body.logMetadata},
|
{ ...body.logMetadata },
|
||||||
);
|
);
|
||||||
throw new Error(error.response?.data?.message || error.message);
|
throw new Error(error.response?.data?.message || error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async renameTableOnNimbus(
|
||||||
|
nimbusUrl: string,
|
||||||
|
nimbusId: number,
|
||||||
|
changes: { table_name?: string; table_schema?: string; display_name?: string },
|
||||||
|
): Promise<void> {
|
||||||
|
const endpoint = `${nimbusUrl}/api/catalog/table-metadata/${nimbusId}`;
|
||||||
|
this.logger.info(`Renaming table-metadata ${nimbusId} on Nimbus`, { endpoint, changes });
|
||||||
|
await axios.patch(endpoint, changes);
|
||||||
|
}
|
||||||
|
|
||||||
|
async renameColumnMetadataOnNimbus(
|
||||||
|
nimbusUrl: string,
|
||||||
|
databaseName: string,
|
||||||
|
oldTableName: string,
|
||||||
|
oldTableSchema: string,
|
||||||
|
newTableName: string,
|
||||||
|
newTableSchema: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const listEndpoint = `${nimbusUrl}/api/catalog/column-metadata/?database_name=${encodeURIComponent(databaseName)}&table_name=${encodeURIComponent(oldTableName)}&table_schema=${encodeURIComponent(oldTableSchema)}`;
|
||||||
|
this.logger.info(`Fetching column-metadata records to rename`, { listEndpoint });
|
||||||
|
const { data: columns } = await axios.get(listEndpoint);
|
||||||
|
|
||||||
|
const filtered = Array.isArray(columns) ? columns : [];
|
||||||
|
|
||||||
|
for (const column of filtered) {
|
||||||
|
const patchEndpoint = `${nimbusUrl}/api/catalog/column-metadata/${column.id}`;
|
||||||
|
await axios.patch(patchEndpoint, {
|
||||||
|
table_name: newTableName,
|
||||||
|
table_schema: newTableSchema,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
this.logger.info(`Renamed ${filtered.length} column-metadata records on Nimbus`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async renameDataPreviewOnNimbus(
|
||||||
|
nimbusUrl: string,
|
||||||
|
databaseName: string,
|
||||||
|
oldTableName: string,
|
||||||
|
oldTableSchema: string,
|
||||||
|
newTableName: string,
|
||||||
|
newTableSchema: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const listEndpoint = `${nimbusUrl}/api/catalog/data-preview/?database_name=${encodeURIComponent(databaseName)}&table_name=${encodeURIComponent(oldTableName)}&table_schema=${encodeURIComponent(oldTableSchema)}`;
|
||||||
|
this.logger.info(`Fetching data-preview records to rename`, { listEndpoint });
|
||||||
|
const { data: previews } = await axios.get(listEndpoint);
|
||||||
|
|
||||||
|
const filtered = Array.isArray(previews) ? previews : [];
|
||||||
|
|
||||||
|
for (const preview of filtered) {
|
||||||
|
const patchEndpoint = `${nimbusUrl}/api/catalog/data-preview/${preview.id}`;
|
||||||
|
await axios.patch(patchEndpoint, {
|
||||||
|
table_name: newTableName,
|
||||||
|
table_schema: newTableSchema,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
this.logger.info(`Renamed ${filtered.length} data-preview records on Nimbus`);
|
||||||
|
}
|
||||||
|
|
||||||
async catalogDatasetItem(table_metadata_id: number, metadata: Metadata) {
|
async catalogDatasetItem(table_metadata_id: number, metadata: Metadata) {
|
||||||
const customer_name_raw = metadata.get('customer_name');
|
const customer_name_raw = metadata.get('customer_name');
|
||||||
|
|
||||||
|
|
||||||
const customer_name = customer_name_raw?.[0]?.toString();
|
const customer_name = customer_name_raw?.[0]?.toString();
|
||||||
if (!customer_name) {
|
if (!customer_name) {
|
||||||
throw new BadRequestException('Customer name not found in metadata');
|
throw new BadRequestException('Customer name not found in metadata');
|
||||||
@@ -721,5 +817,4 @@ class CatalogService implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export { CatalogService };
|
export { CatalogService };
|
||||||
|
|||||||
@@ -98,6 +98,8 @@ export class IDataAsset {
|
|||||||
embed?: EmbedObject;
|
embed?: EmbedObject;
|
||||||
@ApiPropertyOptional({ enum: DataAssetShareType })
|
@ApiPropertyOptional({ enum: DataAssetShareType })
|
||||||
share_type?: DataAssetShareType;
|
share_type?: DataAssetShareType;
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
docs?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class IOneDataAsset {
|
export class IOneDataAsset {
|
||||||
@@ -200,6 +202,8 @@ export class IUpdateDataRequest {
|
|||||||
embed: EmbedObject;
|
embed: EmbedObject;
|
||||||
@ApiPropertyOptional({ enum: DataAssetShareType })
|
@ApiPropertyOptional({ enum: DataAssetShareType })
|
||||||
share_type?: DataAssetShareType;
|
share_type?: DataAssetShareType;
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
docs?: string;
|
||||||
}
|
}
|
||||||
export class ICreateDataAsset implements CreateDataAssetRequest {
|
export class ICreateDataAsset implements CreateDataAssetRequest {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
@@ -214,6 +218,8 @@ export class ICreateDataAsset implements CreateDataAssetRequest {
|
|||||||
location: string;
|
location: string;
|
||||||
@ApiPropertyOptional()
|
@ApiPropertyOptional()
|
||||||
embed: EmbedObject;
|
embed: EmbedObject;
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
docs: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class IPreview {
|
export class IPreview {
|
||||||
|
|||||||
@@ -136,4 +136,32 @@ export class CustomersController {
|
|||||||
const result = await this.customersService.getAccessDashboardUrl(user.customer_name, metadata);
|
const result = await this.customersService.getAccessDashboardUrl(user.customer_name, metadata);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get(':id/organization-info')
|
||||||
|
@Authenticated()
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.USERS.permissions.ADMIN)
|
||||||
|
@ApiOkResponse({ description: 'Organization information' })
|
||||||
|
async getOrganizationInfo(@Param('id') id: string) {
|
||||||
|
this.logger.info('getOrganizationInfo', { id });
|
||||||
|
return this.customersService.getOrganizationInfo(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put(':id/organization-info')
|
||||||
|
@Authenticated()
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.USERS.permissions.ADMIN)
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
@ApiOkResponse({ description: 'Organization information updated' })
|
||||||
|
async updateOrganizationInfo(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() body: {
|
||||||
|
companyName: string;
|
||||||
|
companySite: string;
|
||||||
|
domain: string;
|
||||||
|
cnpj: string;
|
||||||
|
description: string;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
return this.customersService.updateOrganizationInfo(id, body);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -223,4 +223,57 @@ export class CustomersService implements OnModuleInit {
|
|||||||
})
|
})
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updateOrganizationInfo(
|
||||||
|
customerId: string,
|
||||||
|
data: {
|
||||||
|
companyName: string;
|
||||||
|
companySite: string;
|
||||||
|
domain: string;
|
||||||
|
cnpj: string;
|
||||||
|
description: string;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const result = await lastValueFrom(
|
||||||
|
this.customerService.OrganizationUpdate({
|
||||||
|
customerId,
|
||||||
|
companyName: data.companyName || '',
|
||||||
|
companySite: data.companySite || '',
|
||||||
|
domain: data.domain || '',
|
||||||
|
cnpj: data.cnpj || '',
|
||||||
|
description: data.description || '',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (err) {
|
||||||
|
if (err.details === ErrorCodes.CUSTOMER.NOT_FOUND)
|
||||||
|
throw new HttpException(err.details, HttpStatus.NOT_FOUND);
|
||||||
|
else throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getOrganizationInfo(customerId: string) {
|
||||||
|
try {
|
||||||
|
const customerResponse = await lastValueFrom(
|
||||||
|
this.customerService.CustomerFindOneById({ id: customerId })
|
||||||
|
);
|
||||||
|
|
||||||
|
const customer = customerResponse.customer;
|
||||||
|
|
||||||
|
return {
|
||||||
|
companyName: customer.companyName || '',
|
||||||
|
companySite: customer.companySite || '',
|
||||||
|
domain: customer.domain || '',
|
||||||
|
cnpj: customer.cnpj || '',
|
||||||
|
description: customer.description || ''
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
if (err.details === ErrorCodes.CUSTOMER.NOT_FOUND)
|
||||||
|
throw new HttpException(err.details, HttpStatus.NOT_FOUND);
|
||||||
|
else throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
export class OrganizationUpdateRequest {
|
||||||
|
@ApiProperty()
|
||||||
|
name: string;
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
companySite: string;
|
||||||
|
@ApiProperty()
|
||||||
|
domain: string;
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
info: string;
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
cnpj: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class OrganizationResponse {
|
||||||
|
@ApiProperty()
|
||||||
|
name: string;
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
companySite: string;
|
||||||
|
@ApiProperty()
|
||||||
|
domain: string;
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
info: string;
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
cnpj: string;
|
||||||
|
}
|
||||||
@@ -14,6 +14,13 @@ export class TableColumns {
|
|||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
references: Column[];
|
references: Column[];
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
|
identifier_columns: string[];
|
||||||
|
@ApiProperty()
|
||||||
|
destination: Record<'raw' | 'qualify', {
|
||||||
|
table_name: string;
|
||||||
|
table_schema: string;
|
||||||
|
}> | null;
|
||||||
|
@ApiProperty()
|
||||||
type: string;
|
type: string;
|
||||||
}
|
}
|
||||||
export class AvailableEntity {
|
export class AvailableEntity {
|
||||||
|
|||||||
@@ -200,7 +200,7 @@ export class InputsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async update(id: string, data, info: Info) {
|
async update(id: string, data, info: Info) {
|
||||||
this.validateCron({ ...data, info });
|
// this.validateCron({ ...data, info });
|
||||||
try {
|
try {
|
||||||
const updateInputResponse: any = await this.OLD_inputClient.update({
|
const updateInputResponse: any = await this.OLD_inputClient.update({
|
||||||
id,
|
id,
|
||||||
|
|||||||
@@ -1,6 +1,15 @@
|
|||||||
import { ApiProperty, ApiPropertyOptional, OmitType } from '@nestjs/swagger';
|
import { ApiProperty, ApiPropertyOptional, OmitType } from '@nestjs/swagger';
|
||||||
import { Info } from '@dadosfera/protospack/dist/lib/interfaces';
|
import { Info } from '@dadosfera/protospack/dist/lib/interfaces';
|
||||||
|
|
||||||
|
export class PipelineInputsDTO {
|
||||||
|
@ApiProperty()
|
||||||
|
tables: Array<{
|
||||||
|
name: string,
|
||||||
|
type: string,
|
||||||
|
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
|
||||||
export class IPipelineV2 {
|
export class IPipelineV2 {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
id: string;
|
id: string;
|
||||||
@@ -123,3 +132,30 @@ export class PipelineFindAllReq {
|
|||||||
@ApiPropertyOptional()
|
@ApiPropertyOptional()
|
||||||
type?: string | undefined;
|
type?: string | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface UpdateTableDTO {
|
||||||
|
name: string;
|
||||||
|
type: string;
|
||||||
|
columns: string[];
|
||||||
|
destinations: {
|
||||||
|
raw: {
|
||||||
|
table_schema: string;
|
||||||
|
table_name: string;
|
||||||
|
};
|
||||||
|
qualify: {
|
||||||
|
table_schema: string;
|
||||||
|
table_name: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
identifier_columns: string[];
|
||||||
|
reference_column: {
|
||||||
|
name: string;
|
||||||
|
type: string;
|
||||||
|
};
|
||||||
|
memory: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdatePlatformInputRequest {
|
||||||
|
cron: string;
|
||||||
|
tables: Array<UpdateTableDTO>;
|
||||||
|
}
|
||||||
|
|||||||
@@ -43,11 +43,15 @@ import {
|
|||||||
IPipelineV2,
|
IPipelineV2,
|
||||||
IInitUploadCSVFile,
|
IInitUploadCSVFile,
|
||||||
PipelineFindAllReq,
|
PipelineFindAllReq,
|
||||||
|
UpdatePlatformInputRequest,
|
||||||
} from './interfaces';
|
} from './interfaces';
|
||||||
import { GrpcToHttpExceptionFilter } from 'src/error/grpc-to-http-exception.filter';
|
import { GrpcToHttpExceptionFilter } from 'src/error/grpc-to-http-exception.filter';
|
||||||
import { LanguageEnum } from 'src/utils/languages.enum';
|
import { LanguageEnum } from 'src/utils/languages.enum';
|
||||||
import { Language } from 'src/decorators/language.decorator';
|
import { Language } from 'src/decorators/language.decorator';
|
||||||
import { ApiInternalOnlyEndpoint } from 'src/decorators/swagger.decorator';
|
import { ApiInternalOnlyEndpoint } from 'src/decorators/swagger.decorator';
|
||||||
|
import { TableColumns } from '../inputs/dtos/input.model';
|
||||||
|
import { UpdateInputRequest } from '../inputs/dtos/old_interfaces';
|
||||||
|
import { Info } from '@dadosfera/protospack-v2/dist/lib/Input/interfaces/entities';
|
||||||
|
|
||||||
@ApiTags('PipelinesV2')
|
@ApiTags('PipelinesV2')
|
||||||
@ApiHeaders([{ name: 'dadosfera-lang', enum: LanguageEnum, required: false }])
|
@ApiHeaders([{ name: 'dadosfera-lang', enum: LanguageEnum, required: false }])
|
||||||
@@ -223,6 +227,7 @@ export class PipelinesController {
|
|||||||
.then((res) => {
|
.then((res) => {
|
||||||
//{pipeline:{tables: {tables: [], input_id: ''}}}
|
//{pipeline:{tables: {tables: [], input_id: ''}}}
|
||||||
let tables = JSON.parse(res.pipeline.config.tables);
|
let tables = JSON.parse(res.pipeline.config.tables);
|
||||||
|
const input_id = tables?.input_id;
|
||||||
if (tables?.tables) tables = tables.tables;
|
if (tables?.tables) tables = tables.tables;
|
||||||
Object.assign(res.pipeline, {
|
Object.assign(res.pipeline, {
|
||||||
transformations: res.pipeline.transformations
|
transformations: res.pipeline.transformations
|
||||||
@@ -231,6 +236,7 @@ export class PipelinesController {
|
|||||||
config: {
|
config: {
|
||||||
cron: res.pipeline.config.cron,
|
cron: res.pipeline.config.cron,
|
||||||
tables,
|
tables,
|
||||||
|
input_id
|
||||||
},
|
},
|
||||||
properties: res.pipeline.properties
|
properties: res.pipeline.properties
|
||||||
? JSON.parse(res.pipeline.properties)
|
? JSON.parse(res.pipeline.properties)
|
||||||
@@ -277,6 +283,45 @@ export class PipelinesController {
|
|||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Patch('/:pipelineId/inputs/:id')
|
||||||
|
@RequireSomePermission(PERMISSIONS_GROUPS.PIPELINE.permissions.UPDATE)
|
||||||
|
async updatePipelineInput(
|
||||||
|
@Language() language: LanguageEnum,
|
||||||
|
@Body() pipelineInputDTO: UpdatePlatformInputRequest,
|
||||||
|
@Param('id') inputId: string,
|
||||||
|
@Param('pipelineId') pipelineId: string,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
) {
|
||||||
|
this.logger.info('PipelinesController - update', { user });
|
||||||
|
|
||||||
|
|
||||||
|
const { customer_id, customer_name, user_id, username } = user;
|
||||||
|
const info: Info = {
|
||||||
|
user_id: user.user_id,
|
||||||
|
customer: user.customer_name,
|
||||||
|
customer_id: user.customer_id,
|
||||||
|
};
|
||||||
|
const metadata = PackTheMetadata({
|
||||||
|
customer_id,
|
||||||
|
customer_name,
|
||||||
|
user_id,
|
||||||
|
username,
|
||||||
|
language,
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await this.pipelinesClientService.updatePipelineInput(
|
||||||
|
pipelineId,
|
||||||
|
inputId,
|
||||||
|
pipelineInputDTO,
|
||||||
|
info,
|
||||||
|
user,
|
||||||
|
metadata,
|
||||||
|
);
|
||||||
|
|
||||||
|
this.logger.info('PipelinesController - update: OK', { user });
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
@ApiInternalOnlyEndpoint()
|
@ApiInternalOnlyEndpoint()
|
||||||
@Put('/:id')
|
@Put('/:id')
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { PipelinesModule as OldPipelineModule } from 'src/modules/pipelines/pipe
|
|||||||
import { ConnectorModule } from '../connector/connector.module';
|
import { ConnectorModule } from '../connector/connector.module';
|
||||||
import { InputsModule } from '../inputs/inputs.module';
|
import { InputsModule } from '../inputs/inputs.module';
|
||||||
import { TransformationsModule } from '../transformations/transformations.module';
|
import { TransformationsModule } from '../transformations/transformations.module';
|
||||||
|
import { PlatformApiModule } from '../platform-api/platform-api.module';
|
||||||
|
|
||||||
const client = new PipelinesClientConfiguration();
|
const client = new PipelinesClientConfiguration();
|
||||||
|
|
||||||
@@ -21,6 +22,7 @@ const client = new PipelinesClientConfiguration();
|
|||||||
ConnectorModule,
|
ConnectorModule,
|
||||||
InputsModule,
|
InputsModule,
|
||||||
TransformationsModule,
|
TransformationsModule,
|
||||||
|
PlatformApiModule
|
||||||
],
|
],
|
||||||
controllers: [PipelinesController],
|
controllers: [PipelinesController],
|
||||||
providers: [PipelinesService, DadosferaLogger],
|
providers: [PipelinesService, DadosferaLogger],
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-async-promise-executor */
|
||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
HttpException,
|
HttpException,
|
||||||
@@ -16,7 +17,7 @@ import { lastValueFrom } from 'rxjs';
|
|||||||
|
|
||||||
import { DadosferaLogger } from '@dadosfera/dadosfera-logs';
|
import { DadosferaLogger } from '@dadosfera/dadosfera-logs';
|
||||||
import { PipelinesClientConfiguration } from './pipelines-client';
|
import { PipelinesClientConfiguration } from './pipelines-client';
|
||||||
import { ICreatePipelineV2Req } from './interfaces';
|
import { ICreatePipelineV2Req, UpdatePlatformInputRequest, UpdateTableDTO } from './interfaces';
|
||||||
import { PipelineV2CreateRequest } from '@dadosfera/protospack-v2/dist/lib/PipelineV2/interfaces/messages';
|
import { PipelineV2CreateRequest } from '@dadosfera/protospack-v2/dist/lib/PipelineV2/interfaces/messages';
|
||||||
import { Metadata } from '@grpc/grpc-js';
|
import { Metadata } from '@grpc/grpc-js';
|
||||||
import { ConnectorClientService } from '../connector/client.service';
|
import { ConnectorClientService } from '../connector/client.service';
|
||||||
@@ -26,6 +27,8 @@ import { TransformationsService } from '../transformations/transformations.servi
|
|||||||
import { getObjValueFromPath, objHasPath } from 'src/utils/ObjValueFromPath';
|
import { getObjValueFromPath, objHasPath } from 'src/utils/ObjValueFromPath';
|
||||||
import ErrorCodes from 'src/utils/errorCodes';
|
import ErrorCodes from 'src/utils/errorCodes';
|
||||||
import ErrorBuilder from 'src/utils/ErrorBuilder';
|
import ErrorBuilder from 'src/utils/ErrorBuilder';
|
||||||
|
import { PlatformApiService } from '../platform-api/platform-api.service';
|
||||||
|
import { Info } from '@dadosfera/protospack-v2/dist/lib/Input/interfaces/entities';
|
||||||
|
|
||||||
export class PipelinesService implements OnModuleInit {
|
export class PipelinesService implements OnModuleInit {
|
||||||
logger: DadosferaLogger;
|
logger: DadosferaLogger;
|
||||||
@@ -39,6 +42,7 @@ export class PipelinesService implements OnModuleInit {
|
|||||||
private readonly connectorService: ConnectorClientService,
|
private readonly connectorService: ConnectorClientService,
|
||||||
private readonly inputsService: InputsService,
|
private readonly inputsService: InputsService,
|
||||||
private readonly transformationsService: TransformationsService,
|
private readonly transformationsService: TransformationsService,
|
||||||
|
private readonly platformAPI: PlatformApiService
|
||||||
) {
|
) {
|
||||||
this.logger = dadosferaLogger.logger;
|
this.logger = dadosferaLogger.logger;
|
||||||
}
|
}
|
||||||
@@ -138,6 +142,7 @@ export class PipelinesService implements OnModuleInit {
|
|||||||
const findOnePipelineResponse = await lastValueFrom(
|
const findOnePipelineResponse = await lastValueFrom(
|
||||||
this.pipelineReadService.PipelineV2FindOne(data, metadata),
|
this.pipelineReadService.PipelineV2FindOne(data, metadata),
|
||||||
);
|
);
|
||||||
|
console.log('pipeline find one response', findOnePipelineResponse);
|
||||||
this.logger.info('Done');
|
this.logger.info('Done');
|
||||||
|
|
||||||
return findOnePipelineResponse;
|
return findOnePipelineResponse;
|
||||||
@@ -339,4 +344,137 @@ export class PipelinesService implements OnModuleInit {
|
|||||||
|
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updatePipelineInput(pipelineId: string, inputId: string, updateInputDTO: UpdatePlatformInputRequest, info: Info, user: RequestUser, metadata: Metadata) {
|
||||||
|
this.logger.info('InputClientService - Update');
|
||||||
|
|
||||||
|
this.logger.info('Update Dynamo Reference');
|
||||||
|
const pipelineIdFormat = pipelineId.split('-').join('_');
|
||||||
|
const updateInputResponse = await this.inputsService.update(
|
||||||
|
inputId,
|
||||||
|
updateInputDTO,
|
||||||
|
info
|
||||||
|
)
|
||||||
|
|
||||||
|
const requests = [];
|
||||||
|
|
||||||
|
this.logger.info('Dynamo Response', updateInputResponse);
|
||||||
|
|
||||||
|
for (const [index, table] of updateInputDTO.tables.entries()) {
|
||||||
|
const id = `${pipelineIdFormat}_${index}`;
|
||||||
|
this.logger.info('Updating input reference for table', table.name);
|
||||||
|
const body = {}
|
||||||
|
if (table.columns) {
|
||||||
|
body['column_include_list'] = table.columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (table.reference_column) {
|
||||||
|
body['incremental_column_name'] = table.reference_column.name;
|
||||||
|
body['incremental_column_type'] = table.reference_column.type;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (table.identifier_columns) {
|
||||||
|
body['primary_keys'] = table.identifier_columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.info('Request body', body);
|
||||||
|
const updateCollumns = this.platformAPI.proxy(
|
||||||
|
'PATCH',
|
||||||
|
`/jobs/${id}/input`,
|
||||||
|
user,
|
||||||
|
body
|
||||||
|
)
|
||||||
|
requests.push(updateCollumns);
|
||||||
|
|
||||||
|
if (table.memory) {
|
||||||
|
this.logger.info('Updating memory allocation for table', table.name);
|
||||||
|
const updateMemory = this.platformAPI.proxy(
|
||||||
|
'PUT',
|
||||||
|
`/jobs/${id}/memory`,
|
||||||
|
user,
|
||||||
|
{
|
||||||
|
amount: table.memory
|
||||||
|
}
|
||||||
|
)
|
||||||
|
requests.push(updateMemory);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (table.type) {
|
||||||
|
const updateSyncMode = this.updatePipelineSyncMode(table, id, user);
|
||||||
|
requests.push(updateSyncMode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.info('Create Platform Request for each JOB');
|
||||||
|
|
||||||
|
if (updateInputDTO.cron) {
|
||||||
|
const crnUpdatedRequest = new Promise(async (resolve, reject) => {
|
||||||
|
const response = await this.updatePipelineCron(updateInputDTO.cron, pipelineIdFormat, user);
|
||||||
|
|
||||||
|
if (response.error) {
|
||||||
|
this.logger.error('Error updating pipeline cron', response.error);
|
||||||
|
return reject(new ErrorBuilder(response.error));
|
||||||
|
}
|
||||||
|
this.logger.error('Pipeline cron updated successfully', response);
|
||||||
|
return resolve(response);
|
||||||
|
});
|
||||||
|
requests.push(crnUpdatedRequest);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.info('Executing all request for the platform api');
|
||||||
|
|
||||||
|
const results = await Promise.allSettled(requests);
|
||||||
|
this.logger.info('Platform api response', results);
|
||||||
|
|
||||||
|
return updateInputResponse;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private async updatePipelineSyncMode(table: UpdateTableDTO, pipelineId: string, user: RequestUser) {
|
||||||
|
const body = {
|
||||||
|
target_load_type: table.type
|
||||||
|
}
|
||||||
|
|
||||||
|
if (table.type === 'incremental_with_qualify') {
|
||||||
|
body['incremental_column_name'] = table.reference_column.name;
|
||||||
|
body['incremental_column_type'] = table.reference_column.type;
|
||||||
|
body['primary_keys'] = table.identifier_columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (table.type === 'incremental') {
|
||||||
|
body['incremental_column_name'] = table.reference_column.name;
|
||||||
|
body['incremental_column_type'] = table.reference_column.type;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.info('Updating pipeline sync mode', {
|
||||||
|
pipelineId,
|
||||||
|
body
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.platformAPI.proxy(
|
||||||
|
"POST",
|
||||||
|
`/jobs/jdbc/${pipelineId}/sync-mode`,
|
||||||
|
user,
|
||||||
|
body
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private async updatePipelineCron(cron: string, pipelineId: string, user: RequestUser) {
|
||||||
|
try {
|
||||||
|
const response = await this.platformAPI.proxy(
|
||||||
|
'PATCH',
|
||||||
|
`/pipeline/${pipelineId}`,
|
||||||
|
user,
|
||||||
|
{
|
||||||
|
cron
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return response
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
error: error.message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
Query,
|
Query,
|
||||||
Inject,
|
Inject,
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
|
HttpException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ApiTags, ApiOperation } from '@nestjs/swagger';
|
import { ApiTags, ApiOperation } from '@nestjs/swagger';
|
||||||
import { DadosferaLogger } from '@dadosfera/dadosfera-logs';
|
import { DadosferaLogger } from '@dadosfera/dadosfera-logs';
|
||||||
@@ -25,6 +26,22 @@ import { ElasticsearchService } from '../../services/elasticsearch';
|
|||||||
import { DynamoDBService, ReferenceColumn } from '../../services/dynamodb';
|
import { DynamoDBService, ReferenceColumn } from '../../services/dynamodb';
|
||||||
import { CustomersService } from '../customers/customers.service';
|
import { CustomersService } from '../customers/customers.service';
|
||||||
import { validateCronAgainstScheduleLimit } from '../../utils/cron-validation';
|
import { validateCronAgainstScheduleLimit } from '../../utils/cron-validation';
|
||||||
|
import { CatalogService } from '../catalog/catalog.service';
|
||||||
|
import { PackTheMetadata } from '../../utils/PackTheMetadata';
|
||||||
|
import { ValidationTableDTO } from './platform-api.dto';
|
||||||
|
|
||||||
|
|
||||||
|
type ValidateTablesDTO = {
|
||||||
|
tables: Array<{
|
||||||
|
table_schema: string,
|
||||||
|
table_name: string
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
|
||||||
|
type RenameTablesBody = {
|
||||||
|
raw?: { table_name: string; table_schema: string };
|
||||||
|
qualify?: { table_name: string; table_schema: string };
|
||||||
|
}
|
||||||
|
|
||||||
@ApiTags('Platform API')
|
@ApiTags('Platform API')
|
||||||
@Controller('platform')
|
@Controller('platform')
|
||||||
@@ -36,6 +53,7 @@ export class PlatformApiController {
|
|||||||
private readonly elasticsearchService: ElasticsearchService,
|
private readonly elasticsearchService: ElasticsearchService,
|
||||||
private readonly dynamoDBService: DynamoDBService,
|
private readonly dynamoDBService: DynamoDBService,
|
||||||
private readonly customersService: CustomersService,
|
private readonly customersService: CustomersService,
|
||||||
|
private readonly catalogService: CatalogService,
|
||||||
@Inject(DadosferaLogger) dadosferaLogger: DadosferaLogger,
|
@Inject(DadosferaLogger) dadosferaLogger: DadosferaLogger,
|
||||||
) {
|
) {
|
||||||
this.logger = dadosferaLogger.logger;
|
this.logger = dadosferaLogger.logger;
|
||||||
@@ -67,6 +85,23 @@ export class PlatformApiController {
|
|||||||
return jobId?.replace(/-/g, '_') || '';
|
return jobId?.replace(/-/g, '_') || '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async getJobByAnyConnectorType(normalizedJobId: string, user: RequestUser): Promise<any> {
|
||||||
|
const connectorTypes = ['jdbc', 'singer', 's3'];
|
||||||
|
for (const type of connectorTypes) {
|
||||||
|
try {
|
||||||
|
const job = await this.platformApiService.proxy(
|
||||||
|
'GET',
|
||||||
|
`/jobs/${type}/${normalizedJobId}`,
|
||||||
|
user,
|
||||||
|
);
|
||||||
|
return job;
|
||||||
|
} catch (error) {
|
||||||
|
// Continue to next connector type
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new HttpException(`Job ${normalizedJobId} not found in any connector type (jdbc, singer, s3)`, 404);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Extract the pipeline ID (base UUID) from a job ID.
|
* Extract the pipeline ID (base UUID) from a job ID.
|
||||||
* Job IDs have format "uuid-suffix" where suffix is the job index (e.g., "0", "1").
|
* Job IDs have format "uuid-suffix" where suffix is the job index (e.g., "0", "1").
|
||||||
@@ -720,6 +755,41 @@ export class PlatformApiController {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== PIPELINE VALIDATION ====================
|
||||||
|
|
||||||
|
@Get('pipelines/catalog/schemas')
|
||||||
|
@ApiOperation({ summary: 'Get available schemas' })
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.PIPELINE.permissions.GET)
|
||||||
|
async getAvailableSchemas(
|
||||||
|
@User() user: RequestUser,
|
||||||
|
@Query() query: Record<string, string>,
|
||||||
|
) {
|
||||||
|
return this.platformApiService.proxy(
|
||||||
|
'GET',
|
||||||
|
`/catalog/schemas`,
|
||||||
|
user,
|
||||||
|
undefined,
|
||||||
|
query,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('pipelines/catalog/tables/validate')
|
||||||
|
@ApiOperation({ summary: 'Validate Table and Schema' })
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.PIPELINE.permissions.GET)
|
||||||
|
async validateTableAndSchema(
|
||||||
|
@Body() payload: ValidationTableDTO,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
@Query() query: Record<string, string>,
|
||||||
|
) {
|
||||||
|
return this.platformApiService.proxy(
|
||||||
|
'POST',
|
||||||
|
`/catalog/tables/validate`,
|
||||||
|
user,
|
||||||
|
payload,
|
||||||
|
query,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ==================== PIPELINE RUN ROUTES ====================
|
// ==================== PIPELINE RUN ROUTES ====================
|
||||||
|
|
||||||
@Get('pipeline/:pipelineId/pipeline_run')
|
@Get('pipeline/:pipelineId/pipeline_run')
|
||||||
@@ -909,6 +979,192 @@ export class PlatformApiController {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post('jobs/:jobId/rename-tables')
|
||||||
|
@ApiOperation({ summary: 'Rename job output tables and sync to catalog' })
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.PIPELINE.permissions.UPDATE)
|
||||||
|
async renameJobTables(
|
||||||
|
@Param('jobId') jobId: string,
|
||||||
|
@Body() body: RenameTablesBody,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
) {
|
||||||
|
const normalizedJobId = this.normalizeJobId(jobId);
|
||||||
|
|
||||||
|
const currentJob = await this.getJobByAnyConnectorType(normalizedJobId, user);
|
||||||
|
|
||||||
|
const result = await this.platformApiService.proxy(
|
||||||
|
'POST',
|
||||||
|
`/jobs/${normalizedJobId}/rename-tables`,
|
||||||
|
user,
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.syncTableRenameToCatalog(jobId, body, currentJob, user);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error('Catalog sync failed, rolling back Snowflake rename', { jobId, error: error.message });
|
||||||
|
|
||||||
|
const reverseBody = this.buildSnowflakeRollbackBody(body, currentJob.output_config || {});
|
||||||
|
if (reverseBody) {
|
||||||
|
try {
|
||||||
|
await this.platformApiService.proxy('POST', `/jobs/${normalizedJobId}/rename-tables`, user, reverseBody);
|
||||||
|
this.logger.info('Snowflake rename rolled back', { jobId });
|
||||||
|
} catch (rollbackError) {
|
||||||
|
this.logger.error('Snowflake rollback failed', { jobId, error: rollbackError.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new HttpException('Table rename failed: catalog sync error, Snowflake reverted', 500);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildSnowflakeRollbackBody(
|
||||||
|
body: RenameTablesBody,
|
||||||
|
outputConfig: any,
|
||||||
|
): RenameTablesBody | null {
|
||||||
|
const reverse: RenameTablesBody = {};
|
||||||
|
|
||||||
|
if (body.raw) {
|
||||||
|
const nested = outputConfig.raw;
|
||||||
|
const oldTableName = nested?.table_name || outputConfig.table_name;
|
||||||
|
const oldTableSchema = nested?.table_schema || 'PUBLIC';
|
||||||
|
if (oldTableName) reverse.raw = { table_name: oldTableName, table_schema: oldTableSchema };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body.qualify) {
|
||||||
|
const nested = outputConfig.qualify;
|
||||||
|
if (nested?.table_name) reverse.qualify = { table_name: nested.table_name, table_schema: nested.table_schema || 'STAGED' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.keys(reverse).length > 0 ? reverse : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sync table rename to Elasticsearch and Nimbus.
|
||||||
|
*
|
||||||
|
* For each target (raw, qualify):
|
||||||
|
* 1. Resolve old table name from output_config
|
||||||
|
* 2. Find the ES data asset by pipeline + table + schema
|
||||||
|
* 3. Update ES, Nimbus table-metadata, column-metadata, and data-preview
|
||||||
|
* 4. If any step fails, rollback all completed steps for that target
|
||||||
|
*/
|
||||||
|
private async syncTableRenameToCatalog(
|
||||||
|
jobId: string,
|
||||||
|
body: RenameTablesBody,
|
||||||
|
currentJob: any,
|
||||||
|
user: RequestUser,
|
||||||
|
): Promise<void> {
|
||||||
|
const pipelineId = this.extractPipelineIdFromJobId(jobId);
|
||||||
|
const outputConfig = currentJob.output_config || {};
|
||||||
|
const nimbusUrl = this.catalogService._getNimbusUrl({ info: { customer: user.customer_name } });
|
||||||
|
const databaseName = `DADOSFERA_PRD_${user.customer_name.toUpperCase()}`;
|
||||||
|
|
||||||
|
const targets = this.buildRenameTargets(body, outputConfig);
|
||||||
|
|
||||||
|
for (const { key, oldTableName, oldTableSchema, newValues } of targets) {
|
||||||
|
const rollbackSteps: Array<() => Promise<void>> = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const dataAsset = await this.elasticsearchService.findDataAssetByTable(
|
||||||
|
user.customer_name, oldTableName, oldTableSchema,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!dataAsset) {
|
||||||
|
this.logger.warn(`No data asset found for ${key}`, { jobId, pipelineId, oldTableName, oldTableSchema });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { _es_id: esAssetId, nimbus_id: nimbusId } = dataAsset;
|
||||||
|
const oldValues = { table_name: oldTableName, table_schema: oldTableSchema };
|
||||||
|
|
||||||
|
// ES update
|
||||||
|
const esFields = { name: newValues.table_name, table_name: newValues.table_name, table_schema: newValues.table_schema, display_name: newValues.table_name };
|
||||||
|
await this.elasticsearchService.updateDataAsset(user.customer_name, esAssetId, esFields);
|
||||||
|
rollbackSteps.push(() => this.elasticsearchService.updateDataAsset(
|
||||||
|
user.customer_name, esAssetId,
|
||||||
|
{ name: oldTableName, table_name: oldTableName, table_schema: oldTableSchema, display_name: oldTableName },
|
||||||
|
));
|
||||||
|
|
||||||
|
const newTableNameUpper = newValues.table_name.toUpperCase();
|
||||||
|
const newTableSchemaUpper = newValues.table_schema.toUpperCase();
|
||||||
|
const oldTableNameUpper = oldTableName.toUpperCase();
|
||||||
|
const oldTableSchemaUpper = oldTableSchema.toUpperCase();
|
||||||
|
|
||||||
|
// Nimbus table-metadata
|
||||||
|
if (nimbusId) {
|
||||||
|
await this.catalogService.renameTableOnNimbus(nimbusUrl, nimbusId, { table_name: newTableNameUpper, table_schema: newTableSchemaUpper });
|
||||||
|
rollbackSteps.push(() => this.catalogService.renameTableOnNimbus(nimbusUrl, nimbusId, { table_name: oldTableNameUpper, table_schema: oldTableSchemaUpper }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nimbus column-metadata
|
||||||
|
await this.catalogService.renameColumnMetadataOnNimbus(
|
||||||
|
nimbusUrl, databaseName, oldTableNameUpper, oldTableSchemaUpper, newTableNameUpper, newTableSchemaUpper,
|
||||||
|
);
|
||||||
|
rollbackSteps.push(() => this.catalogService.renameColumnMetadataOnNimbus(
|
||||||
|
nimbusUrl, databaseName, newTableNameUpper, newTableSchemaUpper, oldTableNameUpper, oldTableSchemaUpper,
|
||||||
|
));
|
||||||
|
|
||||||
|
// Nimbus data-preview
|
||||||
|
await this.catalogService.renameDataPreviewOnNimbus(
|
||||||
|
nimbusUrl, databaseName, oldTableNameUpper, oldTableSchemaUpper, newTableNameUpper, newTableSchemaUpper,
|
||||||
|
);
|
||||||
|
rollbackSteps.push(() => this.catalogService.renameDataPreviewOnNimbus(
|
||||||
|
nimbusUrl, databaseName, newTableNameUpper, newTableSchemaUpper, oldTableNameUpper, oldTableSchemaUpper,
|
||||||
|
));
|
||||||
|
|
||||||
|
this.logger.info(`Synced catalog rename for ${key}`, { jobId, oldTableName, newTableName: newValues.table_name });
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(`Catalog sync failed for ${key}, rolling back catalog`, { jobId, error: error.message });
|
||||||
|
await this.executeRollback(rollbackSteps, key, jobId);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildRenameTargets(
|
||||||
|
body: RenameTablesBody,
|
||||||
|
outputConfig: any,
|
||||||
|
): Array<{ key: string; oldTableName: string; oldTableSchema: string; newValues: { table_name: string; table_schema: string } }> {
|
||||||
|
const DEFAULT_SCHEMAS = { raw: 'PUBLIC', qualify: 'STAGED' };
|
||||||
|
const targets: Array<{ key: string; oldTableName: string; oldTableSchema: string; newValues: { table_name: string; table_schema: string } }> = [];
|
||||||
|
|
||||||
|
for (const key of ['raw', 'qualify'] as const) {
|
||||||
|
if (!body[key]) continue;
|
||||||
|
|
||||||
|
const nested = outputConfig[key];
|
||||||
|
|
||||||
|
// qualify: only sync if output_config.qualify already exists
|
||||||
|
if (key === 'qualify' && !nested?.table_name) continue;
|
||||||
|
|
||||||
|
const oldTableName = nested?.table_name || outputConfig.table_name;
|
||||||
|
if (!oldTableName) continue;
|
||||||
|
|
||||||
|
targets.push({
|
||||||
|
key,
|
||||||
|
oldTableName,
|
||||||
|
oldTableSchema: nested?.table_schema || DEFAULT_SCHEMAS[key],
|
||||||
|
newValues: body[key],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return targets;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async executeRollback(
|
||||||
|
steps: Array<() => Promise<void>>,
|
||||||
|
targetKey: string,
|
||||||
|
jobId: string,
|
||||||
|
): Promise<void> {
|
||||||
|
for (const rollback of steps.reverse()) {
|
||||||
|
try {
|
||||||
|
await rollback();
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(`Rollback failed for ${targetKey}`, { jobId, error: error.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Get('jobs/jdbc/configs/allowed_datatypes')
|
@Get('jobs/jdbc/configs/allowed_datatypes')
|
||||||
@ApiOperation({ summary: 'Get allowed datatypes for JDBC' })
|
@ApiOperation({ summary: 'Get allowed datatypes for JDBC' })
|
||||||
@RequireAllPermissions(PERMISSIONS_GROUPS.PIPELINE.permissions.GET)
|
@RequireAllPermissions(PERMISSIONS_GROUPS.PIPELINE.permissions.GET)
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { ApiProperty } from "@nestjs/swagger";
|
||||||
|
|
||||||
|
export class ValidationTableDTO {
|
||||||
|
@ApiProperty()
|
||||||
|
tables: Array<{
|
||||||
|
table_name: string;
|
||||||
|
table_schema: string;
|
||||||
|
}>
|
||||||
|
}
|
||||||
@@ -7,9 +7,10 @@ import { PlatformApiService } from './platform-api.service';
|
|||||||
import { ElasticsearchModule } from '../../services/elasticsearch';
|
import { ElasticsearchModule } from '../../services/elasticsearch';
|
||||||
import { DynamoDBModule } from '../../services/dynamodb';
|
import { DynamoDBModule } from '../../services/dynamodb';
|
||||||
import { CustomersModule } from '../customers/customers.module';
|
import { CustomersModule } from '../customers/customers.module';
|
||||||
|
import { CatalogModule } from '../catalog/catalog.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ElasticsearchModule, DynamoDBModule, CustomersModule],
|
imports: [ElasticsearchModule, DynamoDBModule, CustomersModule, CatalogModule],
|
||||||
controllers: [PlatformApiController],
|
controllers: [PlatformApiController],
|
||||||
providers: [PlatformApiService, DadosferaLogger],
|
providers: [PlatformApiService, DadosferaLogger],
|
||||||
exports: [PlatformApiService],
|
exports: [PlatformApiService],
|
||||||
|
|||||||
@@ -89,6 +89,12 @@ export class PlatformApiService {
|
|||||||
|
|
||||||
// Propagate non-2xx responses as HttpExceptions
|
// Propagate non-2xx responses as HttpExceptions
|
||||||
if (response.status >= 400) {
|
if (response.status >= 400) {
|
||||||
|
this.logger.error('Platform API upstream error', {
|
||||||
|
status: response.status,
|
||||||
|
data: response.data,
|
||||||
|
path,
|
||||||
|
method: method.toUpperCase(),
|
||||||
|
});
|
||||||
throw new HttpException(response.data, response.status);
|
throw new HttpException(response.data, response.status);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -229,27 +229,33 @@ export class RolesService {
|
|||||||
const [roleTreated] = this.getRolesPermissionsName([role.role]);
|
const [roleTreated] = this.getRolesPermissionsName([role.role]);
|
||||||
return { role: roleTreated };
|
return { role: roleTreated };
|
||||||
}
|
}
|
||||||
|
|
||||||
getRolesPermissionsName(roles: GetRolesPermissionsName[]): RoleDto[] {
|
getRolesPermissionsName(roles: GetRolesPermissionsName[]): RoleDto[] {
|
||||||
const newRoles: RoleDto[] = [];
|
const newRoles: RoleDto[] = [];
|
||||||
for (const role of roles) {
|
for (const role of roles) {
|
||||||
const allPermissions = this.permissionsService.getAllPermissions(
|
const newRole: RoleDto = this.formatRole(role);
|
||||||
this.language,
|
|
||||||
);
|
|
||||||
const newPermissions = role.permissions.map((p) => {
|
|
||||||
const permission = allPermissions.find((per) => per.seqid === p.seqid);
|
|
||||||
return {
|
|
||||||
...p,
|
|
||||||
name: permission.name,
|
|
||||||
id: p.seqid,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
const newRole: RoleDto = {
|
|
||||||
...role,
|
|
||||||
permissions: newPermissions,
|
|
||||||
isPublic: role.isPublic,
|
|
||||||
};
|
|
||||||
newRoles.push(newRole);
|
newRoles.push(newRole);
|
||||||
}
|
}
|
||||||
return newRoles;
|
return newRoles;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private formatRole(role: GetRolesPermissionsName): RoleDto {
|
||||||
|
const allPermissions = this.permissionsService.getAllPermissions(
|
||||||
|
this.language
|
||||||
|
);
|
||||||
|
const newPermissions = role.permissions.map((p) => {
|
||||||
|
const permission = allPermissions.find((per) => per.seqid === p.seqid);
|
||||||
|
return {
|
||||||
|
...p,
|
||||||
|
name: permission.name,
|
||||||
|
id: p.seqid,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
...role,
|
||||||
|
permissions: newPermissions,
|
||||||
|
isPublic: role.isPublic,
|
||||||
|
};;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
export const STORAGE_EXPLORER_CONFIG = {
|
||||||
|
getUrl: (customerName: string): string => {
|
||||||
|
const urlTemplate = process.env.STORAGE_EXPLORER_API_URL;
|
||||||
|
if (!urlTemplate) {
|
||||||
|
throw new Error('STORAGE_EXPLORER_API_URL environment variable is not set');
|
||||||
|
}
|
||||||
|
// Replace {customer_id} placeholder with actual customer ID
|
||||||
|
// For local: http://172.17.0.1:8000/api (no placeholder)
|
||||||
|
// For prod: https://storage-explorer-{customer_id}.dadosfera.ai/api
|
||||||
|
return urlTemplate.replace('{customer}', customerName);
|
||||||
|
},
|
||||||
|
timeout: parseInt(process.env.STORAGE_EXPLORER_TIMEOUT || '30000', 10),
|
||||||
|
};
|
||||||
@@ -0,0 +1,383 @@
|
|||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
Param,
|
||||||
|
Body,
|
||||||
|
Query,
|
||||||
|
Inject,
|
||||||
|
UseInterceptors,
|
||||||
|
UploadedFiles,
|
||||||
|
Headers,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { ApiTags, ApiOperation, ApiConsumes } from '@nestjs/swagger';
|
||||||
|
import { FilesInterceptor } from '@nestjs/platform-express';
|
||||||
|
import { DadosferaLogger } from '@dadosfera/dadosfera-logs';
|
||||||
|
import FormData from 'form-data';
|
||||||
|
|
||||||
|
import {
|
||||||
|
Authenticated,
|
||||||
|
RequireAllPermissions,
|
||||||
|
} from '../../decorators/authentication.decorator';
|
||||||
|
import { User, RequestUser } from '../../decorators/user.decorator';
|
||||||
|
import { StorageExplorerService } from './storage-explorer.service';
|
||||||
|
import { PERMISSIONS_GROUPS } from '../../authentication/permissions.enum';
|
||||||
|
|
||||||
|
@ApiTags('Storage Explorer')
|
||||||
|
@Controller('storage-explorer')
|
||||||
|
@Authenticated()
|
||||||
|
export class StorageExplorerController {
|
||||||
|
private logger: any;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly storageExplorerService: StorageExplorerService,
|
||||||
|
@Inject(DadosferaLogger) dadosferaLogger: DadosferaLogger,
|
||||||
|
) {
|
||||||
|
this.logger = dadosferaLogger.logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// TABLE OPERATIONS
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Validate table name in PostgreSQL and Snowflake' })
|
||||||
|
@Post('tables/validate-name')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.WRITE)
|
||||||
|
async validateTableName(
|
||||||
|
@Body() body: any,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'POST',
|
||||||
|
'/tables/validate-name',
|
||||||
|
user,
|
||||||
|
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Create a new table' })
|
||||||
|
@Post('tables')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.WRITE)
|
||||||
|
async createTable(
|
||||||
|
@Body() body: any,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'POST',
|
||||||
|
'/tables/',
|
||||||
|
user,
|
||||||
|
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'List all tables with pagination' })
|
||||||
|
@Get('tables')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.READ)
|
||||||
|
async listTables(
|
||||||
|
@Query('page') page: number,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'GET',
|
||||||
|
'/tables/',
|
||||||
|
user,
|
||||||
|
|
||||||
|
undefined,
|
||||||
|
{ page },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Get table details by ID' })
|
||||||
|
@Get('tables/:tableId')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.READ)
|
||||||
|
async getTable(
|
||||||
|
@Param('tableId') tableId: string,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'GET',
|
||||||
|
`/tables/${tableId}`,
|
||||||
|
user,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Link a dataset to a table' })
|
||||||
|
@Post('tables/:tableId/datasets/:datasetId')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.WRITE)
|
||||||
|
async linkDatasetToTable(
|
||||||
|
@Param('tableId') tableId: string,
|
||||||
|
@Param('datasetId') datasetId: string,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'POST',
|
||||||
|
`/tables/${tableId}/datasets/${datasetId}`,
|
||||||
|
user,
|
||||||
|
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Get all datasets linked to a table' })
|
||||||
|
@Get('tables/:tableId/datasets')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.READ)
|
||||||
|
async getTableDatasets(
|
||||||
|
@Param('tableId') tableId: string,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'GET',
|
||||||
|
`/tables/${tableId}/datasets`,
|
||||||
|
user,
|
||||||
|
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Get table schema' })
|
||||||
|
@Get('tables/:tableId/schema')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.READ)
|
||||||
|
async getTableSchema(
|
||||||
|
@Param('tableId') tableId: string,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'GET',
|
||||||
|
`/tables/${tableId}/schema`,
|
||||||
|
user,
|
||||||
|
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Validate schema compatibility between table and dataset' })
|
||||||
|
@Post('tables/:tableId/validate-compatibility/:datasetId')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.READ)
|
||||||
|
async validateSchemaCompatibility(
|
||||||
|
@Param('tableId') tableId: string,
|
||||||
|
@Param('datasetId') datasetId: string,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'POST',
|
||||||
|
`/tables/${tableId}/validate-compatibility/${datasetId}`,
|
||||||
|
user,
|
||||||
|
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// DATASET OPERATIONS
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Get dataset preview data' })
|
||||||
|
@Get('datasets/:datasetId/preview')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.READ)
|
||||||
|
async getDatasetPreview(
|
||||||
|
@Param('datasetId') datasetId: string,
|
||||||
|
@Query('limit') limit: number,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'GET',
|
||||||
|
`/datasets/${datasetId}/preview`,
|
||||||
|
user,
|
||||||
|
|
||||||
|
undefined,
|
||||||
|
{ limit },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Get dataset schema information' })
|
||||||
|
@Get('datasets/:datasetId/schema')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.READ)
|
||||||
|
async getDatasetSchema(
|
||||||
|
@Param('datasetId') datasetId: string,
|
||||||
|
@Query('force_refresh') forceRefresh: boolean,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'GET',
|
||||||
|
`/datasets/${datasetId}/schema`,
|
||||||
|
user,
|
||||||
|
|
||||||
|
undefined,
|
||||||
|
{ force_refresh: forceRefresh },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'List all datasets for a specific upload' })
|
||||||
|
@Get('datasets/upload/:uploadId')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.READ)
|
||||||
|
async listDatasetsByUpload(
|
||||||
|
@Param('uploadId') uploadId: string,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'GET',
|
||||||
|
`/datasets/upload/${uploadId}`,
|
||||||
|
user,
|
||||||
|
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Refresh dataset schema with new parsing options (Excel)' })
|
||||||
|
@Put('datasets/:datasetId/refresh-schema')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.WRITE)
|
||||||
|
async refreshDatasetSchema(
|
||||||
|
@Param('datasetId') datasetId: string,
|
||||||
|
@Body() body: any,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'PUT',
|
||||||
|
`/datasets/${datasetId}/refresh-schema`,
|
||||||
|
user,
|
||||||
|
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// STORAGE OPERATIONS
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'List file explorer uploads with pagination' })
|
||||||
|
@Get('storage/uploads/history')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.READ)
|
||||||
|
async listFileExplorerUploads(
|
||||||
|
@Query('page') page: number,
|
||||||
|
@Query('limit') limit: number,
|
||||||
|
@Query('folder_path') folderPath: string,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'GET',
|
||||||
|
'/storage/uploads/history',
|
||||||
|
user,
|
||||||
|
|
||||||
|
undefined,
|
||||||
|
{ page, limit, folder_path: folderPath },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Browse folders and files in storage' })
|
||||||
|
@Get('storage/browse')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.READ)
|
||||||
|
async browseStorage(
|
||||||
|
@Query('path') path: string,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'GET',
|
||||||
|
'/storage/browse',
|
||||||
|
user,
|
||||||
|
|
||||||
|
undefined,
|
||||||
|
{ path },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Upload multiple files to storage' })
|
||||||
|
@Post('storage/upload/batch')
|
||||||
|
@ApiConsumes('multipart/form-data')
|
||||||
|
@UseInterceptors(FilesInterceptor('files'))
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.WRITE)
|
||||||
|
async batchUpload(
|
||||||
|
@UploadedFiles() files: Array<Express.Multer.File>,
|
||||||
|
@Body('folder_path') folderPath: string,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
// Create FormData to forward files to storage-explorer API
|
||||||
|
const formData = new FormData();
|
||||||
|
|
||||||
|
// Add files
|
||||||
|
if (files && files.length > 0) {
|
||||||
|
files.forEach((file) => {
|
||||||
|
formData.append('files', file.buffer, {
|
||||||
|
filename: file.originalname,
|
||||||
|
contentType: file.mimetype,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add folder_path
|
||||||
|
if (folderPath) {
|
||||||
|
formData.append('folder_path', folderPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.storageExplorerService.proxyFormData(
|
||||||
|
'POST',
|
||||||
|
'/storage/upload/batch',
|
||||||
|
user,
|
||||||
|
|
||||||
|
formData,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Create a new folder in storage' })
|
||||||
|
@Post('storage/folder/create')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.WRITE)
|
||||||
|
async createFolder(
|
||||||
|
@Body() body: any,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'POST',
|
||||||
|
'/storage/folder/create',
|
||||||
|
user,
|
||||||
|
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Download a file from storage' })
|
||||||
|
@Get('storage/download')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.READ)
|
||||||
|
async downloadFile(
|
||||||
|
@Query('file_path') filePath: string,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'GET',
|
||||||
|
'/storage/download',
|
||||||
|
user,
|
||||||
|
|
||||||
|
undefined,
|
||||||
|
{ file_path: filePath },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiOperation({ summary: 'Get detailed file metadata' })
|
||||||
|
@Get('storage/metadata')
|
||||||
|
@RequireAllPermissions(PERMISSIONS_GROUPS.STORAGE_EXPLORER.permissions.READ)
|
||||||
|
async getFileMetadata(
|
||||||
|
@Query('file_path') filePath: string,
|
||||||
|
@User() user: RequestUser,
|
||||||
|
|
||||||
|
) {
|
||||||
|
return this.storageExplorerService.proxy(
|
||||||
|
'GET',
|
||||||
|
'/storage/metadata',
|
||||||
|
user,
|
||||||
|
undefined,
|
||||||
|
{ file_path: filePath },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { DadosferaLogger } from '@dadosfera/dadosfera-logs';
|
||||||
|
|
||||||
|
import { StorageExplorerController } from './storage-explorer.controller';
|
||||||
|
import { StorageExplorerService } from './storage-explorer.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [],
|
||||||
|
controllers: [StorageExplorerController],
|
||||||
|
providers: [StorageExplorerService, DadosferaLogger],
|
||||||
|
exports: [StorageExplorerService],
|
||||||
|
})
|
||||||
|
export class StorageExplorerModule {}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
import { Injectable, Inject, HttpException } from '@nestjs/common';
|
||||||
|
import axios, { AxiosResponse, Method } from 'axios';
|
||||||
|
import { DadosferaLogger } from '@dadosfera/dadosfera-logs';
|
||||||
|
|
||||||
|
import { RequestUser } from '../../decorators/user.decorator';
|
||||||
|
import { STORAGE_EXPLORER_CONFIG } from './storage-explorer.config';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class StorageExplorerService {
|
||||||
|
private logger: any;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@Inject(DadosferaLogger) dadosferaLogger: DadosferaLogger,
|
||||||
|
) {
|
||||||
|
this.logger = dadosferaLogger.logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
async proxy(
|
||||||
|
method: string,
|
||||||
|
path: string,
|
||||||
|
user: RequestUser,
|
||||||
|
body?: any,
|
||||||
|
query?: Record<string, any>
|
||||||
|
): Promise<any> {
|
||||||
|
// Validate customer_id is present for multi-tenant isolation
|
||||||
|
if (!user.customer_id) {
|
||||||
|
throw new HttpException('Customer ID is required for storage operations', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get customer-specific storage-explorer URL
|
||||||
|
const baseUrl = STORAGE_EXPLORER_CONFIG.getUrl(user.customer_name);
|
||||||
|
const url = new URL(`${baseUrl}${path}`);
|
||||||
|
|
||||||
|
// Add query params
|
||||||
|
if (query) {
|
||||||
|
Object.entries(query).forEach(([key, value]) => {
|
||||||
|
if (value !== undefined && value !== null) {
|
||||||
|
url.searchParams.set(key, String(value));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
'content-type': 'application/json',
|
||||||
|
};
|
||||||
|
|
||||||
|
this.logger.info('Proxying request to storage-explorer', {
|
||||||
|
method: method.toUpperCase(),
|
||||||
|
path,
|
||||||
|
customer_id: user.customer_id,
|
||||||
|
storage_url: baseUrl,
|
||||||
|
user_id: user.user_id,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response: AxiosResponse = await axios({
|
||||||
|
method: method as Method,
|
||||||
|
url: url.href,
|
||||||
|
headers,
|
||||||
|
data: body,
|
||||||
|
timeout: STORAGE_EXPLORER_CONFIG.timeout,
|
||||||
|
validateStatus: () => true, // Don't throw on non-2xx
|
||||||
|
});
|
||||||
|
|
||||||
|
// Propagate non-2xx responses as HttpExceptions
|
||||||
|
if (response.status >= 400) {
|
||||||
|
throw new HttpException(response.data, response.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error('Storage Explorer API proxy error', {
|
||||||
|
error: error.message,
|
||||||
|
status: error.response?.status,
|
||||||
|
path,
|
||||||
|
storage_url: baseUrl,
|
||||||
|
method: method.toUpperCase(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error instanceof HttpException) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error.response) {
|
||||||
|
throw new HttpException(error.response.data, error.response.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error.code === 'ECONNREFUSED') {
|
||||||
|
throw new HttpException('Storage Explorer API service unavailable', 503);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error.code === 'ETIMEDOUT' || error.code === 'ECONNABORTED') {
|
||||||
|
throw new HttpException('Storage Explorer API request timeout', 504);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new HttpException('Internal server error', 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Proxy with file upload support (multipart/form-data)
|
||||||
|
*/
|
||||||
|
async proxyFormData(
|
||||||
|
method: string,
|
||||||
|
path: string,
|
||||||
|
user: RequestUser,
|
||||||
|
formData: any,
|
||||||
|
query?: Record<string, any>,
|
||||||
|
): Promise<any> {
|
||||||
|
// Validate customer_id is present for multi-tenant isolation
|
||||||
|
if (!user.customer_id) {
|
||||||
|
throw new HttpException('Customer ID is required for storage operations', 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get customer-specific storage-explorer URL
|
||||||
|
const baseUrl = STORAGE_EXPLORER_CONFIG.getUrl(user.customer_name);
|
||||||
|
const url = new URL(`${baseUrl}${path}`);
|
||||||
|
|
||||||
|
// Add query params
|
||||||
|
if (query) {
|
||||||
|
Object.entries(query).forEach(([key, value]) => {
|
||||||
|
if (value !== undefined && value !== null) {
|
||||||
|
url.searchParams.set(key, String(value));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
// Let axios set Content-Type for multipart/form-data with boundary
|
||||||
|
...formData.getHeaders?.(),
|
||||||
|
};
|
||||||
|
|
||||||
|
this.logger.info('Proxying form data request to storage-explorer', {
|
||||||
|
method: method.toUpperCase(),
|
||||||
|
path,
|
||||||
|
customer_id: user.customer_id,
|
||||||
|
storage_url: baseUrl,
|
||||||
|
user_id: user.user_id,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response: AxiosResponse = await axios({
|
||||||
|
method: method as Method,
|
||||||
|
url: url.href,
|
||||||
|
headers,
|
||||||
|
data: formData,
|
||||||
|
timeout: STORAGE_EXPLORER_CONFIG.timeout,
|
||||||
|
maxContentLength: Infinity,
|
||||||
|
maxBodyLength: Infinity,
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status >= 400) {
|
||||||
|
throw new HttpException(response.data, response.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error('Storage Explorer API form data proxy error', {
|
||||||
|
error: error.message,
|
||||||
|
status: error.response?.status,
|
||||||
|
path,
|
||||||
|
storage_url: baseUrl,
|
||||||
|
method: method.toUpperCase(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error instanceof HttpException) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error.response) {
|
||||||
|
throw new HttpException(error.response.data, error.response.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new HttpException('Internal server error', 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -38,6 +38,12 @@ export class User {
|
|||||||
department?: string;
|
department?: string;
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
hierarchy?: string;
|
hierarchy?: string;
|
||||||
|
@ApiProperty()
|
||||||
|
bio?: string;
|
||||||
|
@ApiProperty()
|
||||||
|
companyName?: string;
|
||||||
|
@ApiProperty()
|
||||||
|
personalSite?: string;
|
||||||
@ApiPropertyOptional()
|
@ApiPropertyOptional()
|
||||||
customer?: Customer;
|
customer?: Customer;
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
@@ -58,6 +64,8 @@ export class UserNoRolesAndCustomer extends OmitType(UserNoRoles, [
|
|||||||
export class IUserByCustomer extends OmitType(User, ['customer']) {
|
export class IUserByCustomer extends OmitType(User, ['customer']) {
|
||||||
@ApiPropertyOptional()
|
@ApiPropertyOptional()
|
||||||
permissions?: string[];
|
permissions?: string[];
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
authProvider?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class CreateUserReq {
|
export class CreateUserReq {
|
||||||
@@ -109,6 +117,12 @@ export class UpdateUserReq {
|
|||||||
@ApiPropertyOptional()
|
@ApiPropertyOptional()
|
||||||
hierarchy?: string;
|
hierarchy?: string;
|
||||||
@ApiPropertyOptional()
|
@ApiPropertyOptional()
|
||||||
|
bio?: string;
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
personalSite?: string;
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
companyName?: string;
|
||||||
|
@ApiPropertyOptional()
|
||||||
roleNames?: string[];
|
roleNames?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -266,7 +266,6 @@ export class UsersController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Patch(':id')
|
@Patch(':id')
|
||||||
@RequireAllPermissions(PERMISSIONS_GROUPS.USERS.permissions.ADMIN)
|
|
||||||
@ApiOkResponse({ type: UpdateUserRes })
|
@ApiOkResponse({ type: UpdateUserRes })
|
||||||
async updateUser(
|
async updateUser(
|
||||||
@User() user: RequestUser,
|
@User() user: RequestUser,
|
||||||
@@ -274,6 +273,18 @@ export class UsersController {
|
|||||||
@Param('id') id: string,
|
@Param('id') id: string,
|
||||||
@Language() language: LanguageEnum,
|
@Language() language: LanguageEnum,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
|
const isSameUser = user.user_id === id;
|
||||||
|
const isSuperAdmin = user.permissions.includes(PERMISSIONS_GROUPS.USERS.permissions.ADMIN.seqid)
|
||||||
|
if (!isSameUser && !isSuperAdmin) {
|
||||||
|
throw new ErrorBuilder(ErrorCodes.AUTH.FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isSameUser && !isSuperAdmin && body.roleNames) {
|
||||||
|
// Prevent users from updating their own roles
|
||||||
|
delete body.roleNames;
|
||||||
|
}
|
||||||
|
|
||||||
this.logger.info('updateUser', { user });
|
this.logger.info('updateUser', { user });
|
||||||
this.userService.setLanguage(language);
|
this.userService.setLanguage(language);
|
||||||
return await this.userService.updateUser(body, id, user.customer_id);
|
return await this.userService.updateUser(body, id, user.customer_id);
|
||||||
|
|||||||
@@ -125,6 +125,7 @@ export class UsersService implements OnModuleInit {
|
|||||||
return { permissions };
|
return { permissions };
|
||||||
});
|
});
|
||||||
res.user.permissions = permissions;
|
res.user.permissions = permissions;
|
||||||
|
res.user.authProvider = process.env.AUTH_PROVIDER || 'cognito';
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,20 +149,23 @@ export class UsersService implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async updateUser(req: UpdateUserReq, id: string, customerId: string) {
|
async updateUser(req: UpdateUserReq, id: string, customerId: string) {
|
||||||
const { department, hierarchy, jobTitle, name, roleNames, email } = req;
|
const { roleNames, ...updateUserDTO } = req;
|
||||||
if (roleNames) {
|
if (roleNames && roleNames.length > 0) {
|
||||||
await this.setRoles({ roleNames, userId: id }, customerId);
|
await this.setRoles({ roleNames, userId: id }, customerId);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { user } = await lastValueFrom(
|
const { user } = await lastValueFrom(
|
||||||
this.usersClientService.UserUpdate({
|
this.usersClientService.UserUpdate({
|
||||||
name,
|
department: updateUserDTO.department,
|
||||||
|
email: updateUserDTO.email,
|
||||||
|
hierarchy: updateUserDTO.hierarchy,
|
||||||
|
jobTitle: updateUserDTO.jobTitle,
|
||||||
|
name: updateUserDTO.name,
|
||||||
|
bio: updateUserDTO.bio,
|
||||||
|
companyName: updateUserDTO.companyName,
|
||||||
|
personalSite: updateUserDTO.personalSite,
|
||||||
customerId,
|
customerId,
|
||||||
id,
|
id,
|
||||||
department,
|
|
||||||
hierarchy,
|
|
||||||
jobTitle,
|
|
||||||
email,
|
|
||||||
metabaseUserId: undefined,
|
metabaseUserId: undefined,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -14,7 +14,10 @@ export class ValidationPipe implements PipeTransform<any> {
|
|||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
const object = plainToInstance(metatype, value);
|
const object = plainToInstance(metatype, value);
|
||||||
const errors = await validate(object);
|
const errors = await validate(object, {
|
||||||
|
forbidUnknownValues: false,
|
||||||
|
whitelist: true,
|
||||||
|
});
|
||||||
if (errors.length > 0) {
|
if (errors.length > 0) {
|
||||||
const errorMessages = errors.map((err) => err.constraints);
|
const errorMessages = errors.map((err) => err.constraints);
|
||||||
throw new BadRequestException(errorMessages);
|
throw new BadRequestException(errorMessages);
|
||||||
|
|||||||
@@ -358,6 +358,81 @@ export class ElasticsearchService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private getDataAssetIndex(customerName: string): string {
|
||||||
|
return `${customerName}_data_assets_catalog`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findDataAssetByTable(
|
||||||
|
customerName: string,
|
||||||
|
tableName: string,
|
||||||
|
tableSchema: string,
|
||||||
|
): Promise<{ id: string; nimbus_id: number | null; [key: string]: any } | null> {
|
||||||
|
const index = this.getDataAssetIndex(customerName);
|
||||||
|
|
||||||
|
this.logger.info('Elasticsearch: Searching data asset', {
|
||||||
|
index,
|
||||||
|
tableName,
|
||||||
|
tableSchema,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.client.post(`/${index}/_search`, {
|
||||||
|
query: {
|
||||||
|
bool: {
|
||||||
|
must: [
|
||||||
|
{ term: { 'table_name.keyword': tableName.toUpperCase() } },
|
||||||
|
{ term: { 'table_schema.keyword': tableSchema.toUpperCase() } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
size: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
const hits = response.data.hits?.hits || [];
|
||||||
|
if (hits.length === 0) {
|
||||||
|
this.logger.warn('Elasticsearch: Data asset not found', { tableName, tableSchema, index });
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ...hits[0]._source, _es_id: hits[0]._id };
|
||||||
|
} catch (error) {
|
||||||
|
this.handleError('findDataAssetByTable', error, { tableName, tableSchema, index });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateDataAsset(
|
||||||
|
customerName: string,
|
||||||
|
assetId: string,
|
||||||
|
updates: Record<string, any>,
|
||||||
|
): Promise<any> {
|
||||||
|
const index = this.getDataAssetIndex(customerName);
|
||||||
|
|
||||||
|
this.logger.info('Elasticsearch: Updating data asset', {
|
||||||
|
index,
|
||||||
|
assetId,
|
||||||
|
fields: Object.keys(updates),
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.client.post(
|
||||||
|
`/${index}/_update/${assetId}`,
|
||||||
|
{ doc: updates },
|
||||||
|
{ params: { refresh: 'wait_for' } },
|
||||||
|
);
|
||||||
|
|
||||||
|
this.logger.info('Elasticsearch: Data asset updated', {
|
||||||
|
assetId,
|
||||||
|
result: response.data.result,
|
||||||
|
});
|
||||||
|
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
this.handleError('updateDataAsset', error, { assetId, index });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private handleError(
|
private handleError(
|
||||||
operation: string,
|
operation: string,
|
||||||
error: any,
|
error: any,
|
||||||
|
|||||||
Reference in New Issue
Block a user