mirror of
https://github.com/EvolutionAPI/evolution-api.git
synced 2025-07-14 01:41:24 -06:00
chore: equations and adjustments for the new manager
This commit is contained in:
parent
837f7f310a
commit
c1d3209f2f
@ -0,0 +1,12 @@
|
|||||||
|
/*
|
||||||
|
Warnings:
|
||||||
|
|
||||||
|
- A unique constraint covering the columns `[name]` on the table `OpenaiCreds` will be added. If there are existing duplicate values, this will fail.
|
||||||
|
|
||||||
|
*/
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "OpenaiCreds" ADD COLUMN "name" VARCHAR(255),
|
||||||
|
ALTER COLUMN "apiKey" DROP NOT NULL;
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "OpenaiCreds_name_key" ON "OpenaiCreds"("name");
|
@ -0,0 +1,2 @@
|
|||||||
|
-- DropIndex
|
||||||
|
DROP INDEX "OpenaiCreds_instanceId_key";
|
@ -0,0 +1,8 @@
|
|||||||
|
/*
|
||||||
|
Warnings:
|
||||||
|
|
||||||
|
- A unique constraint covering the columns `[openaiCredsId]` on the table `OpenaiSetting` will be added. If there are existing duplicate values, this will fail.
|
||||||
|
|
||||||
|
*/
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "OpenaiSetting_openaiCredsId_key" ON "OpenaiSetting"("openaiCredsId");
|
@ -77,7 +77,7 @@ model Instance {
|
|||||||
TypebotSession TypebotSession[]
|
TypebotSession TypebotSession[]
|
||||||
TypebotSetting TypebotSetting?
|
TypebotSetting TypebotSetting?
|
||||||
Media Media[]
|
Media Media[]
|
||||||
OpenaiCreds OpenaiCreds?
|
OpenaiCreds OpenaiCreds[]
|
||||||
OpenaiBot OpenaiBot[]
|
OpenaiBot OpenaiBot[]
|
||||||
OpenaiSession OpenaiSession[]
|
OpenaiSession OpenaiSession[]
|
||||||
OpenaiSetting OpenaiSetting?
|
OpenaiSetting OpenaiSetting?
|
||||||
@ -333,14 +333,15 @@ model Media {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model OpenaiCreds {
|
model OpenaiCreds {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
apiKey String @unique @db.VarChar(255)
|
name String? @unique @db.VarChar(255)
|
||||||
createdAt DateTime? @default(now()) @db.Timestamp
|
apiKey String? @unique @db.VarChar(255)
|
||||||
updatedAt DateTime @updatedAt @db.Timestamp
|
createdAt DateTime? @default(now()) @db.Timestamp
|
||||||
Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade)
|
updatedAt DateTime @updatedAt @db.Timestamp
|
||||||
instanceId String @unique
|
Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade)
|
||||||
|
instanceId String
|
||||||
OpenaiAssistant OpenaiBot[]
|
OpenaiAssistant OpenaiBot[]
|
||||||
OpenaiSetting OpenaiSetting[]
|
OpenaiSetting OpenaiSetting?
|
||||||
}
|
}
|
||||||
|
|
||||||
model OpenaiBot {
|
model OpenaiBot {
|
||||||
@ -404,7 +405,7 @@ model OpenaiSetting {
|
|||||||
createdAt DateTime? @default(now()) @db.Timestamp
|
createdAt DateTime? @default(now()) @db.Timestamp
|
||||||
updatedAt DateTime @updatedAt @db.Timestamp
|
updatedAt DateTime @updatedAt @db.Timestamp
|
||||||
OpenaiCreds OpenaiCreds? @relation(fields: [openaiCredsId], references: [id])
|
OpenaiCreds OpenaiCreds? @relation(fields: [openaiCredsId], references: [id])
|
||||||
openaiCredsId String
|
openaiCredsId String @unique
|
||||||
Fallback OpenaiBot? @relation(fields: [openaiIdFallback], references: [id])
|
Fallback OpenaiBot? @relation(fields: [openaiIdFallback], references: [id])
|
||||||
openaiIdFallback String? @db.VarChar(100)
|
openaiIdFallback String? @db.VarChar(100)
|
||||||
Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade)
|
Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade)
|
||||||
|
@ -67,8 +67,8 @@ export class ChatController {
|
|||||||
return await this.waMonitor.waInstances[instanceName].fetchStatusMessage(query);
|
return await this.waMonitor.waInstances[instanceName].fetchStatusMessage(query);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async fetchChats({ instanceName }: InstanceDto) {
|
public async fetchChats({ instanceName }: InstanceDto, query: Query<Contact>) {
|
||||||
return await this.waMonitor.waInstances[instanceName].fetchChats();
|
return await this.waMonitor.waInstances[instanceName].fetchChats(query);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async sendPresence({ instanceName }: InstanceDto, data: SendPresenceDto) {
|
public async sendPresence({ instanceName }: InstanceDto, data: SendPresenceDto) {
|
||||||
|
@ -594,7 +594,8 @@ export class InstanceController {
|
|||||||
switch (state) {
|
switch (state) {
|
||||||
case 'open':
|
case 'open':
|
||||||
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) instance.clearCacheChatwoot();
|
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) instance.clearCacheChatwoot();
|
||||||
await instance.reloadConnection();
|
// await instance.reloadConnection();
|
||||||
|
await instance.client?.ws?.close();
|
||||||
await delay(2000);
|
await delay(2000);
|
||||||
|
|
||||||
return await this.connectionState({ instanceName });
|
return await this.connectionState({ instanceName });
|
||||||
|
@ -19,6 +19,12 @@ export class OpenaiController {
|
|||||||
return this.openaiService.findCreds(instance);
|
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) {
|
public async createOpenai(instance: InstanceDto, data: OpenaiDto) {
|
||||||
if (!configService.get<Openai>('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled');
|
if (!configService.get<Openai>('OPENAI').ENABLED) throw new BadRequestException('Openai is disabled');
|
||||||
|
|
||||||
|
@ -9,6 +9,7 @@ export class Session {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class OpenaiCredsDto {
|
export class OpenaiCredsDto {
|
||||||
|
name: string;
|
||||||
apiKey: string;
|
apiKey: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -38,6 +38,16 @@ export class OpenaiRouter extends RouterBroker {
|
|||||||
|
|
||||||
res.status(HttpStatus.OK).json(response);
|
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) => {
|
.post(this.routerPath('create'), ...guards, async (req, res) => {
|
||||||
const response = await this.dataValidate<OpenaiDto>({
|
const response = await this.dataValidate<OpenaiDto>({
|
||||||
request: req,
|
request: req,
|
||||||
|
@ -32,10 +32,12 @@ export class OpenaiService {
|
|||||||
.then((instance) => instance.id);
|
.then((instance) => instance.id);
|
||||||
|
|
||||||
if (!data.apiKey) throw new Error('API Key is required');
|
if (!data.apiKey) throw new Error('API Key is required');
|
||||||
|
if (!data.name) throw new Error('Name is required');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const creds = await this.prismaRepository.openaiCreds.create({
|
const creds = await this.prismaRepository.openaiCreds.create({
|
||||||
data: {
|
data: {
|
||||||
|
name: data.name,
|
||||||
apiKey: data.apiKey,
|
apiKey: data.apiKey,
|
||||||
instanceId: instanceId,
|
instanceId: instanceId,
|
||||||
},
|
},
|
||||||
@ -69,6 +71,43 @@ export class OpenaiService {
|
|||||||
return creds;
|
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) {
|
public async create(instance: InstanceDto, data: OpenaiDto) {
|
||||||
const instanceId = await this.prismaRepository.instance
|
const instanceId = await this.prismaRepository.instance
|
||||||
.findFirst({
|
.findFirst({
|
||||||
@ -98,9 +137,9 @@ export class OpenaiService {
|
|||||||
|
|
||||||
if (!data.openaiCredsId) data.openaiCredsId = defaultSettingCheck?.openaiCredsId || null;
|
if (!data.openaiCredsId) data.openaiCredsId = defaultSettingCheck?.openaiCredsId || null;
|
||||||
if (!data.expire) data.expire = defaultSettingCheck?.expire || 0;
|
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.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.listeningFromMe) data.listeningFromMe = defaultSettingCheck?.listeningFromMe || false;
|
||||||
if (!data.stopBotFromMe) data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false;
|
if (!data.stopBotFromMe) data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false;
|
||||||
if (!data.keepOpen) data.keepOpen = defaultSettingCheck?.keepOpen || false;
|
if (!data.keepOpen) data.keepOpen = defaultSettingCheck?.keepOpen || false;
|
||||||
@ -149,6 +188,7 @@ export class OpenaiService {
|
|||||||
whereDuplication = {
|
whereDuplication = {
|
||||||
...whereDuplication,
|
...whereDuplication,
|
||||||
assistantId: data.assistantId,
|
assistantId: data.assistantId,
|
||||||
|
botType: data.botType,
|
||||||
};
|
};
|
||||||
} else if (data.botType === 'chatCompletion') {
|
} else if (data.botType === 'chatCompletion') {
|
||||||
if (!data.model) throw new Error('Model is required');
|
if (!data.model) throw new Error('Model is required');
|
||||||
@ -158,6 +198,7 @@ export class OpenaiService {
|
|||||||
...whereDuplication,
|
...whereDuplication,
|
||||||
model: data.model,
|
model: data.model,
|
||||||
maxTokens: data.maxTokens,
|
maxTokens: data.maxTokens,
|
||||||
|
botType: data.botType,
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
throw new Error('Bot type is required');
|
throw new Error('Bot type is required');
|
||||||
|
@ -54,10 +54,11 @@ export const openaiCredsSchema: JSONSchema7 = {
|
|||||||
$id: v4(),
|
$id: v4(),
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
|
name: { type: 'string' },
|
||||||
apiKey: { type: 'string' },
|
apiKey: { type: 'string' },
|
||||||
},
|
},
|
||||||
required: ['apiKey'],
|
required: ['name', 'apiKey'],
|
||||||
...isNotEmpty('apiKey'),
|
...isNotEmpty('name', 'apiKey'),
|
||||||
};
|
};
|
||||||
|
|
||||||
export const openaiStatusSchema: JSONSchema7 = {
|
export const openaiStatusSchema: JSONSchema7 = {
|
||||||
|
@ -557,6 +557,7 @@ export class TypebotService {
|
|||||||
return await this.prismaRepository.typebotSession.findMany({
|
return await this.prismaRepository.typebotSession.findMany({
|
||||||
where: {
|
where: {
|
||||||
remoteJid: remoteJid,
|
remoteJid: remoteJid,
|
||||||
|
instanceId: instanceId,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -583,6 +584,7 @@ export class TypebotService {
|
|||||||
await this.prismaRepository.typebotSession.deleteMany({
|
await this.prismaRepository.typebotSession.deleteMany({
|
||||||
where: {
|
where: {
|
||||||
remoteJid: remoteJid,
|
remoteJid: remoteJid,
|
||||||
|
instanceId: instanceId,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -714,6 +716,7 @@ export class TypebotService {
|
|||||||
where: {
|
where: {
|
||||||
url: url,
|
url: url,
|
||||||
typebot: typebot,
|
typebot: typebot,
|
||||||
|
instanceId: instance.instanceId,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -738,6 +741,7 @@ export class TypebotService {
|
|||||||
await this.prismaRepository.typebotSession.deleteMany({
|
await this.prismaRepository.typebotSession.deleteMany({
|
||||||
where: {
|
where: {
|
||||||
remoteJid: remoteJid,
|
remoteJid: remoteJid,
|
||||||
|
instanceId: instance.instanceId,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -177,11 +177,11 @@ export class ChatRouter extends RouterBroker {
|
|||||||
return res.status(HttpStatus.OK).json(response);
|
return res.status(HttpStatus.OK).json(response);
|
||||||
})
|
})
|
||||||
.post(this.routerPath('findChats'), ...guards, async (req, res) => {
|
.post(this.routerPath('findChats'), ...guards, async (req, res) => {
|
||||||
const response = await this.dataValidate<InstanceDto>({
|
const response = await this.dataValidate<Query<Contact>>({
|
||||||
request: req,
|
request: req,
|
||||||
schema: null,
|
schema: contactValidateSchema,
|
||||||
ClassRef: InstanceDto,
|
ClassRef: Query<Contact>,
|
||||||
execute: (instance) => chatController.fetchChats(instance),
|
execute: (instance, data) => chatController.fetchChats(instance, data),
|
||||||
});
|
});
|
||||||
|
|
||||||
return res.status(HttpStatus.OK).json(response);
|
return res.status(HttpStatus.OK).json(response);
|
||||||
|
@ -1138,15 +1138,22 @@ export class ChannelStartupService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async fetchContacts(query: Query<Contact>) {
|
public async fetchContacts(query: Query<Contact>) {
|
||||||
const remoteJid = query.where?.remoteJid.includes('@')
|
const remoteJid = query?.where?.remoteJid
|
||||||
? query.where?.remoteJid
|
? query?.where?.remoteJid.includes('@')
|
||||||
: this.createJid(query.where?.remoteJid);
|
? 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({
|
return await this.prismaRepository.contact.findMany({
|
||||||
where: {
|
where,
|
||||||
instanceId: this.instanceId,
|
|
||||||
remoteJid,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1164,8 +1171,6 @@ export class ChannelStartupService {
|
|||||||
: this.createJid(keyFilters?.remoteJid)
|
: this.createJid(keyFilters?.remoteJid)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
console.log(remoteJid);
|
|
||||||
|
|
||||||
const count = await this.prismaRepository.message.count({
|
const count = await this.prismaRepository.message.count({
|
||||||
where: {
|
where: {
|
||||||
instanceId: this.instanceId,
|
instanceId: this.instanceId,
|
||||||
@ -1246,9 +1251,47 @@ export class ChannelStartupService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async fetchChats() {
|
public async fetchChats(query: any) {
|
||||||
return await this.prismaRepository.chat.findMany({
|
const remoteJid = query?.where?.remoteJid
|
||||||
where: { instanceId: this.instanceId },
|
? 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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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') {
|
if (connection === 'open') {
|
||||||
this.instance.wuid = this.client.user.id.replace(/:\d+/, '');
|
this.instance.wuid = this.client.user.id.replace(/:\d+/, '');
|
||||||
this.instance.profilePictureUrl = (await this.profilePicture(this.instance.wuid)).profilePictureUrl;
|
this.instance.profilePictureUrl = (await this.profilePicture(this.instance.wuid)).profilePictureUrl;
|
||||||
|
@ -79,6 +79,13 @@ export class WAMonitoringService {
|
|||||||
Sqs: true,
|
Sqs: true,
|
||||||
Websocket: true,
|
Websocket: true,
|
||||||
Setting: true,
|
Setting: true,
|
||||||
|
_count: {
|
||||||
|
select: {
|
||||||
|
Message: true,
|
||||||
|
Contact: true,
|
||||||
|
Chat: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user