Esempio n. 1
0
        private JsonResult GetDirect(int Height, int startHeight, int chainHeight)
        {
            List <int> blockHeights = new List <int>();

            for (var x = startHeight; x < chainHeight; x++)
            {
                blockHeights.Add(x);
            }
            //fetch the transactions directly from the Blockchain
            var args = new Dictionary <string, object>();

            args.Add("blockHeights", blockHeights);
            var             blocks       = RpcHelper.Request <BlockResp>("get_blocks_details_by_heights", args).blocks;
            List <CachedTx> transactions = new List <CachedTx>();

            foreach (var block in blocks)
            {
                foreach (var transaction in block.transactions)
                {
                    var cachedTx = TransactionHelpers.MapTx(transaction);
                    //persist tx's to cache
                    if (cachedTx != null)
                    {
                        transactions.Add(cachedTx);
                    }
                }
            }
            return(new JsonResult(JsonConvert.SerializeObject(transactions)));
        }
Esempio n. 2
0
 public void OneTimeSetUp()
 {
     _network            = CirrusNetwork.NetworksSelector.Testnet();
     _transactionHelpers = new TransactionHelpers(_network);
     ValidAddress        = "tNuiVJiEhvbQgXu4P32S4TnAVEG3kgLnu8";
     InvalidAddress      = "CWNYqR11FFsbt14FVtmV1X3rPntoxGtYrR";
 }
        public async Task TestDomainEventsAreRegistered()
        {
            //Arrange
            var aggregate = ServiceLocator.Current.GetInstance <EventAggregate>();
            var module    = ServiceLocator.Current.GetInstance <IExtractEventMetadataService>();
            var command   = await module.ExtractEventMetadata(new DateTime(2015, 7, 14));

            using (var scope = TransactionHelpers.GetTransactionScope())
            {
                //Act
                aggregate.ImportEvent(command);

                var successEvent = aggregate.DomainEvents.FirstOrDefault();

                //Assert
                Assert.IsNotNull(successEvent);
                Assert.IsTrue(successEvent is EventImported);

                var importedEvent = successEvent as EventImported;
                Assert.AreEqual(26, importedEvent.DealIds.Count());
                Assert.AreEqual(26, importedEvent.PairIds.Count());

                scope.Dispose();
            }
        }
Esempio n. 4
0
    public static async IAsyncEnumerable <ChangeAvoidanceSuggestionViewModel> GenerateSuggestionsAsync(
        TransactionInfo transactionInfo, BitcoinAddress destination, Wallet wallet, [EnumeratorCancellation] CancellationToken cancellationToken)
    {
        Task <ChangeAvoidanceSuggestionViewModel?> bnbSuggestionTask = Task.Run(() =>
        {
            if (ChangelessTransactionCoinSelector.TryGetCoins(transactionInfo.Coins, transactionInfo.FeeRate, new TxOut(transactionInfo.Amount, destination), out IEnumerable <SmartCoin>?selection, cancellationToken))
            {
                BuildTransactionResult transaction = TransactionHelpers.BuildChangelessTransaction(
                    wallet,
                    destination,
                    transactionInfo.UserLabels,
                    transactionInfo.FeeRate,
                    selection,
                    tryToSign: false);

                return(new ChangeAvoidanceSuggestionViewModel(
                           transactionInfo.Amount.ToDecimal(MoneyUnit.BTC),
                           transaction,
                           wallet.Synchronizer.UsdExchangeRate,
                           isOriginal: false));
            }

            return(null);
        });

        ChangeAvoidanceSuggestionViewModel?bnbSuggestion = await bnbSuggestionTask;

        if (bnbSuggestion is not null)
        {
            yield return(bnbSuggestion);
        }
    }
        public ActionResult Create(int?Id)
        {
            // Household Id
            if (Id is null)
            {
                TempData.Add("Message", "Improper Id");
                TempData.Add("MessageColour", "danger");
                return(RedirectToAction("Index", "Household"));
            }

            var viewModel = new CreateTransactionViewModel()
            {
                HouseholdId = (int)Id,
                Date        = DateTime.Now
            };

            TransactionHelpers.SetDropDownLists(viewModel, Request);

            if (TransactionHelpers.BankAccntOrCategoriesIsNull(viewModel, TempData))
            {
                return(RedirectToAction("Index", "Household"));
            }

            return(View(viewModel));
        }
    public static async IAsyncEnumerable <ChangeAvoidanceSuggestionViewModel> GenerateSuggestionsAsync(
        TransactionInfo transactionInfo,
        BitcoinAddress destination,
        Wallet wallet,
        [EnumeratorCancellation] CancellationToken cancellationToken)
    {
        var selections = ChangelessTransactionCoinSelector.GetAllStrategyResultsAsync(
            transactionInfo.Coins,
            transactionInfo.FeeRate,
            new TxOut(transactionInfo.Amount, destination),
            cancellationToken).ConfigureAwait(false);

        await foreach (var selection in selections)
        {
            if (selection.Any())
            {
                BuildTransactionResult transaction = TransactionHelpers.BuildChangelessTransaction(
                    wallet,
                    destination,
                    transactionInfo.UserLabels,
                    transactionInfo.FeeRate,
                    selection,
                    tryToSign: false);

                yield return(new ChangeAvoidanceSuggestionViewModel(
                                 transactionInfo.Amount.ToDecimal(MoneyUnit.BTC),
                                 transaction,
                                 wallet.Synchronizer.UsdExchangeRate));
            }
        }
    }
Esempio n. 7
0
        public JsonResult Index()
        {
            var rawTxs   = RpcHelper.RequestJson <TxPoolResp>("f_on_transactions_pool_json", new Dictionary <string, object>()).result.transactions;
            var txHashes = new List <string>();

            foreach (var rawTx in rawTxs)
            {
                txHashes.Add(rawTx.hash);
            }
            var tx_args = new Dictionary <string, object>();

            tx_args.Add("transactionHashes", txHashes.ToArray());
            var txs = RpcHelper.Request <TxDetailResp>("get_transaction_details_by_hashes", tx_args);

            List <CachedTx> transactions = new List <CachedTx>();

            if (txs != null)
            {
                foreach (var rawTx in txs.transactions)
                {
                    var memPoolTx = TransactionHelpers.MapTx(rawTx);
                    memPoolTx.height = 0;
                    transactions.Add(memPoolTx);
                }
            }
            return(new JsonResult(JsonConvert.SerializeObject(transactions)));
        }
Esempio n. 8
0
        private List <JournalEntryLine> GetGlEntries(FinancialBatch financialBatch, ref string debugLava, string DescriptionLava = "")
        {
            if (string.IsNullOrWhiteSpace(DescriptionLava))
            {
                DescriptionLava = "{{ Batch.Id }}: {{ Batch.Name }}";
            }

            var rockContext = new RockContext();

            //
            // Group/Sum Transactions by Account and Project since Project can come from Account or Transaction Details
            //
            List <RegistrationInstance> registrationLinks;
            List <GroupMember>          groupMemberLinks;
            var batchTransactionsSummary = TransactionHelpers.GetTransactionSummary(financialBatch, rockContext, out registrationLinks, out groupMemberLinks);

            //
            // Get the Dimensions from the Account since the Transaction Details have been Grouped already
            //
            var customDimensions = TransactionHelpers.GetCustomDimensions();
            var batchSummary     = new List <GLBatchTotals>();

            foreach (var summary in batchTransactionsSummary)
            {
                var account = new FinancialAccountService(rockContext).Get(summary.FinancialAccountId);
                var customDimensionValues = new Dictionary <string, dynamic>();
                account.LoadAttributes();
                var mergeFieldObjects = new MergeFieldObjects
                {
                    Account          = account,
                    Batch            = financialBatch,
                    Registrations    = registrationLinks,
                    GroupMembers     = groupMemberLinks,
                    Summary          = summary,
                    CustomDimensions = customDimensions
                };
                Dictionary <string, object> mergeFields = TransactionHelpers.GetMergeFieldsAndDimensions(ref debugLava, customDimensionValues, mergeFieldObjects);

                var batchSummaryItem = new GLBatchTotals()
                {
                    Amount                = summary.Amount,
                    CreditAccount         = account.GetAttributeValue("rocks.kfs.Intacct.ACCOUNTNO"),
                    DebitAccount          = account.GetAttributeValue("rocks.kfs.Intacct.DEBITACCOUNTNO"),
                    TransactionFeeAmount  = summary.TransactionFeeAmount,
                    TransactionFeeAccount = summary.TransactionFeeAccount,
                    Class                  = account.GetAttributeValue("rocks.kfs.Intacct.CLASSID"),
                    Department             = account.GetAttributeValue("rocks.kfs.Intacct.DEPARTMENT"),
                    Location               = account.GetAttributeValue("rocks.kfs.Intacct.LOCATION"),
                    Project                = summary.Project,
                    Description            = DescriptionLava.ResolveMergeFields(mergeFields),
                    CustomDimensions       = customDimensionValues,
                    ProcessTransactionFees = summary.ProcessTransactionFees
                };

                batchSummary.Add(batchSummaryItem);
            }

            return(GenerateLineItems(batchSummary));
        }
Esempio n. 9
0
        public async Task <string> DeployContractAsync()
        {
            var transactionHelper = new TransactionHelpers();
            var web3 = new Web3(publicNode);

            return(await transactionHelper.DeployContract(privateKey, web3, account,
                                                          byteCode));
        }
        /// <summary>Registers the patient.</summary>
        /// <param name="firstName">The first name.</param>
        /// <param name="lastName">The last name.</param>
        /// <param name="city">The city.</param>
        /// <param name="state">The state.</param>
        /// <param name="zip">The zip.</param>
        /// <param name="phone">The phone.</param>
        /// <param name="dob">The dob.</param>
        /// <param name="gender">The gender.</param>
        /// <param name="address1">The address1.</param>
        /// <param name="address2">The address2.</param>
        /// <returns>true if patient was registerd, false otherwise</returns>
        public static bool RegisterPatient(string firstName, string lastName, string city, string state, int zip,
                                           string phone, DateTime dob, Gender gender, string address1, string address2)
        {
            MySqlTransaction transaction = TransactionHelpers.BeginTransaction();
            int  userId = UserDAL.Register(firstName, lastName, city, state, zip, phone, dob, gender, address1, address2);
            bool registrationSuccess = PatientDAL.Register(userId);

            return(TransactionHelpers.CommitTransaction(transaction) && registrationSuccess);
        }
        public virtual async Task ShouldDeployStandardSchema()
        {
            var transactionHelper = new TransactionHelpers();
            var web3 = await CreateNewWeb3Instance();

            string contract = await
                              transactionHelper.DeployContract(web3, Account, _password,
                                                               WorkStandardSchemaByteCode, false);
        }
Esempio n. 12
0
        public JsonResult Get(int height = 0)
        {
            //TODO: Update this to split get Tx's from Split BC cache
            var sizeBlock   = 1000;
            var startHeight = height;
            var endHeight   = startHeight + 100;

            if (startHeight < 1)
            {
                startHeight = 1;
            }
            //todo, we don't have to query the chain height every time this is requested
            var chainHeight = RpcHelper.Request <GetHeightResp>("getheight").Height;

            if (chainHeight == 0)
            {
                chainHeight = endHeight + 100;
            }
            if (endHeight > chainHeight)
            {
                endHeight = chainHeight;
            }

            List <int> dbSegments   = new List <int>();
            var        segmentStart = Convert.ToInt32(Math.Floor((double)(startHeight / sizeBlock) * sizeBlock)) + 1;

            dbSegments.Add(segmentStart);
            if (startHeight + 100 > segmentStart + sizeBlock - 1)
            {
                dbSegments.Add(segmentStart + sizeBlock);
            }
            try
            {
                //TODO:... if we find a problem - ie: there are ANY tx's that don't return at least one Tx poer height, then we need to re-cache the DB file we're working with for this height...
                //we need to ensure that there is at least one Tx per block
                //should this be in a seperate "validation background job that's checking completed files - maybe to run once per day?
                List <LightTx> transactions = new List <LightTx>();
                foreach (var start in dbSegments)
                {
                    var end = start + sizeBlock - 1;

                    using (var db = new LiteDatabase(string.Concat(AppContext.BaseDirectory, @"App_Data\", "transactions_", start, "-", end, ".db")))
                    {
                        var cachedtxs = db.GetCollection <CachedTx>("cached_txs");
                        var txs       = cachedtxs.Find(x => x.height >= startHeight && x.height <= endHeight).Distinct().ToList();
                        transactions.AddRange(TransactionHelpers.MapTxs(txs));
                    }
                }
                return(new JsonResult(JsonConvert.SerializeObject(transactions)));
            }
            catch (Exception ex)
            {
                //todo: log and return client handlable exception
            }

            return(new JsonResult(""));
        }
        public async Task <string> DeployContractAsync()
        {
            var transactionHelper = new TransactionHelpers();

            //var address = System.Configuration.ConfigurationManager.
            return(await
                   transactionHelper.DeployContract(new Web3(), "0xbb7e97e5670d7475437943a1b314e661d7a9fa2a", "password",
                                                    "0x60606040525b600060016000508190555060006000600050819055505b6106ee8061002a6000396000f360606040523615610074576000357c0100000000000000000000000000000000000000000000000000000000900480632ec2c246146100765780634420e4861461008e578063469e9067146100a6578063788cadf914610113578063b5d1990d14610155578063c5ea3c651461017857610074565b005b61008c60048080359060200190919050506104ff565b005b6100a4600480803590602001909190505061025e565b005b6100bc60048080359060200190919050506101ad565b604051808573ffffffffffffffffffffffffffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff16815260200183815260200182815260200194505050505060405180910390f35b6101296004808035906020019091905050610226565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b610162600480505061019b565b6040518082815260200191505060405180910390f35b61018560048050506101a4565b6040518082815260200191505060405180910390f35b60006000505481565b60016000505481565b60026000506020528060005260406000206000915090508060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16908060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16908060020160005054908060030160005054905084565b600360005060205280600052604060002060009150909054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000600260005060008373ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000506002016000505414156104fb5742600260005060008373ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000506002016000508190555033600260005060008373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff02191690830217905550600160016000505401600160005081905550600160005054600260005060008373ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600050600301600050819055508060036000506000600160005054815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff02191690830217905550600160006000505401600060005081905550600260005060008273ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16600260005060008373ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600050600301600050548273ffffffffffffffffffffffffffffffffffffffff167fa1559e2788bce2e1be76d17f52a99fe897d4f30c22381249c19f197b567365e9600260005060008673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600050600201600050546040518082815260200191505060405180910390a45b5b50565b60003373ffffffffffffffffffffffffffffffffffffffff16600260005060008473ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614156106e957600260005060008373ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600050600301600050549050600260005060008373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006000820160006101000a81549073ffffffffffffffffffffffffffffffffffffffff02191690556001820160006101000a81549073ffffffffffffffffffffffffffffffffffffffff02191690556002820160005060009055600382016000506000905550506000600081815054809291906001900391905055506003600050600082815260200190815260200160002060006101000a81549073ffffffffffffffffffffffffffffffffffffffff0219169055808273ffffffffffffffffffffffffffffffffffffffff167f15f7469572dc44ee54c08cc4adf4e1031d7b6254626e8894015195a560039d0960405180905060405180910390a35b5b505056"));
        }
Esempio n. 14
0
        public override async Task <string> DeployContractAsync()
        {
            var transactionHelper = new TransactionHelpers();
            var web3 = await CreateNewWeb3Instance();

            var contract = await
                           transactionHelper.DeployContract(PrivateKey, WorkContractDefinition.ABI, web3, Account,
                                                            ByteCode, new[] { WorkStandardSchemaAddress });

            return(contract);
        }
Esempio n. 15
0
        public virtual async Task <string> ShouldDeployStandardSchema()
        {
            var transactionHelper = new TransactionHelpers();
            var web3 = await CreateNewWeb3Instance();

            var contract = await
                           transactionHelper.DeployContract(PrivateKey, web3, Account,
                                                            WorkStandardSchemaByteCode);

            return(contract);
        }
Esempio n. 16
0
        public virtual async Task <string> ShouldDeployRegistryFactory()
        {
            var transactionHelper = new TransactionHelpers();
            var web3 = await CreateNewWeb3Instance();

            var contract = await
                           transactionHelper.DeployContract(PrivateKey, web3, Account,
                                                            WorkFactoryService.BYTE_CODE);

            return(contract);
        }
        /// <summary>Registers the administrator.</summary>
        /// <param name="firstName">The first name.</param>
        /// <param name="lastName">The last name.</param>
        /// <param name="city">The city.</param>
        /// <param name="state">The state.</param>
        /// <param name="zip">The zip.</param>
        /// <param name="phone">The phone.</param>
        /// <param name="dob">The dob.</param>
        /// <param name="gender">The gender.</param>
        /// <param name="address1">The address1.</param>
        /// <param name="address2">The address2.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <returns>true if admin was registered, false otherwise</returns>
        public static bool RegisterAdministrator(string firstName, string lastName, string city, string state, int zip,
                                                 string phone, DateTime dob, Gender gender, string address1, string address2, string username, string password)
        {
            MySqlTransaction transaction = TransactionHelpers.BeginTransaction();
            int  userId = UserDAL.Register(firstName, lastName, city, state, zip, phone, dob, gender, address1, address2);
            bool accountRegistrationSuccess       = AccountDAL.Register(username, password);
            bool administratorRegistrationSuccess = AdministratorDAL.Register(userId, username);
            bool registrationSuccess = accountRegistrationSuccess && administratorRegistrationSuccess;

            return(TransactionHelpers.CommitTransaction(transaction) && registrationSuccess);
        }
        public override async Task <string> DeployContractAsync()
        {
            var transactionHelper = new TransactionHelpers();
            var web3 = await CreateNewWeb3Instance();

            var contract = await
                           transactionHelper.DeployContract(WorkContractDefinition.ABI, web3, Account, _password,
                                                            ByteCode, new[] { WorkStandardSchemaAddress });

            Debug.WriteLine("Contract created: " + contract);
            return(contract);
        }
        public ActionResult Edit(EditTransactionViewModel transactionViewModel)
        {
            if (!ModelState.IsValid)
            {
                TransactionHelpers.SetCategoryDropDownList(transactionViewModel, Request);

                if (transactionViewModel.Categories is null)
                {
                    TempData.Add("Message", "Error: Categories missing");
                    TempData.Add("MessageColour", "danger");
                    return(RedirectToAction("Index", "Household"));
                }

                return(View(transactionViewModel));
            }

            var url = $"{ProjectConstants.APIURL}/api/transaction/edit/{transactionViewModel.Id}";

            var parameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Title", transactionViewModel.Title),
                new KeyValuePair <string, string>("Description", transactionViewModel.Description),
                new KeyValuePair <string, string>("Amount", transactionViewModel.Amount.ToString()),
                new KeyValuePair <string, string>("Date", transactionViewModel.Date.ToString()),
                new KeyValuePair <string, string>("CategoryId", transactionViewModel.CategoryId.ToString()),
            };

            var encodedParameters = new FormUrlEncodedContent(parameters);
            var response          = HttpClientContext.httpClient.PostAsync(url, encodedParameters).Result;

            if (response.IsSuccessStatusCode)
            {
                TempData.Add("Message", $"Transaction '{transactionViewModel.Title}' Edited!");
                return(RedirectToAction("HouseholdTransactions", "Transaction", new { Id = transactionViewModel.HouseholdId }));
            }
            else
            {
                ErrorHelpers.HandleResponseErrors(response, TempData, ModelState);

                TransactionHelpers.SetCategoryDropDownList(transactionViewModel, Request);

                if (transactionViewModel.Categories is null)
                {
                    TempData.Add("Message", "Error: Categories missing");
                    TempData.Add("MessageColour", "danger");
                    return(RedirectToAction("Index", "Household"));
                }

                return(View(transactionViewModel));
            }
        }
Esempio n. 20
0
        public async Task <string> RegisterDeployedContract(string address)
        {
            var web3 = CreateNewWeb3Instance();
            var contractRegistryService = new RegistryService(web3, contractAddress);

            var tx = await contractRegistryService.RegisterAsync(account,
                                                                 address,
                                                                 defaultGas);

            var transactionHelper = new TransactionHelpers();
            var receipt           = await transactionHelper.GetTransactionReceipt(web3, tx);

            return(tx);
        }
Esempio n. 21
0
        public IActionResult PostTransaction([FromBody] TransactionForDisplay transaction)
        {
            var transactions = new List <TransactionForDisplay>();

            if (transaction.TransactionId == null || transaction.TransactionId == Guid.Empty)
            {
                transaction.TransactionId = Guid.NewGuid();
            }
            if (transaction.AccountId == null)
            {
                transaction.AccountId = _accountRepo.GetAll().Single(a => a.Name.Equals(transaction.AccountName, StringComparison.CurrentCultureIgnoreCase)).AccountId;
            }
            transaction.SetAmount();
            transaction.EnteredDate = DateTime.Now;
            if (transaction.CategoryId.IsNullOrEmpty() && !string.IsNullOrWhiteSpace(transaction.CategoryName))
            {
                var category = _categoryRepo.GetAll().SingleOrDefault(c => (c.Name.Equals(transaction.CategoryName, StringComparison.CurrentCultureIgnoreCase)));
                if (category == null)
                {
                    category = new Category
                    {
                        CategoryId = Guid.NewGuid(),
                        Name       = transaction.CategoryName,
                        Type       = "Expenses"
                    };
                    _categoryRepo.Insert(category);
                }
                transaction.CategoryId = category.CategoryId;
            }

            var bankFeeTransactions = TransactionHelpers.GetBankFeeTransactions(transaction, _categoryRepo, _accountRepo);

            transactions.Add(transaction);
            transactions.AddRange(bankFeeTransactions);
            foreach (var trx in transactions)
            {
                _transactionRepo.Insert(trx);
            }

            var accountBalances       = _accountRepo.GetAccountBalances().Select(a => new { a.AccountId, a.CurrentBalance });
            InvoiceForPosting invoice = null;

            if (transaction.InvoiceId.HasValue)
            {
                invoice = _invoiceRepo.Get(transaction.InvoiceId.Value);
            }
            var vendor = _vendorRepo.GetAll().SingleOrDefault(v => v.Name == transaction.Vendor);

            return(CreatedAtAction("PostTransaction", new { id = transaction.TransactionId }, new { transactions, accountBalances, invoice, vendor }));
        }
Esempio n. 22
0
        public IActionResult PostAccount([FromBody] AccountForPosting account)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var newAccount = new Account
            {
                AccountId       = Guid.NewGuid(),
                Name            = account.Name,
                Currency        = account.Currency,
                Vendor          = account.Vendor,
                AccountType     = account.AccountType,
                MortgagePayment = account.MortgagePayment,
                MortgageType    = account.MortgageType
            };

            _accountRepo.Insert(newAccount);

            var category    = TransactionHelpers.GetOrCreateCategory("Starting Balance", _categoryRepo);
            var transaction = new TransactionForDisplay
            {
                TransactionId   = Guid.NewGuid(),
                AccountId       = newAccount.AccountId,
                Amount          = account.StartingBalance,
                TransactionDate = account.StartDate,
                Vendor          = "",
                Description     = "",
                CategoryId      = category.CategoryId,
                CategoryName    = category.Name,
                EnteredDate     = account.StartDate,
                IsReconciled    = true
            };

            _transactionRepo.Insert(transaction);

            var model = new AccountWithTransactions
            {
                AccountId      = newAccount.AccountId,
                Name           = newAccount.Name,
                Transactions   = new List <TransactionForDisplay>(new[] { transaction }),
                CurrentBalance = account.StartingBalance
            };

            return(CreatedAtAction("PostAccount", new { id = newAccount.AccountId }, model));
        }
        public ActionResult Create(CreateTransactionViewModel transactionViewModel)
        {
            if (!ModelState.IsValid || transactionViewModel.BankAccountId is null || transactionViewModel.CategoryId is null)
            {
                TransactionHelpers.SetDropDownLists(transactionViewModel, Request);

                if (TransactionHelpers.BankAccntOrCategoriesIsNull(transactionViewModel, TempData))
                {
                    return(RedirectToAction("Index", "Household"));
                }

                return(View(transactionViewModel));
            }


            var url = $"{ProjectConstants.APIURL}/api/transaction/create/{transactionViewModel.BankAccountId}";

            var parameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Title", transactionViewModel.Title),
                new KeyValuePair <string, string>("Description", transactionViewModel.Description),
                new KeyValuePair <string, string>("Amount", transactionViewModel.Amount.ToString()),
                new KeyValuePair <string, string>("Date", transactionViewModel.Date.ToString()),
                new KeyValuePair <string, string>("CategoryId", transactionViewModel.CategoryId.ToString()),
            };

            var encodedParameters = new FormUrlEncodedContent(parameters);
            var response          = HttpClientContext.httpClient.PostAsync(url, encodedParameters).Result;

            if (response.IsSuccessStatusCode)
            {
                TempData.Add("Message", "Transaction Created!");
                return(RedirectToAction("HouseholdTransactions", "Transaction", new { Id = transactionViewModel.HouseholdId }));
            }
            else
            {
                TransactionHelpers.SetDropDownLists(transactionViewModel, Request);
                if (TransactionHelpers.BankAccntOrCategoriesIsNull(transactionViewModel, TempData))
                {
                    return(RedirectToAction("Index", "Household"));
                }

                ErrorHelpers.HandleResponseErrors(response, TempData, ModelState);

                return(View(transactionViewModel));
            }
        }
        public IHttpActionResult Create(int?Id, TransactionBindingModel transactionBinding)
        {
            // Id being the id of the bankAccount
            if (ModelState is null || !ModelState.IsValid || Id is null)
            {
                return(BadRequest(ModelState));
            }

            var bankAccount = DbContext.BankAccounts.FirstOrDefault(p => p.Id == Id);

            if (bankAccount is null)
            {
                return(BadRequest("No bank account with that Id"));
            }

            // Ensure that the bank account and category are in the same houeshold.
            if (!bankAccount.Household.Categories.Any(p => p.Id == transactionBinding.CategoryId))
            {
                return(BadRequest("No category with that Id"));
            }

            var transaction = new Transaction
            {
                Title         = transactionBinding.Title,
                Description   = transactionBinding.Description,
                CategoryId    = transactionBinding.CategoryId,
                Date          = transactionBinding.Date,
                Amount        = transactionBinding.Amount,
                CreatorId     = User.Identity.GetUserId(),
                DateCreated   = DateTime.Now,
                DateUpdated   = null,
                BankAccountId = (int)Id,
                IsVoid        = false
            };

            bankAccount.AddTransaction(transaction);
            DbContext.SaveChanges();

            var transactionView = TransactionHelpers.MapToView(transaction);

            return(Created(Url.Link(
                               "GetTransactionById",
                               new { transaction.Id }),
                           transactionView
                           ));
        }
Esempio n. 25
0
        public IActionResult PostTransfer([FromBody] TransactionForDisplay transaction)
        {
            var transactions = new List <TransactionForDisplay>();

            if (transaction.TransactionId == null || transaction.TransactionId == Guid.Empty)
            {
                transaction.TransactionId = Guid.NewGuid();
            }
            if (!transaction.AccountId.HasValue)
            {
                transaction.AccountId = _accountRepo.GetAll().Single(
                    a => a.Name.Equals(transaction.AccountName, StringComparison.CurrentCultureIgnoreCase)).AccountId;
            }
            transaction.SetAmount();
            var relatedTransactionId = Guid.NewGuid();
            var relatedTransaction   = new TransactionForDisplay {
                TransactionDate      = transaction.TransactionDate,
                TransactionId        = relatedTransactionId,
                Vendor               = transaction.Vendor,
                Description          = transaction.Description,
                AccountId            = transaction.RelatedAccountId.Value,
                Amount               = 0 - transaction.Amount,
                EnteredDate          = DateTime.Now,
                RelatedTransactionId = transaction.TransactionId
            };

            relatedTransaction.SetDebitAndCredit();

            transaction.RelatedTransactionId = relatedTransactionId;

            var bankFeeTransactions = TransactionHelpers.GetBankFeeTransactions(transaction, _categoryRepo, _accountRepo);

            transactions.Add(transaction);
            transactions.Add(relatedTransaction);
            transactions.AddRange(bankFeeTransactions);
            _transactionRepo.InsertRelatedTransaction(transaction, relatedTransaction);
            foreach (var trx in bankFeeTransactions)
            {
                _transactionRepo.Insert(trx);
            }

            var accountBalances = _accountRepo.GetAccountBalances().Select(a => new { a.AccountId, a.CurrentBalance });

            return(CreatedAtAction("PostTransfer",
                                   new { id = transaction.TransactionId }, new { transactions, accountBalances }));
        }
        public ActionResult HouseholdTransactions(int?Id)
        {
            if (Id is null)
            {
                TempData.Add("Message", "Improper Id");
                TempData.Add("MessageColour", "danger");
                return(RedirectToAction("Index", "Household"));
            }

            var url = $"{ProjectConstants.APIURL}/api/transaction/getallbyhousehold/{Id}";

            var token      = Request.Cookies["UserAuthCookie"].Value;
            var authHeader = new AuthenticationHeaderValue("Bearer", token);

            HttpClientContext.httpClient.DefaultRequestHeaders.Authorization = authHeader;

            // Handling lack of connection??? try catch?
            var response = HttpClientContext.httpClient.GetAsync(url).Result;

            if (response.IsSuccessStatusCode)
            {
                var responseResult = response.Content.ReadAsStringAsync().Result;

                var datas = JsonConvert.DeserializeObject <List <TransactionViewModel> >(responseResult);

                foreach (var item in datas)
                {
                    item.CategoryName    = HouseholdHelpers.GetCategoryName(item.CategoryId, Request);
                    item.BankAccountName = HouseholdHelpers.GetBankAccountName(item.BankAccountId, Request);
                    item.UserCanEdit     = TransactionHelpers.IsUserCreator(item.Id, Request, TempData);
                }

                var viewModel = new TransactionListViewModel
                {
                    Transactions             = datas,
                    HouseholdId              = (int)Id,
                    IsHouseholdOwnerOrMember = HouseholdHelpers.IsUserCreatorOrMember((int)Id, Request, TempData)
                };
                return(View(viewModel));
            }
            else
            {
                ErrorHelpers.HandleResponseErrors(response, TempData, ModelState);
                return(RedirectToAction("Index", "Household"));
            }
        }
        public TransactionPreviewViewModel(Wallet wallet, TransactionInfo info, BuildTransactionResult transaction)
        {
            _wallet = wallet;
            _labels = SmartLabel.Empty;
            _info   = info;
            SetupCancel(enableCancel: false, enableCancelOnEscape: true, enableCancelOnPressed: false);
            EnableBack            = true;
            _confirmationTimeText = "";

            var destinationAmount = transaction.CalculateDestinationAmount().ToDecimal(MoneyUnit.BTC);
            var btcAmountText     = $"{destinationAmount} bitcoins ";
            var fiatAmountText    = destinationAmount.GenerateFiatText(_wallet.Synchronizer.UsdExchangeRate, "USD");

            AmountText = $"{btcAmountText}{fiatAmountText}";

            AddressText = info.Address.ToString();

            var fee         = transaction.Fee;
            var btcFeeText  = $"{fee.ToDecimal(MoneyUnit.Satoshi)} sats ";
            var fiatFeeText = fee.ToDecimal(MoneyUnit.BTC).GenerateFiatText(_wallet.Synchronizer.UsdExchangeRate, "USD");

            FeeText = $"{btcFeeText}{fiatFeeText}";

            PayJoinUrl = info.PayJoinClient?.PaymentUrl.AbsoluteUri;
            IsPayJoin  = PayJoinUrl is not null;

            if (PreferPsbtWorkflow)
            {
                SkipCommand = ReactiveCommand.CreateFromTask(async() => await OnConfirmAsync(transaction));
                NextCommand = ReactiveCommand.CreateFromTask(async() =>
                {
                    var saved = await TransactionHelpers.ExportTransactionToBinaryAsync(transaction);

                    if (saved)
                    {
                        Navigate().To(new SuccessViewModel("The PSBT has been successfully created."));
                    }
                });
                _nextButtonText = "Save PSBT file";
            }
            else
            {
                NextCommand     = ReactiveCommand.CreateFromTask(async() => await OnConfirmAsync(transaction));
                _nextButtonText = "Confirm";
            }
        }
Esempio n. 28
0
    public static async IAsyncEnumerable <ChangeAvoidanceSuggestionViewModel> GenerateSuggestionsAsync(
        TransactionInfo transactionInfo,
        BitcoinAddress destination,
        Wallet wallet,
        ImmutableArray <SmartCoin> coinsToUse,
        int maxInputCount,
        decimal usdExchangeRate,
        [EnumeratorCancellation] CancellationToken cancellationToken)
    {
        var selections = ChangelessTransactionCoinSelector.GetAllStrategyResultsAsync(
            coinsToUse,
            transactionInfo.FeeRate,
            new TxOut(transactionInfo.Amount, destination),
            maxInputCount,
            cancellationToken).ConfigureAwait(false);

        HashSet <Money> foundSolutionsByAmount = new();

        await foreach (var selection in selections)
        {
            if (selection.Any())
            {
                BuildTransactionResult transaction = TransactionHelpers.BuildChangelessTransaction(
                    wallet,
                    destination,
                    transactionInfo.UserLabels,
                    transactionInfo.FeeRate,
                    selection,
                    tryToSign: false);

                var destinationAmount = transaction.CalculateDestinationAmount();

                // If BnB solutions become the same transaction somehow, do not show the same suggestion twice.
                if (!foundSolutionsByAmount.Contains(destinationAmount))
                {
                    foundSolutionsByAmount.Add(destinationAmount);

                    yield return(new ChangeAvoidanceSuggestionViewModel(
                                     transactionInfo.Amount.ToDecimal(MoneyUnit.BTC),
                                     transaction,
                                     usdExchangeRate));
                }
            }
        }
    }
Esempio n. 29
0
        private async Task OnNext(TransactionBroadcaster broadcaster)
        {
            var transactionInfo       = _transactionInfo;
            var wallet                = _owner.Wallet;
            var targetAnonymitySet    = wallet.ServiceConfiguration.GetMixUntilAnonymitySetValue();
            var mixedCoins            = wallet.Coins.Where(x => x.HdPubKey.AnonymitySet >= targetAnonymitySet).ToList();
            var totalMixedCoinsAmount = Money.FromUnit(mixedCoins.Sum(coin => coin.Amount), MoneyUnit.Satoshi);

            if (transactionInfo.Amount <= totalMixedCoinsAmount)
            {
                try
                {
                    try
                    {
                        var txRes = await Task.Run(() => TransactionHelpers.BuildTransaction(wallet, transactionInfo.Address, transactionInfo.Amount, transactionInfo.Labels, transactionInfo.FeeRate, mixedCoins, subtractFee: false));

                        Navigate().To(new OptimisePrivacyViewModel(wallet, transactionInfo, broadcaster, txRes));
                        return;
                    }
                    catch (InsufficientBalanceException)
                    {
                        var txRes = await Task.Run(() => TransactionHelpers.BuildTransaction(wallet, transactionInfo.Address, totalMixedCoinsAmount, transactionInfo.Labels, transactionInfo.FeeRate, mixedCoins, subtractFee: true));

                        var dialog = new InsufficientBalanceDialogViewModel(BalanceType.Private, txRes, wallet.Synchronizer.UsdExchangeRate);
                        var result = await NavigateDialog(dialog, NavigationTarget.DialogScreen);

                        if (result.Result)
                        {
                            Navigate().To(new OptimisePrivacyViewModel(wallet, transactionInfo, broadcaster, txRes));
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex);
                    await ShowErrorAsync("Transaction Building", ex.ToUserFriendlyString(), "Wasabi was unable to create your transaction.");

                    return;
                }
            }

            Navigate().To(new PrivacyControlViewModel(wallet, transactionInfo, broadcaster));
        }
Esempio n. 30
0
        public IActionResult MakeCorrectingEntries()
        {
            var investments        = GetInvestments();
            var currencyController = new CurrenciesController(_currencyRepo);
            var currency           = currencyController.GetExchangeRateFor("CAD").GetAwaiter().GetResult();
            var investmentsTotal   = investments.Sum(i => i.Price * i.Shares);
            var totalInUsd         = investmentsTotal / currency;
            var investmentAccount  = _accountRepo.GetAll().FirstOrDefault(a => a.AccountType == "Investment");

            if (investmentAccount == null)
            {
                return(Ok());
            }

            var bookBalance = _transactionRepo.GetByAccount(investmentAccount.AccountId).Sum(i => i.Amount);

            var difference = Math.Round(totalInUsd - bookBalance, 2);

            if (Math.Abs(difference) >= 1)
            {
                var category    = TransactionHelpers.GetOrCreateCategory("Gain/loss on investments", _categoryRepo);
                var transaction = new TransactionForDisplay {
                    TransactionId   = Guid.NewGuid(),
                    AccountId       = investmentAccount.AccountId,
                    Amount          = difference,
                    CategoryId      = category.CategoryId,
                    CategoryName    = category.Name,
                    CategoryDisplay = category.Name,
                    TransactionDate = DateTime.Now,
                    EnteredDate     = DateTime.Now,
                    Description     = "Gain/loss"
                };
                transaction.SetDebitAndCredit();
                _transactionRepo.Insert(transaction);
                var accountBalances = _accountRepo.GetAccountBalances().Select(a => new { a.AccountId, a.CurrentBalance });
                var transactions    = new[] { transaction };

                return(CreatedAtAction("PostTransaction", new { id = transaction.TransactionId }, new { transactions, accountBalances }));
            }
            else
            {
                return(Ok());
            }
        }