File size: 1,619 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
54
import ChatwootClient from '@figuro/chatwoot-sdk';
import { ChatWootAccountAPIConfig } from '@waha/apps/chatwoot/client/interfaces';
import {
  CustomAttributeModel,
  CustomAttributeType,
} from '@waha/apps/chatwoot/client/types';

export interface CustomAttribute {
  key: string;
  name: string;
  type: CustomAttributeType;
  description: string;
  model: CustomAttributeModel;
}

export class CustomAttributesAPI {
  constructor(
    private config: ChatWootAccountAPIConfig,
    private accountAPI: ChatwootClient,
  ) {}

  async upsert(attribute: CustomAttribute): Promise<void> {
    const attributes = await this.accountAPI.customAttributes.list({
      accountId: this.config.accountId,
      attributeModel: String(attribute.model) as '0' | '1',
    });
    const existing = attributes.find((a) => a.attribute_key === attribute.key);

    if (existing) {
      await this.accountAPI.customAttributes.update({
        accountId: this.config.accountId,
        id: existing.id,
        data: {
          attribute_key: attribute.key,
          attribute_display_name: attribute.name,
          attribute_display_type: attribute.type,
          attribute_description: attribute.description,
        },
      });
    } else {
      await this.accountAPI.customAttributes.create({
        accountId: this.config.accountId,
        data: {
          attribute_key: attribute.key,
          attribute_display_name: attribute.name,
          attribute_display_type: attribute.type,
          attribute_description: attribute.description,
          attribute_model: attribute.model,
        },
      });
    }
  }
}