public void CountWorkTimeThisMonth() { List <ClockInOut> dataIn = new List <ClockInOut> { new ClockInOut { UserId = 1, Date = new DateTime(2020, DateTime.UtcNow.Month, 19, 9, 10, 0), Type = ClockType.In }, }; List <ClockInOut> dataOut = new List <ClockInOut> { new ClockInOut { UserId = 1, Date = new DateTime(2020, DateTime.UtcNow.Month, 19, 11, 20, 0), Type = ClockType.Out } }; BalanceDto result = CountBalance.CountWorkTimeCurrent(dataIn, dataOut); result.HoursWorked.Should().Be(2); result.MinutesWorked.Should().Be(10); }
public async Task <Result> Modify(RechargeDto dto, string opt) { var redis = ObjectContainer.Resolve <RedisHelper>(); var balance = ObjectContainer.Resolve <IBalanceService>(); var obj = ObjectContainer.Resolve <IRechargeService>(); var b = new BalanceDto { Bank = dto.Bank, RechargeMode = dto.RechargeMode, SalesMan = dto.SalesMan, UserId = dto.UserId, Value = dto.Value, Money = dto.Money, OperatorId = LoginInfo.Id, ModifyDate = DateTime.Now, Remark = dto.Remark, TradeResult = TradeResult.Success, TradeType = TradeType.Offline, IdenTity = IdenTity.Server }; if (opt == "add") { await balance.Rechange(b, LoginInfo.Role); await redis.StringGetAsync(RedisKeyName.CreateUserAmountKey(dto.UserId)); await redis.StringIncrementAsync(RedisKeyName.CreateUserAmountKey(dto.UserId), dto.Value); return(new Result { Status = true }); } return(await Task.Run(() => obj.Update(dto))); }
public void CountWorkTime_UserWorks2HoursAnd10MinutesInTheSameDay_ReturnCorrectAmountOfHoursAndMinutes() { List <ClockInOut> dataIn = new List <ClockInOut> { new ClockInOut { UserId = 1, Date = new DateTime(2020, 08, 19, 9, 10, 0), Type = ClockType.In }, }; List <ClockInOut> dataOut = new List <ClockInOut> { new ClockInOut { UserId = 1, Date = new DateTime(2020, 08, 19, 11, 20, 0), Type = ClockType.Out } }; BalanceDto result = CountBalance.CountWorkTime(dataIn, dataOut); result.HoursWorked.Should().Be(2); result.MinutesWorked.Should().Be(10); result.HoursLeft.Should().Be(157); result.MinutesLeft.Should().Be(50); }
public static BalanceDto getBalanceDTO(TraceWriter logger) { BalanceDto dto = null; string result = getBalance().Result; if (deserialization["balance"] == "application/json") { try { dto = JsonConvert.DeserializeObject <BalanceDto>(result); } catch (Exception) { logger.Info("An unexpected error was occured when we tried to deserialize the response."); } } else { try { logger.Info("The deserialization was made from XML"); XmlSerializer serializer = new XmlSerializer(typeof(BalanceDto)); using (TextReader reader = new StringReader(result)) { dto = (BalanceDto)serializer.Deserialize(reader); } } catch (Exception) { logger.Info("An unexpected error was occured when we tried to deserialize the response."); } } return(dto); }
public async Task AddMember_Database_Call_Is_Made_Once() { // Arrange var cardId = "ByDJ0lbYcPkzp2Ja"; var newAmount = new AdjustAmount { CardId = cardId, Amount = 10 }; var newBalance = new BalanceDto() { Balance = 10 }; var transactionRepo = new Mock <ITransactionsRepository>(); transactionRepo.Setup(x => x.AddAmount(newAmount)).Returns(newBalance); // Act var transactionService = new TransactionService(transactionRepo.Object); var result = transactionService.AddAmount(newAmount); // Assert transactionRepo.Verify(x => x.AddAmount(newAmount), Times.Once); }
public IActionResult Balance(BalanceDto dto) { // if valid ... dto.ShouldCheckBalance = true; this.TempData[TempDataKeys.BalanceDto] = JsonConvert.SerializeObject(dto); return(this.RedirectToAction(nameof(this.Balance))); }
public async Task AddAmount_Controller_Action_Returns_BadRequest_If_Amendment_Fails() { // Arrange var cardId = "ByDJ0lbYcPkzp2Ja"; var newAmount = new AdjustAmount { CardId = cardId, Amount = 10 }; var newBalance = new BalanceDto() { Balance = 10 }; var transactionService = new Mock <ITransactionService>(); transactionService.Setup(x => x.AddAmount(It.IsAny <AdjustAmount>())).Returns(() => null); // Act var controller = new TransactionController(transactionService.Object); var result = (StatusCodeResult)controller.AddAmount(newAmount); // Assert Assert.Equal(StatusCodes.Status400BadRequest, result.StatusCode); }
public async Task AddAmount_Controller_Action_Returns_Latest_Balance_When_Amount_Added() { // Arrange var cardId = "ByDJ0lbYcPkzp2Ja"; var newAmount = new AdjustAmount { CardId = cardId, Amount = 10 }; var newBalance = new BalanceDto() { Balance = 10 }; var transactionService = new Mock <ITransactionService>(); transactionService.Setup(x => x.AddAmount(newAmount)).Returns(newBalance); // Act var controller = new TransactionController(transactionService.Object); var result = controller.AddAmount(newAmount); var resultMember = (CreatedAtActionResult)result; // Assert Assert.Equal(newBalance, resultMember.Value); }
private bool HasBalance(BalanceDto balance, int cardId, decimal cost) { if (balance == null) { return(false); } return(balance.Balance >= cost); }
public BalanceEntity MapFromBalanceDtoToBalanceEntity(BalanceDto dto) { return(new BalanceEntity() { BalanceId = dto.BalanceId, Balance = dto.Balance, CardId = dto.CardId }); }
public static void AssertStateIsValid(this BalanceDto balance) { balance.Should().NotBeNull(); balance.CurrencyType.Should().NotBeNull(); (balance.Available >= DecimalValue.FromDecimal(decimal.Zero)).Should().BeTrue(); (balance.Pending >= DecimalValue.FromDecimal(decimal.Zero)).Should().BeTrue(); }
public async Task recharge(BalanceDto dto, UserType roleId) { var rechangeEntity = dto.MapTo <RechargeEntity>(); var id = _rechangeRpo.InsertAndGetId(rechangeEntity); var orgId = _staffRepository.GetOrgId(dto.SalesMan).OrgId; var dataInOrg = new DataInOrgEntity { DataId = id.ToString(), DataType = (int)DataType.Recharge, OrgId = orgId, RoleId = ((int)roleId).ToString() }; _dataInOrgRepository.Inserts(dataInOrg); }
public async Task CreateBalance(int?tenantId, long userId, BalanceDto data) { var balance = _mapper.Map <Balance>(data); if (!string.IsNullOrEmpty(data.BalanceDate)) { balance.BalanceDate = Convert.ToDateTime(data.BalanceDate); } balance.Code = Constants.GenerateCode(); balance.CreatedDate = DateTime.Now; balance.UserModifiedId = userId; balance.TenantId = tenantId.Value; _unitOfWork.BalanceRepository.Create(balance); await _unitOfWork.Commit(); }
public async Task balance(BalanceDto dto, UserType roleId) { var entity = dto.MapTo <BalanceEntity>(); await _repo.ChangeBalance(entity); var orgId = _staffRepository.GetOrgId(dto.SalesMan).OrgId; var dataInOrg = new DataInOrgEntity { DataId = dto.UserId, DataType = (int)DataType.Balance, OrgId = orgId, RoleId = ((int)roleId).ToString() }; _dataInOrgRepository.Inserts(dataInOrg); }
/// <summary> /// Обновление баланса /// </summary> /// <param name="item">BalanceDto</param> public async Task <(bool, string)> UpdateAsync(BalanceDto item) { try { if (!await ExistAsync(item.Id)) { return(false, "Попытка отредактировать в БД несуществующий баланс"); } _instanceDb.Balances.Update(item.Id, Mapper.Map <BalanceDto, Balance>(item)); return(true, string.Empty); } catch (Exception e) { return(false, e.Message); } }
/// <summary> /// Добавление баланса в БД /// </summary> /// <param name="item">Баланс</param> public async Task <(bool, string)> AddAsync(BalanceDto item) { try { if (await ExistAsync(item)) { return(false, "Попытка добавить в БД уже существующий баланс."); } _instanceDb.Balances.Create(Mapper.Map <BalanceDto, Balance>(item)); return(true, string.Empty); } catch (Exception e) { return(false, e.Message); } }
public IActionResult Balance() { var dtoAsStr = this.TempData[TempDataKeys.BalanceDto] as string; BalanceDto dto = null; if (string.IsNullOrWhiteSpace(dtoAsStr)) { dto = new BalanceDto(); } else { dto = JsonConvert.DeserializeObject <BalanceDto>(dtoAsStr); } return(this.View(dto)); }
/// <summary> /// 充值1,扣费-1 /// </summary> /// <param name="dto"></param> /// <returns></returns> public async Task Rechange(BalanceDto dto, UserType roleId) { try { UnitOfWorkService.ExecuteNonQuery(async() => { await balance(dto, roleId); await recharge(dto, roleId); }); await Task.CompletedTask; } catch (Exception ex) { Logger.Error("充值错误", ex); await Task.CompletedTask; } }
public void CloseCurrentDayToCalculateBalance() { List <ClockInOut> dataIn = new List <ClockInOut> { new ClockInOut { UserId = 1, Date = new DateTime(2020, DateTime.UtcNow.Month, 19, 9, 10, 0), Type = ClockType.In }, }; List <ClockInOut> dataOut = new List <ClockInOut>(); BalanceDto result = CountBalance.CountWorkTimeCurrent(dataIn, dataOut); dataIn.Count.Should().Equals(dataOut.Count); }
private string SaveTransaction(PurchaseEntity purchase, CardDto card, BalanceDto balance) { var today = DateTime.Now; var transactionCode = card.Number + today.ToString("dd-MM-yyyy-HH-mm-ss"); var transaction = new TransactionDto() { Description = purchase.Description, Cost = purchase.Cost, Date = today, CardId = card.CardId, InitialBalance = balance.Balance, FinalBalance = balance.Balance - purchase.Cost, TransactionCode = transactionCode }; transactionRepository.Insert(transaction); return(transactionCode); }
// GET: Balance/Details/5 public async Task <IActionResult> Details(int?id) { if (id == null) { return(NotFound()); } BalanceDto balanceDto = new BalanceDto(); balanceDto.Balance = await _repository.Get((int)id); balanceDto.Year = await _repository.GetParentAnualBalance(balanceDto.Balance.Id); if (balanceDto == null) { return(NotFound()); } return(View(balanceDto)); }
public BalanceDto AddAmount(AdjustAmount adjustAmount) { var lastestBalance = new BalanceDto(); try { _executers.ExecuteCommand(_connStr, conn => { var addAmount = conn.Query <AdjustAmount>(_commandText.AddAmountToCard, new { TransactionId = Guid.NewGuid(), CardId = adjustAmount.CardId, Amount = adjustAmount.Amount }); }); lastestBalance = GetBalance(adjustAmount.CardId); } catch (SqlException ex) when(ex.Number == 2627 | ex.Number == 547) { return(null); } return(lastestBalance); }
public BalanceDto GetBalance(int modelId) { var sin = GetSINByModelId(modelId, s => s.Wallet, s => s.Scoring, s => s.Passport.Metatype); var insur = GetInsurance(modelId, r => r.Sku); var lics = ProductTypeEnum.Licences.ToString(); var licences = GetList <Renta>(r => r.Sku.Nomenklatura.Specialisation.ProductType.Alias == lics && r.SinId == sin.Id, r => r.Sku.Nomenklatura) .OrderByDescending(r => r.DateCreated) .GroupBy(l => l.Sku.NomenklaturaId) .Select(g => g.FirstOrDefault()?.Sku?.Name) .ToList(); var lifestyle = BillingHelper.GetLifeStyleDto(); var balance = new BalanceDto(sin) { ModelId = modelId, LifeStyle = lifestyle.GetLifeStyle(sin.Wallet).ToString(), ForecastLifeStyle = lifestyle.GetForecastLifeStyle(sin.Wallet).ToString(), Insurance = insur?.Sku?.Name ?? "нет страховки", Licenses = licences }; return(balance); }
private static void Strategy(Dictionary <string, ExchangeRateDto> exchangeRates) { BalanceDto balance = apiHandler.getBalanceDTO(logger); Dictionary <string, double> currencyBalances = new Dictionary <string, double> { { "BTC", balance.btc }, { "ETH", balance.eth }, { "XRP", balance.xrp } }; Random rnd = new Random(); foreach (var item in exchangeRates) { ExchangeRateDto dto = item.Value; //random hogy előbb eladni, vagy venni próbál //egy körben egyszerre csak eladni vagy venni tud if (dto.LastRefreshed != lastTradeDate[dto.Symbol]) { if (rnd.Next(2) == 0) { if (!SellStrategy(dto, currencyBalances, balance)) { BuyStrategy(dto, currencyBalances, balance); } } else { if (!BuyStrategy(dto, currencyBalances, balance)) { SellStrategy(dto, currencyBalances, balance); } } } else { logger.Info("The datas were not refreshed."); } } }
public BalanceDto ObtenerBalance(long numeroTarjeta) { var tarjeta = this.GetByNumeroTarjeta(numeroTarjeta); if (tarjeta != null) { var modelo = new BalanceDto() { CantidadEnCuenta = tarjeta.Monto, FechaVencimiento = tarjeta.FechaVencimiento, NumeroTarjeta = tarjeta.Numero }; this.balanceRepository.GenerarBalance(tarjeta.Id); return(modelo); } else { throw new Exception("No existe una tarjeta con el número ingresado en el sistema."); } }
/// <summary> /// Проверка наличия баланса по экземпляру /// </summary> /// <param name="item">Экземпляр баланса</param> /// <returns>bool</returns> public async Task <bool> ExistAsync(BalanceDto item) { return(await _instanceDb.Balances.ExistAsync(Mapper.Map <BalanceDto, Balance>(item))); }
private static bool BuyStrategy(ExchangeRateDto dto, Dictionary <string, double> currencyBalances, BalanceDto balance) { if (balance.usd > 0 && dto.CurrentRate < exchangeRatesAverage[dto.Symbol] * 1 - allowedDifferentePrecent) { double quantity = calculateQuantity(dto.Symbol, dto.History); double forTheLogger = quantity; if (quantity * dto.CurrentRate > balance.usd) { quantity = balance.usd / dto.CurrentRate; logger.Info("The recommended quantity for buy " + dto.Symbol + " was " + forTheLogger + ", but we didn't have enough money for that. The new quantity is " + quantity + " which is costs " + quantity * dto.CurrentRate + " usd."); } else { logger.Info("The calculated quantity for buy " + dto.Symbol + " is " + quantity + ", which is costs " + quantity * dto.CurrentRate + " usd."); } logger.Info(apiHandler.buy(dto.Symbol, quantity) + " when invoked buyCurrency method with " + dto.Symbol + " currency and " + quantity + " quantity parameters"); balance.usd -= quantity * dto.CurrentRate; lastTradeDate[dto.Symbol] = dto.LastRefreshed; calculateNeweExchangeRatesAverage(dto.Symbol, dto.CurrentRate, 1 - allowedDifferentePrecent); return(true); } return(false); }
//[Route("alinotify")] public async void AliNotify() { /* 实际验证过程建议商户添加以下校验。 * 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号, * 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额), * 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email) * 4、验证app_id是否为该商户本身。 */ var tradeResult = string.Empty; try { var sArray = GetRequestPost(); Logger.Info($"array:{sArray}"); if (sArray.Count != 0) { //var flag = AlipaySignature.RSACheckV1(sArray, Config.alipay_public_key, Config.charset, Config.sign_type, false); bool flag = _alipayService.RSACheckV1(sArray); Logger.Info($"判断异步:{flag}"); if (flag) { Logger.Info($"支付状态:{Request.Form["trade_status"]},{Request.Form["out_trade_no"]},{Request.Form["app_id"]}"); //交易状态 //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //请务必判断请求时的total_amount与通知时获取的total_fee为一致的 //如果有做过处理,不执行商户的业务程序 //注意: //退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知 string trade_status = Request.Form["trade_status"]; var out_trade_no = Request.Form["out_trade_no"]; //商户订单号 var trade_no = Request.Form["trade_no"]; //支付宝交易号 var seller_id = Request.Form["seller_id"]; //支付宝账号//卖家支付宝用户ID 2088102170353417 var total_amount = Request.Form["total_amount"]; //金额 var timestamp = Request.Form["timestamp"]; //交易时间 var value = Request.Form["value"]; //数量 var appid = Request.Form["app_id"]; //appid //根据订单号取数据 var order = _rechargeService.GetNumber(out_trade_no); var price = _prodService.GetNumber(decimal.ToInt32(Convert.ToDecimal(total_amount))).Price; //var price = _customerService.Get(LoginInfo.Id).Price;//todo:单价怎么取 var salesMan = _customerService.Get(LoginInfo.Id).SalesMan; #region switch (trade_status) { case "TRADE_FINISHED": //支付完成 case "TRADE_SUCCESS": //支付成功 //注意: //付款完成后,支付宝系统发送该交易状态通知 var app_id = _configuration.GetValue("Alipay:AppId", "2016080700188416"); Logger.Info($"appid:{app_id}"); if (app_id.Equals(appid)) //账号对比//todo:seller_id需要改 { if (order != null) //订单对比 { var balance = new BalanceDto { SalesMan = salesMan, UserId = LoginInfo.Id, Value = Convert.ToInt32(total_amount) / Convert.ToInt32(price), Money = Convert.ToInt32(total_amount), OperatorId = LoginInfo.Id, ModifyDate = DateTime.Now, Remark = "客户端购买", }; await _balanceService.Rechange(balance, UserType.Admin); //更改客户余额 await _redisHelper.StringGetAsync(RedisKeyName.CreateUserAmountKey(LoginInfo.Id)); await _redisHelper.StringIncrementAsync(RedisKeyName.CreateUserAmountKey(LoginInfo.Id), balance.Value); order.TradeResult = TradeResult.Success; //修改订单结果 order.OrderDate = Convert.ToDateTime(timestamp); //添加交易时间 _rechargeService.Update(order); Json("success"); } else //无效订单 { order.TradeResult = TradeResult.Invalid; //修改订单结果 order.OrderDate = Convert.ToDateTime(timestamp); //添加交易时间 _rechargeService.Update(order); Json("fail"); } } break; case "TRADE_CLOSED": //订单关闭/买家未在规定时间内付款 order.TradeResult = TradeResult.Cancel; //修改订单结果 order.OrderDate = Convert.ToDateTime(timestamp); //添加交易时间 _rechargeService.Update(order); Json("fail"); break; default: //支付失败 order.TradeResult = TradeResult.Fail; //修改订单结果 order.OrderDate = Convert.ToDateTime(timestamp); //添加交易时间 _rechargeService.Update(order); Json("fail"); break; } #endregion #region // if (order != null)//订单对比 // { // //if (trade_status == "TRADE_FINISHED" || trade_status == "TRADE_SUCCESS") // if (Config.app_id.Equals(appid)) // { //#if DEBUG // var val = Convert.ToDecimal(total_amount) / price; // var s = Math.Ceiling(val);//Math.Ceiling:向上取整,只要有小数都加1 // var balance = new BalanceDto // { // SalesMan = salesMan, // UserId = LoginInfo.Id, // Value = decimal.ToInt32(s), // Money = decimal.ToInt32(Convert.ToDecimal(total_amount)), // OperatorId = LoginInfo.Id, // ModifyDate = DateTime.Now, // Remark = "客户端" // }; // await _balanceService.OnlineRechange(balance, UserType.Admin);//更改客户余额//todo:充值表两条,考虑加订单表 // // await _redisHelper.StringGetAsync(RedisKeyName.CreateUserAmountKey(LoginInfo.Id)); // //await _redisHelper.StringIncrementAsync(RedisKeyName.CreateUserAmountKey(LoginInfo.Id), balance.Value); // order.TradeResult = TradeResult.Success;//修改订单结果 // order.OrderDate = Convert.ToDateTime(timestamp);//添加交易时间 // _rechargeService.Update(order); // tradeResult = "支付成功!"; // Json("success"); //#else // tradeResult = "支付成功!"; // Json("success"); //#endif // } // else // { //#if DEBUG // order.TradeResult = TradeResult.Fail;//修改订单结果 // order.OrderDate = Convert.ToDateTime(timestamp);//添加交易时间 // _rechargeService.Update(order); // tradeResult = "支付失败!"; // Json("fail"); //#else // tradeResult = "支付失败!"; // Json("fail"); //#endif // } // } // else//无效订单 // { // order.TradeResult = TradeResult.Invalid;//修改订单结果 // order.OrderDate = Convert.ToDateTime(timestamp);//添加交易时间 // _rechargeService.Update(order); // Json("fail"); // } #endregion //Json("success"); } else { Json("fail"); } } } catch (Exception ex) { Logger.Error("zfb 异步:", ex); } }