Exemple #1
0
        public static Account CreatePracticeAccount(string accountName, double initialBalance, User grantTo)
        {
            var accountingApi           = new AccountingApi();
            var templateAccount         = accountingApi.GetAllAccounts().First();
            var usersApi                = new UsersApi();
            var openDemoAccountResponse = usersApi.OpenDemoAccount(new OpenDemoAccount(templateAccount.Id, accountName, initialBalance));

            Console.WriteLine(openDemoAccountResponse);
            if (openDemoAccountResponse.AccountId != null)
            {
                var practiceAccount = accountingApi.GetAccount(openDemoAccountResponse.AccountId);
                Console.WriteLine(practiceAccount);
                var tradingPermissionResponse = usersApi.RequestTradingPermission(new RequestTradingPermission(AccountId: practiceAccount.Id,
                                                                                                               CtaContact: "John Uppee",
                                                                                                               CtaEmail: grantTo.Email));
                Console.WriteLine(tradingPermissionResponse);
                if (tradingPermissionResponse.ErrorText != null)
                {
                    throw new Exception($"Failed granting trading permissions: {tradingPermissionResponse.ErrorText}");
                }
                return(practiceAccount);
            }
            else
            {
                return(null);
            }
        }
Exemple #2
0
        // GET: /InvoiceSync/
        public async Task <ActionResult> Index()
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig.Value, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var AccountingApi = new AccountingApi();


            var sevenDaysAgo   = DateTime.Now.AddDays(-7).ToString("yyyy, MM, dd");
            var invoicesFilter = "Date >= DateTime(" + sevenDaysAgo + ")";

            var response = await AccountingApi.GetInvoicesAsync(accessToken, xeroTenantId, null, invoicesFilter);

            var invoices = response._Invoices;

            return(View(invoices));
        }
Exemple #3
0
        public async Task <ActionResult> Create(string Name, string EmailAddress)
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig.Value, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var contact = new Contact();

            contact.Name         = Name;
            contact.EmailAddress = EmailAddress;
            var contacts = new Contacts();

            contacts._Contacts = new List <Contact>()
            {
                contact
            };

            var AccountingApi = new AccountingApi();
            var response      = await AccountingApi.CreateContactsAsync(accessToken, xeroTenantId, contacts);

            return(RedirectToAction("Index", "ContactsInfo"));
        }
Exemple #4
0
        public async Task <Invoices> GetAccounts()
        {
            var accountingApi = new AccountingApi();
            var response      = await accountingApi.GetInvoicesAsync(_xeroToken.AccessToken, _xeroToken.Tenants[0].TenantId.ToString());

            return(response);
        }
        // GET: /Organisation/
        public async Task <ActionResult> Index()
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig.Value, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var AccountingApi = new AccountingApi();
            var response      = await AccountingApi.GetOrganisationsAsync(accessToken, xeroTenantId);

            var organisation_info = new Organisation();

            organisation_info = response._Organisations[0];

            return(View(organisation_info));
        }
Exemple #6
0
 public ConfigurationTests(ITestOutputHelper output, ApplicationBaseFixture app)
 {
     _output        = output;
     _app           = app;
     _access        = _app.ServiceProvider.GetService <TenantAccess>();
     _accountingApi = new AccountingApi();
 }
Exemple #7
0
        // GET: ContactsInfo
        public async Task <ActionResult> Index()
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            var serviceProvider   = new ServiceCollection().AddHttpClient().BuildServiceProvider();
            var httpClientFactory = serviceProvider.GetService <IHttpClientFactory>();

            XeroConfiguration XeroConfig = new XeroConfiguration
            {
                ClientId     = ConfigurationManager.AppSettings["XeroClientId"],
                ClientSecret = ConfigurationManager.AppSettings["XeroClientSecret"],
                CallbackUri  = new Uri(ConfigurationManager.AppSettings["XeroCallbackUri"]),
                Scope        = ConfigurationManager.AppSettings["XeroScope"],
                State        = ConfigurationManager.AppSettings["XeroState"]
            };

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var AccountingApi = new AccountingApi();
            var response      = await AccountingApi.GetContactsAsync(accessToken, xeroTenantId);

            var contacts = response._Contacts;

            return(View(contacts));
        }
Exemple #8
0
 public WebhookTests(ITestOutputHelper output, ApplicationBaseFixture app)
 {
     _output            = output;
     _app               = app;
     _access            = _app.ServiceProvider.GetService <TenantAccess>();
     _accountingApi     = new AccountingApi();
     _storageRepository = _app.ServiceProvider.GetService <StorageRepository>();
 }
Exemple #9
0
        public static void PrepopulateCache()
        {
            // Cache pre-populating can save some latency at trading time
            Log.Write("PRE-POPULATING ACCOUNT INFO");
            var apiInstance = new AccountingApi();

            apiInstance.GetAllTradingPermissions();
        }
Exemple #10
0
        public async Task <ActionResult> Create(string Name, string LineDescription, string LineQuantity, string LineUnitAmount, string LineAccountCode)
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig.Value, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var contact = new Contact();

            contact.Name = Name;

            var line = new LineItem()
            {
                Description = LineDescription,
                Quantity    = decimal.Parse(LineQuantity),
                UnitAmount  = decimal.Parse(LineUnitAmount),
                AccountCode = LineAccountCode
            };

            var lines = new List <LineItem>()
            {
                line
            };

            var invoice = new Invoice()
            {
                Type      = Invoice.TypeEnum.ACCREC,
                Contact   = contact,
                Date      = DateTime.Today,
                DueDate   = DateTime.Today.AddDays(30),
                LineItems = lines
            };

            var invoiceList = new List <Invoice>();

            invoiceList.Add(invoice);

            var invoices = new Invoices();

            invoices._Invoices = invoiceList;

            var AccountingApi = new AccountingApi();
            var response      = await AccountingApi.CreateInvoicesAsync(accessToken, xeroTenantId, invoices);

            var updatedUTC = response._Invoices[0].UpdatedDateUTC;

            return(RedirectToAction("Index", "InvoiceSync"));
        }
        public async Task <IActionResult> GetInvoices()
        {
            var accountingApi = new AccountingApi();
            var accessToken   = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", string.Empty);
            var tenantId      = await GetTenantId(accessToken);

            var response = await accountingApi.GetInvoicesAsync(accessToken, tenantId);

            return(Ok(response));
        }
Exemple #12
0
        public static Account GetAccount(int myUserId)
        {
            var apiInstance = new AccountingApi();
            var result      = apiInstance.GetAllAccounts();

            Log.Write($"Accounts: {result.Count}");
            var account = result.First(x => x.Active == true && (myUserId == 0 || x.UserId == myUserId));

            Log.Write($"Account: {account}");
            return(account);
        }
Exemple #13
0
 public WebhookServices(ISignatureVerifier signatureVerifier
                        , PayloadTable storeTable, ITokenStore tokenStore, TenantAccess tenantAccess
                        , AccountingApi accountingApi)
 {
     //_client = httpClient;
     _signatureVerifier = signatureVerifier;
     _storeTable        = storeTable;
     _tokenStore        = tokenStore;
     _accountingApi     = accountingApi;
     _tenantAccess      = tenantAccess;
 }
Exemple #14
0
        public async Task <ActionResult> Create(string Name, string EmailAddress)
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            var serviceProvider   = new ServiceCollection().AddHttpClient().BuildServiceProvider();
            var httpClientFactory = serviceProvider.GetService <IHttpClientFactory>();

            XeroConfiguration XeroConfig = new XeroConfiguration
            {
                ClientId     = ConfigurationManager.AppSettings["XeroClientId"],
                ClientSecret = ConfigurationManager.AppSettings["XeroClientSecret"],
                CallbackUri  = new Uri(ConfigurationManager.AppSettings["XeroCallbackUri"]),
                Scope        = ConfigurationManager.AppSettings["XeroScope"],
                State        = ConfigurationManager.AppSettings["XeroState"]
            };

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig, httpClientFactory);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var contact = new Contact
            {
                Name         = Name,
                EmailAddress = EmailAddress
            };

            var contacts = new Contacts();

            contacts._Contacts = new List <Contact>()
            {
                contact
            };

            var AccountingApi = new AccountingApi();
            var response      = await AccountingApi.CreateContactsAsync(accessToken, xeroTenantId, contacts);

            return(RedirectToAction("Index", "ContactsInfo"));
        }
Exemple #15
0
        public static void ShowAccountActivities(Account account)
        {
            Log.Write($"ShowAccountActivities for {account.Name} account");
            var accountingApi = new AccountingApi();

            foreach (var cashBalance in accountingApi.GetOwnedCashBalances(account.Id))
            {
                Log.Write(cashBalance);
            }
            var marginSnapshot = accountingApi.GetMarginSnapshot(account.Id);

            Log.Write(marginSnapshot);
            var balanceSnapshot = accountingApi.GetCashBalanceSnapshot(new GetCashBalanceSnapshot(account.Id));

            Log.Write(balanceSnapshot);
            var ordersApi = new OrdersApi();
            var orders    = ordersApi.GetOwnedOrders(account.Id);

            foreach (var order in orders)
            {
                Log.Write(order);
            }
            var accountOrders = orders.ToDictionary(x => x.Id);
            var fills         = ordersApi.GetAllFills().Where(fill => accountOrders.ContainsKey(fill.OrderId));

            foreach (var fill in fills)
            {
                Log.Write(fill);
            }
            var positionsApi = new PositionsApi();

            foreach (var position in positionsApi.GetOwnedPositions(account.Id))
            {
                Log.Write(position);
            }
        }
Exemple #16
0
        // GET: /InvoicePdf/
        public async Task <ActionResult> Index()
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig.Value);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            Guid invoiceId = Guid.Parse("d5654fc7-be8e-42e5-802a-9f5ab9d2476a");

            var AccountingApi = new AccountingApi();

            var response = await AccountingApi.GetInvoiceAsPdfAsync(accessToken, xeroTenantId, invoiceId);

            return(new FileStreamResult(response, "application/pdf"));
        }
Exemple #17
0
        // GET: /InvoiceSync/
        public async Task <ActionResult> Index()
        {
            var xeroToken  = TokenUtilities.GetStoredToken();
            var utcTimeNow = DateTime.UtcNow;

            if (utcTimeNow > xeroToken.ExpiresAtUtc)
            {
                var client = new XeroClient(XeroConfig.Value);
                xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);

                TokenUtilities.StoreToken(xeroToken);
            }

            string accessToken  = xeroToken.AccessToken;
            string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();

            var AccountingApi = new AccountingApi();

            var response = await AccountingApi.GetInvoicesAsync(accessToken, xeroTenantId);

            var invoices = response._Invoices;

            return(Json(invoices));
        }
 public ApplicantsControl(AccountingApi api, ITextPicker textPicker) : this()
 {
     this.api        = api;
     this.textPicker = textPicker;
 }
Exemple #19
0
 public void Init()
 {
     instance = new AccountingApi();
 }
Exemple #20
0
 public void Init()
 {
     instance = new AccountingApi(new TestConfig());
 }
Exemple #21
0
        public static async void ShowOrderDetails(Order order)
        {
            Log.Write($"SHOW ORDER DETAILS FOR {order.Id}");
            var ordersApi      = new OrdersApi();
            var orderCommands  = ordersApi.GetOwnedCommands(order.Id);
            var currentCommand = orderCommands.LastOrDefault(command => command.CommandType == Command.CommandTypeEnum.New || command.CommandType == Command.CommandTypeEnum.Modify && (command.CommandStatus == Command.CommandStatusEnum.AtExecution || command.CommandStatus == Command.CommandStatusEnum.OnHold || command.CommandStatus == Command.CommandStatusEnum.ExecutionSuspended));

            if (currentCommand != null)
            {
                var currentOrderVersion = ordersApi.GetOrderVersion(currentCommand.Id);
                var fills            = ordersApi.GetOwnedFills(order.Id);
                var commandIds       = orderCommands.Select(command => command.Id).ToList();
                var executionReports = ordersApi.GetOwnedExecutionReportsBatch(commandIds);
                var commandReports   = ordersApi.GetOwnedCommandReportsBatch(commandIds);

                var contractLibraryApi = new ContractLibraryApi();
                var contract           = await contractLibraryApi.GetContractAsync(order.ContractId);

                var contractMaturity = await contractLibraryApi.GetContractMaturityAsync(contract.ContractMaturityId);

                var product = await contractLibraryApi.GetProductAsync(contractMaturity.ProductId);

                var lines = orderCommands.Select(command => new
                {
                    Id        = command.Id,
                    Timestamp = command.Timestamp,
                    Text      = GetCommandDescription(order, contract, command)
                })
                            .Concat(
                    fills.Select(fill => new
                {
                    Id        = fill.Id,
                    Timestamp = fill.Timestamp,
                    Text      = GetFillDescription(fill)
                }))
                            .Concat(
                    commandReports.Select(commandReport => new
                {
                    Id        = commandReport.Id,
                    Timestamp = commandReport.Timestamp,
                    Text      = GetCommandReportDescription(commandReport)
                }))
                            .Concat(
                    executionReports.Select(executionReport => new
                {
                    Id        = executionReport.Id,
                    Timestamp = executionReport.Timestamp,
                    Text      = GetExecutionReportDescription(executionReport)
                }));

                string orderStatus;

                switch (order.OrdStatus)
                {
                case Order.OrdStatusEnum.Working:
                    var totalFilled = fills.Where(fill => fill.Active == true).Sum(fill => fill.Qty);
                    if (totalFilled > 0)
                    {
                        orderStatus = "Partially Filled";
                    }
                    else
                    {
                        orderStatus = order.OrdStatus.ToString();
                    }
                    break;

                default:
                    orderStatus = order.OrdStatus.ToString();
                    break;
                }

                string accountHolderEmail;
                var    accountingApi = new AccountingApi();
                var    account       = await accountingApi.GetAccountAsync(order.AccountId);

                try
                {
                    // CTA should look through trading permissions
                    var allTradingPermissions = await accountingApi.GetAllTradingPermissionsAsync();

                    var tradingPermission = allTradingPermissions.First(x => x.AccountId == account.Id && x.Status == TradingPermission.StatusEnum.Approved);
                    accountHolderEmail = tradingPermission.AccountHolderEmail;
                }
                catch
                {
                    // Organization Admin or actual owner of the account has access to User entity
                    var userApi = new UsersApi();
                    var user    = await userApi.GetUserAsync(account.UserId);

                    accountHolderEmail = user.Email;
                }

                Log.Write($"Order #{order.Id} {GetOrderVersionDescription(order, contract, currentOrderVersion)} - {orderStatus}, Acc: #{account.Name}, Email: #{accountHolderEmail}");
                foreach (var line in lines.OrderBy(x => x.Id).ThenBy(x => x.Timestamp))
                {
                    Console.WriteLine($"{line.Timestamp} #{line.Id}: {line.Text}");
                }
                Console.WriteLine();
            }
        }
        public void Run(string name)
        {
            try
            {
                Console.WriteLine(name + ": Starting ");
                var clientId = _config["ClientId"];

                XeroClient client = null;
                IXeroToken token  = null;
                lock (_lockObj)
                {
                    client = new XeroClient(new XeroConfiguration {
                        ClientId = clientId
                    });

                    if (System.IO.File.Exists("Token.json"))
                    {
                        var savedJson = System.IO.File.ReadAllText("Token.json");
                        token = JsonConvert.DeserializeObject <XeroOAuth2Token>(savedJson);
                    }

                    if (token == null)
                    {
                        token = new XeroOAuth2Token {
                            RefreshToken = _config["RefreshToken"]
                        }
                    }
                    ;

                    IXeroToken newToken = Task.Run(() => client.RefreshAccessTokenAsync(token)).GetAwaiter().GetResult();
                    if (newToken != null)
                    {
                        token = newToken;
                    }

                    var json = JsonConvert.SerializeObject(token, Formatting.Indented);
                    System.IO.File.WriteAllText("Token.json", json);
                }

                Console.WriteLine(name + ": Token refreshed");
                var accessToken = token.AccessToken;

                var tenant = "";
                try
                {
                    var conRes = Task.Run(() => client.GetConnectionsAsync(token)).GetAwaiter().GetResult();
                    tenant = conRes[0].TenantId.ToString();
                    Console.WriteLine(name + ": Tenants");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    SerializeException(e);
                    return;
                }

                var api = new AccountingApi {
                    ExceptionFactory = CustomExceptionFactory
                };

                Console.WriteLine(name + ": New token process");

                var response     = Task.Run(() => api.GetInvoicesAsyncWithHttpInfo(accessToken, tenant)).GetAwaiter().GetResult();
                var respInvoices = Task.Run(() => api.GetInvoicesAsyncWithHttpInfo(accessToken, tenant, page: 1, where : "")).GetAwaiter().GetResult();
                var invDate      = respInvoices.Data._Invoices[0].Date;

                var recurring = Task.Run(() => api.GetRepeatingInvoicesAsyncWithHttpInfo(accessToken, tenant)).GetAwaiter().GetResult();
                var status    = recurring.Data._RepeatingInvoices[0].Status;
                var schedule  = recurring.Data._RepeatingInvoices[0].Schedule;

                Console.WriteLine(name + ": Complete");
            }
            catch (CustomApiException ce)
            {
                Console.WriteLine(name + ": Failed: " + ce.Message);
                SerializeException(ce);
                Console.WriteLine(ce);
                var limits = new XeroLimits(ce.Headers);
            }
            catch (Exception e)
            {
                Console.WriteLine(name + ": Failed: " + e.Message);
                SerializeException(e);
            }
        }