public async Task <ActionResult> Account([FromUri] string address) { using (var client = new NanoRpcClient("http://localhost:7043")) { decimal sent = 0; decimal received = 0; AccountHistory h = await client.GetAccountHistoryAsync(new NanoAccount(address.Trim()), 10000); AccountInformationResponse account = await client.GetAccountInformationAsync(new NanoAccount(address.Trim())); if (h.History != null) { foreach (var a in h.History) { if (a.Type == "send") { sent += (decimal)a.Amount.Raw / 10000000000M; } else { received += (decimal)a.Amount.Raw / 10000000000M; } } } return(View(new AccountInfo { account = account, History = h.History, sent = sent, received = received })); } }
public object GetWithdraw(int acount_id, [FromBody] decimal amount) { AccountHistory ah = new AccountHistory(); ah.Amount = amount; ah.ChangeAt = DateTime.Now; ah.AccountID = acount_id; ah.ID = 0; decimal tes = repositury.UpdateAccount(ah); if (tes > 0) { SucessResult sucessResult = new SucessResult(); sucessResult.Result = tes.ToString(); sucessResult.Status = "Ok"; return(JsonConvert.SerializeObject(sucessResult)); } else { SucessResult sucessResult = new SucessResult(); sucessResult.Result = "Пользователь не существует или отрицательный балланс!"; sucessResult.Status = "Error"; return(JsonConvert.SerializeObject(sucessResult)); } }
public ActionResult <AccountHistory> GetHistory([Required, FromRoute] string accountNumber) { AccountHistory history; try { UserInputValidation.ValidateAccountNumber(accountNumber); var userInfo = User.GetUserInfo(); var username = userInfo.AccountsUsername; using (var session = Logic.Login(Repository, username)) { history = new AccountHistory { StartingBalance = 0.0, FinalBalance = 0.0, History = Logic.GetTransactionHistory(session, accountNumber) .Select(t => new Transaction(t)) .ToList() }; history.FinalBalance += history.History.Sum(t => (t.Action == ETransactionType.Credit) ? t.Amount : (-t.Amount)); } } catch (AccountsLibException ex) { return(new ActionFailureResult(new ApiResponse(500, ex.Message))); } return(history); }
protected void LogAccountHistory(int accountId, decimal changeValue, string comefrom) { AccountHistory accountHistory = new AccountHistory(); accountHistory.CreateAt = DateTime.Now; accountHistory.AccountId = accountId; accountHistory.ChangeValue = changeValue; accountHistory.ComeFrom = comefrom; db.AccountHistory.Add(accountHistory); }
public void EmptyCheckEnumeration() { var toTest = new AccountHistory(); var callbackCalled = false; toTest.Enumerate(item => callbackCalled = true); Assert.IsFalse(callbackCalled); }
public ActionResult RechargeAccount(RechargeAccountModel model) { //find account var userAccount = db.User.FirstOrDefault( p => p.AccountName == model.RechargeAccount || p.MobilePhone == model.RechargeAccount); if (userAccount == null) { ModelState.AddModelError("RechargeAccount", "帐户不存在,请核对帐户"); return(View(model)); } if (ModelState.IsValid) { var rechargeStatusId = SystemStaticData.LookUpRechargeRewardStatusId(SystemStaticData.RechargeRewardDictionary.Normal); DataAccessLayer.RechargeHistory history = new DataAccessLayer.RechargeHistory(); history.CreateAt = DateTime.Now; history.CreateUserId = this.CurrentLoginUserId; history.Details = model.Remark; history.RechargeCash = model.Cash; var reward = db.RechargeReward.OrderByDescending(p => p.TargetValue) .FirstOrDefault(m => m.TargetValue <= model.Cash && m.Status == rechargeStatusId); history.RechargeRewardTypeId = reward == null ? 0 : reward.RechargeRewardId; history.UserId = userAccount.UserId; //账户余额增加 UserAccount account = db.UserAccount.First(p => p.UserId == userAccount.UserId); //记录账户历史记录 AccountHistory accountHistory = new AccountHistory(); accountHistory.CreateAt = DateTime.Now; accountHistory.AccountId = account.AccountId; accountHistory.ChangeValue = model.Cash; accountHistory.ComeFrom = "账户充值"; account.AccountBalance += model.Cash; if (reward != null) { account.AccountBalance += reward.RewardValue; accountHistory.ChangeValue += reward.RewardValue; accountHistory.Description = "账户充值获得奖励 " + reward.RewardValue; } db.RechargeHistory.Add(history); db.AccountHistory.Add(accountHistory); db.SaveChanges(); if (reward != null) { SystemIncome("充值奖励", -reward.RewardValue, history.RechargeHistoryId, "用户" + userAccount.AccountName + "充值 " + model.Cash + " 元,获得系统奖励 " + reward.RewardValue); db.SaveChanges(); } return(Content("<script>alert('充值成功');window.location.href=window.location.href</script>")); } return(View(model)); }
//veel moed hiermee, als het teveel wordt is The Expanse kijken ook altijd een optie public void StartCompetitivePanel(DateTime periodStartDate) { storageManagerScript = FindObjectOfType <StorageManager>(); scoreBordScript = FindObjectOfType <ScoreBord>(); playerOptions = storageManagerScript.GetPlayerOptions(); playerOptions.Remove(""); rankingsList.Add(numberOfSessionsRanking); rankingsList.Add(totalTImeRanking); rankingsList.Add(totalDistanceRanking); rankingsList.Add(numberOfRacesWonRanking); rankingsList.Add(averageRankingRanking); foreach (string player in playerOptions) //Geeft iedere speler een AcountHistory met de data van deze speler. { //Haal alle bestanden op van de speler vanaf een bepaalde datum List <FileInfo> selectedEventFiles = scoreBordScript.GetAllSelectedEventFiles(player, periodStartDate); //Lees deze bestanden List <List <float> > selectedEventFilesData = scoreBordScript.ReadAllEventFiles(selectedEventFiles); //Creer een Accounthistory en prop deze vol met de informatie over de speler AccountHistory accountHistory = gameObject.AddComponent <AccountHistory>(); accountHistory.accountName = player; accountHistory.numberOfSessions = scoreBordScript.GetNumberOfSessions(selectedEventFiles); accountHistory.totalTime = scoreBordScript.GetTotalVar(selectedEventFilesData, 3, 2); //Tijd heeft in racebestanden index 3 en in training index 2 accountHistory.totalDistance = scoreBordScript.GetTotalVar(selectedEventFilesData, 2, 1); //Afstand heeft in racebestanden index 2 en in training index 1 accountHistory.numberOfRacesWon = scoreBordScript.GetRacesWon(selectedEventFilesData); accountHistory.averageRanking = scoreBordScript.GetAverageRankingInRaces(selectedEventFilesData); accountHistory.UpdateDataList(); accountHistories.Add(accountHistory); } //Maakt nu verschillende lijsten waarin de gesorteerde AccountHistories worden geplaatst accountsSortedByNumberOfSessions = new List <AccountHistory>(accountHistories); //Sorteer de lijsten op de geselecteerde waarde accountsSortedByNumberOfSessions.Sort(SortByNumberOfSessions); //Voeg toe aan de lijst van de lijst van gesorteerde accounts sortedAccounts.Add(accountsSortedByNumberOfSessions); //Repeat accountsSortedByTotalTime = new List <AccountHistory>(accountHistories); accountsSortedByTotalTime.Sort(SortByTotalTime); sortedAccounts.Add(accountsSortedByTotalTime); accountsSortedByTotalDistance = new List <AccountHistory>(accountHistories); accountsSortedByTotalDistance.Sort(SortByTotalDistance); sortedAccounts.Add(accountsSortedByTotalDistance); accountsSortedByNumberOfRacesWon = new List <AccountHistory>(accountHistories); accountsSortedByNumberOfRacesWon.Sort(SortByNumberOfRacesWon); sortedAccounts.Add(accountsSortedByNumberOfRacesWon); accountsSortedByAverageRanking = new List <AccountHistory>(accountHistories); accountsSortedByAverageRanking.Sort(SortByAverageRanking); sortedAccounts.Add(accountsSortedByAverageRanking); int i = 0; foreach (Rankings rankings in rankingsList) //Iedere ranking krijgt nu een gesorteerde lijst toegewezen om te laten zien { rankings.ApplyRankings(sortedAccounts[i], i); i += 1; } }
private void AddHistoryEntry(Account account) { var history = new AccountHistory { AccountId = account.Id, Balance = account.Balance, DebtLimit = account.DebtLimit, EntryDate = DateTime.Now, FirstName = account.FirstName, LastName = account.LastName }; _dbContext.AccountHistories.Add(history); }
protected override bool PrepareInsert(PXCache sender, object row, PXAccumulatorCollection columns) { if (!base.PrepareInsert(sender, row, columns)) { return(false); } AccountHistory hist = (AccountHistory)row; columns.RestrictPast <GLHistory.finPeriodID>(PXComp.GE, hist.FinPeriodID.Substring(0, 4) + "01"); columns.RestrictFuture <GLHistory.finPeriodID>(PXComp.LE, hist.FinPeriodID.Substring(0, 4) + "99"); return(true); }
static void Main(string[] args) { Console.Clear(); Console.WriteLine("Familly name:"); var name = Console.ReadLine(); Console.WriteLine("First name:"); var firstName = Console.ReadLine(); // must be initialized with external sources. var accountHistory = new AccountHistory(); var account = new Account(new Client(firstName, name), accountHistory); displayMenu(); while (true) { Console.WriteLine(); Console.Write("Your Choice >"); var key = Console.ReadKey(); switch (key.KeyChar) { case '1': save(account); break; case '2': withdraw(account); break; case '3': history(account); break; case 'q': case 'Q': Console.WriteLine("Bye..."); return; default: displayMenu(); break; } } }
public async Task Handle(WalletCreated notification, CancellationToken cancellationToken) { User user = _userRepository.GetById(notification.UserId); user.MustNotBeNull(ex: new UserNotFoundException(ExceptionMessage.UserNotFoundExceptionMessage)); var accountHistory = new AccountHistory( notification.UserId, DateTime.Now, $"New wallet created for {user.Name} with an initial balance of {notification.InitialBalance}." ); _accountHistoryRepository.Add(accountHistory); await _accountHistoryRepository.SaveChanges(cancellationToken); }
public void AddOperation_Multiple_Unordered() { var toTest = new AccountHistory(); var expectedOperations = new List <IOperation>(); IOperation mockOperation; mockOperation = Substitute.For <IOperation>(); mockOperation.Amount.Returns(123.456); mockOperation.Operation.Returns(OperationType.SAVE); mockOperation.Date.Returns(new DateTime(2017, 12, 5, 1, 2, 3)); expectedOperations.Add(mockOperation); mockOperation = Substitute.For <IOperation>(); mockOperation.Amount.Returns(54.87); mockOperation.Operation.Returns(OperationType.WITHDRAW); mockOperation.Date.Returns(new DateTime(2017, 12, 5, 1, 4, 5)); expectedOperations.Add(mockOperation); mockOperation = Substitute.For <IOperation>(); mockOperation.Amount.Returns(32.65); mockOperation.Operation.Returns(OperationType.WITHDRAW); mockOperation.Date.Returns(new DateTime(2017, 12, 5, 1, 3, 4)); expectedOperations.Add(mockOperation); expectedOperations.ForEach(item => toTest.AddOperation(item)); Assert.AreEqual(3, toTest.Count); var items = new List <IOperation>(); toTest.Enumerate(item => items.Add(item)); Assert.AreEqual(expectedOperations.Count, items.Count); Assert.AreEqual(expectedOperations[0].Amount, items[0].Amount); Assert.AreEqual(expectedOperations[0].Operation, items[0].Operation); Assert.AreEqual(expectedOperations[0].Date.Ticks, items[0].Date.Ticks); Assert.AreEqual(expectedOperations[2].Amount, items[1].Amount); Assert.AreEqual(expectedOperations[2].Operation, items[1].Operation); Assert.AreEqual(expectedOperations[2].Date.Ticks, items[1].Date.Ticks); Assert.AreEqual(expectedOperations[1].Amount, items[2].Amount); Assert.AreEqual(expectedOperations[1].Operation, items[2].Operation); Assert.AreEqual(expectedOperations[1].Date.Ticks, items[2].Date.Ticks); }
public void AddAccountHistory(Guid accountId, AccountHistory accountHistory) { if (accountId == Guid.Empty) { throw new ArgumentNullException(nameof(accountId)); } if (accountHistory == null) { throw new ArgumentNullException(nameof(accountHistory)); } var account = GetAccount(accountId); // check if balance of acount will't become less than 0 switch (accountHistory.Operation) { case Operation.Increase: break; case Operation.Decrease: if ((account.Balance - accountHistory.Amount) >= 0) { break; } else { throw new WithDrawException( $"Operation of withdraw denied! Balance of account less, " + $"than amount to withdraw. Your balance: {account.Balance}." ); } } accountHistory.AccountId = accountId; _context.AccountHistories.Add(accountHistory); }
public void AddOperation_Single() { var toTest = new AccountHistory(); var mockOperation = Substitute.For <IOperation>(); mockOperation.Amount.Returns(123.456); mockOperation.Operation.Returns(OperationType.SAVE); mockOperation.Date.Returns(new DateTime(2017, 12, 5, 1, 2, 3)); toTest.AddOperation(mockOperation); Assert.AreEqual(1, toTest.Count); var items = new List <IOperation>(); toTest.Enumerate(item => items.Add(item)); Assert.AreEqual(1, items.Count); Assert.AreEqual(mockOperation.Amount, items[0].Amount); Assert.AreEqual(mockOperation.Operation, items[0].Operation); Assert.AreEqual(mockOperation.Date.Ticks, items[0].Date.Ticks); }
public Discount GetBigSpenderDiscount(AccountHistory customerAccount, CustomerType customerAccountCustomerType) { switch (customerAccountCustomerType) { case CustomerType.Bronze: if (customerAccount.YearlySpend > 3000) { return new Discount { DiscountType = DiscountType.BigSpenderDiscount, DiscountValue = 1 } } ; break; case CustomerType.Silver: if (customerAccount.YearlySpend > 2000) { return new Discount { DiscountType = DiscountType.BigSpenderDiscount, DiscountValue = 2 } } ; break; case CustomerType.Gold: if (customerAccount.YearlySpend > 1000) { return new Discount { DiscountType = DiscountType.BigSpenderDiscount, DiscountValue = 2 } } ; break; } return(GetBigSpenderDiscount(customerAccount)); }
public Discount GetBigSpenderDiscount(AccountHistory customerAccount) { var discountType = DiscountType.BigSpenderDiscount; decimal discountValue; if (_util.SpendOver5K(customerAccount.YearlySpend)) { discountValue = 2; } else if (_util.Between2KAnd5K(customerAccount.YearlySpend)) { discountValue = 1; } else if (_util.Between1KAnd2K(customerAccount.YearlySpend)) { discountValue = 0.5M; } else { if (_util.Between500And1K(customerAccount.YearlySpend)) { discountValue = 0.25M; } else { discountType = DiscountType.None; discountValue = 0; } } return(new Discount { DiscountType = discountType, DiscountValue = discountValue }); }
public async Task Handle(WithdrewMoney notification, CancellationToken cancellationToken) { Wallet wallet = _walletRepository.GetById(notification.EntityId); User user = _userRepository.GetById(notification.UserId); wallet.MustNotBeNull(ex: new WalletNotFoundException("Wallet not found.")); user.MustNotBeNull(ex: new UserNotFoundException(ExceptionMessage.UserNotFoundExceptionMessage)); var withdrawnMoney = new Money(notification.Amount); Money originalWithdrawnMoney = notification.Currency.OriginalMoneyValue(); var accountHistory = new AccountHistory( notification.UserId, DateTime.Now, notification.Currency.Key == CurrencySettings.DefaultCurrencyKey ? $"{user.Name} has withdrawn {withdrawnMoney}. Total account balance is {wallet.Balance}." : $"{user.Name} has withdrawn {notification.Currency.Key} {originalWithdrawnMoney.Value:#.00} or {withdrawnMoney}. Total account balance is {wallet.Balance}." ); _accountHistoryRepository.Add(accountHistory); await _accountHistoryRepository.SaveChanges(cancellationToken); }
public async Task Handle(CreditedMoney notification, CancellationToken cancellationToken) { Wallet wallet = _walletRepository.GetById(notification.EntityId); User fromUser = _userRepository.GetById(notification.FromUserId); wallet.MustNotBeNull(ex: new WalletNotFoundException(ExceptionMessage.WalletNotFoundExceptionMessage)); fromUser.MustNotBeNull(ex: new UserNotFoundException(ExceptionMessage.UserNotFoundExceptionMessage)); var creditedMoney = new Money(notification.Amount); Money originalDepositedMoney = notification.Currency.OriginalMoneyValue(); var accountHistory = new AccountHistory( notification.ToUserId, DateTime.Now, notification.Currency.Key == CurrencySettings.DefaultCurrencyKey ? $"{creditedMoney} has been credited to your account from {fromUser.Name}. New account balance is {wallet.Balance}." : $"{notification.Currency.Key} {originalDepositedMoney.Value:#.00} or {creditedMoney} has been credited to your account from {fromUser.Name}. New account balance is {wallet.Balance}." ); _accountHistoryRepository.Add(accountHistory); await _accountHistoryRepository.SaveChanges(cancellationToken); }
public object TopUp(int account_id, [FromBody] decimal amount) { AccountHistory ah = new AccountHistory(); ah.AccountID = account_id; ah.Amount = amount; ah.ChangeAt = DateTime.Now; ah.ID = 0; SucessResult sucessResult = new SucessResult(); var tes = repositury.CreateAccountHistory(ah); if (tes.Item2 != "OK") { sucessResult.Status = tes.Item2; sucessResult.Result = "Контрагент не создан"; } else { sucessResult.Status = tes.Item2; sucessResult.Result = tes.Item1.ToString(); } object result = JsonConvert.SerializeObject(sucessResult); return(result); }
public void EmptyCheckCount() { var toTest = new AccountHistory(); Assert.AreEqual(0, toTest.Count); }
public IActionResult GetHistory(string walletName, string address) { if (string.IsNullOrWhiteSpace(walletName)) { return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "No wallet name", "No wallet name provided")); } if (string.IsNullOrWhiteSpace(address)) { return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "No address", "No address provided")); } try { var transactionItems = new List <ContractTransactionItem>(); HdAccount account = this.walletManager.GetAccounts(walletName).First(); // Get a list of all the transactions found in an account (or in a wallet if no account is specified), with the addresses associated with them. IEnumerable <AccountHistory> accountsHistory = this.walletManager.GetHistory(walletName, account.Name); // Wallet manager returns only 1 when an account name is specified. AccountHistory accountHistory = accountsHistory.First(); List <FlatHistory> items = accountHistory.History.OrderByDescending(o => o.Transaction.CreationTime).Where(x => x.Address.Address == address).ToList(); // Represents a sublist of transactions associated with receive addresses + a sublist of already spent transactions associated with change addresses. // In effect, we filter out 'change' transactions that are not spent, as we don't want to show these in the history. List <FlatHistory> history = items.Where(t => !t.Address.IsChangeAddress() || (t.Address.IsChangeAddress() && t.Transaction.IsSpent())).ToList(); foreach (FlatHistory item in history) { TransactionData transaction = item.Transaction; // Record a receive transaction transactionItems.Add(new ContractTransactionItem { Amount = transaction.Amount.ToUnit(MoneyUnit.Satoshi), BlockHeight = transaction.BlockHeight, Hash = transaction.Id, Type = ReceivedTransactionType(transaction), To = address }); // Add outgoing transaction details if (transaction.SpendingDetails != null) { // Get if it's an SC transaction PaymentDetails scPayment = transaction.SpendingDetails.Payments?.FirstOrDefault(x => x.DestinationScriptPubKey.IsSmartContractExec()); if (scPayment != null) { if (scPayment.DestinationScriptPubKey.IsSmartContractCreate()) { // Create a record for a Create transaction Receipt receipt = this.receiptRepository.Retrieve(transaction.SpendingDetails.TransactionId); transactionItems.Add(new ContractTransactionItem { Amount = scPayment.Amount.ToUnit(MoneyUnit.Satoshi), BlockHeight = transaction.SpendingDetails.BlockHeight, Type = ContractTransactionItemType.ContractCreate, Hash = transaction.SpendingDetails.TransactionId, To = receipt?.NewContractAddress?.ToBase58Address(this.network) ?? "" }); } else { // Create a record for a Call transaction Result <ContractTxData> txData = this.callDataSerializer.Deserialize(scPayment.DestinationScriptPubKey.ToBytes()); transactionItems.Add(new ContractTransactionItem { Amount = scPayment.Amount.ToUnit(MoneyUnit.Satoshi), BlockHeight = transaction.SpendingDetails.BlockHeight, Type = ContractTransactionItemType.ContractCall, Hash = transaction.SpendingDetails.TransactionId, To = txData.Value.ContractAddress.ToBase58Address(this.network) }); } } else { // Create a record for every external payment sent if (transaction.SpendingDetails.Payments != null) { foreach (PaymentDetails payment in transaction.SpendingDetails.Payments) { transactionItems.Add(new ContractTransactionItem { Amount = payment.Amount.ToUnit(MoneyUnit.Satoshi), BlockHeight = transaction.SpendingDetails.BlockHeight, Type = ContractTransactionItemType.Send, Hash = transaction.SpendingDetails.TransactionId, To = payment.DestinationAddress }); } } } } } return(this.Json(transactionItems.OrderByDescending(x => x.BlockHeight ?? Int32.MaxValue).ThenBy(x => x.Hash.ToString()))); } catch (Exception e) { this.logger.LogError("Exception occurred: {0}", e.ToString()); return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString())); } }
private void AddHistory(Account account) { AccountHistory accountHistory = _mapper.Map <AccountHistory>(account); _unitOfWork.AccountHistory.Add(accountHistory); }
public ActionResult SaveAccount(Account account) { try { if (account.AccountId == Numbers.Zero) { var typeCode = (AccountType)AppCache.Instance.AccountTypes.FirstOrDefault(t => ((AccountType)t).AccountTypeId == account.AccountTypeId); var lastAccount = db.Accounts.Where(a => a.AccountTypeId == account.AccountTypeId). OrderByDescending(a => a.Sequential).FirstOrDefault(); var sequential = lastAccount != null ? lastAccount.Sequential + Numbers.One : Numbers.One; account.Sequential = sequential; account.Code = string.Format(Formats.AccoutMask, typeCode.Code, sequential.ToString(Formats.Sequential)); account.AccountStatusId = Common.Enums.StatusAccount.Active; account.HasMaintenance = (account.MaintPeriodId > Numbers.Zero); account.HasPolicy = (account.PaymentPeriodId > Numbers.Zero); account.CutOffDate = DateTime.Now.ToLocal(); account.Occurences = TaskManager.Instance.CreateOccerrences(account); db.Accounts.Add(account); } else { var original = db.Accounts.FirstOrDefault(a => a.AccountId == account.AccountId); var history = new AccountHistory { InsDate = original.UpdDate, InsUser = original.UpdUser, AccountId = original.AccountId, Comment = original.Comment, HasMaintenance = original.HasMaintenance, HasPolicy = original.HasPolicy, MaintenancePeriod = original.MaintPeriodId, PaymentPeriod = original.PaymentPeriodId, PolicyCost = original.PolicyCost, Status = original.AccountStatus.Name }; db.AccountHistories.Add(history); original.Comment = account.Comment; original.PaymentPeriodId = account.PaymentPeriodId; original.MaintPeriodId = account.MaintPeriodId; original.PolicyCost = account.PolicyCost; original.UpdDate = DateTime.Now.ToLocal(); original.UpdUser = HttpContext.User.Identity.Name; db.Entry(original); } db.SaveChanges(); return(Json(new JResponse { Code = Responses.Codes.Success, Result = Responses.Success, Id = account.AccountId })); } catch (Exception ex) { db.ErrorLogs.Add(new ErrorLog { Action = "SaveAccount", Controller = GetType().Name, Description = ex.Message }); db.SaveChanges(); return(Json(new JResponse { Code = Argos.Common.Constants.Responses.Codes.ServerError, Result = Argos.Common.Constants.Responses.Danger, Body = "Detalle del error:" + ex.InnerException ?? ex.Message, Header = "Error al guardar los datos" })); } }
public static void Approve(List <GLBudgetLine> list) { bool anyFailed = false; GLBudgetEntry graph = PXGraph.CreateInstance <GLBudgetEntry>(); graph.Views.Caches.Add(typeof(AccountHistory)); for (int i = 0; i < list.Count; i++) { try { GLBudgetLine article = list[i]; Ledger ledger = PXSelect <Ledger, Where <Ledger.ledgerID, Equal <Required <Ledger.ledgerID> > > > .Select(graph, article.LedgerID); if (article.AllocatedAmount != article.Amount) { PXProcessing <GLBudgetLine> .SetError(i, Messages.BudgetArticleIsNotAllocatedProperly); anyFailed = true; continue; } Account acct = PXSelect <Account, Where <Account.accountID, Equal <Required <Account.accountID> > > > .Select(graph, article.AccountID); foreach (GLBudgetLineDetail alloc in PXSelect <GLBudgetLineDetail, Where <GLBudgetLineDetail.ledgerID, Equal <Required <GLBudgetLineDetail.ledgerID> >, And <GLBudgetLineDetail.branchID, Equal <Required <GLBudgetLineDetail.branchID> >, And <GLBudgetLineDetail.finYear, Equal <Required <GLBudgetLineDetail.finYear> >, And <GLBudgetLineDetail.accountID, Equal <Required <GLBudgetLineDetail.accountID> >, And <GLBudgetLineDetail.subID, Equal <Required <GLBudgetLineDetail.subID> > > > > > > > .Select(graph, article.LedgerID, article.BranchID, article.FinYear, article.AccountID, article.SubID)) { decimal delta = (decimal)((alloc.Amount ?? 0m) - (alloc.ReleasedAmount ?? 0m)); if (delta != 0m) { AccountHistory accthist = new AccountHistory { BranchID = alloc.BranchID, AccountID = alloc.AccountID, FinPeriodID = alloc.FinPeriodID, LedgerID = alloc.LedgerID, SubID = alloc.SubID, CuryID = null, BalanceType = ledger.BalanceType }; accthist = (AccountHistory)graph.Caches[typeof(AccountHistory)].Insert(accthist); if (accthist == null) { PXProcessing <GLBudgetLine> .SetError(i, Messages.BudgetApproveUnexpectedError); anyFailed = true; } else { accthist.YtdBalance += delta; accthist.CuryFinYtdBalance = accthist.YtdBalance; accthist.TranYtdBalance += delta; accthist.CuryTranYtdBalance = accthist.TranYtdBalance; if (acct.Type == AccountType.Asset || acct.Type == AccountType.Expense) { accthist.FinPtdDebit += delta; accthist.CuryFinPtdDebit = accthist.FinPtdDebit; accthist.TranPtdDebit += delta; accthist.CuryTranPtdDebit = accthist.TranPtdDebit; //accthist.FinPtdCredit += 0; accthist.CuryFinPtdCredit = accthist.FinPtdCredit; //accthist.TranPtdCredit += 0; accthist.CuryTranPtdCredit = accthist.TranPtdCredit; } else { accthist.FinPtdCredit += delta; accthist.CuryFinPtdCredit = accthist.FinPtdCredit; accthist.TranPtdCredit += delta; accthist.CuryTranPtdCredit = accthist.TranPtdCredit; //accthist.FinPtdDebit += 0; accthist.CuryFinPtdDebit = accthist.FinPtdDebit; //accthist.TranPtdDebit += 0; accthist.CuryTranPtdDebit = accthist.TranPtdDebit; } } } alloc.ReleasedAmount = alloc.Amount; graph.Caches[typeof(GLBudgetLineDetail)].Update(alloc); } article.ReleasedAmount = article.Amount; article.Released = true; graph.Caches[typeof(GLBudgetLine)].Update(article); PXProcessing <GLBudgetLine> .SetInfo(i, ActionsMessages.RecordProcessed); } catch (Exception e) { PXProcessing <GLBudgetLine> .SetError(i, e.Message); throw; } } graph.Save.Press(); if (anyFailed) { throw new PXException(Messages.BudgetItemsApprovalFailure); } }
public IActionResult GetHistory(string walletName, string address) { if (string.IsNullOrWhiteSpace(walletName)) { return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "No wallet name", "No wallet name provided")); } if (string.IsNullOrWhiteSpace(address)) { return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "No address", "No address provided")); } try { var transactionItems = new List <ContractTransactionItem>(); HdAccount account = this.walletManager.GetAccounts(walletName).First(); // Get a list of all the transactions found in an account (or in a wallet if no account is specified), with the addresses associated with them. IEnumerable <AccountHistory> accountsHistory = this.walletManager.GetHistory(walletName, account.Name); // Wallet manager returns only 1 when an account name is specified. AccountHistory accountHistory = accountsHistory.First(); List <FlatHistory> items = accountHistory.History.Where(x => x.Address.Address == address).ToList(); // Represents a sublist of transactions associated with receive addresses + a sublist of already spent transactions associated with change addresses. // In effect, we filter out 'change' transactions that are not spent, as we don't want to show these in the history. List <FlatHistory> history = items.Where(t => !t.Address.IsChangeAddress() || (t.Address.IsChangeAddress() && t.Transaction.IsSpent())).ToList(); // TransactionData in history is confusingly named. A "TransactionData" actually represents an input, and the outputs that spend it are "SpendingDetails". // There can be multiple "TransactionData" which have the same "SpendingDetails". // For SCs we need to group spending details by their transaction ID, to get all the inputs related to the same outputs. // Each group represents 1 SC transaction. // Each item.Transaction in a group is an input. // Each item.Transaction.SpendingDetails in the group represent the outputs, and they should all be the same so we can pick any one. var scTransactions = history .Where(item => item.Transaction.SpendingDetails != null) .Where(item => item.Transaction.SpendingDetails.Payments.Any(x => x.DestinationScriptPubKey.IsSmartContractExec())) .GroupBy(item => item.Transaction.SpendingDetails.TransactionId) .Select(g => new { TransactionId = g.Key, InputAmount = g.Sum(i => i.Transaction.Amount), // Sum the inputs to the SC transaction. Outputs = g.First().Transaction.SpendingDetails.Payments, // Each item in the group will have the same outputs. OutputAmount = g.First().Transaction.SpendingDetails.Payments.Sum(o => o.Amount), BlockHeight = g.First().Transaction.SpendingDetails.BlockHeight // Each item in the group will have the same block height. }) .ToList(); foreach (var scTransaction in scTransactions) { // Consensus rules state that each transaction can have only one smart contract exec output, so FirstOrDefault is correct. PaymentDetails scPayment = scTransaction.Outputs?.FirstOrDefault(x => x.DestinationScriptPubKey.IsSmartContractExec()); if (scPayment == null) { continue; } Receipt receipt = this.receiptRepository.Retrieve(scTransaction.TransactionId); Result <ContractTxData> txDataResult = this.callDataSerializer.Deserialize(scPayment.DestinationScriptPubKey.ToBytes()); if (txDataResult.IsFailure) { continue; } ContractTxData txData = txDataResult.Value; // If the receipt is not available yet, we don't know how much gas was consumed so use the full gas budget. ulong gasFee = receipt != null ? receipt.GasUsed * receipt.GasPrice : txData.GasCostBudget; long totalFees = scTransaction.InputAmount - scTransaction.OutputAmount; Money transactionFee = Money.FromUnit(totalFees, MoneyUnit.Satoshi) - Money.FromUnit(txData.GasCostBudget, MoneyUnit.Satoshi); var result = new ContractTransactionItem { Amount = scPayment.Amount.ToUnit(MoneyUnit.Satoshi), BlockHeight = scTransaction.BlockHeight, Hash = scTransaction.TransactionId, TransactionFee = transactionFee.ToUnit(MoneyUnit.Satoshi), GasFee = gasFee }; if (scPayment.DestinationScriptPubKey.IsSmartContractCreate()) { result.Type = ContractTransactionItemType.ContractCreate; result.To = receipt?.NewContractAddress?.ToBase58Address(this.network) ?? string.Empty; } else if (scPayment.DestinationScriptPubKey.IsSmartContractCall()) { result.Type = ContractTransactionItemType.ContractCall; result.To = txData.ContractAddress.ToBase58Address(this.network); } transactionItems.Add(result); } return(this.Json(transactionItems.OrderByDescending(x => x.BlockHeight ?? Int32.MaxValue))); } catch (Exception e) { this.logger.LogError("Exception occurred: {0}", e.ToString()); return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString())); } }
public IActionResult GetHistory(GetHistoryRequest request) { if (string.IsNullOrWhiteSpace(request.WalletName)) { return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "No wallet name", "No wallet name provided")); } if (string.IsNullOrWhiteSpace(request.Address)) { return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "No address", "No address provided")); } try { var transactionItems = new List <ContractTransactionItem>(); HdAccount account = this.walletManager.GetAccounts(request.WalletName).First(); // Get a list of all the transactions found in an account (or in a wallet if no account is specified), with the addresses associated with them. IEnumerable <AccountHistory> accountsHistory = this.walletManager.GetHistory(request.WalletName, account.Name, null, offset: request.Skip ?? 0, limit: request.Take ?? int.MaxValue, accountAddress: request.Address, forSmartContracts: true); // Wallet manager returns only 1 when an account name is specified. AccountHistory accountHistory = accountsHistory.First(); var scTransactions = accountHistory.History.Select(h => new { TransactionId = uint256.Parse(h.Id), Fee = h.Fee, SendToScriptPubKey = Script.FromHex(h.SendToScriptPubkey), OutputAmount = h.Amount, BlockHeight = h.BlockHeight }).ToList(); // Get all receipts in one transaction IList <Receipt> receipts = this.receiptRepository.RetrieveMany(scTransactions.Select(x => x.TransactionId).ToList()); for (int i = 0; i < scTransactions.Count; i++) { var scTransaction = scTransactions[i]; Receipt receipt = receipts[i]; // This will always give us a value - the transaction has to be serializable to get past consensus. Result <ContractTxData> txDataResult = this.callDataSerializer.Deserialize(scTransaction.SendToScriptPubKey.ToBytes()); ContractTxData txData = txDataResult.Value; // If the receipt is not available yet, we don't know how much gas was consumed so use the full gas budget. ulong gasFee = receipt != null ? receipt.GasUsed * receipt.GasPrice : txData.GasCostBudget; long totalFees = scTransaction.Fee; Money transactionFee = Money.FromUnit(totalFees, MoneyUnit.Satoshi) - Money.FromUnit(txData.GasCostBudget, MoneyUnit.Satoshi); var result = new ContractTransactionItem { Amount = new Money(scTransaction.OutputAmount).ToUnit(MoneyUnit.Satoshi), BlockHeight = scTransaction.BlockHeight, Hash = scTransaction.TransactionId, TransactionFee = transactionFee.ToUnit(MoneyUnit.Satoshi), GasFee = gasFee }; if (scTransaction.SendToScriptPubKey.IsSmartContractCreate()) { result.Type = ContractTransactionItemType.ContractCreate; result.To = receipt?.NewContractAddress?.ToBase58Address(this.network) ?? string.Empty; } else if (scTransaction.SendToScriptPubKey.IsSmartContractCall()) { result.Type = ContractTransactionItemType.ContractCall; result.To = txData.ContractAddress.ToBase58Address(this.network); } transactionItems.Add(result); } return(this.Json(transactionItems.OrderByDescending(x => x.BlockHeight ?? int.MaxValue))); } catch (Exception e) { this.logger.LogError("Exception occurred: {0}", e.ToString()); return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString())); } }
/// <summary> /// Displays the item information and item data information /// for the given bank itemSummary. /// </summary> /// <param name="itemSummary">an itemSummary whose containerType is 'bank'</param> public void displayBankDataForItem(ItemSummary itemSummary) { System.Console.WriteLine(""); String containerType = itemSummary.contentServiceInfo.containerInfo.containerName; if (!containerType.Equals("bank")) { throw new Exception("displayBankDataForItem called with invalid container type" + containerType); } DisplayItemInfo displayItemInfo = new DisplayItemInfo(); displayItemInfo.displayItemSummaryInfo(itemSummary); // Get ItemData ItemData1 itemData = itemSummary.itemData; if (itemData == null) { System.Console.WriteLine("\tItemData is null"); } else { object[] accounts = itemData.accounts; if (accounts == null || accounts.Length == 0) { System.Console.WriteLine("\tNo accounts"); } else { for (int i = 0; i < accounts.Length; i++) { System.Console.WriteLine("\n\t\t**BankData**"); BankData bankData = (BankData)accounts[i]; System.Console.WriteLine("\t\tBank Account Name: {0}", bankData.accountName); System.Console.WriteLine("\t\tBank Account Cust Description: {0}", bankData.customDescription); System.Console.WriteLine("\t\tBank Account Identifier: {0}", bankData.bankAccountId); System.Console.WriteLine("\t\tBank Account Balance: {0}", bankData.availableBalance.amount); System.Console.WriteLine("\t\tBank Current Balance: {0}", bankData.currentBalance.amount); System.Console.WriteLine("\t\tBank Current Acct Type: {0}", bankData.acctType); System.Console.WriteLine("\t\tBank Current As of Date: {0}", bankData.asOfDate.date); // BankTransactionData object[] bankTransactions = bankData.bankTransactions; if (bankTransactions == null || bankTransactions.Length == 0) { System.Console.WriteLine("\t\tNo bank transactions"); } else { System.Console.WriteLine("\n\t\t**BankTransactionData**"); for (int j = 0; j < bankTransactions.Length; j++) { BankTransactionData transactionData = (BankTransactionData)bankTransactions[j]; System.Console.WriteLine("\t\t\tTransaction Id: {0}", transactionData.bankTransactionId); System.Console.WriteLine("\t\t\tTransaction Description: {0}", transactionData.description); System.Console.WriteLine("\t\t\tTransaction Amount: {0}", transactionData.transactionAmount.amount); System.Console.WriteLine("\t\t\tTransaction Base Type: {0}", transactionData.transactionBaseType); System.Console.WriteLine("\t\t\tCategory: {0}", transactionData.category); System.Console.WriteLine(""); } } System.Console.WriteLine(""); } } } // Get AccountHistory object[] acctHistories = itemData.accountHistory; if (acctHistories == null || acctHistories.Length == 0) { System.Console.WriteLine("\tNo Account History"); } else { System.Console.WriteLine("\n\t**Account History**"); for (int i = 0; i < acctHistories.Length; i++) { AccountHistory acctHistory = (AccountHistory)acctHistories[i]; System.Console.WriteLine("\tAccount ID: {0}", acctHistory.accountId); // Get History object[] histories = acctHistory.history; if (histories == null || histories.Length == 0) { System.Console.WriteLine("\t\tNo History"); } else { System.Console.WriteLine("\t\t**History**"); for (int j = 0; j < histories.Length; j++) { BankData bankData = (BankData)histories[j]; System.Console.WriteLine("\t\tBank Account Name: {0}", bankData.accountName); System.Console.WriteLine("\t\tBank Account Cust Description: {0}", bankData.customDescription); System.Console.WriteLine("\t\tBank Account Identifier: {0}", bankData.bankAccountId); System.Console.WriteLine("\t\tBank Account Balance: {0}", bankData.availableBalance.amount); System.Console.WriteLine("\t\tBank Current Balance: {0}", bankData.currentBalance.amount); System.Console.WriteLine("\t\tBank Current Acct Type: {0}", bankData.acctType); System.Console.WriteLine("\t\tBank Current As of Date: {0}", bankData.asOfDate.date); System.Console.WriteLine("\t\tLast Updated: {0}\n", UtcToDateTime(bankData.lastUpdated.Value)); } } } } }
private void SyncAccountsWork(object sender, DoWorkEventArgs e) { ProgressVisibility = true; ProgressChanged(null, new ProgressChangedEventArgs(10, e)); // TODO: Does this block of code need to be pulled out and refactored? // Prompt for manual values var runId = _dataAccess.GetNextRunId(); var accounts = _dataAccess.GetList <Account>(); var manualAccounts = accounts.FindAll(m => m.IsManual == true); List <AccountHistory> manualAccountHistory = new List <AccountHistory>(); foreach (var account in manualAccounts) { AccountHistory accountHistory = new AccountHistory(); accountHistory.AccountId = account.ObjectId; accountHistory.AsOfDate = DateTime.Now; accountHistory.RunId = runId; var type = account.AccountMappings.FirstOrDefault(); if (type.AccountType.AccountTypeName == "Physical") { PreciousMetalsView preciousMetalsView = new PreciousMetalsView(); PreciousMetalsViewModel preciousMetalsViewModel = new PreciousMetalsViewModel(runId); preciousMetalsView.DataContext = preciousMetalsViewModel; preciousMetalsView.ShowDialog(); accountHistory.Amount = preciousMetalsViewModel.GetTotals(); } else { ManualAccountView view = new ManualAccountView(); ManualAccountViewModel model = new ManualAccountViewModel(); view.DataContext = model; model.AccountName = account.AccountName; var previousHistory = _dataAccess.GetList <AccountHistory>().Where(a => a.AccountId == account.ObjectId).OrderByDescending(r => r.RunId).FirstOrDefault(); if (previousHistory != null) { model.Value = previousHistory.Amount; } view.ShowDialog(); accountHistory.Amount = model.Value; } manualAccountHistory.Add(accountHistory); } ProgressChanged(null, new ProgressChangedEventArgs(20, e)); CallSyncAccounts(manualAccountHistory); ProgressChanged(null, new ProgressChangedEventArgs(90, e)); RefreshAccountInfo(); ProgressChanged(null, new ProgressChangedEventArgs(100, e)); ProgressVisibility = false; }
public bool InsertAccountHistory(AccountHistory accounHistory) { dbContext.AccountHistorys.Add(accounHistory); return(true); }
public static void Approve(List <GLBudgetLine> list) { bool anyFailed = false; bool lineFailed = false; GLBudgetEntry graph = PXGraph.CreateInstance <GLBudgetEntry>(); graph.Views.Caches.Add(typeof(AccountHistory)); PXCache <AccountHistory> cacheAccountHistory = graph.Caches <AccountHistory>(); PXCache <GLBudgetLine> cacheGLBudgetLine = graph.Caches <GLBudgetLine>(); PXCache <GLBudgetLineDetail> cacheGLBudgetLineDetail = graph.Caches <GLBudgetLineDetail>(); for (int i = 0; i < list.Count; i++) { try { lineFailed = false; GLBudgetLine article = list[i]; Ledger ledger = PXSelect <Ledger, Where <Ledger.ledgerID, Equal <Required <Ledger.ledgerID> > > > .Select(graph, article.LedgerID); if (article.AllocatedAmount != article.Amount) { PXProcessing <GLBudgetLine> .SetError(i, Messages.BudgetArticleIsNotAllocatedProperly); anyFailed = true; continue; } Account acct = PXSelect <Account, Where <Account.accountID, Equal <Required <Account.accountID> > > > .Select(graph, article.AccountID); PXResultset <GLBudgetLineDetail> allocations = PXSelect < GLBudgetLineDetail, Where <GLBudgetLineDetail.ledgerID, Equal <Required <GLBudgetLineDetail.ledgerID> >, And <GLBudgetLineDetail.branchID, Equal <Required <GLBudgetLineDetail.branchID> >, And <GLBudgetLineDetail.finYear, Equal <Required <GLBudgetLineDetail.finYear> >, And <GLBudgetLineDetail.groupID, Equal <Required <GLBudgetLineDetail.groupID> > > > > > > .Select(graph, article.LedgerID, article.BranchID, article.FinYear, article.GroupID); ProcessingResult validateFinPeriodsResult = ValidateFinPeriods(graph, allocations.Select(record => (GLBudgetLineDetail)record)); if (!validateFinPeriodsResult.IsSuccess) { PXProcessing <GLBudgetLine> .SetError(i, validateFinPeriodsResult.GetGeneralMessage()); anyFailed = true; continue; } List <AccountHistory> listHistory = new List <AccountHistory>(); foreach (GLBudgetLineDetail alloc in allocations) { decimal delta = (decimal)((alloc.Amount ?? 0m) - (alloc.ReleasedAmount ?? 0m)); if (delta != 0m) { AccountHistory accthist = new AccountHistory { BranchID = alloc.BranchID, AccountID = alloc.AccountID, FinPeriodID = alloc.FinPeriodID, LedgerID = alloc.LedgerID, SubID = alloc.SubID, CuryID = null, BalanceType = ledger.BalanceType }; accthist = (AccountHistory)cacheAccountHistory.Insert(accthist); if (accthist == null) { PXProcessing <GLBudgetLine> .SetError(i, Messages.BudgetApproveUnexpectedError); lineFailed = true; break; } else { accthist.YtdBalance += delta; accthist.CuryFinYtdBalance = accthist.YtdBalance; accthist.TranYtdBalance += delta; accthist.CuryTranYtdBalance = accthist.TranYtdBalance; if (acct.Type == AccountType.Asset || acct.Type == AccountType.Expense) { accthist.FinPtdDebit += delta; accthist.CuryFinPtdDebit = accthist.FinPtdDebit; accthist.TranPtdDebit += delta; accthist.CuryTranPtdDebit = accthist.TranPtdDebit; //accthist.FinPtdCredit += 0; accthist.CuryFinPtdCredit = accthist.FinPtdCredit; //accthist.TranPtdCredit += 0; accthist.CuryTranPtdCredit = accthist.TranPtdCredit; } else { accthist.FinPtdCredit += delta; accthist.CuryFinPtdCredit = accthist.FinPtdCredit; accthist.TranPtdCredit += delta; accthist.CuryTranPtdCredit = accthist.TranPtdCredit; //accthist.FinPtdDebit += 0; accthist.CuryFinPtdDebit = accthist.FinPtdDebit; //accthist.TranPtdDebit += 0; accthist.CuryTranPtdDebit = accthist.TranPtdDebit; } listHistory.Add(accthist); } } } anyFailed = (anyFailed || lineFailed); if (lineFailed) { foreach (AccountHistory accthist in listHistory) { cacheAccountHistory.Remove(accthist); } continue; } foreach (GLBudgetLineDetail alloc in allocations) { alloc.ReleasedAmount = alloc.Amount; cacheGLBudgetLineDetail.Update(alloc); } article.ReleasedAmount = article.Amount; article.Released = true; article.WasReleased = true; cacheGLBudgetLine.Update(article); PXProcessing <GLBudgetLine> .SetInfo(i, ActionsMessages.RecordProcessed); } catch (Exception e) { PXProcessing <GLBudgetLine> .SetError(i, e.Message); throw; } } graph.Save.Press(); if (anyFailed) { throw new PXException(Messages.BudgetItemsApprovalFailure); } }