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

fix: channel ts strict null check #502

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
15 changes: 11 additions & 4 deletions api/src/channel/channel.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { Request, Response } from 'express';

import { ChannelName } from '@/channel/types';
import { SubscriberService } from '@/chat/services/subscriber.service';
import { CONSOLE_CHANNEL_NAME } from '@/extensions/channels/console/settings';
import { WEB_CHANNEL_NAME } from '@/extensions/channels/web/settings';
Expand All @@ -23,7 +24,6 @@ import { SocketRequest } from '@/websocket/utils/socket-request';
import { SocketResponse } from '@/websocket/utils/socket-response';

import ChannelHandler from './lib/Handler';
import { ChannelName } from './types';

@Injectable()
export class ChannelService {
Expand Down Expand Up @@ -161,10 +161,9 @@ export class ChannelService {
foreign_id: req.session.passport.user.id,
},
{
id: req.session.passport.user.id,
foreign_id: req.session.passport.user.id,
first_name: req.session.passport.user.first_name,
last_name: req.session.passport.user.last_name,
first_name: req.session.passport.user.first_name || 'Anonymous',
last_name: req.session.passport.user.last_name || 'Anonymous',
locale: '',
language: '',
gender: '',
Expand All @@ -173,7 +172,15 @@ export class ChannelService {
channel: {
name: CONSOLE_CHANNEL_NAME,
isSocket: true,
} as {
name: ChannelName;
isSocket: boolean;
},
assignedTo: null,
avatar: null,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
avatar: null,
avatar: req.session.passport.user.avatar,

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently user passport user object does not have avatar property unless its miss typed

assignedAt: null,
lastvisit: new Date(),
retainedFrom: new Date(),
},
);

Expand Down
1 change: 1 addition & 0 deletions api/src/channel/lib/__test__/subscriber.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export const subscriberInstance: Subscriber = {
},
labels: [],
...modelInstance,
avatar: null,
};

export const subscriberWithoutLabels: Subscriber = {
Expand Down
5 changes: 2 additions & 3 deletions api/src/chat/dto/message.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import {
IsBoolean,
IsNotEmpty,
IsObject,
IsString,
IsOptional,
IsString,
} from 'class-validator';

import { IsObjectId } from '@/utils/validation-rules/is-object-id';
Expand All @@ -25,9 +25,8 @@ import { IsValidMessageText } from '../validation-rules/is-valid-message-text';

export class MessageCreateDto {
@ApiProperty({ description: 'Message id', type: String })
@IsOptional()
@IsString()
mid?: string;
mid: string;

@ApiProperty({ description: 'Reply to Message id', type: String })
@IsOptional()
Expand Down
3 changes: 3 additions & 0 deletions api/src/chat/dto/subscriber.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ export class SubscriberCreateDto {
@IsNotEmpty()
@IsChannelData()
channel: SubscriberChannelData<ChannelName>;

@IsOptional()
avatar?: string | null = null;
}

export class SubscriberUpdateDto extends PartialType(SubscriberCreateDto) {}
4 changes: 2 additions & 2 deletions api/src/chat/schemas/message.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ import { StdIncomingMessage, StdOutgoingMessage } from './types/message';
export class MessageStub extends BaseSchema {
@Prop({
type: String,
required: false,
required: true,
//TODO : add default value for mid
})
mid?: string;
mid: string;

@Prop({
type: MongooseSchema.Types.ObjectId,
Expand Down
14 changes: 7 additions & 7 deletions api/src/chat/schemas/subscriber.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,19 +86,19 @@ export class SubscriberStub extends BaseSchema {
type: Date,
default: null,
})
assignedAt?: Date;
assignedAt: Date | null;

@Prop({
type: Date,
default: () => Date.now() + 7 * 24 * 60 * 60 * 1000,
})
lastvisit?: Date;
lastvisit: Date;

@Prop({
type: Date,
default: () => Date.now() + 7 * 24 * 60 * 60 * 1000,
})
retainedFrom?: Date;
retainedFrom: Date;

@Prop({
type: Object,
Expand All @@ -110,7 +110,7 @@ export class SubscriberStub extends BaseSchema {
ref: 'Attachment',
default: null,
})
avatar?: unknown;
avatar?: unknown | null;

@Prop({
type: Object,
Expand All @@ -132,10 +132,10 @@ export class Subscriber extends SubscriberStub {
labels: string[];

@Transform(({ obj }) => (obj.assignedTo ? obj.assignedTo.toString() : null))
assignedTo?: string;
assignedTo: string | null;

@Transform(({ obj }) => obj.avatar?.toString() || null)
avatar?: string;
avatar: string | null;
}

@Schema({ timestamps: true })
Expand All @@ -144,7 +144,7 @@ export class SubscriberFull extends SubscriberStub {
labels: Label[];

@Type(() => User)
assignedTo?: User | null;
assignedTo: User | null;

@Type(() => Attachment)
avatar: Attachment | null;
Expand Down
4 changes: 2 additions & 2 deletions api/src/chat/schemas/types/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
import { ChannelName } from '@/channel/types';

export type SubscriberChannelData<
C extends ChannelName = null,
C extends ChannelName = 'undefined-name-channel',
marrouchi marked this conversation as resolved.
Show resolved Hide resolved
// K extends keyof SubscriberChannelDict[C] = keyof SubscriberChannelDict[C],
> = C extends null
> = C extends 'undefined-name-channel'
marrouchi marked this conversation as resolved.
Show resolved Hide resolved
? { name: ChannelName }
: {
name: C;
Expand Down
18 changes: 17 additions & 1 deletion api/src/chat/services/chat.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,24 @@ export class ChatService {
if (!subscriber) {
const subscriberData = await handler.getUserData(event);
this.eventEmitter.emit('hook:stats:entry', 'new_users', 'New users');
const currentDate = new Date();
subscriberData.channel = event.getChannelData();
subscriber = await this.subscriberService.create(subscriberData);
subscriber = await this.subscriberService.create({
country: subscriberData.country,
first_name: subscriberData.first_name,
last_name: subscriberData.last_name,
gender: subscriberData.gender,
language: subscriberData.language,
locale: subscriberData.locale,
channel: subscriberData.channel,
foreign_id: subscriberData.foreign_id,
labels: subscriberData.labels,
lastvisit: subscriberData.lastvisit || currentDate,
retainedFrom: subscriberData.retainedFrom || currentDate,
assignedAt: subscriberData.assignedAt || null,
assignedTo: subscriberData.assignedTo || null,
avatar: subscriberData.avatar || null,
});
marrouchi marked this conversation as resolved.
Show resolved Hide resolved
} else {
// Already existing user profile
// Exec lastvisit hook
Expand Down
26 changes: 18 additions & 8 deletions api/src/extensions/channels/web/base-web-channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/

import { Injectable } from '@nestjs/common';
import { BadRequestException, Injectable } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
import { Request, Response } from 'express';
import multer, { diskStorage, memoryStorage } from 'multer';
Expand Down Expand Up @@ -49,6 +49,7 @@ import { config } from '@/config';
import { I18nService } from '@/i18n/services/i18n.service';
import { LoggerService } from '@/logger/logger.service';
import { SettingService } from '@/setting/services/setting.service';
import { BaseSchema } from '@/utils/generics/base-schema';
import { SocketRequest } from '@/websocket/utils/socket-request';
import { SocketResponse } from '@/websocket/utils/socket-response';
import { WebsocketGateway } from '@/websocket/websocket.gateway';
Expand Down Expand Up @@ -227,15 +228,17 @@ export default abstract class BaseWebChannelHandler<
createdAt: anyMessage.createdAt,
});
} else {
const message = this.formatOutgoingHistoryMessage(anyMessage);
formattedMessages.push({
...message,
const baseMessage = this.formatOutgoingHistoryMessage(anyMessage);
const outgoingMessage: Web.OutgoingMessage = {
...baseMessage,
author: 'chatbot',
read: true, // Temporary fix as read is false in the bd
mid: anyMessage.mid,
handover: !!anyMessage.handover,
createdAt: anyMessage.createdAt,
});
};

formattedMessages.push(outgoingMessage);
}
}

Expand Down Expand Up @@ -443,7 +446,7 @@ export default abstract class BaseWebChannelHandler<
return subscriber;
}

const newProfile: SubscriberCreateDto = {
const newProfile: Omit<Subscriber, keyof BaseSchema> = {
foreign_id: this.generateId(),
first_name: data.first_name ? data.first_name.toString() : 'Anon.',
last_name: data.last_name ? data.last_name.toString() : 'Web User',
Expand All @@ -461,7 +464,9 @@ export default abstract class BaseWebChannelHandler<
gender: 'male',
country: '',
labels: [],
avatar: null,
};

const subscriber = await this.subscriberService.create(newProfile);
// Init session
const profile: SubscriberFull = {
Expand Down Expand Up @@ -520,6 +525,11 @@ export default abstract class BaseWebChannelHandler<

const fetchMessages = async (req: Request, res: Response, retrials = 1) => {
try {
if (!req.query.since) {
throw new BadRequestException(
`QueryParam 'since' is missing: Unable to fetchMessages()`,
);
}
const since = new Date(req.query.since.toString());
const messages = await this.pollMessages(req, since);
if (messages.length === 0 && retrials <= 5) {
Expand Down Expand Up @@ -722,7 +732,7 @@ export default abstract class BaseWebChannelHandler<
return {
isSocket: this.isSocketRequest(req),
ipAddress: this.getIpAddress(req),
agent: req.headers['user-agent'],
agent: req.headers['user-agent']!,
};
}

Expand Down Expand Up @@ -966,7 +976,7 @@ export default abstract class BaseWebChannelHandler<
type: Web.OutgoingMessageType.file,
data: {
type: message.attachment.type,
url: message.attachment.payload.url,
url: message.attachment.payload.url!,
},
};
if (message.quickReplies && message.quickReplies.length > 0) {
Expand Down
4 changes: 2 additions & 2 deletions api/src/user/schemas/user.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export class UserStub extends BaseSchema {
ref: 'Attachment',
default: null,
})
avatar?: unknown;
avatar?: unknown | null;

@Prop({
type: String,
Expand All @@ -112,7 +112,7 @@ export class User extends UserStub {
roles: string[];

@Transform(({ obj }) => obj.avatar?.toString() || null)
avatar?: string;
avatar?: string | null;
}

@Schema({ timestamps: true })
Expand Down
8 changes: 8 additions & 0 deletions api/src/utils/test/fixtures/conversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ const conversations: ConversationCreateDto[] = [
labels: [],
assignedTo: null,
channel: { name: 'messenger-channel' },
avatar: null,
assignedAt: null,
lastvisit: null,
retainedFrom: null,
},
skip: {},
attempt: 0,
Expand Down Expand Up @@ -107,6 +111,10 @@ const conversations: ConversationCreateDto[] = [
labels: [],
assignedTo: null,
channel: { name: 'web-channel' },
avatar: null,
assignedAt: null,
lastvisit: null,
retainedFrom: null,
},
skip: {},
attempt: 0,
Expand Down
28 changes: 15 additions & 13 deletions api/src/utils/test/fixtures/subscriber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import mongoose from 'mongoose';

import { SubscriberCreateDto } from '@/chat/dto/subscriber.dto';
import { Subscriber, SubscriberModel } from '@/chat/schemas/subscriber.schema';
import { SubscriberModel } from '@/chat/schemas/subscriber.schema';

import { getFixturesWithDefaultValues } from '../defaultValues';
import { TFixturesDefaultValues } from '../types';
Expand Down Expand Up @@ -84,19 +84,21 @@ const subscribers: SubscriberCreateDto[] = [
},
];

export const subscriberDefaultValues: TFixturesDefaultValues<Subscriber> = {
timezone: 0,
assignedTo: null,
assignedAt: null,
lastvisit: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
retainedFrom: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
avatar: null,
};
export const subscriberDefaultValues: TFixturesDefaultValues<SubscriberCreateDto> =
{
timezone: 0,
assignedTo: null,
assignedAt: null,
lastvisit: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
retainedFrom: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
avatar: null,
};

export const subscriberFixtures = getFixturesWithDefaultValues<Subscriber>({
fixtures: subscribers,
defaultValues: subscriberDefaultValues,
});
export const subscriberFixtures =
getFixturesWithDefaultValues<SubscriberCreateDto>({
fixtures: subscribers,
defaultValues: subscriberDefaultValues,
});

export const installSubscriberFixtures = async () => {
const Subscriber = mongoose.model(
Expand Down
Loading
Loading