diff --git a/docsfera.json b/docsfera.json index 0922da4..0f21c43 100644 --- a/docsfera.json +++ b/docsfera.json @@ -5371,6 +5371,92 @@ ] } }, + "/customers/{id}/theme": { + "post": { + "operationId": "CustomersController_saveCustomertheme", + "parameters": [ + { + "name": "id", + "required": true, + "in": "path", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomerThemeRequest" + } + } + } + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomerThemeResponse" + } + } + } + }, + "201": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomerThemeResponse" + } + } + } + } + }, + "tags": [ + "Customers" + ], + "security": [ + { + "access-token": [] + }, + { + "access-token": [] + } + ] + }, + "get": { + "operationId": "CustomersController_getCustomerTheme", + "parameters": [ + { + "name": "id", + "required": true, + "in": "path", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomerThemeResponse" + } + } + } + } + }, + "tags": [ + "Customers" + ] + } + }, "/customers/token": { "get": { "operationId": "CustomersController_getCustomerToken", @@ -5444,6 +5530,43 @@ "Health" ] } + }, + "/open-data/sharing-ocean-data": { + "post": { + "operationId": "OpenDataController_createUser", + "parameters": [ + { + "name": "dadosfera-lang", + "in": "header", + "required": false, + "schema": { + "enum": [ + "pt-br", + "en-us" + ], + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateUserOpenDataDTO" + } + } + } + }, + "responses": { + "201": { + "description": "" + } + }, + "tags": [ + "OpenData" + ] + } } }, "info": { @@ -8221,6 +8344,63 @@ "links" ] }, + "CustomerThemeRequest": { + "type": "object", + "properties": { + "backgroundColor": { + "type": "string" + }, + "textColor": { + "type": "string" + }, + "logoWhite": { + "type": "string" + }, + "logoBlack": { + "type": "string" + } + }, + "required": [ + "backgroundColor", + "textColor", + "logoWhite", + "logoBlack" + ] + }, + "CustomerTheme": { + "type": "object", + "properties": { + "backgroundColor": { + "type": "string" + }, + "textColor": { + "type": "string" + }, + "logoWhite": { + "type": "string" + }, + "logoBlack": { + "type": "string" + } + }, + "required": [ + "backgroundColor", + "textColor", + "logoWhite", + "logoBlack" + ] + }, + "CustomerThemeResponse": { + "type": "object", + "properties": { + "theme": { + "$ref": "#/components/schemas/CustomerTheme" + } + }, + "required": [ + "theme" + ] + }, "CustomerLinkRequest": { "type": "object", "properties": { @@ -8234,8 +8414,35 @@ "required": [ "links" ] + }, + "CreateUserOpenDataDTO": { + "type": "object", + "properties": { + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "email": { + "type": "string" + }, + "organization": { + "type": "string" + }, + "enquiryType": { + "type": "string" + } + }, + "required": [ + "firstName", + "lastName", + "email", + "organization", + "enquiryType" + ] } } } } -} +} \ No newline at end of file diff --git a/environment.d.ts b/environment.d.ts index 727c484..c910516 100644 --- a/environment.d.ts +++ b/environment.d.ts @@ -12,6 +12,8 @@ declare global { INTERNAL_SWAGGER: 'true' | 'false'; AWS_REGION: string; + OPEN_GROUP_ID: string; + OPEN_CUSTOMER_ID: string; } } } diff --git a/package-lock.json b/package-lock.json index 61c7a9a..c1ea922 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,7 @@ "@aws-sdk/client-secrets-manager": "^3.414.0", "@dadosfera/dadosfera-logs": "^1.0.0-beta.4", "@dadosfera/protospack": "2.5.3", - "@dadosfera/protospack-v2": "3.34.0", + "@dadosfera/protospack-v2": "3.37.0-beta.1", "@grpc/grpc-js": "^1.9.3", "@grpc/proto-loader": "^0.7.9", "@nestjs/cli": "^9.5.0", @@ -1403,9 +1403,10 @@ } }, "node_modules/@dadosfera/protospack-v2": { - "version": "3.34.0", - "resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com/npm/dadosfera-npm/@dadosfera/protospack-v2/-/protospack-v2-3.34.0.tgz", - "integrity": "sha512-VUjpoHg5/uNNkg1cTxWbUv+20t5CTAf1tB4dhBmGSYjgb+Efo5gi3aO/p3ajYuzOOMOxF+EhjQVouU6BD3E+Xg==", + "version": "3.37.0-beta.1", + "resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com/npm/dadosfera-npm/@dadosfera/protospack-v2/-/protospack-v2-3.37.0-beta.1.tgz", + "integrity": "sha512-AcDxeg7KruBJncOXbLJFHKH/5GQ9VHR8MxU7s1o1lrZVfZY4Ht3UWmvwL1F2b+6DIhTDqzVOsKjfg7KAbuDYuw==", + "license": "ISC", "dependencies": { "@grpc/grpc-js": "^1.9.3", "rxjs": "^7.5.5" diff --git a/package.json b/package.json index fbe7eea..8300759 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "@aws-sdk/client-secrets-manager": "^3.414.0", "@dadosfera/dadosfera-logs": "^1.0.0-beta.4", "@dadosfera/protospack": "2.5.3", - "@dadosfera/protospack-v2": "3.34.0", + "@dadosfera/protospack-v2": "3.37.0-beta.1", "@grpc/grpc-js": "^1.9.3", "@grpc/proto-loader": "^0.7.9", "@nestjs/cli": "^9.5.0", diff --git a/src/app.module.ts b/src/app.module.ts index fa831fd..1cf1611 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -26,9 +26,9 @@ import { PipelinesV2Module } from './modules/pipelinesV2/pipelines.module'; import { ProductboardModule } from './modules/productboard/productboard.module'; import { MixpanelModule } from './modules/mixpanel/mixpanel.module'; import { CustomersModule } from './modules/customers/customers.module'; +import { OpenDataModule } from './modules/open-data/open-data.module'; @Module({ - controllers: [], providers: [ DadosferaLogger, { @@ -60,6 +60,7 @@ import { CustomersModule } from './modules/customers/customers.module'; CustomersModule, //Always leave HealthModule last, so it is on the bottom of swagger HealthModule, + OpenDataModule, ], }) export class AppModule {} diff --git a/src/modules/customers/customers.controller.ts b/src/modules/customers/customers.controller.ts index 04073ec..4268e6a 100644 --- a/src/modules/customers/customers.controller.ts +++ b/src/modules/customers/customers.controller.ts @@ -5,9 +5,11 @@ import { Controller, Get, HttpCode, + HttpException, HttpStatus, Inject, Param, + Post, Put, Query, UseFilters, @@ -18,17 +20,16 @@ import { Authenticated, RequireAllPermissions, } from 'src/decorators/authentication.decorator'; -import { ApiInternalOnlyEndpoint } from 'src/decorators/swagger.decorator'; import { GrpcToHttpExceptionFilter } from 'src/error/grpc-to-http-exception.filter'; import { CustomersService } from './customers.service'; -import { CustomerLinkRequest, CustomerLinksResponse } from './dtos/customers'; +import { CustomerLinkRequest, CustomerLinksResponse, CustomerThemeRequest, CustomerThemeResponse } from './dtos/customers'; import { RequestUser, User } from 'src/decorators/user.decorator'; import type { StringValue } from 'ms'; import { PackTheMetadata } from 'src/utils/ PackTheMetadata'; +import ErrorCodes from 'src/utils/errorCodes'; @ApiTags('Customers') @Controller('customers') -@Authenticated() @UseFilters(GrpcToHttpExceptionFilter) export class CustomersController { logger: DadosferaLogger; @@ -42,6 +43,7 @@ export class CustomersController { } @Get(':id/links') + @Authenticated() @ApiOkResponse({ type: CustomerLinksResponse }) async getCustomerLinks(@Param('id') id: string) { this.logger.info('getCustomerLinks', { id }); @@ -49,7 +51,41 @@ export class CustomersController { return { links }; } + @Post(':id/theme') + @Authenticated() + @RequireAllPermissions(PERMISSIONS_GROUPS.USERS.permissions.ADMIN) + @ApiOkResponse({ type: CustomerThemeResponse }) + async saveCustomertheme(@Param('id') id: string, @Body() data: CustomerThemeRequest) { + this.logger.info('saveCustomertheme', JSON.stringify({ + id, theme: data + })); + const theme = await this.customersService.createThemeByCustomer(id, data); + + return theme; + } + + @Get(':id/theme') + @ApiOkResponse({ type: CustomerThemeResponse }) + async getCustomerTheme(@Param('id') id: string) { + this.logger.info('getCustomerTheme with id' + id); + + try { + const data = await this.customersService.getThemeByCustomer(id); + this.logger.info('Success - getCustomerTheme with id'+ id); + return data; + }catch (err) { + if (err.details === ErrorCodes.CUSTOMER.NOT_FOUND) { + this.logger.error('Error - getCustomerTheme - Expect CUSTOMER.NOT_FOUND'); + throw new HttpException(err.details, HttpStatus.NOT_FOUND); + } else { + this.logger.error('Error - getCustomerTheme Unknown Error:' + err?.message); + return { theme: null }; + }; + } + } + @Put(':id/links') + @Authenticated() @RequireAllPermissions(PERMISSIONS_GROUPS.USERS.permissions.ADMIN) @ApiOkResponse() @HttpCode(HttpStatus.OK) @@ -63,6 +99,7 @@ export class CustomersController { } @Get('token') + @Authenticated() @RequireAllPermissions(PERMISSIONS_GROUPS.AUTH.permissions.GENERATE_TOKEN) @ApiProduces('text/plain') async getCustomerToken( @@ -79,6 +116,7 @@ export class CustomersController { } @Get('monitoring-dashboard') + @Authenticated() @RequireAllPermissions( PERMISSIONS_GROUPS.CUSTOMER.permissions.MONITORING_DASHBOARD, ) diff --git a/src/modules/customers/customers.service.ts b/src/modules/customers/customers.service.ts index 5102db5..5dc43f3 100644 --- a/src/modules/customers/customers.service.ts +++ b/src/modules/customers/customers.service.ts @@ -28,19 +28,25 @@ import { } from '@dadosfera/protospack-v2/dist/lib/PipelineV2'; import { Metadata } from '@grpc/grpc-js'; import { PipelinesClientConfiguration } from '../pipelinesV2/pipelines-client'; +import { CustomerThemeRequest, CustomerThemeResponse } from './dtos/customers'; +import DadosferaLogger from '@dadosfera/dadosfera-logs'; // This function will accept any string, which may result in a bug. @Injectable() export class CustomersService implements OnModuleInit { private customerService: CustomersProtoService; - + private logger: DadosferaLogger; private pipelineReadService: ReadService.PipelineV2ReadService; constructor( @Inject(DucClient.name) private readonly grpcClient: ClientGrpc, @Inject(PipelinesClientConfiguration.name) private readonly pipelinesGrpcClient: ClientGrpc, - ) {} + @Inject(DadosferaLogger) + dadosferaLogger: DadosferaLogger, + ) { + this.logger = dadosferaLogger.logger; + } onModuleInit() { this.customerService = this.grpcClient.getService( @@ -84,6 +90,48 @@ export class CustomersService implements OnModuleInit { } } + async createThemeByCustomer(id: string, theme: CustomerThemeRequest): Promise { + if (!id) { + this.logger.error('Error - saveCustomertheme - not found id:' + id); + throw new HttpException(null, HttpStatus.BAD_REQUEST); + } + + try { + const result = await firstValueFrom( + this.customerService.CustomerCreateTheme({ + customerId: id, + theme + }), + ); + return { theme: result }; + } catch (err) { + if (err.details === ErrorCodes.CUSTOMER.NOT_FOUND) { + this.logger.error('Error - saveCustomertheme - Expect CUSTOMER.NOT_FOUND'); + throw new HttpException(err.details, HttpStatus.NOT_FOUND); + } else { + this.logger.error('Error - saveCustomertheme Unknown Error:' + err?.message); + throw err + }; + } + } + + async getThemeByCustomer(id: string): Promise { + if (!id) { + this.logger.error('Error - getCustomerTheme - not found id:' + id); + throw new HttpException(null, HttpStatus.BAD_REQUEST); + } + + const result = await firstValueFrom( + this.customerService.CustomerGetTheme({ + id + }), + ); + + return { + theme: result + } + } + async generateToken( expiresIn = '30m', data: { customerId: string; userId: string; customerName: string }, diff --git a/src/modules/customers/dtos/customers.ts b/src/modules/customers/dtos/customers.ts index c3b3070..e26fc94 100644 --- a/src/modules/customers/dtos/customers.ts +++ b/src/modules/customers/dtos/customers.ts @@ -1,4 +1,4 @@ -import { Link } from '@dadosfera/protospack-v2/dist/lib/Duc/interfaces/entities'; +import { Link, Theme } from '@dadosfera/protospack-v2/dist/lib/Duc/interfaces/entities'; import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; export class CustomerLink implements Link { @@ -20,3 +20,30 @@ export class CustomerLinksResponse { @ApiProperty({ type: [CustomerLink] }) links: CustomerLink[]; } + +export class CustomerTheme implements Theme { + @ApiProperty() + backgroundColor: string; + @ApiProperty() + textColor: string; + @ApiProperty() + logoWhite: string; + @ApiProperty() + logoBlack: string; +} + +export class CustomerThemeResponse { + @ApiProperty() + theme: CustomerTheme; +} + +export class CustomerThemeRequest { + @ApiProperty() + backgroundColor: string; + @ApiProperty() + textColor: string; + @ApiProperty() + logoWhite: string; + @ApiProperty() + logoBlack: string; +} diff --git a/src/modules/open-data/dto/wordpres-form.ts b/src/modules/open-data/dto/wordpres-form.ts new file mode 100644 index 0000000..39b6ed7 --- /dev/null +++ b/src/modules/open-data/dto/wordpres-form.ts @@ -0,0 +1,48 @@ +import { ApiProperty } from "@nestjs/swagger"; + +export class CreateUserOpenDataDTO { + @ApiProperty() + firstName: string; + @ApiProperty() + lastName: string; + @ApiProperty() + email: string; + @ApiProperty() + organization: string; + @ApiProperty() + enquiryType: string; +} + +type FormField = { + id: string; + type: string; + title: string; + value: string; + raw_value: string; + required: string; +}; + +type MetaData = { + title: string; + value: string; +}; + +export type WordpressForm = { + form: { + id: string; + name: string; + }; + fields: { + [key: string]: FormField; + }; + meta: { + date: MetaData; + time: MetaData; + page_url: MetaData; + user_agent: MetaData; + remote_ip: MetaData; + credit: MetaData; + }; +}; + + diff --git a/src/modules/open-data/open-data.controller.ts b/src/modules/open-data/open-data.controller.ts new file mode 100644 index 0000000..05f915b --- /dev/null +++ b/src/modules/open-data/open-data.controller.ts @@ -0,0 +1,74 @@ +import DadosferaLogger from '@dadosfera/dadosfera-logs'; +import { Body, Controller, Inject, Post, UseFilters } from '@nestjs/common'; +import { ApiCreatedResponse, ApiHeaders, ApiTags } from '@nestjs/swagger'; +import { ApiInternalOnlyController } from 'src/decorators/swagger.decorator'; +import { GrpcToHttpExceptionFilter } from 'src/error/grpc-to-http-exception.filter'; +import { LanguageEnum } from 'src/utils/languages.enum'; +import { UsersService } from '../users/users.service'; +import { Language } from 'src/decorators/language.decorator'; +import { OpenDataService } from './open-data.service'; +import { CreateUserOpenDataDTO, WordpressForm } from './dto/wordpres-form'; + +@Controller('open-data') +@ApiInternalOnlyController() +@ApiTags('OpenData') +@ApiHeaders([{ name: 'dadosfera-lang', enum: LanguageEnum, required: false }]) +@UseFilters(GrpcToHttpExceptionFilter) +export class OpenDataController { + logger: DadosferaLogger; + + constructor( + @Inject(DadosferaLogger) + dadosferaLogger: DadosferaLogger, + private openDataService: OpenDataService, + ) { + this.logger = dadosferaLogger.logger; + } + + @Post("/sharing-ocean-data") + @ApiCreatedResponse() + async createUser( + @Body() + body: WordpressForm + ) { + this.logger.info('createUser for open data' + JSON.stringify({ body })); + + // "401573bb-334f-44b2-b30e-88d4cea31ae9" + const OPENDATA_PUBLIC_USERS_GROUP_ID = process.env.OPEN_GROUP_ID; + // ""f239718a-a271-4ef9-ae7e-02a2f0f3aa6e"" + const OPENDATA_CUSTOMER_ID = process.env.OPEN_CUSTOMER_ID; + const roles = [OPENDATA_PUBLIC_USERS_GROUP_ID]; + + const data = {} + + try { + Object.keys(body.fields) + .filter(key => body.fields[key].required === "1") + .forEach(key => { + const field = body.fields[key] + data[field.id] = field.value + }); + } catch (e) { + this.logger.error('user data' + e.message); + } + + + const user: CreateUserOpenDataDTO = { + email: data["email"], + enquiryType: data["enquiry_type"], + firstName: data["first_name"], + lastName: data["last_name"], + organization: data["organization"] + } + this.logger.info('user data' + JSON.stringify({ user })); + + try { + await this.openDataService.createUser(OPENDATA_CUSTOMER_ID, user, roles); + return "success" + } catch (e) { + this.logger.error('user data' + e.message); + return e; + } + } + +} diff --git a/src/modules/open-data/open-data.module.ts b/src/modules/open-data/open-data.module.ts new file mode 100644 index 0000000..f82b125 --- /dev/null +++ b/src/modules/open-data/open-data.module.ts @@ -0,0 +1,22 @@ +import { Module } from '@nestjs/common'; +import { OpenDataController } from './open-data.controller'; +import { UsersService } from '../users/users.service'; +import { ClientsModule } from '@nestjs/microservices' +import { DucClient } from '../duc/client.config'; +import DadosferaLogger from '@dadosfera/dadosfera-logs'; +import { RolesModule } from '../roles/roles.module'; +import { PermissionsModule } from '../permissions/permissions.module'; +import { OpenDataService } from './open-data.service'; + +const client = new DucClient(); + +@Module({ + controllers: [OpenDataController], + imports: [ + ClientsModule.register([client.providerOptions]), + RolesModule, + // PermissionsModule, + ], + providers: [DadosferaLogger, UsersService, OpenDataService] +}) +export class OpenDataModule {} diff --git a/src/modules/open-data/open-data.service.ts b/src/modules/open-data/open-data.service.ts new file mode 100644 index 0000000..8f37e7f --- /dev/null +++ b/src/modules/open-data/open-data.service.ts @@ -0,0 +1,50 @@ +import { Inject, Injectable, OnModuleInit } from '@nestjs/common'; +import { lastValueFrom } from 'rxjs'; +import { CreateUserOpenDataDTO } from './dto/wordpres-form'; +import DadosferaLogger from '@dadosfera/dadosfera-logs'; +import { UsersProtoService } from '@dadosfera/protospack-v2/dist/lib/Duc/interfaces/write-service'; +import { DucClient } from '../duc/client.config'; +import { ClientGrpc } from '@nestjs/microservices'; +import { ProtoServices } from '@dadosfera/protospack-v2/dist/lib/Duc'; + +@Injectable() +export class OpenDataService implements OnModuleInit { + logger: DadosferaLogger; + + private usersClientService: UsersProtoService; + constructor( + @Inject(DadosferaLogger) + private dadosferaLogger: DadosferaLogger, + @Inject(DucClient.name) + private readonly grpcClient: ClientGrpc, + ) { + this.logger = dadosferaLogger.logger; + } + + onModuleInit() { + this.usersClientService = this.grpcClient.getService( + ProtoServices.UsersProtoService, + ); + + } + + async createUser(customerId: string, data: CreateUserOpenDataDTO, roleIds: string[]) { + const body = { + email: data.email, + name: data.firstName + " " + data.lastName, + department: data.organization, + jobTitle: data.enquiryType, + customerId: customerId, + roleIds: roleIds + } + + try { + await lastValueFrom( + this.usersClientService.SimpleUserCreate(body), + ); + return "User created"; + } catch(err) { + return err; + } + } +}