### Install python-quickbooks Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Install the library using pip. This is the first step to using the Quickbooks API. ```bash pip install python-quickbooks ``` -------------------------------- ### Example Integration Test Case Source: https://github.com/routablehq/python-quickbooks/blob/main/contributing.md An example of an integration test case that inherits from QuickbooksTestCase. This setup automatically provides a configured `self.qb_client` for interacting with the QBO API. ```python from tests.integration.test_base import QuickbooksTestCase class SampleTestCase(QuickbooksTestCase): def test_something(self): vendors = Vendor.all(max_results=1, qb=self.qb_client) ``` -------------------------------- ### Create and Manage Items in Python Source: https://context7.com/routablehq/python-quickbooks/llms.txt Demonstrates creating service and inventory items, retrieving them by ID, listing active items, searching by name, and getting item references. Ensure necessary accounts are set up before creating inventory items. ```python from quickbooks.objects.item import Item from quickbooks.objects.account import Account from quickbooks.objects.base import Ref # Create a service item service_item = Item() service_item.Name = "Consulting Services" service_item.Description = "Professional consulting by the hour" service_item.Type = "Service" service_item.UnitPrice = 150.00 service_item.Active = True # Set income account income_account = Account.filter(AccountType="Income", qb=client)[0] service_item.IncomeAccountRef = income_account.to_ref() saved_item = service_item.save(qb=client) print(f"Created item: {saved_item.Name} (ID: {saved_item.Id})") # Create an inventory item inventory_item = Item() inventory_item.Name = "Widget Pro" inventory_item.Description = "High-quality professional widget" inventory_item.Type = "Inventory" inventory_item.TrackQtyOnHand = True inventory_item.QtyOnHand = 100 inventory_item.InvStartDate = "2024-01-01" inventory_item.UnitPrice = 29.99 inventory_item.PurchaseCost = 15.00 inventory_item.PurchaseDesc = "Widget for resale" inventory_item.Sku = "WIDGET-PRO-001" # Set required accounts for inventory asset_account = Account.filter(AccountType="Other Current Asset", qb=client)[0] expense_account = Account.filter(AccountType="Cost of Goods Sold", qb=client)[0] income_account = Account.filter(AccountType="Income", qb=client)[0] inventory_item.AssetAccountRef = asset_account.to_ref() inventory_item.ExpenseAccountRef = expense_account.to_ref() inventory_item.IncomeAccountRef = income_account.to_ref() saved_inventory = inventory_item.save(qb=client) # Get item by ID item = Item.get(1, qb=client) # List all active items active_items = Item.filter(Active=True, qb=client) # Search items by name items = Item.where("Name LIKE '%Widget%'", qb=client) # Get item reference for use in invoices item_ref = item.to_ref() ``` -------------------------------- ### Install Testing Dependencies Source: https://github.com/routablehq/python-quickbooks/blob/main/contributing.md Install the necessary Python packages for running tests, including pytest, coverage, and pytest-cov. Use pip or your preferred package manager. ```bash pip install pytest coverage pytest-cov ``` -------------------------------- ### Get and Update Single Customer Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Retrieve a single customer record by its ID, modify its properties, and save the changes. ```python customer = Customer.get(1, qb=client) customer.CompanyName = "New Test Company Name" customer.save(qb=client) ``` -------------------------------- ### Filter Customers with Paging Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Retrieve a paginated list of customers, specifying the starting position and maximum number of results per page. This is useful for handling large datasets. ```python customers = Customer.filter(start_position=1, max_results=25, Active=True, FamilyName="Smith", qb=client) ``` -------------------------------- ### Get Customer Record Count Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Retrieve the total count of records matching specific criteria. Do not include the 'WHERE' keyword in the count query. ```python customer_count = Customer.count("Active = True AND CompanyName LIKE 'S%'", qb=client) ``` -------------------------------- ### Create and Manage Accounts in Python Source: https://context7.com/routablehq/python-quickbooks/llms.txt Shows how to create new accounts, retrieve them by ID, list all accounts, filter by type, search using conditions, deactivate accounts, and convert them to references or JSON. Ensure the 'qb=client' argument is passed for all operations. ```python from quickbooks.objects.account import Account # Create a new account account = Account() account.Name = "Office Equipment" account.AccountType = "Fixed Asset" account.AccountSubType = "FurnitureAndFixtures" account.Description = "Office furniture and equipment" account.AcctNum = "1500" saved_account = account.save(qb=client) print(f"Created account: {saved_account.FullyQualifiedName}") # Get account by ID account = Account.get(1, qb=client) # List all accounts all_accounts = Account.all(qb=client) # Filter by account type income_accounts = Account.filter(AccountType="Income", qb=client) expense_accounts = Account.filter(AccountType="Expense", qb=client) bank_accounts = Account.filter(AccountType="Bank", qb=client) # Search accounts accounts = Account.where("Active = True AND AccountType = 'Income'", qb=client) # Deactivate an account (soft delete) account = Account.get(42, qb=client) account.Active = False account.save(qb=client) # Get account reference account_ref = account.to_ref() # Convert account to JSON json_data = account.to_json() # Create account from JSON account = Account.from_json({ "AccountType": "Accounts Receivable", "AcctNum": "1100", "Name": "Trade Receivables" }) account.save(qb=client) ``` -------------------------------- ### Initialize AuthClient for Quickbooks Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Set up an AuthClient with your credentials and environment details. The access token can be optionally provided; if omitted, the client will refresh it. ```python from intuitlib.client import AuthClient auth_client = AuthClient( client_id='CLIENT_ID', client_secret='CLIENT_SECRET', access_token='ACCESS_TOKEN', # If you do not pass this in, the Quickbooks client will call refresh and get a new access token. environment='sandbox', redirect_uri='http://localhost:8000/callback', ) ``` -------------------------------- ### Initialize QuickBooks Client Source: https://context7.com/routablehq/python-quickbooks/llms.txt Set up the AuthClient for OAuth 2.0 and create a QuickBooks client instance. Ensure to replace placeholders with your actual credentials and company ID. The minorversion parameter is crucial for API compatibility. ```python from intuitlib.client import AuthClient from quickbooks import QuickBooks # Set up OAuth 2.0 authentication client auth_client = AuthClient( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', access_token='YOUR_ACCESS_TOKEN', # Optional: will refresh if not provided environment='sandbox', # Use 'production' for live data redirect_uri='http://localhost:8000/callback', ) # Create QuickBooks client instance client = QuickBooks( auth_client=auth_client, refresh_token='YOUR_REFRESH_TOKEN', company_id='YOUR_COMPANY_ID', minorversion=75, # API minor version (minimum supported is 75) use_decimal=True, # Optional: use Decimal for monetary values ) # Access the refresh token after session initialization current_refresh_token = client.refresh_token ``` -------------------------------- ### Batch Create Customers in Python Source: https://context7.com/routablehq/python-quickbooks/llms.txt Illustrates how to perform batch create operations for multiple customers using the `batch_create` function. The system handles automatic batching for lists exceeding 30 items. It also shows how to process successful creations and handle any faults or errors. ```python from quickbooks.batch import batch_create, batch_update, batch_delete from quickbooks.objects.customer import Customer from quickbooks.objects.payment import Payment from datetime import date # Batch create multiple customers customers_to_create = [] customer1 = Customer() customer1.DisplayName = "Customer A" customer1.CompanyName = "Company A Inc." customers_to_create.append(customer1) customer2 = Customer() customer2.DisplayName = "Customer B" customer2.CompanyName = "Company B LLC" customers_to_create.append(customer2) customer3 = Customer() customer3.DisplayName = "Customer C" customer3.CompanyName = "Company C Corp" customers_to_create.append(customer3) results = batch_create(customers_to_create, qb=client) # Process successful creates for customer in results.successes: print(f"Created: {customer.DisplayName} (ID: {customer.Id})") # Handle any failures for fault in results.faults: print(f"Failed to create: {fault.original_object.DisplayName}") for error in fault.Error: print(f" Error {error.code}: {error.Message}") print(f" Detail: {error.Detail}") ``` -------------------------------- ### Create New Customer Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Instantiate a new customer object, set its properties, and save it to QuickBooks. ```python customer = Customer() customer.CompanyName = "Test Company" customer.save(qb=client) ``` -------------------------------- ### Attach File to Customer by Path Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Attach a file to a customer record by providing the file's full path. Ensure the file exists at the specified location. ```python attachment = Attachable() attachable_ref = AttachableRef() attachable_ref.EntityRef = customer.to_ref() attachment.AttachableRef.append(attachable_ref) attachment.FileName = 'Filename' attachment._FilePath = '/folder/filename' # full path to file attachment.ContentType = 'application/pdf' attachment.save(qb=client) ``` -------------------------------- ### Create Quickbooks Client Object Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Instantiate a QuickBooks client by passing the configured AuthClient, refresh token, and company ID. This client is used for all subsequent API interactions. ```python from quickbooks import QuickBooks client = QuickBooks( auth_client=auth_client, refresh_token='REFRESH_TOKEN', company_id='COMPANY_ID', ) ``` -------------------------------- ### Run All Tests with Coverage Source: https://github.com/routablehq/python-quickbooks/blob/main/contributing.md Execute the entire test suite and generate a coverage report. This command runs all unit and integration tests. ```bash pytest --cov ``` -------------------------------- ### JSON Serialization and Deserialization with QuickBooks Objects Source: https://context7.com/routablehq/python-quickbooks/llms.txt Shows how to convert QuickBooks objects to JSON strings or dictionaries, and how to create objects from JSON data. This is useful for data exchange and storage. ```python from quickbooks.objects.customer import Customer from quickbooks.objects.account import Account # Convert object to JSON customer = Customer.get(42, qb=client) json_string = customer.to_json() print(json_string) ``` ```python # Convert object to dictionary customer_dict = customer.to_dict() print(customer_dict['DisplayName']) ``` ```python # Create object from JSON data account = Account.from_json({ "AccountType": "Accounts Receivable", "AcctNum": "1200", "Name": "Customer Deposits", "Description": "Advance payments from customers" }) saved_account = account.save(qb=client) ``` ```python # Load customer from JSON customer_data = { "DisplayName": "New Customer", "CompanyName": "New Company Inc", "Active": True, "BillAddr": { "Line1": "100 First Street", "City": "New York", "CountrySubDivisionCode": "NY", "PostalCode": "10001" }, "PrimaryEmailAddr": { "Address": "contact@newcompany.com" } } new_customer = Customer.from_json(customer_data) saved_customer = new_customer.save(qb=client) ``` -------------------------------- ### Attach File to Customer by Bytes Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Attach a file to a customer record by providing its content as bytes. This is useful when the file content is already in memory. ```python attachment = Attachable() attachable_ref = AttachableRef() attachable_ref.EntityRef = customer.to_ref() attachment.AttachableRef.append(attachable_ref) attachment.FileName = 'Filename' attachment._FileBytes = pdf_bytes # bytes object containing the file content attachment.ContentType = 'application/pdf' attachment.save(qb=client) ``` -------------------------------- ### Create and Save an Invoice Source: https://context7.com/routablehq/python-quickbooks/llms.txt Use this snippet to create a new invoice with multiple line items, set customer details, due dates, and enable online payment options. Ensure the 'client' object is properly initialized. ```python from quickbooks.objects.invoice import Invoice from quickbooks.objects.detailline import SalesItemLine, SalesItemLineDetail from quickbooks.objects.base import Ref, CustomerMemo, EmailAddress from quickbooks.objects.customer import Customer from quickbooks.objects.item import Item # Create an invoice invoice = Invoice() # Set customer reference customer = Customer.get(42, qb=client) invoice.CustomerRef = customer.to_ref() # Add line items line1 = SalesItemLine() line1.LineNum = 1 line1.Description = "Professional Services" line1.Amount = 500.00 # Set item details line1.SalesItemLineDetail = SalesItemLineDetail() item = Item.get(1, qb=client) line1.SalesItemLineDetail.ItemRef = item.to_ref() line1.SalesItemLineDetail.UnitPrice = 100.00 line1.SalesItemLineDetail.Qty = 5 invoice.Line.append(line1) # Add second line item line2 = SalesItemLine() line2.LineNum = 2 line2.Description = "Consulting Hours" line2.Amount = 250.00 line2.SalesItemLineDetail = SalesItemLineDetail() line2.SalesItemLineDetail.UnitPrice = 50.00 line2.SalesItemLineDetail.Qty = 5 invoice.Line.append(line2) # Set invoice details invoice.DueDate = "2024-02-01" invoice.TxnDate = "2024-01-15" invoice.PrivateNote = "Internal note for this invoice" # Add customer memo invoice.CustomerMemo = CustomerMemo() invoice.CustomerMemo.value = "Thank you for your business!" # Set billing email invoice.BillEmail = EmailAddress() invoice.BillEmail.Address = "customer@example.com" # Enable online payment invoice.AllowOnlineCreditCardPayment = True invoice.AllowOnlineACHPayment = True # Save invoice saved_invoice = invoice.save(qb=client) print(f"Created Invoice #{saved_invoice.DocNumber}, Total: ${saved_invoice.TotalAmt}") ``` -------------------------------- ### Fetch QuickBooks Reports with Date Ranges Source: https://context7.com/routablehq/python-quickbooks/llms.txt Demonstrates fetching various financial reports from QuickBooks using the client.get_report method. Specify date ranges or report dates using the 'qs' parameter for filtered results. ```python params = { 'start_date': '2024-01-01', 'end_date': '2024-03-31' } quarterly_pnl = client.get_report('ProfitAndLoss', qs=params) ``` ```python balance_sheet = client.get_report('BalanceSheet') ``` ```python ar_aging = client.get_report('AgedReceivables', qs={ 'report_date': '2024-01-31' }) ``` ```python cash_flow = client.get_report('CashFlow', qs={ 'start_date': '2024-01-01', 'end_date': '2024-12-31' }) ``` ```python customer_sales = client.get_report('CustomerSales', qs={ 'start_date': '2024-01-01', 'end_date': '2024-01-31' }) ``` -------------------------------- ### Run Only Unit Tests with Coverage Source: https://github.com/routablehq/python-quickbooks/blob/main/contributing.md Execute only the unit tests and generate a coverage report. Unit tests do not connect to the QBO API. ```bash pytest tests/unit --cov ``` -------------------------------- ### Run Only Integration Tests with Coverage Source: https://github.com/routablehq/python-quickbooks/blob/main/contributing.md Execute only the integration tests and generate a coverage report. Integration tests connect to the QBO API. ```bash pytest tests/integration --cov ``` -------------------------------- ### Create Quickbooks Client with Minor Version Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md When accessing specific minor versions of the Quickbooks API, pass the minorversion parameter during client initialization. Note that older minor versions will be deprecated. ```python client = QuickBooks( auth_client=auth_client, refresh_token='REFRESH_TOKEN', company_id='COMPANY_ID', minorversion=69 ) ``` -------------------------------- ### Attach Notes and Files to QuickBooks Objects Source: https://context7.com/routablehq/python-quickbooks/llms.txt Manage file attachments and notes linked to transactions or items. Supports attaching notes, files via path, and files via in-memory bytes. ```python from quickbooks.objects.attachable import Attachable from quickbooks.objects.base import AttachableRef from quickbooks.objects.customer import Customer from quickbooks.objects.invoice import Invoice # Attach a note to a customer customer = Customer.get(42, qb=client) attachment = Attachable() attachable_ref = AttachableRef() attachable_ref.EntityRef = customer.to_ref() attachment.AttachableRef.append(attachable_ref) attachment.Note = "Important customer - priority support required" saved_attachment = attachment.save(qb=client) print(f"Created note attachment ID: {saved_attachment.Id}") # Attach a file to an invoice using file path invoice = Invoice.get(123, qb=client) file_attachment = Attachable() attachable_ref = AttachableRef() attachable_ref.EntityRef = invoice.to_ref() file_attachment.AttachableRef.append(attachable_ref) file_attachment.FileName = "contract.pdf" file_attachment._FilePath = "/path/to/contract.pdf" # Full path to file file_attachment.ContentType = "application/pdf" saved_file = file_attachment.save(qb=client) print(f"Attached file: {saved_file.FileName}") print(f"File URI: {saved_file.FileAccessUri}") # Attach file using bytes (in-memory) with open('/path/to/document.pdf', 'rb') as f: pdf_bytes = f.read() bytes_attachment = Attachable() attachable_ref = AttachableRef() attachable_ref.EntityRef = customer.to_ref() bytes_attachment.AttachableRef.append(attachable_ref) bytes_attachment.FileName = "document.pdf" bytes_attachment._FileBytes = pdf_bytes # Bytes object bytes_attachment.ContentType = "application/pdf" saved_bytes = bytes_attachment.save(qb=client) # List all attachments all_attachments = Attachable.all(qb=client) # Get attachment by ID attachment = Attachable.get(1, qb=client) # Delete an attachment attachment = Attachable.get(456, qb=client) attachment.delete(qb=client) ``` -------------------------------- ### Batch Create Customers Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Perform multiple customer creation operations in a single API request for efficiency. Ensure all customer objects are properly initialized. ```python from quickbooks.batch import batch_create customer1 = Customer() customer1.CompanyName = "Test Company 1" customer2 = Customer() customer2.CompanyName = "Test Company 2" customers = [customer1, customer2] results = batch_create(customers, qb=client) ``` -------------------------------- ### Set Environment Variables for Testing Source: https://github.com/routablehq/python-quickbooks/blob/main/contributing.md These environment variables are required to authenticate with the QBO API for integration tests. Ensure these are set before running tests that interact with the QuickBooks API. ```bash export CLIENT_ID="" export CLIENT_SECRET="" export COMPANY_ID="" export REFRESH_TOKEN="" ``` -------------------------------- ### Order Customers by Multiple Fields Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Retrieve all customers, ordered by 'FamilyName' and then by 'GivenName'. This allows for multi-level sorting of results. ```python # Order customers by FamilyName then by GivenName customers = Customer.all(order_by='FamilyName, GivenName', qb=client) ``` -------------------------------- ### Load JSON into QuickBooks Object Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Use the `from_json` class method to load JSON data into a QuickBooks object, then save it. ```python account = Account.from_json( { "AccountType": "Accounts Receivable", "AcctNum": "123123", "Name": "MyJobs" } ) account.save(qb=client) ``` -------------------------------- ### Download Invoice as PDF Source: https://context7.com/routablehq/python-quickbooks/llms.txt Downloads the PDF content of a specific invoice. The binary content is then saved to a local file named 'invoice.pdf'. ```python # Download invoice as PDF pdf_content = invoice.download_pdf(qb=client) with open('invoice.pdf', 'wb') as f: f.write(pdf_content) ``` -------------------------------- ### Format Dates for QuickBooks Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Utilize helper functions `qb_date_format`, `qb_datetime_format`, and `qb_datetime_utc_offset_format` for correct date and datetime string formatting. ```python date_string = qb_date_format(date(2016, 7, 22)) ``` ```python date_time_string = qb_datetime_format(datetime(2016, 7, 22, 10, 35, 00)) ``` ```python date_time_with_utc_string = qb_datetime_utc_offset_format(datetime(2016, 7, 22, 10, 35, 00), '-06:00') ``` -------------------------------- ### Create and Save a Payment for an Invoice Source: https://context7.com/routablehq/python-quickbooks/llms.txt Records a customer payment against a specific invoice. This involves linking the payment to the invoice and setting the payment details. An optional deposit account can be specified. ```python from quickbooks.objects.payment import Payment, PaymentLine from quickbooks.objects.invoice import Invoice from quickbooks.objects.customer import Customer from quickbooks.objects.base import Ref, LinkedTxn # Create a payment for an invoice payment = Payment() # Set customer customer = Customer.get(42, qb=client) payment.CustomerRef = customer.to_ref() # Set payment amount payment.TotalAmt = 500.00 payment.TxnDate = "2024-01-20" payment.PaymentRefNum = "CHK-1234" # Link to specific invoice invoice = Invoice.get(123, qb=client) payment_line = PaymentLine() payment_line.Amount = 500.00 linked_txn = LinkedTxn() linked_txn.TxnId = invoice.Id linked_txn.TxnType = "Invoice" payment_line.LinkedTxn.append(linked_txn) payment.Line.append(payment_line) # Set deposit account (optional) deposit_account_ref = Ref() deposit_account_ref.value = "4" # Account ID payment.DepositToAccountRef = deposit_account_ref # Save payment saved_payment = payment.save(qb=client) print(f"Recorded payment ID: {saved_payment.Id}") ``` -------------------------------- ### Create an Unapplied Payment (Credit) Source: https://context7.com/routablehq/python-quickbooks/llms.txt Creates a payment that is not immediately applied to a specific invoice or credit memo, effectively acting as a customer credit. ```python # Create unapplied payment (credit) unapplied_payment = Payment() unapplied_payment.CustomerRef = customer.to_ref() unapplied_payment.TotalAmt = 1000.00 unapplied_payment.save(qb=client) ``` -------------------------------- ### Create and Manage Customers Source: https://context7.com/routablehq/python-quickbooks/llms.txt Perform CRUD operations on customer objects, including creating new customers with detailed addresses and contact information, retrieving, updating, and listing customers. Supports various filtering and querying methods. ```python from quickbooks.objects.customer import Customer from quickbooks.objects.base import Address, PhoneNumber, EmailAddress # Create a new customer with full details customer = Customer() customer.CompanyName = "Acme Corporation" customer.DisplayName = "Acme Corp" customer.GivenName = "John" customer.FamilyName = "Smith" customer.Active = True customer.Taxable = True # Add billing address customer.BillAddr = Address() customer.BillAddr.Line1 = "123 Main Street" customer.BillAddr.City = "San Francisco" customer.BillAddr.CountrySubDivisionCode = "CA" customer.BillAddr.PostalCode = "94105" customer.BillAddr.Country = "US" # Add contact information customer.PrimaryPhone = PhoneNumber() customer.PrimaryPhone.FreeFormNumber = "(555) 123-4567" customer.PrimaryEmailAddr = EmailAddress() customer.PrimaryEmailAddr.Address = "john@acmecorp.com" # Save to QuickBooks saved_customer = customer.save(qb=client) print(f"Created customer ID: {saved_customer.Id}") ``` ```python # Get a customer by ID customer = Customer.get(42, qb=client) ``` ```python # Update customer customer.CompanyName = "Acme Corporation Inc." customer.save(qb=client) ``` ```python # List all customers (default 100, max 1000) all_customers = Customer.all(qb=client) ``` ```python # List with ordering and pagination customers = Customer.all( order_by='FamilyName, GivenName', start_position=1, max_results=50, qb=client ) ``` ```python # Filter customers by field values active_smiths = Customer.filter( Active=True, FamilyName="Smith", qb=client ) ``` ```python # Filter with pagination paginated_customers = Customer.filter( start_position=1, max_results=25, Active=True, qb=client ) ``` ```python # Custom WHERE clause (do NOT include 'WHERE') customers = Customer.where( "Active = True AND CompanyName LIKE 'A%'", order_by='DisplayName', qb=client ) ``` ```python # Full SQL query customers = Customer.query( "SELECT * FROM Customer WHERE Balance > '1000' STARTPOSITION 1 MAXRESULTS 25", qb=client ) ``` ```python # Get customers by list of values customer_names = ['Acme Corp', 'Beta Inc', 'Gamma LLC'] selected_customers = Customer.choose(customer_names, field="DisplayName", qb=client) ``` ```python # Count customers matching criteria count = Customer.count("Active = True AND CompanyName LIKE 'A%'", qb=client) print(f"Total matching customers: {count}") ``` ```python # Convert customer to reference object for use in transactions customer_ref = customer.to_ref() ``` -------------------------------- ### Filter Customer List with Custom Query Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Use custom SQL queries to filter lists of customers. Ensure your query syntax is supported by the QuickBooks API. ```python customers = Customer.query("SELECT * FROM Customer WHERE Active = True", qb=client) ``` -------------------------------- ### List Customers with Custom WHERE and Ordering Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Filter customers using a custom WHERE clause and specify an ordering for the results. The ordering is applied after the filtering. ```python customers = Customer.where("Active = True AND CompanyName LIKE 'S%'", order_by='DisplayName', qb=client) ``` -------------------------------- ### QuickBooks API Exception Handling Source: https://context7.com/routablehq/python-quickbooks/llms.txt Illustrates comprehensive error handling for various QuickBooks API exceptions. This allows for specific responses to different error types, such as object not found, validation errors, or authorization failures. ```python from quickbooks.exceptions import ( QuickbooksException, AuthorizationException, ValidationException, ObjectNotFoundException, UnsupportedException, GeneralException, SevereException ) from quickbooks.objects.customer import Customer # Comprehensive error handling try: customer = Customer.get(99999, qb=client) except ObjectNotFoundException as e: # Error code 610: Object not found print(f"Customer not found: {e.message}") print(f"Error code: {e.error_code}") print(f"Detail: {e.detail}") except AuthorizationException as e: # Error codes 1-499: Authentication/authorization issues print(f"Authorization failed: {e.message}") # May need to refresh tokens except ValidationException as e: # Error codes 2000-4999: Validation errors print(f"Validation error: {e.message}") print(f"Detail: {e.detail}") except UnsupportedException as e: # Error codes 500-599: Unsupported operations print(f"Operation not supported: {e.message}") except GeneralException as e: # Error codes 600-1999: General errors print(f"General error: {e.message}") except SevereException as e: # Error codes 10000+: Severe/system errors print(f"Severe error: {e.message}") except QuickbooksException as e: # Catch-all for any QuickBooks error print(f"QuickBooks error: {e.message}") print(f"Error code: {e.error_code}") print(f"Detail: {e.detail}") ``` ```python # Error handling during save operations try: customer = Customer() customer.DisplayName = "" # Invalid: empty display name customer.save(qb=client) except ValidationException as e: print(f"Cannot save customer: {e.message}") # Handle validation errors (e.g., show form errors to user) ``` -------------------------------- ### List Customers by Display Name Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Retrieve customers whose display names are within a provided list. This method allows for efficient selection based on a set of known names. ```python customer_names = ['Customer1', 'Customer2', 'Customer3'] customers = Customer.choose(customer_names, field="DisplayName", qb=client) ``` -------------------------------- ### List All Customers Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Retrieve all customer records using the Customer.all() method. The maximum number of entities returned per response is 1000, with a default of 100 if not specified. ```python from quickbooks.objects.customer import Customer customers = Customer.all(qb=client) ``` -------------------------------- ### List Customers with Custom WHERE and Paging Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Apply a custom WHERE clause for filtering and use paging parameters to retrieve results in batches. This is efficient for large result sets. ```python customers = Customer.where("CompanyName LIKE 'S%'", start_position=1, max_results=25, qb=client) ``` -------------------------------- ### QuickBooks Date Formatting Helpers Source: https://context7.com/routablehq/python-quickbooks/llms.txt Utilizes helper functions for formatting dates and datetimes into the specific formats required by QuickBooks API. This ensures correct data submission for date-sensitive fields. ```python from quickbooks.helpers import qb_date_format, qb_datetime_format, qb_datetime_utc_offset_format from datetime import date, datetime # Format date for QuickBooks (YYYY-MM-DD) invoice_date = date(2024, 7, 22) formatted_date = qb_date_format(invoice_date) print(formatted_date) # "2024-07-22" ``` ```python # Format datetime for QuickBooks (YYYY-MM-DDTHH:MM:SS) transaction_time = datetime(2024, 7, 22, 10, 35, 0) formatted_datetime = qb_datetime_format(transaction_time) print(formatted_datetime) # "2024-07-22T10:35:00" ``` ```python # Format datetime with UTC offset utc_offset = "-08:00" # Pacific Time formatted_with_offset = qb_datetime_utc_offset_format( datetime(2024, 7, 22, 10, 35, 0), utc_offset ) print(formatted_with_offset) # "2024-07-22T10:35:00-08:00" ``` ```python # Use in invoice from quickbooks.objects.invoice import Invoice invoice = Invoice() invoice.TxnDate = qb_date_format(date.today()) invoice.DueDate = qb_date_format(date(2024, 8, 22)) ``` -------------------------------- ### Attach Note to Customer Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Create an Attachable object to add a note to an existing customer record. The note is saved as metadata associated with the customer. ```python attachment = Attachable() attachable_ref = AttachableRef() attachable_ref.EntityRef = customer.to_ref() attachment.AttachableRef.append(attachable_ref) attachment.Note = 'This is a note' attachment.save(qb=client) ``` -------------------------------- ### Handle QuickBooks API Exceptions Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Catch `QuickbooksException` to access error messages, QBO error codes, and additional details returned from the API. ```python from quickbooks.exceptions import QuickbooksException try: # perform a Quickbooks operation except QuickbooksException as e: e.message # contains the error message returned from QBO e.error_code # contains the e.detail # contains additional information when available ``` -------------------------------- ### Convert Object to JSON Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Use the `to_json` method on a QuickBooks object to convert it into JSON data. ```python account = Account.get(1, qb=client) json_data = account.to_json() ``` -------------------------------- ### Implement Idempotent Requests with Python Quickbooks Source: https://context7.com/routablehq/python-quickbooks/llms.txt Ensures idempotent operations by using unique request IDs when creating or updating QuickBooks entities. This prevents duplicate records if requests are retried. Supports objects like Customer, Invoice, and Purchase. ```python import uuid from quickbooks.objects.customer import Customer from quickbooks.objects.invoice import Invoice # Generate unique request ID request_id = str(uuid.uuid4()) # Create customer with request ID (idempotent) customer = Customer() customer.DisplayName = "Unique Customer" customer.CompanyName = "Unique Corp" # If this request is retried, the same customer won't be created twice saved_customer = customer.save(qb=client, request_id=request_id) # Same for invoices invoice_request_id = str(uuid.uuid4()) invoice = Invoice() invoice.CustomerRef = saved_customer.to_ref() # ... add line items ... saved_invoice = invoice.save(qb=client, request_id=invoice_request_id) # Pass optional params with save from quickbooks.objects.purchase import Purchase purchase = Purchase() # ... set purchase details ... # Some objects support additional params purchase.save( qb=client, params={'include': 'allowduplicatedocnum'} ) ``` -------------------------------- ### Filter Customers by Criteria Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Fetch a filtered list of customers based on specified criteria such as 'Active' status or 'FamilyName'. Ensure user input is sanitized before passing to queries. ```python customers = Customer.filter(Active=True, FamilyName="Smith", qb=client) ``` -------------------------------- ### List Customers with Custom WHERE Clause Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Query customers using a custom WHERE clause for complex filtering. Do not include the 'WHERE' keyword itself in the clause string. ```python customers = Customer.where("Active = True AND CompanyName LIKE 'S%'", qb=client) ``` -------------------------------- ### Filter Customer List with Paged Custom Query Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Apply custom SQL queries with pagination to retrieve specific subsets of customer data. Use STARTPOSITION and MAXRESULTS to control the data range. ```python customers = Customer.query("SELECT * FROM Customer WHERE Active = True STARTPOSITION 1 MAXRESULTS 25", qb=client) ``` -------------------------------- ### Retrieve Financial Reports Source: https://context7.com/routablehq/python-quickbooks/llms.txt Access various financial reports like Profit and Loss using the get_report method. Reports can be customized with optional query parameters. ```python # Get Profit and Loss report profit_loss = client.get_report('ProfitAndLoss') print(profit_loss) ``` -------------------------------- ### Batch Update and Delete Operations Source: https://context7.com/routablehq/python-quickbooks/llms.txt Perform batch updates on multiple customer records and batch deletions on payments. Access results to check for successes and failures. ```python customers_to_update = Customer.filter(Active=True, qb=client) for customer in customers_to_update: customer.Notes = "Updated via batch operation" update_results = batch_update(customers_to_update, qb=client) print(f"Updated {len(update_results.successes)} customers") # Batch delete payments (only entities supporting delete) payments_to_delete = Payment.filter(TxnDate=date.today(), qb=client) delete_results = batch_delete(payments_to_delete, qb=client) # Check results print(f"Deleted: {len(delete_results.successes)}") print(f"Failed: {len(delete_results.faults)}") # Access batch response details for response in results.batch_responses: if response.Fault: print(f"Batch item {response.bId} failed") else: print(f"Batch item {response.bId} succeeded") ``` -------------------------------- ### Filter and Order Invoices by Date Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Retrieve invoices for a specific customer, ordered by transaction date. You can specify ascending (default) or descending order. ```python # Get customer invoices ordered by TxnDate invoices = Invoice.filter(CustomerRef='100', order_by='TxnDate', qb=client) # Same, but in reverse order invoices = Invoice.filter(CustomerRef='100', order_by='TxnDate DESC', qb=client) ``` -------------------------------- ### Convert Quickbooks Exception to Dictionary Source: https://context7.com/routablehq/python-quickbooks/llms.txt Handles Quickbooks API exceptions by converting them into a dictionary for easier inspection of error details. This is useful for debugging and logging API errors. ```python try: customer = Customer.get(99999, qb=client) except QuickbooksException as e: error_dict = dict(e) print(error_dict) # {'error_code': 610, 'detail': '...', 'message': '...'} ``` -------------------------------- ### Retrieve a Payment by ID Source: https://context7.com/routablehq/python-quickbooks/llms.txt Fetches a specific payment record using its unique identifier. ```python # Get payment by ID payment = Payment.get(789, qb=client) ``` -------------------------------- ### Add Sharable Link to Invoice Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Set AllowOnlineCreditCardPayment to True and BillEmail to an invalid email address to enable a sharable link for an invoice. Include 'invoiceLink' in the params when querying. ```python invoice.AllowOnlineCreditCardPayment = True invoice.BillEmail = EmailAddress() invoice.BillEmail.Address = 'test@email.com' ``` ```python invoice = Invoice.get(id, qb=self.qb_client, params={'include': 'invoiceLink'}) ``` -------------------------------- ### Retrieve an Invoice by ID Source: https://context7.com/routablehq/python-quickbooks/llms.txt Fetches a specific invoice using its unique ID. This method can also include additional details like a sharable link if the minorversion is set appropriately. ```python # Get invoice by ID invoice = Invoice.get(123, qb=client) # Get invoice with sharable link (requires minorversion >= 36) invoice = Invoice.get( 123, qb=client, params={'include': 'invoiceLink'} ) print(f"Invoice link: {invoice.InvoiceLink}") ``` -------------------------------- ### Query Multiple Entity Types with CDC Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Use Change Data Capture to query for changes across multiple entity types (e.g., Invoices and Customers) in a single request. ```python from quickbooks.objects import Invoice, Customer cdc_response = change_data_capture([Invoice, Customer], "2017-01-01T00:00:00", qb=client) ``` -------------------------------- ### Batch Update Customers Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Update multiple customer records simultaneously using a single API call. This method is efficient for bulk updates. ```python from quickbooks.batch import batch_update customers = Customer.filter(Active=True) # Update customer records results = batch_update(customers, qb=client) ``` -------------------------------- ### Review Batch Operation Results Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Process the results of a batch operation to identify successful updates and any failed operations with associated errors. ```python # successes is a list of objects that were successfully updated for obj in results.successes: print("Updated " + obj.DisplayName) # faults contains list of failed operations and associated errors for fault in results.faults: print("Operation failed on " + fault.original_object.DisplayName) for error in fault.Error: print("Error " + error.Message) ``` -------------------------------- ### Pass Optional Query Parameters on Save Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Include optional parameters in the API request's query string when saving an object. This allows for specific API behaviors, like including duplicated document numbers. ```python purchase.save(qb=self.qb_client, params={'include': 'allowduplicatedocnum'}) ``` -------------------------------- ### Send Invoice via Email Source: https://context7.com/routablehq/python-quickbooks/llms.txt Sends an invoice to the customer's registered email address or to a specified alternative email address. ```python # Send invoice via email invoice.send(qb=client) # Send to specific email address invoice.send(qb=client, send_to="alternative@email.com") ``` -------------------------------- ### Change Data Capture for Invoices Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Retrieve a list of Invoice objects that have changed since a specified timestamp. This is useful for synchronizing data. ```python from quickbooks.cdc import change_data_capture from quickbooks.objects import Invoice cdc_response = change_data_capture([Invoice], "2017-01-01T00:00:00", qb=client) for invoice in cdc_response.Invoice: # Do something with the invoice ``` -------------------------------- ### Filter Payments by Date Source: https://context7.com/routablehq/python-quickbooks/llms.txt Retrieves all payments made on a specific date. Requires importing the `date` object from the `datetime` module. ```python # Filter payments by date from datetime import date todays_payments = Payment.filter(TxnDate=date.today(), qb=client) ``` -------------------------------- ### Filter Invoices by Customer Source: https://context7.com/routablehq/python-quickbooks/llms.txt Retrieves a list of invoices associated with a specific customer, ordered by transaction date in descending order. Ensure 'CustomerRef' is the correct customer ID. ```python # Filter invoices by customer customer_invoices = Invoice.filter( CustomerRef='100', order_by='TxnDate DESC', qb=client ) ``` -------------------------------- ### Validate Webhook Signature with Python Quickbooks Source: https://context7.com/routablehq/python-quickbooks/llms.txt Validates incoming webhook payloads from QuickBooks to ensure authenticity. Initialize the QuickBooks client with a verifier token and use the `validate_webhook_signature` method in your webhook handler. ```python from quickbooks import QuickBooks # Initialize client with verifier token client = QuickBooks( auth_client=auth_client, refresh_token='REFRESH_TOKEN', company_id='COMPANY_ID', minorversion=75, verifier_token='YOUR_WEBHOOK_VERIFIER_TOKEN' ) # In your webhook endpoint handler def webhook_handler(request): request_body = request.body.decode('utf-8') signature = request.headers.get('intuit-signature') # Validate the webhook signature is_valid = client.validate_webhook_signature( request_body=request_body, signature=signature ) if is_valid: # Process the webhook payload import json payload = json.loads(request_body) for event in payload.get('eventNotifications', []): realm_id = event['realmId'] for entity in event['dataChangeEvent']['entities']: entity_name = entity['name'] entity_id = entity['id'] operation = entity['operation'] print(f"{operation}: {entity_name} {entity_id}") return {"status": "success"} else: return {"status": "invalid signature"}, 401 # You can also pass verifier token directly is_valid = client.validate_webhook_signature( request_body=request_body, signature=signature, verifier_token='ALTERNATIVE_VERIFIER_TOKEN' ) ``` -------------------------------- ### Change Data Capture with Datetime Object Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Pass a Python datetime object directly to the change_data_capture function; it will be automatically converted to the required string format. ```python from datetime import datetime cdc_response = change_data_capture([Invoice, Customer], datetime(2017, 1, 1, 0, 0, 0), qb=client) ``` -------------------------------- ### Delete an Invoice Source: https://context7.com/routablehq/python-quickbooks/llms.txt Deletes an invoice from the system. First, retrieve the invoice using its ID, then call the delete method. ```python # Delete an invoice invoice = Invoice.get(456, qb=client) invoice.delete(qb=client) ``` -------------------------------- ### Delete a Payment Source: https://context7.com/routablehq/python-quickbooks/llms.txt Deletes a payment record from the system. First, retrieve the payment by its ID, then call the delete method. ```python # Delete a payment payment = Payment.get(456, qb=client) payment.delete(qb=client) ``` -------------------------------- ### Change Data Capture (CDC) with Different Date Formats Source: https://context7.com/routablehq/python-quickbooks/llms.txt Retrieve objects that have changed since a specified timestamp using Change Data Capture. Supports both string and datetime object formats for the timestamp. ```python from quickbooks.cdc import change_data_capture from quickbooks.objects.invoice import Invoice from quickbooks.objects.customer import Customer from quickbooks.objects.payment import Payment from datetime import datetime, timedelta # Get changes since a specific date (string format) cdc_response = change_data_capture( [Invoice], "2024-01-01T00:00:00", qb=client ) # Process changed invoices for invoice in cdc_response.Invoice: print(f"Invoice {invoice.DocNumber} changed: ${invoice.TotalAmt}") # Query multiple entity types at once cdc_response = change_data_capture( [Invoice, Customer, Payment], "2024-01-01T00:00:00", qb=client ) # Process each entity type if hasattr(cdc_response, 'Invoice'): for invoice in cdc_response.Invoice: print(f"Changed Invoice: {invoice.Id}") if hasattr(cdc_response, 'Customer'): for customer in cdc_response.Customer: print(f"Changed Customer: {customer.DisplayName}") if hasattr(cdc_response, 'Payment'): for payment in cdc_response.Payment: print(f"Changed Payment: ${payment.TotalAmt}") # Use datetime object (automatically converted) yesterday = datetime.now() - timedelta(days=1) cdc_response = change_data_capture( [Invoice, Customer], yesterday, qb=client ) # Track changes for synchronization last_sync = datetime(2024, 1, 15, 0, 0, 0) changes = change_data_capture([Invoice, Customer, Payment], last_sync, qb=client) # Update your local database with changes for invoice in changes.Invoice: print(f"Sync invoice {invoice.Id}: {invoice.TotalAmt}") ``` -------------------------------- ### Void an Invoice Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Call the `void` method on an invoice object after setting its `Id`. ```python invoice = Invoice() invoice.Id = 7 invoice.void(qb=client) ``` -------------------------------- ### Convert Invoice to Linked Transaction Source: https://context7.com/routablehq/python-quickbooks/llms.txt Converts an invoice object into a linked transaction format, typically used when applying payments. ```python # Convert invoice to linked transaction for payments linked_txn = invoice.to_linked_txn() ``` -------------------------------- ### Batch Delete Payments Source: https://github.com/routablehq/python-quickbooks/blob/main/README.md Delete multiple payment records in a single request. Only entities that support deletion can be used with batch delete. ```python from quickbooks.batch import batch_delete payments = Payment.filter(TxnDate=date.today()) results = batch_delete(payments, qb=client) ``` -------------------------------- ### Void a Payment Source: https://context7.com/routablehq/python-quickbooks/llms.txt Voids a previously recorded payment. This operation marks the payment as voided in the system. ```python # Void a payment payment = Payment.get(789, qb=client) payment.void(qb=client) ``` -------------------------------- ### Void an Invoice Source: https://context7.com/routablehq/python-quickbooks/llms.txt Voids a specific invoice. This operation requires the current SyncToken of the invoice to be provided. ```python # Void an invoice invoice_to_void = Invoice() invoice_to_void.Id = 123 invoice_to_void.SyncToken = 0 # Must have current SyncToken invoice_to_void.void(qb=client) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.