public bool DisableService(ProtectedOperationContext ctx, int serviceId, out WalletError error) { error = WalletError.OK; if (Channel == null) { throw new Exception("WalletManagerProxy: связь не установлена"); } try { return(Channel.DisableService(ctx, serviceId, out error)); } catch { RenewFactory(); try { return(Channel.DisableService(ctx, serviceId, out error)); } catch (Exception ex2) { Logger.Error("DisableService() error: ", ex2); return(false); } } }
public List <UserPaymentSystem> GetUserRegistredPaymentSystemWallets(ProtectedOperationContext ctx, string userLogin, string walletPwrd, out WalletError error) { if (Channel == null) { throw new Exception("WalletManagerProxy: связь не установлена"); } try { return(Channel.GetUserRegistredPaymentSystemWallets(ctx, userLogin, walletPwrd, out error)); } catch { RenewFactory(); try { return(Channel.GetUserRegistredPaymentSystemWallets(ctx, userLogin, walletPwrd, out error)); } catch (Exception ex2) { Logger.Error("GetPaidServiceDetail() error: ", ex2); error = WalletError.CommonError; return(null); } } }
/// <summary> /// Creates wallet error object with HTTP_ERROR flag indicating that the error was in the request /// </summary> /// <returns></returns> private WalletError CreateHttpErrorResponse(HttpResponseMessage message) { var error = new WalletError(); error.Code = WalletErrorCodes.HTTP_ERROR; error.Message = message.StatusCode.ToString(); return(error); }
/// <summary> /// Set data container object to error /// </summary> /// <returns>Response wrapper with error</returns> public static ParsedWalletResponse <T> CreateError(WalletError error) { var obj = new ParsedWalletResponse <T>(); obj.IsError = true; obj.SetContent(error); return(obj); }
/// <summary> /// отключить сервис /// отключить клиентам торговые сигналы - вывести их из ПАММ-а и т.п. /// </summary> public bool DisableService(ProtectedOperationContext secCtx, int serviceId, out WalletError error) { if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false)) { error = WalletError.InsufficientRights; return(false); } // найти сервис - и - удалить try { using (var ctx = DatabaseContext.Instance.Make()) { // собственно сервис var service = ctx.SERVICE.FirstOrDefault(s => s.ID == serviceId); if (service == null) { error = WalletError.InvalidData; return(false); } // отписать всех подписчиков var subs = ctx.SUBSCRIPTION.Where(s => s.Service == serviceId).ToList(); foreach (var sub in subs) { if (!walletRepository.UnsubscribeSubscriber(ctx, sub)) { error = WalletError.ServerError; return(false); } } // удалить сервис-рейты (прогрессивная шкала) var rates = ctx.SERVICE_RATE.Where(r => r.Service == serviceId).ToList(); foreach (var rate in rates) { ctx.SERVICE_RATE.Remove(rate); } // удалить сам сервис ctx.SERVICE.Remove(service); ctx.SaveChanges(); error = WalletError.OK; return(true); } } catch (Exception ex) { Logger.ErrorFormat("Ошибка в DisableService({0}): {1}", serviceId, ex); error = WalletError.ServerError; return(false); } }
public bool SubscribeOnService(ProtectedOperationContext secCtx, string login, int serviceId, bool renewAuto, bool unsubscribe, AutoTradeSettings tradeSets, out WalletError error) { try { return(Proxy.SubscribeOnService(secCtx, login, serviceId, renewAuto, unsubscribe, tradeSets, out error)); } catch (Exception) { RenewChannel(); return(Proxy.SubscribeOnService(secCtx, login, serviceId, renewAuto, unsubscribe, tradeSets, out error)); } }
public List <UserPaymentSystem> GetUserRegistredPaymentSystemWallets(ProtectedOperationContext secCtx, string userLogin, string walletPwrd, out WalletError error) { if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false)) { error = WalletError.InsufficientRights; return(null); } try { using (var ctx = DatabaseContext.Instance.Make()) { var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin); if (user == null) { error = WalletError.AuthenticationError; return(null); } var systems = new List <UserPaymentSystem>(); var query = ctx.USER_PAYMENT_SYSTEM.Where(s => s.UserId == user.ID); foreach (var payment in query) { systems.Add(LinqToEntity.DecorateUserPaymentSystem(payment)); } error = WalletError.OK; return(systems); } } catch (Exception ex) { error = WalletError.ServerError; Logger.Error("GetUserRegistredPaymentSystemWallets() error", ex); return(null); } }
public bool DisableService(ProtectedOperationContext ctx, int serviceId, out WalletError error) { error = WalletError.OK; if (Channel == null) throw new Exception("WalletManagerProxy: связь не установлена"); try { return Channel.DisableService(ctx, serviceId, out error); } catch { RenewFactory(); try { return Channel.DisableService(ctx, serviceId, out error); } catch (Exception ex2) { Logger.Error("DisableService() error: ", ex2); return false; } } }
public bool SubscribeOnService(ProtectedOperationContext secCtx, string login, int serviceId, bool renewAuto, bool unsubscribe, AutoTradeSettings tradeSets, out WalletError error) { if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false)) { error = WalletError.InsufficientRights; return(false); } // создать или удалить подписку try { using (var ctx = DatabaseContext.Instance.Make()) { // пользователь var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == login); if (user == null) { Logger.ErrorFormat("SubscribeOnService({0}, srv {1}) - пользователь не найден", login, serviceId); error = WalletError.InvalidData; return(false); } return(walletRepository.SubscribeOnService(ctx, user.ID, serviceId, renewAuto, unsubscribe, tradeSets, out error)); } } catch (Exception ex) { Logger.ErrorFormat("Ошибка в SubscribeOnService({0}): {1}", serviceId, ex); error = WalletError.ServerError; return(false); } }
public Wallet TransferToWallet(ProtectedOperationContext ctx, string userLogin, int accountId, decimal amountInAccountCurrency, out WalletError error) { error = WalletError.OK; if (Channel == null) { throw new Exception("WalletManagerProxy: связь не установлена"); } try { return(Channel.TransferToWallet(ctx, userLogin, accountId, amountInAccountCurrency, out error)); } catch { RenewFactory(); try { return(Channel.TransferToWallet(ctx, userLogin, accountId, amountInAccountCurrency, out error)); } catch (Exception ex2) { Logger.Error("TransferToWallet() error: ", ex2); return(null); } } }
public bool SubscribeOnService(TradeSharpConnection ctx, int userId, int serviceId, bool renewAuto, bool unsubscribe, AutoTradeSettings tradeSets, out WalletError error) { // имеющаяся подписка var subs = ctx.SUBSCRIPTION.FirstOrDefault(s => s.Service == serviceId && s.User == userId); // просто отписаться от сервиса if (unsubscribe) { error = WalletError.OK; if (subs == null) return true; ctx.SUBSCRIPTION.Remove(subs); try { ctx.SaveChanges(); } catch (Exception ex) { Logger.Error("Ошибка удаления подписки (SubscribeOnService)", ex); error = WalletError.ServerError; return false; } return true; } var paidService = ctx.SERVICE.FirstOrDefault(s => s.ID == serviceId); if (paidService == null) { error = WalletError.InvalidData; return false; } // проверить - не подписывается ли пользователь сам на себя? if (paidService.User == userId) { error = WalletError.InvalidData; return false; } // провести списание денежных средств // содрать денежку var feeError = ChargeFeeOnSubscription(ctx, serviceId, userId, false); if (feeError != WalletError.OK) { error = feeError; return false; } // продлить или обновить подписку var subExists = subs != null; if (subs == null) subs = new SUBSCRIPTION(); subs.RenewAuto = renewAuto; subs.TimeEnd = DateTime.Now.Date.AddDays(1); subs.TimeStarted = DateTime.Now.Date; subs.User = userId; subs.Service = serviceId; if (!subExists) ctx.SUBSCRIPTION.Add(subs); // обновить или создать настройки торговли var signalTradeSets = ctx.SUBSCRIPTION_SIGNAL.FirstOrDefault(s => s.Service == serviceId && s.User == userId); var setsExists = signalTradeSets != null; if (signalTradeSets == null) signalTradeSets = new SUBSCRIPTION_SIGNAL(); signalTradeSets.AutoTrade = tradeSets.TradeAuto; signalTradeSets.FixedVolume = tradeSets.FixedVolume; signalTradeSets.HedgingOrdersEnabled = tradeSets.HedgingOrdersEnabled; signalTradeSets.MaxLeverage = tradeSets.MaxLeverage; signalTradeSets.MaxVolume = tradeSets.MaxVolume; signalTradeSets.MinVolume = tradeSets.MinVolume; signalTradeSets.PercentLeverage = tradeSets.PercentLeverage; signalTradeSets.Service = serviceId; signalTradeSets.StepVolume = tradeSets.StepVolume; signalTradeSets.User = userId; signalTradeSets.TargetAccount = tradeSets.TargetAccount; signalTradeSets.VolumeRound = (int?)tradeSets.VolumeRound; if (!setsExists) ctx.SUBSCRIPTION_SIGNAL.Add(signalTradeSets); try { ctx.SaveChanges(); } catch (Exception ex) { Logger.Error("Ошибка сохранения подписки (SubscribeOnService)", ex); error = WalletError.ServerError; return false; } error = WalletError.OK; return true; }
public virtual bool BindToTradeSignal(ProtectedOperationContext secCtx, string userLogin, TradeSignalCategory cat, out WalletError error) { error = WalletError.OK; return true; }
public Wallet GetUserWalletSubscriptionAndLastPayments(string hash, string userLogin, long localTime, int maxPaymentsQuery, out int paymentsTotalCount, out List<Subscription> subscriptions, out List<Transfer> transfers, out WalletError error) { paymentsTotalCount = 0; subscriptions = null; transfers = null; PLATFORM_USER user; using (var ctx = DatabaseContext.Instance.Make()) { user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin); if (user == null) { error = WalletError.AuthenticationError; return null; } } var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime); if (hash != userHash) { error = WalletError.AuthenticationError; return null; } return walletRepository.GetUserWalletSubscriptionAndLastPaymentsInner(userLogin, maxPaymentsQuery, out paymentsTotalCount, out subscriptions, out transfers, out error); }
public bool SubscribeOnService(ProtectedOperationContext secCtx, string login, int serviceId, bool renewAuto, bool unsubscribe, AutoTradeSettings tradeSets, out WalletError error) { throw new NotImplementedException(); }
public List<Transfer> GetAllUserPayments(ProtectedOperationContext secCtx, PlatformUser user, out WalletError error) { if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false)) { error = WalletError.InsufficientRights; return null; } error = WalletError.ServerError; var transfers = new List<Transfer>(); try { using (var ctx = DatabaseContext.Instance.Make()) { var queryTrans = (from trans in ctx.TRANSFER where trans.User == user.ID select trans).ToList().Select( LinqToEntity.DecorateTransfer).ToList(); } return transfers; } catch (Exception ex) { Logger.Error("GetAllUserPayments() error", ex); error = WalletError.ServerError; return null; } }
public Wallet GetUserWalletSubscriptionAndLastPaymentsInner( string userLogin, int maxPaymentsQuery, out int paymentsTotalCount, out List <Subscription> subscriptions, out List <Transfer> transfers, out WalletError error) { subscriptions = null; transfers = null; paymentsTotalCount = 0; error = WalletError.ServerError; // получить кошелек пользователя и вернуть его Wallet wallet = null; try { using (var ctx = DatabaseContext.Instance.Make()) { // получить пользователя var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin); if (user == null) { error = WalletError.AuthenticationError; return(null); } // получить кошелек var walletBase = ctx.WALLET.FirstOrDefault(w => w.User == user.ID); if (walletBase == null) { error = WalletError.ServerError; return(null); } wallet = LinqToEntity.DecorateWallet(walletBase); subscriptions = new List <Subscription>(); transfers = new List <Transfer>(); // получить подписки пользователя subscriptions = (from subs in ctx.SUBSCRIPTION join srv in ctx.SERVICE on subs.Service equals srv.ID where subs.User == user.ID select new TradeSharp.Contract.Entity.Subscription { User = subs.User, RenewAuto = subs.RenewAuto, Service = subs.Service, TimeEnd = subs.TimeEnd, TimeStarted = subs.TimeStarted, PaidService = new PaidService { User = srv.User, AccountId = srv.AccountId, Currency = srv.Currency, Comment = srv.Comment, ServiceType = (PaidServiceType)srv.ServiceType, Id = srv.ID, FixedPrice = srv.FixedPrice } }).ToList(); // получить последние платежи по кошельку paymentsTotalCount = ctx.TRANSFER.Count(t => t.User == user.ID); transfers = (from trans in ctx.TRANSFER where trans.User == user.ID select trans).Take(maxPaymentsQuery).ToList().Select( LinqToEntity.DecorateTransfer).ToList(); error = WalletError.OK; } } catch (Exception ex) { Logger.ErrorFormat("GetUserWalletSubscriptionAndLastPayments({0}) - exception: {1}", userLogin, ex); } return(wallet); }
public List<UserPaymentSystem> GetUserRegistredPaymentSystemWallets(ProtectedOperationContext ctx, string userLogin, string walletPwrd, out WalletError error) { if (Channel == null) throw new Exception("WalletManagerProxy: связь не установлена"); try { return Channel.GetUserRegistredPaymentSystemWallets(ctx, userLogin, walletPwrd, out error); } catch { RenewFactory(); try { return Channel.GetUserRegistredPaymentSystemWallets(ctx, userLogin, walletPwrd, out error); } catch (Exception ex2) { Logger.Error("GetPaidServiceDetail() error: ", ex2); error = WalletError.CommonError; return null; } } }
public Wallet UpdateBalance(int walletId, decimal transferVolume, bool deposit, out WalletError error) { try { using (var ctx = DatabaseContext.Instance.Make()) { var wallet = ctx.WALLET.FirstOrDefault(x => x.User == walletId); if (wallet == null) { Logger.InfoFormat("не найден кошек {0}", walletId); error = WalletError.InvalidData; return(null); } if (transferVolume <= 0) { Logger.Info("объём зачисляемых средств должен быть больше нуля}"); error = WalletError.InvalidData; return(LinqToEntity.DecorateWallet(wallet)); } var currentAmount = deposit ? transferVolume : -transferVolume; var oldWalletBalance = wallet.Balance; wallet.Balance += currentAmount; Logger.InfoFormat("средства на кошеке {0} изменены с {1} на {2}", walletId, oldWalletBalance, wallet.Balance); var newTransfer = new TRANSFER { Amount = currentAmount, TargetAmount = currentAmount, User = walletId, Comment = "Изменение администратором средств кошелька № " + walletId, ValueDate = DateTime.Now, BalanceChange = null, }; ctx.TRANSFER.Add(newTransfer); Logger.Info("Сохраняем изменения..."); ctx.SaveChanges(); error = WalletError.OK; return(LinqToEntity.DecorateWallet(wallet)); } } catch (Exception ex) { Logger.Error("UpdateUserWallet()", ex); error = WalletError.CommonError; return(null); } }
public Wallet ChangeCurrency(int walletId, string walletCurrency, bool recalculationBalance, out WalletError error) { try { using (var ctx = DatabaseContext.Instance.Make()) { var wallet = ctx.WALLET.FirstOrDefault(x => x.User == walletId); if (wallet == null) { Logger.InfoFormat("не найден кошек для пользователя с Id = {0}", walletId); error = WalletError.InvalidData; return null; } var oldWalletCurrency = wallet.Currency; if (oldWalletCurrency != walletCurrency) { wallet.Currency = walletCurrency; Logger.InfoFormat("валюта кошека {0} изменена с {1} на {2}", walletId, oldWalletCurrency, walletCurrency); } if (recalculationBalance) { #region Logger.InfoFormat("пересчёт баланса кошелька {0} {1} в новую валюту {2}...", walletId, oldWalletCurrency, walletCurrency); var oldBalans = wallet.Balance; var newValue = PaymentProcessor.ConvertPaySysCurrencyToWalletCurrency(walletCurrency, oldWalletCurrency, (double) oldBalans); if (newValue != null) { newValue = Math.Round(newValue.Value, 2); wallet.Balance = (decimal) newValue; Logger.InfoFormat("баланса кошелька {0} изменён с {1} на {2}", walletId, oldBalans, wallet.Balance); } else { Logger.ErrorFormat("не удалось пересчитать балланс кошелька {0} в новой валюте {1}", walletId, walletCurrency); error = WalletError.CurrencyExchangeFailed; return LinqToEntity.DecorateWallet(wallet); } #endregion } Logger.Info("Сохраняем изменения..."); ctx.SaveChanges(); error = WalletError.OK; Logger.Info("изменения сохранены"); return LinqToEntity.DecorateWallet(wallet); } } catch (Exception ex) { Logger.Error("ChangeCurrency()", ex); error = WalletError.CommonError; return null; } }
public Wallet TransferToTradingAccount(ProtectedOperationContext secCtx, string userLogin, int accountId, decimal amountInWalletCurrency, out WalletError error) { var rst = DepositOrWithdraw(secCtx, true, userLogin, accountId, amountInWalletCurrency, out error); return rst; }
public bool RegisterOrUpdateService(ProtectedOperationContext secCtx, PaidService service, out WalletError error) { if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false)) { error = WalletError.InsufficientRights; return false; } // проверить сервис - 1 000 000 USD в день, к примеру, перебор // одному пользователю недозволительно высталять 10 сервисов // счет должен быть реальным if (service.ServiceType == PaidServiceType.PAMM || service.ServiceType == PaidServiceType.Signals) { // проверить - реальный счет? if (!service.AccountId.HasValue) { error = WalletError.InvalidData; return false; } if (service.FixedPrice < 0) { error = WalletError.InvalidData; return false; } try { using (var ctx = DatabaseContext.Instance.Make()) { var account = ctx.ACCOUNT.FirstOrDefault(a => a.ID == service.AccountId.Value); if (account == null) { error = WalletError.InvalidData; return false; } service.Currency = account.Currency; // перевести сумму в USD - если она велика - вернуть false // перевести стоимость сервиса в USD var fixedPrice = service.FixedPrice; if (account.Currency != MaxFixedPriceCheckCurrency) { string errorStr; var fixedPriceTarget = DalSpot.Instance.ConvertSourceCurrencyToTargetCurrency(MaxFixedPriceCheckCurrency, account.Currency, (double)service.FixedPrice, QuoteStorage.Instance.ReceiveAllData(), out errorStr); if (!fixedPriceTarget.HasValue) { error = WalletError.InvalidData; return false; } fixedPrice = fixedPriceTarget.Value; } if (fixedPrice > MaxFixedPricePerDayUSD) { error = WalletError.InvalidData; return false; } // проверить, солько сервисов зарегистрировал пользователь? // заодно проверить - нет ли сервиса того же типа с указанием того же счета var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.ID == service.User); if (user == null) { error = WalletError.InvalidData; return false; } var existService = ctx.SERVICE.FirstOrDefault(s => s.User == user.ID && s.ServiceType == (int)service.ServiceType); // обновить сервис if (existService != null) { service.Id = existService.ID; existService.AccountId = service.AccountId; existService.Comment = service.Comment; existService.FixedPrice = service.FixedPrice; existService.Currency = service.Currency; // прогрессивная шкала оплаты if (!CreateOrUpdateServiceFeeRecords(service, ctx, true)) { error = WalletError.ServerError; return false; } ctx.SaveChanges(); error = WalletError.OK; return true; } // создать новый сервис var srvNew = ctx.SERVICE.Add(new SERVICE { User = service.User, AccountId = service.AccountId, Comment = service.Comment, FixedPrice = service.FixedPrice, Currency = service.Currency, ServiceType = (short)service.ServiceType }); Logger.InfoFormat("New service added: user={0}, account={1}, type={2}, price={3} {4}", service.User, service.AccountId, service.ServiceType, service.FixedPrice.ToStringUniformMoneyFormat(), service.Currency); ctx.SaveChanges(); service.Id = srvNew.ID; // прогрессивная шкала оплаты if (!CreateOrUpdateServiceFeeRecords(service, ctx, false)) { error = WalletError.ServerError; return false; } error = WalletError.OK; return true; } } catch (Exception ex) { Logger.Error("RegisterOrUpdateService error", ex); } } // не ПАММ и не сигналы... error = WalletError.CommonError; return false; }
public Wallet GetUserWalletSubscriptionAndLastPayments(ProtectedOperationContext secCtx, string userLogin, int maxPaymentsQuery, out int paymentsTotalCount, out List<Subscription> subscriptions, out List<Transfer> transfers, out WalletError error) { // запрос разрешен? if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false)) { subscriptions = null; transfers = null; paymentsTotalCount = 0; error = WalletError.InsufficientRights; return null; } return walletRepository.GetUserWalletSubscriptionAndLastPaymentsInner(userLogin, maxPaymentsQuery, out paymentsTotalCount, out subscriptions, out transfers, out error); }
public List<UserPaymentSystem> GetUserRegistredPaymentSystemWallets(ProtectedOperationContext secCtx, string userLogin, string walletPwrd, out WalletError error) { if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false)) { error = WalletError.InsufficientRights; return null; } try { using (var ctx = DatabaseContext.Instance.Make()) { var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin); if (user == null) { error = WalletError.AuthenticationError; return null; } var systems = new List<UserPaymentSystem>(); var query = ctx.USER_PAYMENT_SYSTEM.Where(s => s.UserId == user.ID); foreach (var payment in query) systems.Add(LinqToEntity.DecorateUserPaymentSystem(payment)); error = WalletError.OK; return systems; } } catch (Exception ex) { error = WalletError.ServerError; Logger.Error("GetUserRegistredPaymentSystemWallets() error", ex); return null; } }
public Wallet TransferToTradingAccount(ProtectedOperationContext ctx, string userLogin, int accountId, decimal amountInWalletCurrency, out WalletError error) { error = WalletError.OK; if (Channel == null) RenewFactory(); try { return Channel.TransferToTradingAccount(ctx, userLogin, accountId, amountInWalletCurrency, out error); } catch { RenewFactory(); try { return Channel.TransferToTradingAccount(ctx, userLogin, accountId, amountInWalletCurrency, out error); } catch (Exception ex2) { Logger.Error("TransferToTradingAccount() error: ", ex2); return null; } } }
public Wallet TransferToWallet(ProtectedOperationContext ctx, string userLogin, int accountId, decimal amountInAccountCurrency, out WalletError error) { error = WalletError.OK; if (Channel == null) throw new Exception("WalletManagerProxy: связь не установлена"); try { return Channel.TransferToWallet(ctx, userLogin, accountId, amountInAccountCurrency, out error); } catch { RenewFactory(); try { return Channel.TransferToWallet(ctx, userLogin, accountId, amountInAccountCurrency, out error); } catch (Exception ex2) { Logger.Error("TransferToWallet() error: ", ex2); return null; } } }
public Wallet TransferToWallet(ProtectedOperationContext secCtx, string userLogin, int accountId, decimal amountInAccountCurrency, out WalletError error) { return DepositOrWithdraw(secCtx, false, userLogin, accountId, amountInAccountCurrency, out error); }
/// <summary> /// отключить сервис /// отключить клиентам торговые сигналы - вывести их из ПАММ-а и т.п. /// </summary> public bool DisableService(ProtectedOperationContext secCtx, int serviceId, out WalletError error) { if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false)) { error = WalletError.InsufficientRights; return false; } // найти сервис - и - удалить try { using (var ctx = DatabaseContext.Instance.Make()) { // собственно сервис var service = ctx.SERVICE.FirstOrDefault(s => s.ID == serviceId); if (service == null) { error = WalletError.InvalidData; return false; } // отписать всех подписчиков var subs = ctx.SUBSCRIPTION.Where(s => s.Service == serviceId).ToList(); foreach (var sub in subs) if (!walletRepository.UnsubscribeSubscriber(ctx, sub)) { error = WalletError.ServerError; return false; } // удалить сервис-рейты (прогрессивная шкала) var rates = ctx.SERVICE_RATE.Where(r => r.Service == serviceId).ToList(); foreach (var rate in rates) ctx.SERVICE_RATE.Remove(rate); // удалить сам сервис ctx.SERVICE.Remove(service); ctx.SaveChanges(); error = WalletError.OK; return true; } } catch (Exception ex) { Logger.ErrorFormat("Ошибка в DisableService({0}): {1}", serviceId, ex); error = WalletError.ServerError; return false; } }
public Wallet GetUserWalletSubscriptionAndLastPayments(ProtectedOperationContext secCtx, string userLogin, int maxPaymentsQuery, out int paymentsTotalCount, out List <Subscription> subscriptions, out List <Transfer> transfers, out WalletError error) { // запрос разрешен? if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false)) { subscriptions = null; transfers = null; paymentsTotalCount = 0; error = WalletError.InsufficientRights; return(null); } return(walletRepository.GetUserWalletSubscriptionAndLastPaymentsInner(userLogin, maxPaymentsQuery, out paymentsTotalCount, out subscriptions, out transfers, out error)); }
public Wallet UpdateBalance(int walletId, decimal transferVolume, bool deposit, out WalletError error) { try { using (var ctx = DatabaseContext.Instance.Make()) { var wallet = ctx.WALLET.FirstOrDefault(x => x.User == walletId); if (wallet == null) { Logger.InfoFormat("не найден кошек {0}", walletId); error = WalletError.InvalidData; return null; } if (transferVolume <= 0) { Logger.Info("объём зачисляемых средств должен быть больше нуля}"); error = WalletError.InvalidData; return LinqToEntity.DecorateWallet(wallet); } var currentAmount = deposit ? transferVolume : -transferVolume; var oldWalletBalance = wallet.Balance; wallet.Balance += currentAmount; Logger.InfoFormat("средства на кошеке {0} изменены с {1} на {2}", walletId, oldWalletBalance, wallet.Balance); var newTransfer = new TRANSFER { Amount = currentAmount, TargetAmount = currentAmount, User = walletId, Comment = "Изменение администратором средств кошелька № " + walletId, ValueDate = DateTime.Now, BalanceChange = null, }; ctx.TRANSFER.Add(newTransfer); Logger.Info("Сохраняем изменения..."); ctx.SaveChanges(); error = WalletError.OK; return LinqToEntity.DecorateWallet(wallet); } } catch (Exception ex) { Logger.Error("UpdateUserWallet()", ex); error = WalletError.CommonError; return null; } }
public Wallet ChangeCurrency(int walletId, string walletCurrency, bool recalculationBalance, out WalletError error) { try { using (var ctx = DatabaseContext.Instance.Make()) { var wallet = ctx.WALLET.FirstOrDefault(x => x.User == walletId); if (wallet == null) { Logger.InfoFormat("не найден кошек для пользователя с Id = {0}", walletId); error = WalletError.InvalidData; return(null); } var oldWalletCurrency = wallet.Currency; if (oldWalletCurrency != walletCurrency) { wallet.Currency = walletCurrency; Logger.InfoFormat("валюта кошека {0} изменена с {1} на {2}", walletId, oldWalletCurrency, walletCurrency); } if (recalculationBalance) { #region Logger.InfoFormat("пересчёт баланса кошелька {0} {1} в новую валюту {2}...", walletId, oldWalletCurrency, walletCurrency); var oldBalans = wallet.Balance; var newValue = PaymentProcessor.ConvertPaySysCurrencyToWalletCurrency(walletCurrency, oldWalletCurrency, (double)oldBalans); if (newValue != null) { newValue = Math.Round(newValue.Value, 2); wallet.Balance = (decimal)newValue; Logger.InfoFormat("баланса кошелька {0} изменён с {1} на {2}", walletId, oldBalans, wallet.Balance); } else { Logger.ErrorFormat("не удалось пересчитать балланс кошелька {0} в новой валюте {1}", walletId, walletCurrency); error = WalletError.CurrencyExchangeFailed; return(LinqToEntity.DecorateWallet(wallet)); } #endregion } Logger.Info("Сохраняем изменения..."); ctx.SaveChanges(); error = WalletError.OK; Logger.Info("изменения сохранены"); return(LinqToEntity.DecorateWallet(wallet)); } } catch (Exception ex) { Logger.Error("ChangeCurrency()", ex); error = WalletError.CommonError; return(null); } }
private static Wallet PutMoneyOnUserOwnedAccount(int accountId, decimal amountInSrcCurrency, out WalletError error, WALLET wallet, ACCOUNT account, TradeSharpConnection ctx, PLATFORM_USER user) { // достаточно ли денег в кошельке? if (amountInSrcCurrency > wallet.Balance) { error = WalletError.InsufficientFunds; return null; } // перевести объем в валюту счета var amount = amountInSrcCurrency; if (account.Currency != wallet.Currency) { // найти котировку и перевести string errorString; var amountTarget = DalSpot.Instance.ConvertSourceCurrencyToTargetCurrency(account.Currency, wallet.Currency, (double) amount, QuoteStorage.Instance.ReceiveAllData(), out errorString); if (!amountTarget.HasValue) { Logger.ErrorFormat("DepositOrWithdraw({0} {1}): {2}", amountInSrcCurrency, account.Currency + "/" + wallet.Currency, errorString); error = WalletError.CurrencyExchangeFailed; return null; } amount = amountTarget.Value; } // списать с кошелька и пополнить счет wallet.Balance -= amountInSrcCurrency; account.Balance += amount; var dateOper = DateTime.Now; var balanceChange = ctx.BALANCE_CHANGE.Add(new BALANCE_CHANGE { AccountID = accountId, Amount = amount, ChangeType = (int) BalanceChangeType.Deposit, ValueDate = dateOper, Description = "Пополнение с кошелька №" + wallet.User }); try { ctx.SaveChanges(); } catch (Exception ex) { Logger.Error("DepositOrWithdraw() - error saving balance change", ex); error = WalletError.ServerError; return null; } var balanceChangeId = balanceChange.ID; ctx.TRANSFER.Add(new TRANSFER { Amount = -amountInSrcCurrency, TargetAmount = -amountInSrcCurrency, User = user.ID, Comment = "Т. счет №" + account.ID, ValueDate = dateOper, BalanceChange = balanceChangeId, }); try { ctx.SaveChanges(); } //catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException) //{ //} catch (Exception ex) { Logger.Error("DepositOrWithdraw() - error saving transfer for user " + user.ID + ", balance change Id: " + balanceChangeId + ", user: " + user.ID, ex); error = WalletError.ServerError; return null; } error = WalletError.OK; return LinqToEntity.DecorateWallet(wallet); }
public List <Transfer> GetAllUserPayments(ProtectedOperationContext secCtx, PlatformUser user, out WalletError error) { if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false)) { error = WalletError.InsufficientRights; return(null); } error = WalletError.ServerError; var transfers = new List <Transfer>(); try { using (var ctx = DatabaseContext.Instance.Make()) { var queryTrans = (from trans in ctx.TRANSFER where trans.User == user.ID select trans).ToList().Select( LinqToEntity.DecorateTransfer).ToList(); } return(transfers); } catch (Exception ex) { Logger.Error("GetAllUserPayments() error", ex); error = WalletError.ServerError; return(null); } }
/// <summary> /// просто пополнить счет, вывести оттуда долю или пополнить ПАММ-пай /// </summary> private Wallet DepositOrWithdraw(ProtectedOperationContext secCtx, bool putOnAccount, string userLogin, int accountId, decimal amountInSrcCurrency, out WalletError error) { var operationParams = string.Format("DepositOrWithdraw(log={0}, acc={1}, amt={2})", userLogin, accountId, amountInSrcCurrency.ToStringUniformMoneyFormat()); if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false)) { Logger.Error(operationParams + ": InsufficientRights"); error = WalletError.InsufficientRights; return null; } if (amountInSrcCurrency <= 0) { Logger.Error(operationParams + ": amountInSrcCurrency <= 0"); error = WalletError.InvalidData; return null; } // перевести деньги на счет / со счета на кошелек try { using (var ctx = DatabaseContext.Instance.Make()) { // счет var account = ctx.ACCOUNT.FirstOrDefault(a => a.ID == accountId); if (account == null) { Logger.Error(operationParams + ": account is not found"); error = WalletError.InvalidData; return null; } // пользователь и кошелек var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin); if (user == null) { Logger.Error(operationParams + ": user is not found"); error = WalletError.InvalidData; return null; } var wallet = ctx.WALLET.FirstOrDefault(w => w.User == user.ID); if (wallet == null) { Logger.Error(operationParams + ": wallet is not found"); error = WalletError.InvalidData; return null; } // это - ПАММ-счет или обычный счет? var userShare = GetAccountSharePercent(ctx, accountId, user.ID); if (userShare < 100M) { var status = new WalletManager4Pamm(secCtx, userLogin, accountId).InvestOrWithdrawFromPamm( amountInSrcCurrency, !putOnAccount, false, ctx); error = status == RequestStatus.OK ? WalletError.OK : WalletError.InvalidData; if (error != WalletError.OK) Logger.Error(operationParams + ": InvestOrWithdrawFromPamm - " + status); return LinqToEntity.DecorateWallet(wallet); } // деньги - в кошелек if (putOnAccount) return PutMoneyOnUserOwnedAccount(accountId, amountInSrcCurrency, out error, wallet, account, ctx, user); // перевести со счета в кошелек return GetMoneyFromUserOwnedAccount(accountId, amountInSrcCurrency, out error, account, wallet, ctx, user); } } catch (Exception ex) { Logger.ErrorFormat("Ошибка в TransferToTradingAccount({0}): {1}", accountId, ex); error = WalletError.ServerError; return null; } }
public bool SubscribeOnService(TradeSharpConnection ctx, int userId, int serviceId, bool renewAuto, bool unsubscribe, AutoTradeSettings tradeSets, out WalletError error) { // имеющаяся подписка var subs = ctx.SUBSCRIPTION.FirstOrDefault(s => s.Service == serviceId && s.User == userId); // просто отписаться от сервиса if (unsubscribe) { error = WalletError.OK; if (subs == null) { return(true); } ctx.SUBSCRIPTION.Remove(subs); try { ctx.SaveChanges(); } catch (Exception ex) { Logger.Error("Ошибка удаления подписки (SubscribeOnService)", ex); error = WalletError.ServerError; return(false); } return(true); } var paidService = ctx.SERVICE.FirstOrDefault(s => s.ID == serviceId); if (paidService == null) { error = WalletError.InvalidData; return(false); } // проверить - не подписывается ли пользователь сам на себя? if (paidService.User == userId) { error = WalletError.InvalidData; return(false); } // провести списание денежных средств // содрать денежку var feeError = ChargeFeeOnSubscription(ctx, serviceId, userId, false); if (feeError != WalletError.OK) { error = feeError; return(false); } // продлить или обновить подписку var subExists = subs != null; if (subs == null) { subs = new SUBSCRIPTION(); } subs.RenewAuto = renewAuto; subs.TimeEnd = DateTime.Now.Date.AddDays(1); subs.TimeStarted = DateTime.Now.Date; subs.User = userId; subs.Service = serviceId; if (!subExists) { ctx.SUBSCRIPTION.Add(subs); } // обновить или создать настройки торговли var signalTradeSets = ctx.SUBSCRIPTION_SIGNAL.FirstOrDefault(s => s.Service == serviceId && s.User == userId); var setsExists = signalTradeSets != null; if (signalTradeSets == null) { signalTradeSets = new SUBSCRIPTION_SIGNAL(); } signalTradeSets.AutoTrade = tradeSets.TradeAuto; signalTradeSets.FixedVolume = tradeSets.FixedVolume; signalTradeSets.HedgingOrdersEnabled = tradeSets.HedgingOrdersEnabled; signalTradeSets.MaxLeverage = tradeSets.MaxLeverage; signalTradeSets.MaxVolume = tradeSets.MaxVolume; signalTradeSets.MinVolume = tradeSets.MinVolume; signalTradeSets.PercentLeverage = tradeSets.PercentLeverage; signalTradeSets.Service = serviceId; signalTradeSets.StepVolume = tradeSets.StepVolume; signalTradeSets.User = userId; signalTradeSets.TargetAccount = tradeSets.TargetAccount; signalTradeSets.VolumeRound = (int?)tradeSets.VolumeRound; if (!setsExists) { ctx.SUBSCRIPTION_SIGNAL.Add(signalTradeSets); } try { ctx.SaveChanges(); } catch (Exception ex) { Logger.Error("Ошибка сохранения подписки (SubscribeOnService)", ex); error = WalletError.ServerError; return(false); } error = WalletError.OK; return(true); }
private Wallet GetMoneyFromUserOwnedAccount(int accountId, decimal amountInSrcCurrency, out WalletError error, ACCOUNT account, WALLET wallet, TradeSharpConnection ctx, PLATFORM_USER user) { var amountWallet = amountInSrcCurrency; if (account.Currency != wallet.Currency) { // найти котировку и перевести string errorString; var amountTarget = DalSpot.Instance.ConvertSourceCurrencyToTargetCurrency(wallet.Currency, account.Currency, (double) amountWallet, QuoteStorage.Instance.ReceiveAllData(), out errorString); if (!amountTarget.HasValue) { Logger.ErrorFormat("DepositOrWithdraw({0} {1}): {2} (withdraw)", amountInSrcCurrency, account.Currency + "/" + wallet.Currency, errorString); error = WalletError.CurrencyExchangeFailed; return null; } amountWallet = amountTarget.Value; } // достаточно ли средств на счете? // проверить средства / зарезервированное марж. обеспечение decimal equity, usedMargin; if (!GetAccountEquityAndUsedMargin(account, out equity, out usedMargin)) { error = WalletError.ServerError; return null; } if (equity - usedMargin < amountInSrcCurrency) { error = WalletError.ServerError; return null; } // списать со счета в пользу кошелька wallet.Balance += amountInSrcCurrency; account.Balance -= amountInSrcCurrency; var date = DateTime.Now; var bc = ctx.BALANCE_CHANGE.Add(new BALANCE_CHANGE { AccountID = accountId, Amount = amountInSrcCurrency, ChangeType = (int) BalanceChangeType.Withdrawal, ValueDate = date, Description = "Списание на кошелек №" + wallet.User }); ctx.SaveChanges(); ctx.TRANSFER.Add(new TRANSFER { Amount = amountWallet, TargetAmount = amountWallet, User = user.ID, Comment = "Вывод средств со счета №" + account.ID, ValueDate = date, BalanceChange = bc.ID, }); ctx.SaveChanges(); error = WalletError.OK; return LinqToEntity.DecorateWallet(wallet); }
public bool SubscribeOnService(ProtectedOperationContext secCtx, string login, int serviceId, bool renewAuto, bool unsubscribe, AutoTradeSettings tradeSets, out WalletError error) { error = WalletError.CommonError; return false; }
public bool RegisterOrUpdateService(ProtectedOperationContext secCtx, PaidService service, out WalletError error) { if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false)) { error = WalletError.InsufficientRights; return(false); } // проверить сервис - 1 000 000 USD в день, к примеру, перебор // одному пользователю недозволительно высталять 10 сервисов // счет должен быть реальным if (service.ServiceType == PaidServiceType.PAMM || service.ServiceType == PaidServiceType.Signals) { // проверить - реальный счет? if (!service.AccountId.HasValue) { error = WalletError.InvalidData; return(false); } if (service.FixedPrice < 0) { error = WalletError.InvalidData; return(false); } try { using (var ctx = DatabaseContext.Instance.Make()) { var account = ctx.ACCOUNT.FirstOrDefault(a => a.ID == service.AccountId.Value); if (account == null) { error = WalletError.InvalidData; return(false); } service.Currency = account.Currency; // перевести сумму в USD - если она велика - вернуть false // перевести стоимость сервиса в USD var fixedPrice = service.FixedPrice; if (account.Currency != MaxFixedPriceCheckCurrency) { string errorStr; var fixedPriceTarget = DalSpot.Instance.ConvertSourceCurrencyToTargetCurrency(MaxFixedPriceCheckCurrency, account.Currency, (double)service.FixedPrice, QuoteStorage.Instance.ReceiveAllData(), out errorStr); if (!fixedPriceTarget.HasValue) { error = WalletError.InvalidData; return(false); } fixedPrice = fixedPriceTarget.Value; } if (fixedPrice > MaxFixedPricePerDayUSD) { error = WalletError.InvalidData; return(false); } // проверить, солько сервисов зарегистрировал пользователь? // заодно проверить - нет ли сервиса того же типа с указанием того же счета var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.ID == service.User); if (user == null) { error = WalletError.InvalidData; return(false); } var existService = ctx.SERVICE.FirstOrDefault(s => s.User == user.ID && s.ServiceType == (int)service.ServiceType); // обновить сервис if (existService != null) { service.Id = existService.ID; existService.AccountId = service.AccountId; existService.Comment = service.Comment; existService.FixedPrice = service.FixedPrice; existService.Currency = service.Currency; // прогрессивная шкала оплаты if (!CreateOrUpdateServiceFeeRecords(service, ctx, true)) { error = WalletError.ServerError; return(false); } ctx.SaveChanges(); error = WalletError.OK; return(true); } // создать новый сервис var srvNew = ctx.SERVICE.Add(new SERVICE { User = service.User, AccountId = service.AccountId, Comment = service.Comment, FixedPrice = service.FixedPrice, Currency = service.Currency, ServiceType = (short)service.ServiceType }); Logger.InfoFormat("New service added: user={0}, account={1}, type={2}, price={3} {4}", service.User, service.AccountId, service.ServiceType, service.FixedPrice.ToStringUniformMoneyFormat(), service.Currency); ctx.SaveChanges(); service.Id = srvNew.ID; // прогрессивная шкала оплаты if (!CreateOrUpdateServiceFeeRecords(service, ctx, false)) { error = WalletError.ServerError; return(false); } error = WalletError.OK; return(true); } } catch (Exception ex) { Logger.Error("RegisterOrUpdateService error", ex); } } // не ПАММ и не сигналы... error = WalletError.CommonError; return(false); }
public Wallet GetUserWalletSubscriptionAndLastPaymentsInner( string userLogin, int maxPaymentsQuery, out int paymentsTotalCount, out List<Subscription> subscriptions, out List<Transfer> transfers, out WalletError error) { subscriptions = null; transfers = null; paymentsTotalCount = 0; error = WalletError.ServerError; // получить кошелек пользователя и вернуть его Wallet wallet = null; try { using (var ctx = DatabaseContext.Instance.Make()) { // получить пользователя var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin); if (user == null) { error = WalletError.AuthenticationError; return null; } // получить кошелек var walletBase = ctx.WALLET.FirstOrDefault(w => w.User == user.ID); if (walletBase == null) { error = WalletError.ServerError; return null; } wallet = LinqToEntity.DecorateWallet(walletBase); subscriptions = new List<Subscription>(); transfers = new List<Transfer>(); // получить подписки пользователя subscriptions = (from subs in ctx.SUBSCRIPTION join srv in ctx.SERVICE on subs.Service equals srv.ID where subs.User == user.ID select new TradeSharp.Contract.Entity.Subscription { User = subs.User, RenewAuto = subs.RenewAuto, Service = subs.Service, TimeEnd = subs.TimeEnd, TimeStarted = subs.TimeStarted, PaidService = new PaidService { User = srv.User, AccountId = srv.AccountId, Currency = srv.Currency, Comment = srv.Comment, ServiceType = (PaidServiceType)srv.ServiceType, Id = srv.ID, FixedPrice = srv.FixedPrice } }).ToList(); // получить последние платежи по кошельку paymentsTotalCount = ctx.TRANSFER.Count(t => t.User == user.ID); transfers = (from trans in ctx.TRANSFER where trans.User == user.ID select trans).Take(maxPaymentsQuery).ToList().Select( LinqToEntity.DecorateTransfer).ToList(); error = WalletError.OK; } } catch (Exception ex) { Logger.ErrorFormat("GetUserWalletSubscriptionAndLastPayments({0}) - exception: {1}", userLogin, ex); } return wallet; }
public List <Transfer> GetAllUserPayments(ProtectedOperationContext ctx, PlatformUser user, out WalletError error) { error = WalletError.OK; if (Channel == null) { throw new Exception("WalletManagerProxy: связь не установлена"); } try { return(Channel.GetAllUserPayments(ctx, user, out error)); } catch { RenewFactory(); try { return(Channel.GetAllUserPayments(ctx, user, out error)); } catch (Exception ex2) { Logger.Error("GetAllUserPayments() error: ", ex2); return(null); } } }
public Wallet GetUserWalletSubscriptionAndLastPayments(ProtectedOperationContext ctx, string userLogin, int maxPaymentsQuery, out List <Subscription> subscriptions, out List <Transfer> transfers, out WalletError error) { subscriptions = null; transfers = null; error = WalletError.OK; if (Channel == null) { throw new Exception("WalletManagerProxy: связь не установлена"); } try { return(Channel.GetUserWalletSubscriptionAndLastPayments(ctx, userLogin, maxPaymentsQuery, out subscriptions, out transfers, out error)); } catch { RenewFactory(); try { return(Channel.GetUserWalletSubscriptionAndLastPayments(ctx, userLogin, maxPaymentsQuery, out subscriptions, out transfers, out error)); } catch (Exception ex2) { Logger.Error("GetUserWalletSubscriptionAndLastPayments() error: ", ex2); return(null); } } }
public bool SubscribeOnService(ProtectedOperationContext ctx, string login, int serviceId, bool renewAuto, bool unsubscribe, out WalletError error) { error = WalletError.OK; if (Channel == null) { throw new Exception("WalletManagerProxy: связь не установлена"); } try { return(Channel.SubscribeOnService(ctx, login, serviceId, renewAuto, unsubscribe, out error)); } catch { RenewFactory(); try { return(Channel.SubscribeOnService(ctx, login, serviceId, renewAuto, unsubscribe, out error)); } catch (Exception ex2) { Logger.Error("SubscribeOnService() error: ", ex2); return(false); } } }
public Wallet GetUserWalletSubscriptionAndLastPayments(ProtectedOperationContext ctx, string userLogin, int maxPaymentsQuery, out List<Subscription> subscriptions, out List<Transfer> transfers, out WalletError error) { subscriptions = null; transfers = null; error = WalletError.OK; if (Channel == null) throw new Exception("WalletManagerProxy: связь не установлена"); try { return Channel.GetUserWalletSubscriptionAndLastPayments(ctx, userLogin, maxPaymentsQuery, out subscriptions, out transfers, out error); } catch { RenewFactory(); try { return Channel.GetUserWalletSubscriptionAndLastPayments(ctx, userLogin, maxPaymentsQuery, out subscriptions, out transfers, out error); } catch (Exception ex2) { Logger.Error("GetUserWalletSubscriptionAndLastPayments() error: ", ex2); return null; } } }
public WalletErrorException(WalletError error, Exception innerException) : base(error.ToString(), innerException) { }
public Wallet TransferToTradingAccount(ProtectedOperationContext ctx, string userLogin, int accountId, decimal amountInWalletCurrency, out WalletError error) { error = WalletError.OK; if (Channel == null) { RenewFactory(); } try { return(Channel.TransferToTradingAccount(ctx, userLogin, accountId, amountInWalletCurrency, out error)); } catch { RenewFactory(); try { return(Channel.TransferToTradingAccount(ctx, userLogin, accountId, amountInWalletCurrency, out error)); } catch (Exception ex2) { Logger.Error("TransferToTradingAccount() error: ", ex2); return(null); } } }
public WalletErrorException(WalletError error) : base(error.ToString()) { }
public Wallet TransferToTradingAccount(ProtectedOperationContext secCtx, string userLogin, int accountId, decimal amountInWalletCurrency, out WalletError error) { var rst = DepositOrWithdraw(secCtx, true, userLogin, accountId, amountInWalletCurrency, out error); return(rst); }
public bool SubscribeOnService(ProtectedOperationContext ctx, string login, int serviceId, bool renewAuto, bool unsubscribe, out WalletError error) { error = WalletError.OK; if (Channel == null) throw new Exception("WalletManagerProxy: связь не установлена"); try { return Channel.SubscribeOnService(ctx, login, serviceId, renewAuto, unsubscribe, out error); } catch { RenewFactory(); try { return Channel.SubscribeOnService(ctx, login, serviceId, renewAuto, unsubscribe, out error); } catch (Exception ex2) { Logger.Error("SubscribeOnService() error: ", ex2); return false; } } }
public WalletErrorException(WalletError error, string message) : base(error.ToString() + ": " + message) { }
/// <summary> /// просто пополнить счет, вывести оттуда долю или пополнить ПАММ-пай /// </summary> private Wallet DepositOrWithdraw(ProtectedOperationContext secCtx, bool putOnAccount, string userLogin, int accountId, decimal amountInSrcCurrency, out WalletError error) { var operationParams = string.Format("DepositOrWithdraw(log={0}, acc={1}, amt={2})", userLogin, accountId, amountInSrcCurrency.ToStringUniformMoneyFormat()); if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false)) { Logger.Error(operationParams + ": InsufficientRights"); error = WalletError.InsufficientRights; return(null); } if (amountInSrcCurrency <= 0) { Logger.Error(operationParams + ": amountInSrcCurrency <= 0"); error = WalletError.InvalidData; return(null); } // перевести деньги на счет / со счета на кошелек try { using (var ctx = DatabaseContext.Instance.Make()) { // счет var account = ctx.ACCOUNT.FirstOrDefault(a => a.ID == accountId); if (account == null) { Logger.Error(operationParams + ": account is not found"); error = WalletError.InvalidData; return(null); } // пользователь и кошелек var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin); if (user == null) { Logger.Error(operationParams + ": user is not found"); error = WalletError.InvalidData; return(null); } var wallet = ctx.WALLET.FirstOrDefault(w => w.User == user.ID); if (wallet == null) { Logger.Error(operationParams + ": wallet is not found"); error = WalletError.InvalidData; return(null); } // это - ПАММ-счет или обычный счет? var userShare = GetAccountSharePercent(ctx, accountId, user.ID); if (userShare < 100M) { var status = new WalletManager4Pamm(secCtx, userLogin, accountId).InvestOrWithdrawFromPamm( amountInSrcCurrency, !putOnAccount, false, ctx); error = status == RequestStatus.OK ? WalletError.OK : WalletError.InvalidData; if (error != WalletError.OK) { Logger.Error(operationParams + ": InvestOrWithdrawFromPamm - " + status); } return(LinqToEntity.DecorateWallet(wallet)); } // деньги - в кошелек if (putOnAccount) { return(PutMoneyOnUserOwnedAccount(accountId, amountInSrcCurrency, out error, wallet, account, ctx, user)); } // перевести со счета в кошелек return(GetMoneyFromUserOwnedAccount(accountId, amountInSrcCurrency, out error, account, wallet, ctx, user)); } } catch (Exception ex) { Logger.ErrorFormat("Ошибка в TransferToTradingAccount({0}): {1}", accountId, ex); error = WalletError.ServerError; return(null); } }
public WalletErrorException(WalletError error, string message, Exception innerException) : base(error.ToString() + ": " + message, innerException) { }
private Wallet GetMoneyFromUserOwnedAccount(int accountId, decimal amountInSrcCurrency, out WalletError error, ACCOUNT account, WALLET wallet, TradeSharpConnection ctx, PLATFORM_USER user) { var amountWallet = amountInSrcCurrency; if (account.Currency != wallet.Currency) { // найти котировку и перевести string errorString; var amountTarget = DalSpot.Instance.ConvertSourceCurrencyToTargetCurrency(wallet.Currency, account.Currency, (double)amountWallet, QuoteStorage.Instance.ReceiveAllData(), out errorString); if (!amountTarget.HasValue) { Logger.ErrorFormat("DepositOrWithdraw({0} {1}): {2} (withdraw)", amountInSrcCurrency, account.Currency + "/" + wallet.Currency, errorString); error = WalletError.CurrencyExchangeFailed; return(null); } amountWallet = amountTarget.Value; } // достаточно ли средств на счете? // проверить средства / зарезервированное марж. обеспечение decimal equity, usedMargin; if (!GetAccountEquityAndUsedMargin(account, out equity, out usedMargin)) { error = WalletError.ServerError; return(null); } if (equity - usedMargin < amountInSrcCurrency) { error = WalletError.ServerError; return(null); } // списать со счета в пользу кошелька wallet.Balance += amountInSrcCurrency; account.Balance -= amountInSrcCurrency; var date = DateTime.Now; var bc = ctx.BALANCE_CHANGE.Add(new BALANCE_CHANGE { AccountID = accountId, Amount = amountInSrcCurrency, ChangeType = (int)BalanceChangeType.Withdrawal, ValueDate = date, Description = "Списание на кошелек №" + wallet.User }); ctx.SaveChanges(); ctx.TRANSFER.Add(new TRANSFER { Amount = amountWallet, TargetAmount = amountWallet, User = user.ID, Comment = "Вывод средств со счета №" + account.ID, ValueDate = date, BalanceChange = bc.ID, }); ctx.SaveChanges(); error = WalletError.OK; return(LinqToEntity.DecorateWallet(wallet)); }
private static Wallet PutMoneyOnUserOwnedAccount(int accountId, decimal amountInSrcCurrency, out WalletError error, WALLET wallet, ACCOUNT account, TradeSharpConnection ctx, PLATFORM_USER user) { // достаточно ли денег в кошельке? if (amountInSrcCurrency > wallet.Balance) { error = WalletError.InsufficientFunds; return(null); } // перевести объем в валюту счета var amount = amountInSrcCurrency; if (account.Currency != wallet.Currency) { // найти котировку и перевести string errorString; var amountTarget = DalSpot.Instance.ConvertSourceCurrencyToTargetCurrency(account.Currency, wallet.Currency, (double)amount, QuoteStorage.Instance.ReceiveAllData(), out errorString); if (!amountTarget.HasValue) { Logger.ErrorFormat("DepositOrWithdraw({0} {1}): {2}", amountInSrcCurrency, account.Currency + "/" + wallet.Currency, errorString); error = WalletError.CurrencyExchangeFailed; return(null); } amount = amountTarget.Value; } // списать с кошелька и пополнить счет wallet.Balance -= amountInSrcCurrency; account.Balance += amount; var dateOper = DateTime.Now; var balanceChange = ctx.BALANCE_CHANGE.Add(new BALANCE_CHANGE { AccountID = accountId, Amount = amount, ChangeType = (int)BalanceChangeType.Deposit, ValueDate = dateOper, Description = "Пополнение с кошелька №" + wallet.User }); try { ctx.SaveChanges(); } catch (Exception ex) { Logger.Error("DepositOrWithdraw() - error saving balance change", ex); error = WalletError.ServerError; return(null); } var balanceChangeId = balanceChange.ID; ctx.TRANSFER.Add(new TRANSFER { Amount = -amountInSrcCurrency, TargetAmount = -amountInSrcCurrency, User = user.ID, Comment = "Т. счет №" + account.ID, ValueDate = dateOper, BalanceChange = balanceChangeId, }); try { ctx.SaveChanges(); } //catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException) //{ //} catch (Exception ex) { Logger.Error("DepositOrWithdraw() - error saving transfer for user " + user.ID + ", balance change Id: " + balanceChangeId + ", user: " + user.ID, ex); error = WalletError.ServerError; return(null); } error = WalletError.OK; return(LinqToEntity.DecorateWallet(wallet)); }
public Wallet TransferToWallet(ProtectedOperationContext secCtx, string userLogin, int accountId, decimal amountInAccountCurrency, out WalletError error) { return(DepositOrWithdraw(secCtx, false, userLogin, accountId, amountInAccountCurrency, out error)); }
public List<Transfer> GetAllUserPayments(ProtectedOperationContext ctx, PlatformUser user, out WalletError error) { error = WalletError.OK; if (Channel == null) throw new Exception("WalletManagerProxy: связь не установлена"); try { return Channel.GetAllUserPayments(ctx, user, out error); } catch { RenewFactory(); try { return Channel.GetAllUserPayments(ctx, user, out error); } catch (Exception ex2) { Logger.Error("GetAllUserPayments() error: ", ex2); return null; } } }