コード例 #1
0
ファイル: NuWallet.cs プロジェクト: johnmensen/TradeSharp
        public void TestSetup()
        {
            connectionPersistent = TradeSharpConnectionPersistent.InitializeTradeSharpConnection();
            TradeSharpDictionary.Initialize(MoqTradeSharpDictionary.Mock);
            walletManager = new WalletManager();

            DatabaseContext.InitializeFake(connectionPersistent);
        }
コード例 #2
0
        public RequestStatus InvestOrWithdrawFromPamm(decimal sumInWalletCurrency, bool withdrawNotInvest,
                                                      bool withdrawAll,
                                                      TradeSharpConnection databaseConnection)
        {
            this.sumInWalletCurrency = sumInWalletCurrency;
            this.withdrawNotInvest   = withdrawNotInvest;
            this.withdrawAll         = withdrawAll;

            var checkStatus = CheckAmount();

            if (checkStatus != RequestStatus.OK)
            {
                return(checkStatus);
            }

            ctx = databaseConnection ?? DatabaseContext.Instance.Make();
            try
            {
                // найти подписанта
                var subscriber = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == login);
                if (subscriber == null)
                {
                    Logger.ErrorFormat("InvestOrWithdrawFromPamm(login={0}) - подписант не найден", login);
                    return(RequestStatus.IncorrectData);
                }

                // владелец целевого ПАММ-счета
                var stat = FindPAMMServiceWithOwner();
                if (stat != RequestStatus.OK)
                {
                    return(stat);
                }

                // посчитать средства по счету
                var  account = ctx.ACCOUNT.First(a => a.ID == accountId);
                var  quotes  = QuoteStorage.Instance.ReceiveAllData();
                bool noQuoteError;

                List <AccountShare> shares;
                var equity = WalletManager.CalculateAccountEquityWithShares(ctx, account, owner.ID, quotes, out shares,
                                                                            out noQuoteError);
                if (noQuoteError)
                {
                    Logger.ErrorFormat(
                        "InvestOrWithdrawFromPamm(acc={0}) - невозможно произвести расчет текущей прибыли - нет котировок",
                        accountId);
                    return(RequestStatus.ServerError);
                }
                decimal amountInAccountCurx;
                // пересчитать сумму в валюту ПАММа
                // проверить не выводит ли / не заводит ли слишком много?
                var status = CheckShareAndUpdateSubscriberWallet(shares, subscriber, account, quotes,
                                                                 out amountInAccountCurx);
                if (status != RequestStatus.OK)
                {
                    return(status);
                }

                // добавить денег и пересчитать дольки
                var newEquity    = equity + (withdrawNotInvest ? -1 : 1) * amountInAccountCurx;
                var sharePercent = amountInAccountCurx * 100 / newEquity;
                var sharesNew    = shares.Select(s => new AccountShare
                {
                    UserId       = s.UserId,
                    ShareMoney   = s.ShareMoney,
                    SharePercent = s.ShareMoney * 100 / newEquity,
                    HWM          = s.HWM
                }).ToList();

                // доля нового совладельца - пополнить или создать запись
                if (!withdrawNotInvest)
                {
                    var newOwnerShare = sharesNew.FirstOrDefault(s => s.UserId == subscriber.ID);
                    if (newOwnerShare != null)
                    {
                        newOwnerShare.SharePercent += sharePercent;
                        newOwnerShare.ShareMoney   += amountInAccountCurx;
                    }
                    else
                    {
                        sharesNew.Add(new AccountShare
                        {
                            ShareMoney   = amountInAccountCurx,
                            SharePercent = sharePercent,
                            UserId       = subscriber.ID,
                            HWM          = amountInAccountCurx
                        });
                    }
                }

                // найти существующую подписку и либо добавить денег,
                // либо создать новую подписку
                var subscriptExists = ctx.SUBSCRIPTION.Any(s => s.Service == service.ID && s.User == subscriber.ID);
                if (!subscriptExists && !withdrawNotInvest)
                {
                    // добавить подписку
                    ctx.SUBSCRIPTION.Add(new SUBSCRIPTION
                    {
                        User        = subscriber.ID,
                        RenewAuto   = false,
                        Service     = service.ID,
                        TimeStarted = DateTime.Now,
                        TimeEnd     = DateTime.Now
                    });
                }
                else if (subscriptExists && withdrawNotInvest && withdrawAll)
                {
                    // удалить подписку
                    ctx.SUBSCRIPTION.Remove(
                        ctx.SUBSCRIPTION.First(s => s.Service == service.ID && s.User == subscriber.ID));
                }

                // модифицировать записи ACCOUNT_SHARE
                UpdateShares(sharesNew, subscriber.ID);

                // пополнить баланс счета
                account.Balance += amountInAccountCurx;

                // сохранить изменения
                ctx.SaveChanges();
                return(RequestStatus.OK);
            } // using ...
            catch (Exception ex)
            {
                Logger.Error("Ошибка в InvestOrWithdrawFromPamm", ex);
                return(RequestStatus.ServerError);
            }
            finally
            {
                if (databaseConnection == null)
                {
                    ctx.Dispose();
                }
            }
        }