Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop merge #240

Merged
merged 6 commits into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ COPY --from=build /app/package*.json ./
COPY --from=build /app/prisma ./prisma
COPY --from=build /app/node_modules ./node_modules
EXPOSE 3002
CMD [ "npm", "run", "start:prod" ]
CMD [ "npm", "run", "start:migrate:prod" ]
2 changes: 2 additions & 0 deletions prisma/migrations/20220822130634_bot_add_image/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Bot" ADD COLUMN "botImage" TEXT;
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "BotStatus" ADD VALUE 'PINNED';
1 change: 1 addition & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ enum BotStatus {
ENABLED
DISABLED
DRAFT
PINNED
}

model Adapter {
Expand Down
Binary file added src/.DS_Store
Binary file not shown.
10 changes: 10 additions & 0 deletions src/auth/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { AuthGuard, IAuthGuard } from '@nestjs/passport';
import { User } from './user.entity';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from './public.decorator';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') implements IAuthGuard {
Expand All @@ -12,6 +14,7 @@ export class JwtAuthGuard extends AuthGuard('jwt') implements IAuthGuard {
constructor(
private readonly configService: ConfigService,
private readonly jwtService: JwtService,
private readonly reflector: Reflector,
) {
super();
this.adminToken = configService.get<string>('ADMIN_TOKEN');
Expand All @@ -23,6 +26,13 @@ export class JwtAuthGuard extends AuthGuard('jwt') implements IAuthGuard {
}

public async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublic = this.reflector.getAllAndOverride<boolean>(
IS_PUBLIC_KEY,
[context.getHandler(), context.getClass()],
);
if (isPublic) {
return true;
}
await super.canActivate(context);
const request: Request = context.switchToHttp().getRequest();
let token = "";
Expand Down
4 changes: 4 additions & 0 deletions src/auth/public.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';

export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
3 changes: 3 additions & 0 deletions src/health/health.controller.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import { Body, Controller, Get } from '@nestjs/common';
import { HealthService } from './health.service';
import { HealthCheckResult } from '@nestjs/terminus';
import { Public } from '../auth/public.decorator';

@Controller('health')
export class HealthController {
constructor(
private readonly healthService: HealthService
) {}

@Public()
@Get()
async checkHealth(@Body() body: any): Promise<HealthCheckResult> {
return this.healthService.checkHealth();
}

@Public()
@Get('/ping')
async getServiceHealth(): Promise<HealthCheckResult> {
const resp: HealthCheckResult = {
Expand Down
Binary file added src/migration/.DS_Store
Binary file not shown.
Binary file added src/modules/.DS_Store
Binary file not shown.
15 changes: 14 additions & 1 deletion src/modules/bot/bot.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ const mockBotService = {
if (id == 'disabled') {
mockBotDataCopy['status'] = BotStatus.DISABLED;
}
else if (id == 'enabled') {
mockBotDataCopy['status'] = BotStatus.ENABLED;
}
else if (id == 'pinned') {
mockBotDataCopy['status'] = BotStatus.PINNED;
}
if (id == 'noUser') {
mockBotDataCopy['users'] = []
}
Expand Down Expand Up @@ -85,7 +91,9 @@ const mockBotService = {
};
}),

getBroadcastReport: jest.fn()
getBroadcastReport: jest.fn(),

start: jest.fn(),
}

const mockBotData: Prisma.BotGetPayload<{
Expand Down Expand Up @@ -265,6 +273,11 @@ describe('BotController', () => {
await expect(() => botController.startOne('disabled', {})).rejects.toThrowError(ServiceUnavailableException);
});

it('only disabled bot returns unavailable error',async () => {
expect(botController.startOne('pinned', {})).resolves;
expect(botController.startOne('enabled', {})).resolves;
});

it('update only passes relevant bot data to bot service', async () => {
updateParametersPassed = [
'status',
Expand Down
2 changes: 1 addition & 1 deletion src/modules/bot/bot.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ export class BotController {
throw new BadRequestException('Bot does not contain user segment data');
}
console.log(bot?.users[0].all);
if (bot?.status != BotStatus.ENABLED) {
if (bot?.status == BotStatus.DISABLED) {
throw new ServiceUnavailableException("Bot is not enabled!");
}
const res = await this.botService.start(id, bot?.users[0].all?.config, headers['conversation-authorization']);
Expand Down
18 changes: 18 additions & 0 deletions src/modules/bot/bot.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { CacheModule } from '@nestjs/common';
import { BotStatus } from '../../../prisma/generated/prisma-client-js';
import { UserSegmentService } from '../user-segment/user-segment.service';
import { ConversationLogicService } from '../conversation-logic/conversation-logic.service';
import { assert } from 'console';


const MockPrismaService = {
Expand All @@ -20,6 +21,8 @@ const MockPrismaService = {
mockBotsDbCopy.purpose = createData.data.purpose;
if (createData.data.description)
mockBotsDbCopy.description = createData.data.description;
if (createData.data.status)
mockBotsDbCopy.status = createData.data.status;
return mockBotsDbCopy;
},
findUnique: (filter) => {
Expand Down Expand Up @@ -367,6 +370,7 @@ let deletedIds: any[] = []
describe('BotService', () => {
let botService: BotService;
let configService: ConfigService;
jest.setTimeout(15000);

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
Expand Down Expand Up @@ -758,4 +762,18 @@ describe('BotService', () => {
mockCreateBotDtoCopy.logic = ['NonExisting'];
expect(botService.create(mockCreateBotDtoCopy, mockFile)).rejects.toThrowError('Converstaion Logic does not exist!');
});

it('bot status pinned is passed to db', async () => {
fetchMock.postOnce(`${configService.get<string>('MINIO_MEDIA_UPLOAD_URL')}`, {
fileName: 'testFileName'
});
const mockCreateBotDtoCopy: CreateBotDto & { ownerID: string; ownerOrgID: string } = { ...mockCreateBotDto };
mockCreateBotDtoCopy.status = 'PINNED';
mockCreateBotDtoCopy.name = 'testBotNotExisting';
mockCreateBotDtoCopy.startingMessage = 'testBotStartingMessageNotExisting';
const response = await botService.create(mockCreateBotDtoCopy, mockFile);
assert(response != null);
expect(response!['status']).toStrictEqual('PINNED');
fetchMock.restore();
});
});
20 changes: 18 additions & 2 deletions src/modules/bot/bot.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,7 @@ export class BotService {
name: data.name,
ownerID: data.ownerid,
ownerOrgID: data.ownerorgid,
status:
data.status && data.status.toLocaleLowerCase() === 'enabled' ? BotStatus.ENABLED : BotStatus.DISABLED,
status: this.getBotStatus(data.status),
startDate: this.getDateFromString(data.startDate),
endDate: this.getDateFromString(data.endDate),
tags: data.tags,
Expand Down Expand Up @@ -269,6 +268,20 @@ export class BotService {
}
}

private getBotStatus(status: string): BotStatus {
status = status.toLocaleLowerCase();
switch (status) {
case 'enabled':
return BotStatus.ENABLED;
case 'disabled':
return BotStatus.DISABLED;
case 'pinned':
return BotStatus.PINNED;
default:
return BotStatus.ENABLED;
}
}

async findAllUnresolved(): Promise<Prisma.BotGetPayload<{
include: {
users: {
Expand Down Expand Up @@ -574,6 +587,9 @@ export class BotService {
}
updateBotDto.endDate = new Date(updateBotDto.endDate);
}
if (updateBotDto.status) {
updateBotDto.status = this.getBotStatus(updateBotDto.status);
}
const updatedBot = await this.prisma.bot.update({
where: {
id,
Expand Down
Loading