@@ -207,6 +207,11 @@ public function routeNotificationForTwilio(): ?string
207207 return $ this ->phone ;
208208 }
209209
210+ public function setPhoneAttribute (?string $ value )
211+ {
212+ $ this ->attributes ['phone ' ] = is_string ($ value ) ? Utils::formatPhoneNumber ($ value ) : $ value ;
213+ }
214+
210215 /**
211216 * Get avatar URL attribute.
212217 */
@@ -279,13 +284,27 @@ public static function createUserFromContact(Contact $contact, bool $sendInvite
279284 {
280285 // Check if user already exist with email or phone number
281286 $ existingUser = User::where (function ($ query ) use ($ contact ) {
287+ $ query ->where ('company_uuid ' , $ contact ->company_uuid );
282288 $ query ->where ('email ' , $ contact ->email );
283289 if ($ contact ->phone ) {
284- $ query ->orWhere ('phone ' , $ contact ->phone );
290+ $ query ->orWhere ('phone ' , Utils:: formatPhoneNumber ( $ contact ->phone ) );
285291 }
286292 })->whereNull ('deleted_at ' )->first ();
287293 if ($ existingUser ) {
288- throw new UserAlreadyExistsException ('User already exists, try to assigning the user to this contact. ' , $ existingUser );
294+ // Check if existing user belongs to another contact
295+ $ existingUserContact = Contact::where (['user_uuid ' => $ existingUser ->uuid , 'company_uuid ' => $ contact ->company_uuid ])->first ();
296+ if ($ existingUserContact ) {
297+ throw new UserAlreadyExistsException ('User already exists, try to assigning the user to this contact. ' , $ existingUser );
298+ } else {
299+ // Assign the user to this contact instead
300+ $ contact ->setAttribute ('user_uuid ' , $ existingUser ->uuid );
301+ if ($ update ) {
302+ $ contact ->update (['user_uuid ' => $ existingUser ->uuid ]);
303+ }
304+ $ contact ->setRelation ('user ' , $ existingUser );
305+ }
306+
307+ return $ existingUser ;
289308 }
290309
291310 // Load company
@@ -296,7 +315,7 @@ public static function createUserFromContact(Contact $contact, bool $sendInvite
296315 'company_uuid ' => $ contact ->company_uuid ,
297316 'name ' => $ contact ->name ,
298317 'email ' => $ contact ->email ,
299- 'phone ' => $ contact ->phone ,
318+ 'phone ' => Utils:: formatPhoneNumber ( $ contact ->phone ) ,
300319 'username ' => Str::slug ($ contact ->name . '_ ' . Str::random (4 ), '_ ' ),
301320 'password ' => Str::random (),
302321 'timezone ' => $ contact ->company ->timezone ?? date_default_timezone_get (),
0 commit comments