chore: equations and adjustments for the new manager

This commit is contained in:
Davidson Gomes
2024-07-23 12:34:58 -03:00
parent 837f7f310a
commit c1d3209f2f
16 changed files with 181 additions and 33 deletions

View File

@@ -67,8 +67,8 @@ export class ChatController {
return await this.waMonitor.waInstances[instanceName].fetchStatusMessage(query);
}
public async fetchChats({ instanceName }: InstanceDto) {
return await this.waMonitor.waInstances[instanceName].fetchChats();
public async fetchChats({ instanceName }: InstanceDto, query: Query<Contact>) {
return await this.waMonitor.waInstances[instanceName].fetchChats(query);
}
public async sendPresence({ instanceName }: InstanceDto, data: SendPresenceDto) {

View File

@@ -594,7 +594,8 @@ export class InstanceController {
switch (state) {
case 'open':
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) instance.clearCacheChatwoot();
await instance.reloadConnection();
// await instance.reloadConnection();
await instance.client?.ws?.close();
await delay(2000);
return await this.connectionState({ instanceName });

View File

@@ -19,6 +19,12 @@ export class OpenaiController {
return this.openaiService.findCreds(instance);
}
public async deleteCreds(instance: InstanceDto, openaiCredsId: string) {
if (!configService.get<Openai>('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled');
return this.openaiService.deleteCreds(instance, openaiCredsId);
}
public async createOpenai(instance: InstanceDto, data: OpenaiDto) {
if (!configService.get<Openai>('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled');

View File

@@ -9,6 +9,7 @@ export class Session {
}
export class OpenaiCredsDto {
name: string;
apiKey: string;
}

View File

@@ -38,6 +38,16 @@ export class OpenaiRouter extends RouterBroker {
res.status(HttpStatus.OK).json(response);
})
.delete(this.routerPath('creds/:openaiCredsId'), ...guards, async (req, res) => {
const response = await this.dataValidate<InstanceDto>({
request: req,
schema: instanceSchema,
ClassRef: InstanceDto,
execute: (instance) => openaiController.deleteCreds(instance, req.params.openaiCredsId),
});
res.status(HttpStatus.OK).json(response);
})
.post(this.routerPath('create'), ...guards, async (req, res) => {
const response = await this.dataValidate<OpenaiDto>({
request: req,

View File

@@ -32,10 +32,12 @@ export class OpenaiService {
.then((instance) => instance.id);
if (!data.apiKey) throw new Error('API Key is required');
if (!data.name) throw new Error('Name is required');
try {
const creds = await this.prismaRepository.openaiCreds.create({
data: {
name: data.name,
apiKey: data.apiKey,
instanceId: instanceId,
},
@@ -69,6 +71,43 @@ export class OpenaiService {
return creds;
}
public async deleteCreds(instance: InstanceDto, openaiCredsId: string) {
const instanceId = await this.prismaRepository.instance
.findFirst({
where: {
name: instance.instanceName,
},
})
.then((instance) => instance.id);
const creds = await this.prismaRepository.openaiCreds.findFirst({
where: {
id: openaiCredsId,
},
});
if (!creds) {
throw new Error('Openai Creds not found');
}
if (creds.instanceId !== instanceId) {
throw new Error('Openai Creds not found');
}
try {
await this.prismaRepository.openaiCreds.delete({
where: {
id: openaiCredsId,
},
});
return { openaiCreds: { id: openaiCredsId } };
} catch (error) {
this.logger.error(error);
throw new Error('Error deleting openai creds');
}
}
public async create(instance: InstanceDto, data: OpenaiDto) {
const instanceId = await this.prismaRepository.instance
.findFirst({
@@ -98,9 +137,9 @@ export class OpenaiService {
if (!data.openaiCredsId) data.openaiCredsId = defaultSettingCheck?.openaiCredsId || null;
if (!data.expire) data.expire = defaultSettingCheck?.expire || 0;
if (!data.keywordFinish) data.keywordFinish = defaultSettingCheck?.keywordFinish || '#SAIR';
if (!data.keywordFinish) data.keywordFinish = defaultSettingCheck?.keywordFinish || '';
if (!data.delayMessage) data.delayMessage = defaultSettingCheck?.delayMessage || 1000;
if (!data.unknownMessage) data.unknownMessage = defaultSettingCheck?.unknownMessage || 'Desculpe, não entendi';
if (!data.unknownMessage) data.unknownMessage = defaultSettingCheck?.unknownMessage || '';
if (!data.listeningFromMe) data.listeningFromMe = defaultSettingCheck?.listeningFromMe || false;
if (!data.stopBotFromMe) data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false;
if (!data.keepOpen) data.keepOpen = defaultSettingCheck?.keepOpen || false;
@@ -149,6 +188,7 @@ export class OpenaiService {
whereDuplication = {
...whereDuplication,
assistantId: data.assistantId,
botType: data.botType,
};
} else if (data.botType === 'chatCompletion') {
if (!data.model) throw new Error('Model is required');
@@ -158,6 +198,7 @@ export class OpenaiService {
...whereDuplication,
model: data.model,
maxTokens: data.maxTokens,
botType: data.botType,
};
} else {
throw new Error('Bot type is required');

View File

@@ -54,10 +54,11 @@ export const openaiCredsSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
properties: {
name: { type: 'string' },
apiKey: { type: 'string' },
},
required: ['apiKey'],
...isNotEmpty('apiKey'),
required: ['name', 'apiKey'],
...isNotEmpty('name', 'apiKey'),
};
export const openaiStatusSchema: JSONSchema7 = {

View File

@@ -557,6 +557,7 @@ export class TypebotService {
return await this.prismaRepository.typebotSession.findMany({
where: {
remoteJid: remoteJid,
instanceId: instanceId,
},
});
}
@@ -583,6 +584,7 @@ export class TypebotService {
await this.prismaRepository.typebotSession.deleteMany({
where: {
remoteJid: remoteJid,
instanceId: instanceId,
},
});
@@ -714,6 +716,7 @@ export class TypebotService {
where: {
url: url,
typebot: typebot,
instanceId: instance.instanceId,
},
});
@@ -738,6 +741,7 @@ export class TypebotService {
await this.prismaRepository.typebotSession.deleteMany({
where: {
remoteJid: remoteJid,
instanceId: instance.instanceId,
},
});

View File

@@ -177,11 +177,11 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response);
})
.post(this.routerPath('findChats'), ...guards, async (req, res) => {
const response = await this.dataValidate<InstanceDto>({
const response = await this.dataValidate<Query<Contact>>({
request: req,
schema: null,
ClassRef: InstanceDto,
execute: (instance) => chatController.fetchChats(instance),
schema: contactValidateSchema,
ClassRef: Query<Contact>,
execute: (instance, data) => chatController.fetchChats(instance, data),
});
return res.status(HttpStatus.OK).json(response);

View File

@@ -1138,15 +1138,22 @@ export class ChannelStartupService {
}
public async fetchContacts(query: Query<Contact>) {
const remoteJid = query.where?.remoteJid.includes('@')
? query.where?.remoteJid
: this.createJid(query.where?.remoteJid);
const remoteJid = query?.where?.remoteJid
? query?.where?.remoteJid.includes('@')
? query.where?.remoteJid
: this.createJid(query.where?.remoteJid)
: null;
const where = {
instanceId: this.instanceId,
};
if (remoteJid) {
where['remoteJid'] = remoteJid;
}
return await this.prismaRepository.contact.findMany({
where: {
instanceId: this.instanceId,
remoteJid,
},
where,
});
}
@@ -1164,8 +1171,6 @@ export class ChannelStartupService {
: this.createJid(keyFilters?.remoteJid)
: null;
console.log(remoteJid);
const count = await this.prismaRepository.message.count({
where: {
instanceId: this.instanceId,
@@ -1246,9 +1251,47 @@ export class ChannelStartupService {
});
}
public async fetchChats() {
return await this.prismaRepository.chat.findMany({
where: { instanceId: this.instanceId },
});
public async fetchChats(query: any) {
const remoteJid = query?.where?.remoteJid
? query?.where?.remoteJid.includes('@')
? query.where?.remoteJid
: this.createJid(query.where?.remoteJid)
: null;
let result;
if (remoteJid) {
result = await this.prismaRepository.$queryRaw`
SELECT
"Chat"."id",
"Chat"."remoteJid",
"Chat"."labels",
"Chat"."createdAt",
"Chat"."updatedAt",
"Contact"."pushName",
"Contact"."profilePicUrl"
FROM "Chat"
LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid"
WHERE "Chat"."instanceId" = ${this.instanceId}
AND "Chat"."remoteJid" = ${remoteJid}
ORDER BY "Chat"."updatedAt" DESC
`;
} else {
result = await this.prismaRepository.$queryRaw`
SELECT
"Chat"."id",
"Chat"."remoteJid",
"Chat"."labels",
"Chat"."createdAt",
"Chat"."updatedAt",
"Contact"."pushName",
"Contact"."profilePicUrl"
FROM "Chat"
LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid"
WHERE "Chat"."instanceId" = ${this.instanceId}
ORDER BY "Chat"."updatedAt" DESC
`;
}
return result;
}
}

View File

@@ -416,6 +416,17 @@ export class BaileysStartupService extends ChannelStartupService {
}
}
if (connection === 'connecting') {
if (this.configService.get<Database>('DATABASE').ENABLED) {
await this.prismaRepository.instance.update({
where: { id: this.instanceId },
data: {
connectionStatus: 'connecting',
},
});
}
}
if (connection === 'open') {
this.instance.wuid = this.client.user.id.replace(/:\d+/, '');
this.instance.profilePictureUrl = (await this.profilePicture(this.instance.wuid)).profilePictureUrl;

View File

@@ -79,6 +79,13 @@ export class WAMonitoringService {
Sqs: true,
Websocket: true,
Setting: true,
_count: {
select: {
Message: true,
Contact: true,
Chat: true,
},
},
},
});