File size: 1,550 Bytes
4327358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { public_conversation } from '@figuro/chatwoot-sdk';
import { ILogger } from '@waha/apps/app_sdk/ILogger';
import {
  ChatWootAPIConfig,
  ChatWootInboxAPI,
} from '@waha/apps/chatwoot/client/interfaces';

export class ConversationAPI {
  constructor(
    private config: ChatWootAPIConfig,
    private inboxAPI: ChatWootInboxAPI,
    private logger: ILogger,
  ) {}

  private async find(
    contactIdentifier: string,
  ): Promise<public_conversation | null> {
    const request = {
      inboxIdentifier: this.config.inboxIdentifier,
      contactIdentifier: contactIdentifier,
    };
    const conversations = await this.inboxAPI.conversations.list(request);
    if (conversations.length != 0) {
      return conversations[0];
    }
    return null;
  }

  private async create(
    contactIdentifier: string,
  ): Promise<public_conversation> {
    const conversation = await this.inboxAPI.conversations.create({
      inboxIdentifier: this.config.inboxIdentifier,
      contactIdentifier: contactIdentifier,
    });
    this.logger.info(
      `Created conversation.id: ${conversation.id} for contact.id: ${contactIdentifier}`,
    );
    return conversation;
  }

  async upsert(contactIdentifier: string): Promise<public_conversation> {
    let conversation = await this.find(contactIdentifier);
    if (!conversation) {
      conversation = await this.create(contactIdentifier);
    }
    this.logger.info(
      `Using conversation.id: ${conversation.id} for contact.id: ${contactIdentifier}`,
    );
    return conversation;
  }
}