@@ -457,6 +457,24 @@ export class ChatwootService {
457457 }
458458 }
459459
460+ private async mergeContacts ( baseId : number , mergeId : number ) {
461+ try {
462+ const contact = await chatwootRequest ( this . getClientCwConfig ( ) , {
463+ method : 'POST' ,
464+ url : `/api/v1/accounts/${ this . provider . accountId } /actions/contact_merge` ,
465+ body : {
466+ base_contact_id : baseId ,
467+ mergee_contact_id : mergeId ,
468+ } ,
469+ } ) ;
470+
471+ return contact ;
472+ } catch {
473+ this . logger . error ( 'Error merging contacts' ) ;
474+ return null ;
475+ }
476+ }
477+
460478 private async mergeBrazilianContacts ( contacts : any [ ] ) {
461479 try {
462480 const contact = await chatwootRequest ( this . getClientCwConfig ( ) , {
@@ -561,12 +579,22 @@ export class ChatwootService {
561579 const contact = await this . findContact ( instance , body . key . remoteJid . split ( '@' ) [ 0 ] ) ;
562580 if ( contact && contact . identifier !== body . key . senderPn ) {
563581 this . logger . verbose (
564- `Identifier needs update: (contact.identifier: ${ contact . identifier } , body.key.remoteJid: ${ body . key . remoteJid } , body.key.senderPn: ${ body . key . senderPn } ) ` ,
582+ `Identifier needs update: (contact.identifier: ${ contact . identifier } , body.key.remoteJid: ${ body . key . remoteJid } , body.key.senderPn: ${ body . key . senderPn } ` ,
565583 ) ;
566- await this . updateContact ( instance , contact . id , {
584+ const updateContact = await this . updateContact ( instance , contact . id , {
567585 identifier : body . key . senderPn ,
568586 phone_number : `+${ body . key . senderPn . split ( '@' ) [ 0 ] } ` ,
569587 } ) ;
588+
589+ if ( updateContact === null ) {
590+ const baseContact = await this . findContact ( instance , body . key . senderPn . split ( '@' ) [ 0 ] ) ;
591+ if ( baseContact ) {
592+ await this . mergeContacts ( baseContact . id , contact . id ) ;
593+ this . logger . verbose (
594+ `Merge contacts: (${ baseContact . id } ) ${ baseContact . phone_number } and (${ contact . id } ) ${ contact . phone_number } ` ,
595+ ) ;
596+ }
597+ }
570598 }
571599 }
572600 this . logger . verbose ( `--- Start createConversation ---` ) ;
0 commit comments