xero-php icon indicating copy to clipboard operation
xero-php copied to clipboard

The Account Number already exists. Please enter a different Account Number.

Open criszacca opened this issue 2 years ago • 1 comments

Hey guys.

I'm trying to create a routine that checks the Contact before creating and if I don't find any I'll create a new one. But as the title of the issue says, the routine can't find any Contact, and when trying to create a new one I receive the exception.

This is my current code:

the parameter of the function is: $contacts = $this->xeroApp->load(Contact::class);

the function:

    private function getContact(Query $contacts)
    {
        $contact = (clone $contacts)
            ->where('AccountNumber', $this->actionRecord->Account_Code)
            ->execute()
            ->first();

        if ($contact) {
            echo "Find by Account_Code ".$this->actionRecord->Account_Code." and will return".PHP_EOL;
            return $contact;
        }

        $contact = (clone $contacts)
            ->where('Name', $this->getCustomerName())
            ->execute()
            ->first();

        if ($contact) {
            echo "Find by Name ".$this->getCustomerName()." and will update".PHP_EOL;
            $this->updateContactDetails($contact);
            return $contact;
        }

        return $this->createNewContact();
    }

    private function updateContactDetails(Contact $contact): void
    {
        $contact->setAccountNumber($this->actionRecord->Account_Code);

        $customerAddress = $this->actionRecord->address;
        if ($customerAddress) {
            $address = new Address($this->xeroApp);
            $address->setAddressType('STREET')
                ->setAddressLine1("$customerAddress->street_number $customerAddress->street_name")
                ->setAddressLine2($customerAddress->address_1)
                ->setAddressLine3($customerAddress->address_2)
                ->setCity($customerAddress->city)
                ->setRegion($customerAddress->state)
                ->setCountry($customerAddress->country)
                ->setPostalCode($customerAddress->postcode);

            $contact->addAddress($address);
        }

        XeroFunctions::checkResponse($contact->save());
    }

    private function createNewContact(): Contact
    {
        $contact = new Contact($this->xeroApp);
        $contact->setName($this->getCustomerName());

        $this->updateContactDetails($contact);

        return $contact;
    }

as you can see, I'm using the $contact->save() to store the contact, there is a way to use something like a CreateOrUpdateContact?

Thanks for your help!

criszacca avatar Jan 15 '23 17:01 criszacca

Make sure that you are using includeArchived() to include archived contacts in the search, and that the account code you're searching for actually exists exactly as written. There are no other filters on your query?

Healyhatman avatar May 01 '24 01:05 Healyhatman