def get(self, request, format=None): """ Return a list of all users. """ try: print("TRY LIST ITEMS") xero_items = cache.get("xero_items") if request.query_params.get("force", "false") == "true": xero_items = None if xero_items is None: print("XERO connectToXero") xero = connectToXero() xero_items = xero.items.all() print("XERO xero_items") for item in xero_items: item['codeName'] = "%s %s" % ( item['Code'], item.get('Name', item.get("Description", ""))) cache.set("xero_items", xero_items, 60) # cache for 1 minute return Response(xero_items) except Exception as e: print("An exception occurred while retreiving data from Xero:") print(e)
def get(self, request, format=None): """ Return a list of all users. """ xero = connectToXero() #TODO Cache this return Response(xero.contacts.all())
def get_contacts_choices(): xero = connectToXero() try: # noinspection PyUnresolvedReferences supplier_list = xero.contacts.all() result = [(item["ContactID"], item["Name"]) for item in supplier_list] result += [("", "--Create New--")] except AttributeError: return [] return result
def handle(self, *args, **options): xero = connectToXero() xero_items = xero.items.all() codes = [ "%s %s" % (item['Code'], item.get('Name', item.get("Description", ""))) for item in xero_items ] for item in codes: print(item)
def get(self, request, format=None, id=None): xero = connectToXero() entity = XeroEntity.objects.get(pk=id) # noinspection PyUnresolvedReferences invoice = xero.purchaseorders.get( entity.xero_id, headers={'Accept': 'application/pdf'}) response = HttpResponse(invoice, content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="Purchase_Order_%s.pdf"' % entity.xero_code return response
def downloadItem(itemName, idName, textName): xero = connectToXero() manager = getattr(xero, itemName) for item in manager.all(): entity = XeroEntity() entity.xero_type = itemName entity.xero_id = item.get(idName) entity.xero_text = item.get(textName) entity.xero_data = XeroCleanJSON(item) entity.save()
def get_customer_choices(): xero = connectToXero() try: # noinspection PyUnresolvedReferences supplier_list = xero.contacts.filter(IsCustomer=True) result = sorted([(item["ContactID"], item["Name"]) for item in supplier_list], key=lambda it: it[1]) result += [("", "--Create New Customer--")] except AttributeError: return [] return result
def createContactForSubbie(subbie: Subbie) -> Subbie: contact = { "ContactStatus": "ACTIVE", "Name": subbie.name, "IsCustomer": False, # IsCustomer and IsSupplier is ignored but atleast we show intention "IsSupplier": True, "DefaultCurrency": "AUD" } if checkCanCreate(): xero = connectToXero() newContact = xero.contacts.put(contact) print(newContact) subbie.xero_supplier = newContact[0].get("ContactID") subbie.save() return subbie else: return None
def createContactForClient(client: Client) -> Client: contact = { "ContactStatus": "ACTIVE", "Name": client.name, "IsCustomer": True, # IsCustomer and IsSupplier is ignored but atleast we show intention "IsSupplier": False, "DefaultCurrency": "AUD" } if checkCanCreate(): xero = connectToXero() newContact = xero.contacts.put(contact) print(newContact) client.xero_customer = newContact[0].get("ContactID") client.save() return client else: return None
def createJobPurchaseOrder(job: Job) -> XeroEntity: if not job.sub_contractor.xero_supplier: subbie = createContactForSubbie(job.sub_contractor) else: subbie = job.sub_contractor today = datetime.date.today() lineItems = [{ 'AccountCode': global_preferences[ 'XeroPurchaseOrders__AccountCode'], # SubContractors account 'Description': job.description, 'TaxType': 'INPUT', 'Quantity': job.sqm, 'UnitAmount': subbie.rate_per_m, }] reference = job.address + "\n" + job.suburb purchaseOrder = { 'Telephone': '61 5261 8397', 'CurrencyCode': 'AUD', 'AttentionTo': 'Luke Cormack ', 'LineAmountTypes': 'Exclusive', 'Date': today, 'DeliveryInstructions': job.description, 'DeliveryDate': job.pour_date, 'LineItems': lineItems, 'Status': global_preferences['XeroInvoices__status'], # "AUTHORISED" 'IsDiscounted': False, 'HasAttachments': False, 'DeliveryAddress': '9 Boneyards Ave\nTorquay\nVIC\n3228\nAustralia', 'CurrencyRate': 1.0, 'Reference': reference, 'Contact': { "ContactID": subbie.xero_supplier } } if global_preferences["XeroPurchaseOrders__branding_theme_id"] != "NONE": purchaseOrder['BrandingThemeID'] = global_preferences[ "XeroPurchaseOrders__branding_theme_id"] if checkCanCreate(): xero = connectToXero() result = xero.purchaseorders.put(purchaseOrder) print(result) xeroPurchaseOrder = XeroEntity() xeroPurchaseOrder.other_id = job.id xeroPurchaseOrder.other_name = "job" xeroPurchaseOrder.xero_type = "PurchaseOrder" xeroPurchaseOrder.xero_id = result[0].get("PurchaseOrderID") xeroPurchaseOrder.xero_code = result[0].get("PurchaseOrderNumber") xeroPurchaseOrder.xero_text = result[0].get("Reference") xeroPurchaseOrder.total = result[0].get("Total") xeroPurchaseOrder.xero_data = json.loads( json.dumps(result[0], cls=DjangoJSONEncoder) ) # Clean Convert Date/Times etc to Strings xeroPurchaseOrder.save() job.xero_purchase_order = xeroPurchaseOrder job.save() return xeroPurchaseOrder else: return None
def createRepairInvoice(repair: Repair) -> XeroEntity: """ Create an Invoice from a Job in Xero. :param job: The Job To create the invoice for. :return: The XeroInvoice entity we created """ job = repair.job if not job.client.xero_customer: client = createContactForClient(job.client) else: client = job.client lineItems = [] repair_cost_to_save = [] for repair_cost in repair.repair_costs.all(): if not repair_cost.invoiced: lineItems.append({ "ItemCode": repair_cost.xero_item_code, "Description": repair_cost.details, "Quantity": repair_cost.quantity, "UnitAmount": repair_cost.unit_price, "TaxType": "OUTPUT", "AccountCode": global_preferences['XeroInvoices__sale_account_code'] }) repair_cost.invoiced = True repair_cost_to_save.append(repair_cost) today = datetime.date.today() due = today + timedelta(days=global_preferences['XeroInvoices__due_days'] ) # TODO Change to configurable value.. purchaseOrderNumbers = repair.po_number # IS THIS THE SAME LOGIC?? ", ".join([po.number for po in job.purchase_orders.all()]) invoice_ref = purchaseOrderNumbers + " " + job.address + " " + job.suburb #TODO No State + Postcode?? invoice = { "Type": "ACCREC", "CurrencyCode": "AUD", "Contact": { "ContactID": client.xero_customer }, "Date": today, "DueDate": due, "LineAmountTypes": "Exclusive", 'Reference': invoice_ref, "LineItems": lineItems, "CurrencyRate": 1.0, "Status": global_preferences['XeroInvoices__status'], # "AUTHORISED" "SentToContact": False, # we Sent it TODO: Change to True when we send it. "IsDiscounted": False, "CISDeduction": 0.0, # Assume we don't use this in AU } if global_preferences["XeroInvoices__branding_theme_id"] != "NONE": invoice['BrandingThemeID'] = global_preferences[ "XeroInvoices__branding_theme_id"] if checkCanCreate(): xero = connectToXero() result = xero.invoices.put(invoice) print(result) xeroInvoice = XeroEntity() xeroInvoice.other_id = repair.id xeroInvoice.other_name = "repair" xeroInvoice.xero_type = "Invoice" xeroInvoice.xero_text = result[0].get("Reference") xeroInvoice.xero_id = result[0].get("InvoiceID") xeroInvoice.xero_code = result[0].get("InvoiceNumber") xeroInvoice.total = result[0].get("Total") xeroInvoice.xero_data = json.loads( json.dumps(result[0], cls=DjangoJSONEncoder) ) # Clean Convert Date/Times etc to Strings xeroInvoice.save() for repair_cost in repair_cost_to_save: repair_cost.save() return xeroInvoice else: return None