예제 #1
0
 public static Transfer DecorateTransfer(TRANSFER trans)
 {
     return(new Transfer
     {
         Amount = trans.Amount,
         BalanceChange = trans.BalanceChange,
         Comment = trans.Comment,
         Id = trans.ID,
         RefWallet = trans.RefWallet,
         Subscription = trans.Subscription,
         TargetAmount = trans.TargetAmount,
         User = trans.User,
         ValueDate = trans.ValueDate
     });
 }
예제 #2
0
 private static void CorrectBalance(int acId, decimal deltaAmount, TradeSharpConnection conn)
 {
     // поправить депозит
     var bc = new BALANCE_CHANGE
     {
         AccountID = acId,
         ValueDate = DateTime.Now,
         Amount = deltaAmount,
         ChangeType = (int) BalanceChangeType.Withdrawal,
         Description = "public offering"
     };
     conn.BALANCE_CHANGE.Add(bc);
     conn.SaveChanges();
     var userId = conn.PLATFORM_USER_ACCOUNT.First(a => a.Account == acId).PlatformUser;
     var tr = new TRANSFER
     {
         ValueDate = bc.ValueDate,
         BalanceChange = bc.ID,
         Amount = -deltaAmount,
         Comment = "public offering",
         User = userId,
         TargetAmount = - deltaAmount
     };
     conn.TRANSFER.Add(tr);
 }
예제 #3
0
        private ACCOUNT GetAccountData(int accountId, out List<BalanceChange> transfers)
        {
            if (testOnly)
            {
                transfers = new List<BalanceChange>
                {
                    new BalanceChange
                    {
                        AccountID = accountId,
                        Amount = startDepo,
                        ChangeType = BalanceChangeType.Deposit,
                        Currency = "USD",
                        ValueDate = startTime
                    }
                };

                return new ACCOUNT
                {
                    ID = accountId,
                    Balance = startDepo,
                    Currency = "USD",
                    AccountGroup = "Demo",
                    TimeCreated = startTime
                };
            }

            ACCOUNT accountData;
            try
            {
                using (var conn = DatabaseContext.Instance.Make())
                {
                    accountData = conn.ACCOUNT.First(a => a.ID == accountId);
                    transfers = conn.BALANCE_CHANGE.Where(bc =>
                        bc.AccountID == accountId).ToList().Select(LinqToEntity.DecorateBalanceChange).ToList();
                    if (transfers.Count == 0)
                    {
                        // добавить начальное пополнение счета
                        var firstBc = new BALANCE_CHANGE
                        {
                            AccountID = accountId,
                            ValueDate = accountData.TimeCreated,
                            ChangeType = (int) BalanceChangeType.Deposit,
                            Description = "initial depo",
                            Amount = startDepo
                        };
                        conn.BALANCE_CHANGE.Add(firstBc);
                        conn.SaveChanges();

                        var pa = conn.PLATFORM_USER_ACCOUNT.First(p => p.Account == accountId);

                        var trans = new TRANSFER
                        {
                            Amount = firstBc.Amount,
                            ValueDate = firstBc.ValueDate,
                            BalanceChange = firstBc.ID,
                            Comment = "initial depo",
                            TargetAmount = firstBc.Amount,
                            User = pa.PlatformUser
                        };
                        conn.TRANSFER.Add(trans);
                        conn.SaveChanges();
                        transfers.Add(LinqToEntity.DecorateBalanceChange(firstBc));
                    }
                }
                return accountData;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("Error in GetAccountData({0}): {1}", accountId, ex);
                throw;
            }
        }
예제 #4
0
        /// <summary>
        /// Зачисляем на T# кошелёк пользователя определённую сумму.
        /// </summary>
        /// <param name="wallet">T# кошелёк</param>
        /// <param name="additionalAmount">валюта кошелёка T#</param>
        /// <param name="data"></param>
        /// <param name="userPaymentSysId"></param>
        /// <returns></returns>
        public static bool DepositOnWallet(WALLET wallet, decimal additionalAmount, DateTime data, int userPaymentSysId)
        {
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var comment = string.Format("Зачисление на TradeSharp кошелёк {0} средств в размере {1} {2}.",
                                                wallet.User, additionalAmount.ToStringUniformMoneyFormat(), wallet.Currency);
                    var formatComment = comment.Length < 250 ? comment : comment.Substring(0, 249);
                    #region

                    var transfer = new TRANSFER
                        {
                            User = wallet.User,
                            Amount = additionalAmount,
                            ValueDate = DateTime.Now,
                            TargetAmount = additionalAmount,
                            Comment = formatComment
                        };

                    ctx.TRANSFER.Add(transfer);

                    ctx.PAYMENT_SYSTEM_TRANSFER.Add(new PAYMENT_SYSTEM_TRANSFER
                        {
                            UserPaymentSys = userPaymentSysId,
                            Ammount = additionalAmount,
                            Currency = wallet.Currency,
                            DateProcessed = DateTime.Now,
                            DateValue = data,
                            Transfer = transfer.ID,
                            Comment = formatComment
                        });
                    #endregion

                    try
                    {
                        var wal = ctx.WALLET.SingleOrDefault(x => x.User == wallet.User);
                        if (wal == null)
                        {
                            Logger.ErrorFormat("DepositOnWallet() - WALLET с id {0} не найден в БД", wallet.User);
                            return false;
                        }
                        wal.Balance += additionalAmount;

                        ctx.SaveChanges();
                        Logger.InfoFormat("Произведено зачисление средств на TradeSharp кошелёк {0} в размере {1} {2}.",
                                          wallet.User, additionalAmount, wallet.Currency);
                        return true;
                    }
                    #region catch
                    catch (Exception ex)
                    {
                        var message = string.Format(
                            "Не удалось сохранить в базу данных запись о зачислении на TradeSharp кошелька {0} средств в размере {1} {2}. " +
                            " Будет произведена попытка провести платёж как 'Неопознанный'. Администратор базы данных должен вручную зачислить " +
                            "средства на этот кошелёк, внеся изменения в таблицы WALLET и PAYMENT_SYSTEM_TRANSFER.",
                            wallet.User, additionalAmount.ToStringUniformMoneyFormat(), wallet.Currency);
                        Logger.Error(message, ex);
                        return false;
                    }
                    #endregion
                }
            }
            #region catch
            catch (Exception ex)
            {
                Logger.Error("DepositOnWallet()", ex);
                return false;
            }
            #endregion
        }
예제 #5
0
        /// <summary>
        /// зарегистриорвать 'Неопознанный' платёж. При этом в таблице PAYMENT_SYSTEM_TRANSFER редактируется поле Transfer.
        /// после этого сумма из поля Ammount зачисляется в кошелёк.
        /// </summary>
        /// <param name="paymentSystemTransferId">Уникальный идентификатор "неопознанного" платежа (запись в таблице PAYMENT_SYSTEM_TRANSFER, которую сейчас будем редактировать)</param>
        /// <param name="userPaymentSysId">Уникальный идентификатор записи о платёжной системе (таблица USER_PAYMENT_SYSTEM), из которой беруться данные о кошельке</param>
        public static bool RegistrationUndefinedTransfer(int paymentSystemTransferId, int? userPaymentSysId)
        {
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var paymentSystemTransfer = ctx.PAYMENT_SYSTEM_TRANSFER.Single(x => x.Id == paymentSystemTransferId);
                    var userWalletCurrency = paymentSystemTransfer.Currency;
                    var additionalAmount = paymentSystemTransfer.Ammount;

                    var userId = paymentSystemTransfer.USER_PAYMENT_SYSTEM != null ? paymentSystemTransfer.USER_PAYMENT_SYSTEM.UserId :
                        ctx.USER_PAYMENT_SYSTEM.Single(w => w.Id == userPaymentSysId).UserId;

                    var comment = string.Format("Восстановление 'неопознанного' платежа {3}. Зачисление на TradeSharp кошелёк {0} средств в размере {1} {2}.",
                                                userId, additionalAmount.ToStringUniformMoneyFormat(), userWalletCurrency, paymentSystemTransferId);

                    var transfer = new TRANSFER
                    {
                        User = userId,
                        Amount = additionalAmount,
                        ValueDate = DateTime.Now,
                        TargetAmount = additionalAmount,
                        Comment = comment.Length < 250 ? comment : comment.Substring(0, 249)
                    };
                    ctx.TRANSFER.Add(transfer);

                    if (paymentSystemTransfer.USER_PAYMENT_SYSTEM == null) paymentSystemTransfer.UserPaymentSys = userPaymentSysId;
                    paymentSystemTransfer.Transfer = transfer.ID;

                    try
                    {
                        var wal = ctx.WALLET.Single(x => x.User == userId);
                        wal.Balance += additionalAmount;

                        ctx.SaveChanges();
                        Logger.InfoFormat("RegistrationUndefinedTransfer() - Произведено восстановление 'неопознанного' платежа и зачисление средств на TradeSharp кошелёк {0} в размере {1} {2}.",
                                          userId, additionalAmount, userWalletCurrency);
                        return true;
                    }
                    #region catch
                    catch (Exception ex)
                    {
                        var message = string.Format(
                            "При попытке зарегистриорвать 'Неопознанный' платёж, не удалось сохранить в базу данных запись о зачислении на" +
                            " TradeSharp кошелёк {0} средств в размере {1} {2}. " +
                            " Администратор базы данных должен вручную зачислить " +
                            "средства на этот кошелёк, внеся изменения в таблицы WALLET и PAYMENT_SYSTEM_TRANSFER.",
                            userId, additionalAmount.ToStringUniformMoneyFormat(), userWalletCurrency);
                        Logger.Error(message, ex);
                        return false;
                    }
                    #endregion
                }
            }
            #region catch
            catch (Exception ex)
            {
                Logger.Error("RegistrationUndefinedTransfer()", ex);
                return false;
            }
            #endregion
        }
예제 #6
0
        public static List<string> CorrectBalance(List<int> actIds, int minAmount, int maxAmount, int maxDelta)
        {
            var rand = new Random();
            var messages = new List<string>();
            foreach (var acId in actIds)
            {
                var accountId = acId;
                var targetAmount = rand.Next(minAmount, maxAmount);
                using (var conn = DatabaseContext.Instance.Make())
                {
                    var sumDeltaBalance = conn.BALANCE_CHANGE.Where(b => b.AccountID == accountId).Sum(b =>
                        (b.ChangeType == (int)BalanceChangeType.Loss ||
                         b.ChangeType == (int)BalanceChangeType.Withdrawal)
                            ? -b.Amount
                            : b.Amount);
                    var accountBalance = conn.ACCOUNT.Where(a => a.ID == accountId).Select(a => a.Balance).First();
                    if (accountBalance != sumDeltaBalance)
                    {
                        var acc = conn.ACCOUNT.First(a => a.ID == accountId);
                        acc.Balance = sumDeltaBalance;
                    }

                    var delta = Math.Abs(targetAmount - sumDeltaBalance);
                    if (delta > maxDelta)
                    {
                        // пополнить - вывести
                        var amount = targetAmount - sumDeltaBalance;
                        var bc = new BALANCE_CHANGE
                        {
                            AccountID = accountId,
                            ChangeType =
                                amount > 0 ? (int)BalanceChangeType.Deposit : (int)BalanceChangeType.Withdrawal,
                            Description = amount > 0 ? "rebalance (depo)" : "rebalance (wdth)",
                            ValueDate = DateTime.Now,
                            Amount = delta
                        };
                        conn.BALANCE_CHANGE.Add(bc);
                        conn.SaveChanges();

                        var ownerId = (from pa in conn.PLATFORM_USER_ACCOUNT
                                       join a in conn.ACCOUNT on pa.Account equals a.ID
                                       select pa.PlatformUser).First();

                        // проводка
                        var trans = new TRANSFER
                        {
                            Amount = delta,
                            ValueDate = DateTime.Now,
                            TargetAmount = delta,
                            BalanceChange = bc.ID,
                            Comment = bc.Description,
                            User = ownerId
                        };
                        conn.TRANSFER.Add(trans);

                        messages.Add(string.Format("#{0}: {1} -> {2} USD",
                            accountId, sumDeltaBalance.ToStringUniformMoneyFormat(),
                            targetAmount.ToStringUniformMoneyFormat()));
                    }
                    else
                    {
                        messages.Add(string.Format("#{0}: {1} USD",
                            accountId, sumDeltaBalance.ToStringUniformMoneyFormat()));
                    }
                    conn.SaveChanges();
                }
            }

            return messages;
        }
예제 #7
0
        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;
            }
        }
예제 #8
0
 public static Transfer DecorateTransfer(TRANSFER trans)
 {
     return new Transfer
         {
             Amount = trans.Amount,
             BalanceChange = trans.BalanceChange,
             Comment = trans.Comment,
             Id = trans.ID,
             RefWallet = trans.RefWallet,
             Subscription = trans.Subscription,
             TargetAmount = trans.TargetAmount,
             User = trans.User,
             ValueDate = trans.ValueDate
         };
 }