Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Providers;
- use XeroAPI\XeroPHP\Api\AccountingApi;
- use XeroAPI\XeroPHP\Models\Accounting\Invoice;
- use XeroAPI\XeroPHP\Models\Accounting\Invoices;
- use XeroAPI\XeroPHP\Models\Accounting\Contact;
- use XeroAPI\XeroPHP\Models\Accounting\Contacts;
- use XeroAPI\XeroPHP\Models\Accounting\Email;
- use XeroAPI\XeroPHP\Models\Accounting\LineItem;
- use XeroAPI\XeroPHP\Models\Accounting\Accounts;
- use XeroAPI\XeroPHP\Models\Accounting\InventoryItem;
- use XeroAPI\XeroPHP\Models\Accounting\Payment;
- use XeroAPI\XeroPHP\Models\Accounting\Payments;
- use XeroAPI\XeroPHP\Models\Accounting\Account;
- use Illuminate\Support\Facades\Log;
- use Exception;
- class XeroService2
- {
- protected $xero;
- protected $tenantId;
- /**
- * Constructor
- *
- * @param AccountingApi $xero Injected instance of Xero Accounting API
- * @param string $tenantId Xero Tenant ID
- */
- public function __construct(AccountingApi $xero, $tenantId)
- {
- $this->xero = $xero;
- $this->tenantId = $tenantId;
- }
- /**
- * Create and send an invoice to Xero.
- *
- * @param Contact $contact The Xero contact object
- * @param LineItem[] $lineItems Array of line items
- * @param string|null $invoiceNumber Optional invoice number
- * @param string|null $reference Optional reference
- * @param array|null $terms Optional terms array
- * @param string|null $dueDate Optional due date (Y-m-d)
- * @return Invoice
- * @throws Exception
- */
- public function createInvoice($contact, $lineItems, $invoiceNumber = null, $reference = null, $terms = null, $dueDate = null)
- {
- try {
- $invoice = new Invoice([
- 'type' => Invoice::TYPE_ACCREC,
- 'contact' => $contact,
- 'line_items' => $lineItems,
- 'date' => now()->format('Y-m-d'),
- 'due_date' => $dueDate ?: now()->addDays(14)->format('Y-m-d'),
- 'status' => Invoice::STATUS_AUTHORISED,
- 'invoice_number' => $invoiceNumber,
- 'reference' => $reference,
- 'terms' => $terms,
- ]);
- $invoices = new Invoices();
- $invoices->setInvoices([$invoice]);
- $response = $this->xero->createInvoices($this->tenantId, $invoices);
- return $response->getInvoices()[0];
- } catch (Exception $e) {
- Log::error('Invoice creation failed', ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Update the status of an invoice (e.g., AUTHORIZED, VOIDED).
- *
- * @param string $invoiceId UUID of the invoice
- * @param string $status New status
- * @return Invoice
- * @throws Exception
- */
- public function updateInvoiceStatus($invoiceId, $status)
- {
- try {
- $invoice = new Invoice(['status' => $status]);
- return $this->xero->updateInvoice($this->tenantId, $invoiceId, $invoice);
- } catch (Exception $e) {
- Log::error('Update invoice status failed', ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Update the reference field on an invoice.
- *
- * @param string $invoiceId UUID of the invoice
- * @param string|null $reference Reference text
- * @return Invoice
- * @throws Exception
- */
- public function updateInvoiceReference($invoiceId, $reference = null)
- {
- try {
- $invoice = new Invoice(['reference' => $reference]);
- return $this->xero->updateInvoice($this->tenantId, $invoiceId, $invoice);
- } catch (Exception $e) {
- Log::error('Update invoice reference failed', ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Fetch a single invoice by its ID.
- *
- * @param string $invoiceId UUID of the invoice
- * @return Invoice
- * @throws Exception
- */
- public function getInvoiceById($invoiceId)
- {
- try {
- return $this->xero->getInvoice($this->tenantId, $invoiceId)->getInvoices()[0];
- } catch (Exception $e) {
- Log::error('Fetch invoice failed', ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Fetch all invoices for a specific contact ID.
- *
- * @param string $contactId UUID of the contact
- * @return Invoice[]
- * @throws Exception
- */
- public function getInvoicesByContactId($contactId)
- {
- try {
- $response = $this->xero->getInvoices($this->tenantId, null, 'Contact.ContactID=="' . $contactId . '"');
- return $response->getInvoices();
- } catch (Exception $e) {
- Log::error('Fetch invoices by contact failed', ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Send an invoice to the contact's email.
- *
- * @param string $invoiceId UUID of the invoice
- * @return mixed
- * @throws Exception
- */
- public function emailInvoice($invoiceId)
- {
- try {
- return $this->xero->emailInvoice($this->tenantId, $invoiceId);
- } catch (Exception $e) {
- Log::error('Send invoice email failed', ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Create or update a Xero contact.
- *
- * @param string|null $contactId Existing contact ID to update
- * @param string|null $name Contact name
- * @param string|null $email Email address
- * @param string|null $phone Phone number
- * @param string|null $firstName First name
- * @param string|null $lastName Last name
- * @return Contact
- * @throws Exception
- */
- public function upsertContact($contactId = null, $name = null, $email = null, $phone = null, $firstName = null, $lastName = null)
- {
- try {
- $contact = new Contact([
- 'contact_id' => $contactId,
- 'name' => $name,
- 'email_address' => $email,
- 'first_name' => $firstName,
- 'last_name' => $lastName,
- 'phones' => $phone ? [['phone_number' => $phone]] : [],
- ]);
- $contacts = new Contacts();
- $contacts->setContacts([$contact]);
- $response = $this->xero->createContacts($this->tenantId, $contacts);
- return $response->getContacts()[0];
- } catch (Exception $e) {
- Log::error('Upsert contact failed', ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Update contact status (e.g., ARCHIVED, ACTIVE).
- *
- * @param string $contactId UUID of the contact
- * @param string $status New status
- * @return Contact
- * @throws Exception
- */
- public function updateContactStatus($contactId, $status)
- {
- try {
- $contact = new Contact(['contact_status' => $status]);
- return $this->xero->updateContact($this->tenantId, $contactId, $contact);
- } catch (Exception $e) {
- Log::error('Update contact status failed', ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Get a contact by ID.
- *
- * @param string $contactId UUID of the contact
- * @return Contact
- * @throws Exception
- */
- public function getContactById($contactId)
- {
- try {
- return $this->xero->getContact($this->tenantId, $contactId)->getContacts()[0];
- } catch (Exception $e) {
- Log::error('Get contact failed', ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Find contact by email.
- *
- * @param string $email
- * @return Contact[]
- * @throws Exception
- */
- public function findContactByEmail($email)
- {
- return $this->findContactByField('EmailAddress', $email);
- }
- /**
- * Find contact by name.
- *
- * @param string $name
- * @return Contact[]
- * @throws Exception
- */
- public function findContactByName($name)
- {
- return $this->findContactByField('Name', $name);
- }
- /**
- * Find contact by phone number.
- *
- * @param string $phone
- * @return Contact[]
- * @throws Exception
- */
- public function findContactByPhone($phone)
- {
- return $this->findContactByField('Phones.PhoneNumber', $phone);
- }
- /**
- * Generic helper to find a contact by any field.
- *
- * @param string $field
- * @param string $value
- * @return Contact[]
- * @throws Exception
- */
- protected function findContactByField($field, $value)
- {
- try {
- $where = "$field==\"$value\"";
- $response = $this->xero->getContacts($this->tenantId, null, $where);
- return $response->getContacts();
- } catch (Exception $e) {
- Log::error("Search contact by $field failed", ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Get all chart of accounts from Xero.
- *
- * @return Accounts[]
- * @throws Exception
- */
- public function getAccountsList()
- {
- try {
- return $this->xero->getAccounts($this->tenantId)->getAccounts();
- } catch (Exception $e) {
- Log::error('Get accounts list failed', ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Fetch all inventory items from Xero
- *
- * @param string $xeroTenantId The Xero tenant ID for the authenticated account.
- *
- * @return array An array of inventory items from Xero.
- * @throws \XeroAPI\XeroPHP\ApiException If the API request fails.
- */
- public function getAllInventoryItems()
- {
- try {
- // Make API call to get all inventory items
- $items = $this->xero->getItems($this->tenantId);
- // Return the retrieved inventory items
- return $items;
- } catch (\XeroAPI\XeroPHP\ApiException $e) {
- // Log or handle the exception as needed
- // For now, we simply rethrow it
- throw new \Exception("Error fetching inventory items: " . $e->getMessage());
- }
- }
- /**
- * Create or update an inventory item.
- *
- * @param string $code Unique item code
- * @param string $name Item name
- * @param string|null $description Description
- * @param float|null $unitPrice Sale and purchase price
- * @param string|null $inventoryAssetAccountCode Inventory account code
- * @param bool $isTracked Whether item is tracked in inventory
- * @return InventoryItem
- * @throws Exception
- */
- public function upsertInventoryItem($code, $name, $description = null, $unitPrice = null, $inventoryAssetAccountCode = null, $isTracked = false)
- {
- try {
- $item = new InventoryItem([
- 'code' => $code,
- 'name' => $name,
- 'description' => $description,
- 'purchase_details' => ['unit_price' => $unitPrice],
- 'sales_details' => ['unit_price' => $unitPrice],
- 'inventory_asset_account_code' => $inventoryAssetAccountCode,
- 'is_tracked_as_inventory' => $isTracked,
- ]);
- return $this->xero->createInventoryItem($this->tenantId, $item);
- } catch (Exception $e) {
- Log::error('Upsert inventory item failed', ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Delete an inventory item by ID.
- *
- * @param string $itemId UUID of the item
- * @return mixed
- * @throws Exception
- */
- public function deleteInventoryItem($itemId)
- {
- try {
- return $this->xero->deleteInventoryItem($this->tenantId, $itemId);
- } catch (Exception $e) {
- Log::error('Delete inventory item failed', ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Find inventory by code.
- *
- * @param string $code
- * @return InventoryItem[]
- * @throws Exception
- */
- public function getInventoryByCode($code)
- {
- return $this->findInventoryByField('Code', $code);
- }
- /**
- * Find inventory by name.
- *
- * @param string $name
- * @return InventoryItem[]
- * @throws Exception
- */
- public function getInventoryByName($name)
- {
- return $this->findInventoryByField('Name', $name);
- }
- /**
- * Generic helper to find an inventory item by field.
- *
- * @param string $field
- * @param string $value
- * @return InventoryItem[]
- * @throws Exception
- */
- protected function findInventoryByField($field, $value)
- {
- try {
- $where = "$field==\"$value\"";
- $response = $this->xero->getItems($this->tenantId, null, $where);
- return $response->getItems();
- } catch (Exception $e) {
- Log::error("Search inventory by $field failed", ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- /**
- * Create a payment in Xero for a specific invoice using either account code or account ID.
- *
- * @param string $invoiceId The Xero Invoice ID (UUID) for which payment is being made.
- * @param float $amount The amount to be paid.
- * @param string $accountCodeOrId The account code (e.g., '090') or account ID (UUID) of the bank account.
- *
- * @return \XeroAPI\XeroPHP\Models\Accounting\Payment The created payment object from Xero.
- *
- * @throws \Exception If the payment creation fails or an error occurs in the API call.
- */
- public function createPayment(string $invoiceId, float $amount, string $accountCodeOrId)
- {
- try {
- // Determine if the provided account identifier is a UUID (account ID) or a code
- $isUuid = preg_match('/^[0-9a-fA-F-]{36}$/', $accountCodeOrId);
- // Create Account object using either account_id or code
- $account = $isUuid ? new Account(['account_id' => $accountCodeOrId]): new Account(['code' => $accountCodeOrId]);
- // Prepare the Payment object
- $payment = new Payment([
- 'invoice' => new Invoice(['invoice_id' => $invoiceId]), // Link to the invoice
- 'account' => $account, // Specify the payment account
- 'date' => now()->format('Y-m-d'), // Use today's date for payment
- 'amount' => $amount, // Set the payment amount
- ]);
- // Wrap the payment in a Payments collection
- $payments = new Payments();
- $payments->setPayments([$payment]);
- // Send the payment to Xero
- $response = $this->xero->createPayments($this->tenantId, $payments);
- // Return the created payment from the response
- return $response->getPayments()[0];
- } catch (Exception $e) {
- // Log and rethrow the exception in case of failure
- Log::error('Create payment failed', ['error' => $e->getMessage()]);
- throw $e;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement