示例#1
0
        public void DistributeRewards(FiiiPayRewardMessage message, int fiiicoinId)
        {
            MerchantAccountDAC maDAC = new MerchantAccountDAC();
            var merchant             = maDAC.GetByUsername(message.Account);

            if (merchant == null)
            {
                throw new CommonException(10000, $"无效的商家名:{message.Account}");
            }

            InviteRecord invitor = GetInvitor(merchant.Id);

            if (invitor == null)
            {
                throw new CommonException(10000, "没有邀请人");
            }

            var invitedList = new InviteRecordDAC().GetFiiiPosRecordsByInvitorId(invitor.InviterAccountId, InviteType.Fiiipos);
            var rewardRate  = GetRewardPercentage(invitedList == null ? 0 : invitedList.Count);

            if (rewardRate == 0)
            {
                throw new CommonException(10000, "没有达到奖励条件");
            }

            decimal t            = (decimal)Math.Pow(10, -8);
            long    nTotalReward = (long)Math.Floor(message.Reward * rewardRate);

            if (nTotalReward == 0)
            {
                throw new CommonException(10000, "奖励金额为0");
            }
            decimal  rewardAmount = nTotalReward * t;
            DateTime dtNow        = DateTime.UtcNow;

            if (message.CurrentDate > 0)
            {
                dtNow = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(message.CurrentDate);
            }
            var distributeRecord = new RewardDistributeRecords
            {
                UserAccountId     = invitor.InviterAccountId,
                MerchantAccountId = merchant.Id,
                SN             = message.SN,
                OriginalReward = message.Reward,
                Percentage     = rewardRate,
                ActualReward   = rewardAmount,
                Timestamp      = dtNow
            };

            long    profitId;
            decimal oldBalance    = 0;
            var     invitorWallet = uwDAC.GetByAccountId(invitor.InviterAccountId, fiiicoinId);

            using (var scope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 0, 1, 30)))
            {
                if (invitorWallet == null)
                {
                    invitorWallet = CreateWallet(invitor.InviterAccountId, fiiicoinId, rewardAmount);
                }
                else
                {
                    oldBalance = invitorWallet.Balance;
                    uwDAC.Increase(invitorWallet.Id, rewardAmount);
                }

                var profitDetail = new ProfitDetail
                {
                    InvitationId = invitor.Id,
                    CryptoAmount = rewardAmount,
                    AccountId    = invitor.InviterAccountId,
                    Status       = InviteStatusType.IssuedActive,
                    Type         = ProfitType.InvitePiiiPos,
                    OrderNo      = CreateOrderno(),
                    Timestamp    = dtNow,
                    CryptoId     = invitorWallet.CryptoId,
                    CryptoCode   = "FIII"
                };
                profitId = pfDAC.Insert(profitDetail);

                uwsDAC.Insert(new UserWalletStatement
                {
                    WalletId      = invitorWallet.Id,
                    Action        = UserWalletStatementAction.Reward,
                    Amount        = rewardAmount,
                    Balance       = oldBalance + rewardAmount,
                    FrozenAmount  = 0,
                    FrozenBalance = invitorWallet.FrozenBalance,
                    Timestamp     = dtNow
                });

                transDAC.Insert(new UserTransaction
                {
                    AccountId    = invitor.InviterAccountId,
                    Amount       = rewardAmount,
                    CryptoCode   = "FIII",
                    CryptoId     = fiiicoinId,
                    DetailId     = profitId.ToString(),
                    Id           = Guid.NewGuid(),
                    MerchantName = string.Empty,
                    OrderNo      = profitDetail.OrderNo,
                    Status       = 2,
                    Timestamp    = dtNow,
                    Type         = UserTransactionType.Profit
                });

                distributeRecord.ProfitId = profitId;
                rdrDAC.Insert(distributeRecord);

                scope.Complete();
            }

            if (profitId > 0)
            {
                try
                {
                    MessagePushService.PubUserInviteSuccessed(profitId, 0);
                }
                catch (Exception ex)
                {
                    throw new CommonException(10000, ex.Message);
                }
            }
        }
示例#2
0
        /// <summary>
        /// 插入记录
        /// </summary>
        /// <param name="inviteCode">邀请码</param>
        /// <param name="accoundId">被邀请人id</param>
        /// /// <param name="type">1:fiiipay 2:fiiipos</param>
        public void InsertRecord(InviteRecordIM im)
        {
            //判断是fiiipos还是fiiipay

            //1 插入数据 invite profit两个表 邀请双方都支持插入数据 钱包 流水进行更新
            // 判断当前邀请人数到达五十 进行推送。。。。。。。。。。。。

            //2 插入数据 invite
            if (!(im.Type == (int)SystemPlatform.FiiiPay || im.Type == (int)SystemPlatform.FiiiPOS))
            {
                throw new ArgumentException("只支持fiiipay和fiiipos邀请");
            }
            var userAccountDAC    = new UserAccountDAC();
            var account           = userAccountDAC.GetByInvitationCode(im.InvitationCode);
            var settingCollection = new MasterSettingDAC().SelectByGroup("InviteReward");
            var cryptoCurrencty   = new CryptocurrencyDAC().GetByCode("FIII");
            var cryptoId          = cryptoCurrencty.Id;

            if (im.Type == (int)SystemPlatform.FiiiPay)
            {
                var iDAC        = new InviteRecordDAC();
                var pfDAC       = new ProfitDetailDAC();
                var uwComponent = new UserWalletComponent();

                var uwDAC  = new UserWalletDAC();
                var uwsDAC = new UserWalletStatementDAC();
                var utDAC  = new UserTransactionDAC();

                var inviteMoney  = decimal.Parse(settingCollection.Where(item => item.Name == "Invite_Reward_Amount").Select(item => item.Value).FirstOrDefault());
                var rewardMoney  = decimal.Parse(settingCollection.Where(item => item.Name == "Over_People_Count_Reward_Amount").Select(item => item.Value).FirstOrDefault());
                var maxCount     = decimal.Parse(settingCollection.Where(item => item.Name == "Max_Reward_Amount").Select(item => item.Value).FirstOrDefault());
                var orderNo1     = CreateOrderno();
                var orderNo2     = CreateOrderno();
                var inviteWallet = uwComponent.GetUserWallet(account.Id, cryptoId);
                if (inviteWallet == null)
                {
                    inviteWallet = uwComponent.GenerateWallet(account.Id, cryptoId);
                }

                var beInvitedWallet = uwComponent.GetUserWallet(im.BeInvitedAccountId, cryptoId);
                if (beInvitedWallet == null)
                {
                    beInvitedWallet = uwComponent.GenerateWallet(im.BeInvitedAccountId, cryptoId);
                }

                int     inviteId;
                long    profitId1    = 0; //邀请人奖励ID
                long    profitId2    = 0; //被邀请人奖励ID
                long    exProfitId1  = 0; //邀请人额外奖励ID
                decimal totalReward  = pfDAC.GetTotalReward(account);
                int     invitedCount = pfDAC.GetInvitedCount(account);

                using (var scope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, new TimeSpan(0, 0, 1, 30)))
                {
                    //插入数据到inviterecord表中
                    inviteId = iDAC.Insert(new InviteRecord()
                    {
                        Type = (InviteType)im.Type, AccountId = im.BeInvitedAccountId, Timestamp = DateTime.UtcNow, InviterCode = im.InvitationCode, InviterAccountId = account.Id
                    });

                    if (totalReward < maxCount)
                    {
                        profitId1 = pfDAC.Insert(new ProfitDetail()
                        {
                            InvitationId = inviteId,
                            CryptoAmount = inviteMoney,
                            AccountId    = account.Id,
                            Status       = InviteStatusType.IssuedFrozen,
                            Type         = ProfitType.InvitePiiiPay,
                            OrderNo      = orderNo1,
                            Timestamp    = DateTime.UtcNow,
                            CryptoId     = cryptoId
                        });

                        utDAC.Insert(new UserTransaction
                        {
                            Id         = Guid.NewGuid(),
                            AccountId  = account.Id,
                            CryptoId   = cryptoCurrencty.Id,
                            CryptoCode = cryptoCurrencty.Code,
                            Type       = UserTransactionType.Profit,
                            DetailId   = profitId1.ToString(),
                            Status     = (byte)InviteStatusType.IssuedFrozen,
                            Timestamp  = DateTime.UtcNow,
                            Amount     = inviteMoney,
                            OrderNo    = orderNo1
                        });

                        uwDAC.IncreaseFrozen(inviteWallet.Id, inviteMoney);

                        uwsDAC.Insert(new UserWalletStatement
                        {
                            WalletId      = inviteWallet.Id,
                            Action        = UserWalletStatementAction.Invite,
                            Amount        = 0,
                            Balance       = inviteWallet.Balance,
                            FrozenAmount  = inviteMoney,
                            FrozenBalance = inviteWallet.FrozenBalance + inviteMoney,
                            Timestamp     = DateTime.UtcNow
                        });

                        // 每当满50人时则可以奖励 采用了插入操作 所以只要满足为49个就可以了
                        if ((invitedCount + 1) % 50 == 0)
                        {
                            var pd50 = new ProfitDetail()
                            {
                                InvitationId = inviteId,
                                CryptoAmount = rewardMoney,
                                AccountId    = account.Id,
                                Status       = InviteStatusType.IssuedFrozen,
                                Type         = ProfitType.Reward,
                                OrderNo      = CreateOrderno(),
                                Timestamp    = DateTime.UtcNow,
                                CryptoId     = cryptoId
                            };
                            exProfitId1 = pfDAC.Insert(pd50);

                            utDAC.Insert(new UserTransaction
                            {
                                Id         = Guid.NewGuid(),
                                AccountId  = account.Id,
                                CryptoId   = cryptoCurrencty.Id,
                                CryptoCode = cryptoCurrencty.Code,
                                Type       = UserTransactionType.Profit,
                                DetailId   = exProfitId1.ToString(),
                                Status     = (byte)InviteStatusType.IssuedFrozen,
                                Timestamp  = DateTime.UtcNow,
                                Amount     = rewardMoney,
                                OrderNo    = pd50.OrderNo
                            });

                            uwDAC.IncreaseFrozen(inviteWallet.Id, rewardMoney);

                            uwsDAC.Insert(new UserWalletStatement
                            {
                                WalletId      = inviteWallet.Id,
                                Action        = UserWalletStatementAction.Invite,
                                Amount        = 0,
                                Balance       = inviteWallet.Balance,
                                FrozenAmount  = rewardMoney,
                                FrozenBalance = inviteWallet.FrozenBalance + inviteMoney + rewardMoney,
                                Timestamp     = DateTime.UtcNow
                            });
                        }
                        profitId2 = pfDAC.Insert(new ProfitDetail()
                        {
                            InvitationId = inviteId,
                            CryptoAmount = inviteMoney,
                            AccountId    = im.BeInvitedAccountId,
                            Type         = ProfitType.BeInvited,
                            Status       = InviteStatusType.IssuedActive,
                            OrderNo      = orderNo2,
                            Timestamp    = DateTime.UtcNow,
                            CryptoId     = cryptoId
                        });
                        utDAC.Insert(new UserTransaction
                        {
                            Id         = Guid.NewGuid(),
                            AccountId  = im.BeInvitedAccountId,
                            CryptoId   = cryptoCurrencty.Id,
                            CryptoCode = cryptoCurrencty.Code,
                            Type       = UserTransactionType.Profit,
                            DetailId   = profitId2.ToString(),
                            Status     = (byte)InviteStatusType.IssuedActive,
                            Timestamp  = DateTime.UtcNow,
                            Amount     = inviteMoney,
                            OrderNo    = orderNo2
                        });
                        uwDAC.Increase(beInvitedWallet.Id, inviteMoney);
                        uwsDAC.Insert(new UserWalletStatement
                        {
                            WalletId      = beInvitedWallet.Id,
                            Action        = UserWalletStatementAction.BeInvite,
                            Amount        = inviteMoney,
                            Balance       = beInvitedWallet.Balance + inviteMoney,
                            FrozenAmount  = 0,
                            FrozenBalance = beInvitedWallet.FrozenBalance,
                            Timestamp     = DateTime.UtcNow
                        });
                    }
                    scope.Complete();
                }

                if (!(im.Type == (int)SystemPlatform.FiiiPay || im.Type == (int)SystemPlatform.FiiiPOS))
                {
                    throw new ArgumentException("只支持fiiipay和fiiipos邀请");
                }

                if (im.Type == (int)SystemPlatform.FiiiPay)
                {
                    UserMSMQ.PubUserInviteSuccessed(profitId2, 0);
                }
                //else if (im.Type == SystemPlatform.FiiiPOS)
                //    MerchantMSMQ.PubUserInviteSuccessed(profitId2, 0);
            }
            //else
            //{
            //    var iDAC = new InviteRecordDAC();
            //    iDAC.Insert(new InviteRecord() { Type = im.Type, AccountId = im.BeInvitedAccountId, Timestamp = DateTime.UtcNow, InviterCode = im.InvitationCode, InviterAccountId = account.Id });
            //}
        }
示例#3
0
        public RedPocketDetailOM Receive(UserAccount userAccount, string passcode, bool isZH = false)
        {
            if (userAccount == null)
            {
                throw new SystemErrorException();
            }

            if (string.IsNullOrWhiteSpace(passcode))
            {
                throw new CommonException(Argument_Error, MessageResources.InvalidDataFormat);
            }

            if (userAccount.L1VerifyStatus != Entities.Enums.VerifyStatus.Certified)
            {
                throw new CommonException(ReasonCode.NOT_VERIFY_LV1, Resources.EMNeedLV1Verfied);
            }

            var count = RedisHelper.StringGet(LockDbIndex, string.Format(KeyFormat, userAccount.Id));

            if (!string.IsNullOrWhiteSpace(count) && int.Parse(count) >= 10)
            {
                var ttl = RedisHelper.KeyTimeToLive(LockDbIndex, string.Format(KeyFormat, userAccount.Id));
                if (ttl != null)
                {
                    var message = "";
                    var t       = "";
                    try
                    {
                        t       = TimeConvert(ttl.Value, isZH);
                        message = string.Format(MessageResources.RedPocket_PassCodeErrorMaxCount, t);
                    }
                    catch (Exception exception)
                    {
                        _log.Error(exception.Message + "    " + MessageResources.RedPocket_PassCodeErrorMaxCount + "    " + t);
                    }

                    throw new CommonException(MaxError, message);
                }
            }

            var redPocketDAC = new RedPocketDAC();

            var redPocket = redPocketDAC.GetByPassCode(passcode);

            if (redPocket == null)
            {
                var errorCount = ErrorCount(userAccount.Id, count, isZH);
                throw new CommonException(PassCodeError, string.Format(MessageResources.RedPocket_PassCodeError, errorCount, 10 - errorCount));
            }

            if (redPocket.ExpirationDate < DateTime.UtcNow)
            {
                var errorCount = ErrorCount(userAccount.Id, count, isZH);
                throw new CommonException(PassCodeExpired, MessageResources.RedPocket_ReceiveExpired + Environment.NewLine + string.Format(MessageResources.RedPocket_PassCodeError, errorCount, 10 - errorCount));
            }

            var crypto = new CryptocurrencyDAC().GetByCode(redPocket.CryptoCode);

            if (!crypto.Status.HasFlag(Foundation.Entities.Enum.CryptoStatus.RedPocket) || crypto.Enable == 0)
            {
                throw new CommonException(ReasonCode.CURRENCY_FORBIDDEN, MessageResources.CurrencyForbidden);
            }

            var om = new RedPocketDetailOM();
            var redPocketReceiveDAC = new RedPocketReceiverDAC();

            var hasReceive = redPocketReceiveDAC.HasReceive(userAccount.Id, redPocket.Id);

            if (redPocket.Status == RedPocketStatus.Actived && hasReceive == null)
            {
                var userWalletDAC          = new UserWalletDAC();
                var userWalletStatementDAC = new UserWalletStatementDAC();
                var uwComponent            = new UserWalletComponent();
                var userTransactionDAC     = new UserTransactionDAC();

                var wallet = userWalletDAC.GetByCryptoCode(userAccount.Id, redPocket.CryptoCode);
                if (wallet == null)
                {
                    wallet = uwComponent.GenerateWallet(userAccount.Id, redPocket.CryptoCode);
                }

                var min = crypto.DecimalPlace == 8 ? 0.00000001M : crypto.DecimalPlace == 6 ? 0.000001M : 0.00000001M;
                var n   = crypto.DecimalPlace == 8 ? 100000000 : crypto.DecimalPlace == 6 ? 1000000 : 100000000;

                var amount = GetRandomMoney(redPocket, min, n);

                var priceDAC   = new PriceInfoDAC();
                var price      = priceDAC.GetPriceByName("USD", crypto.Code);
                var fiatAmount = price * amount;
                using (var scope = new TransactionScope())
                {
                    try
                    {
                        var redPocketReceiver = new RedPocketReceiver
                        {
                            PocketId      = redPocket.Id,
                            AccountId     = userAccount.Id,
                            SendAccountId = redPocket.AccountId,
                            CryptoCode    = redPocket.CryptoCode,
                            Amount        = amount,
                            Timestamp     = DateTime.UtcNow,
                            IsBestLuck    = redPocket.Count == 1,
                            OrderNo       = IdentityHelper.OrderNo(),
                            FiatAmount    = fiatAmount <= 0 ? 0M : Math.Round(fiatAmount, 8)
                        };
                        var id = redPocketReceiveDAC.Insert(redPocketReceiver);

                        userTransactionDAC.Insert(new UserTransaction
                        {
                            Id         = Guid.NewGuid(),
                            AccountId  = redPocketReceiver.AccountId,
                            CryptoId   = redPocket.CryptoId,
                            CryptoCode = redPocket.CryptoCode,
                            Type       = UserTransactionType.ReceiveRedPocket,
                            DetailId   = id.ToString(),
                            Status     = (byte)redPocket.Status,
                            Timestamp  = redPocketReceiver.Timestamp,
                            Amount     = redPocketReceiver.Amount,
                            OrderNo    = redPocketReceiver.OrderNo
                        });

                        userWalletDAC.Increase(wallet.Id, amount);
                        userWalletStatementDAC.Insert(new UserWalletStatement
                        {
                            WalletId      = wallet.Id,
                            Balance       = wallet.Balance + amount,
                            Amount        = amount,
                            FrozenAmount  = 0,
                            FrozenBalance = wallet.FrozenBalance,
                            Action        = "Receive Red Pocket",
                            Timestamp     = DateTime.UtcNow
                        });

                        redPocketDAC.UpdateRemain(redPocket.Id, amount);

                        if (redPocket.RemainCount == 0)
                        {
                            redPocketDAC.UpdateStatus(redPocket.Id, RedPocketStatus.Complate);
                            userTransactionDAC.UpdateStatus(UserTransactionType.PushRedPocket, redPocket.Id.ToString(), redPocket.AccountId, (byte)RedPocketStatus.Complate);

                            if (redPocket.Count > 1)
                            {
                                redPocketReceiveDAC.UpdateBestLuck(redPocket.Id);
                            }
                        }

                        scope.Complete();
                    }
                    catch (Exception ex)
                    {
                        _log.Error(ex);
                        throw new CommonException();
                    }
                }
                om.SelfAmount      = amount.ToString();
                om.ReceiveStatus   = ReceiveStatusEnum.Receive;
                om.HasExpried      = false;
                redPocket.Balance -= amount;
            }
            else
            {
                if (hasReceive != null)
                {
                    om.ReceiveStatus = ReceiveStatusEnum.HasReceive;
                    om.SelfAmount    = hasReceive.Amount.ToString();
                }
                else
                {
                    om.ReceiveStatus = ReceiveStatusEnum.None;
                    om.SelfAmount    = string.Empty;
                }
            }

            var account = new UserAccountComponent().GetById(redPocket.AccountId);

            om.Message        = redPocket.Message;
            om.SnederNickname = account.Nickname;

            om.TotalAmount   = redPocket.Amount.ToString();
            om.TotalCount    = redPocket.Count;
            om.CryptoCode    = redPocket.CryptoCode;
            om.ReceiveAmount = (redPocket.Amount - redPocket.Balance).ToString();
            om.ReceiveCount  = redPocket.Count - redPocket.RemainCount;
            om.Id            = redPocket.Id;
            om.HasExpried    = redPocket.ExpirationDate < DateTime.UtcNow;
            om.HasSelfSned   = redPocket.AccountId == userAccount.Id;

            return(om);
        }
示例#4
0
        public RedPocket Push(UserAccount userAccount, Guid accountId, int cryptoId, decimal amount, int count, string userPIN, string pin, string message = "")
        {
            if (userAccount.L1VerifyStatus != Entities.Enums.VerifyStatus.Certified)
            {
                throw new CommonException(ReasonCode.NOT_VERIFY_LV1, Resources.EMNeedLV1Verfied);
            }

            if (amount <= 0 || cryptoId <= 0)
            {
                throw new CommonException(Argument_Error, MessageResources.InvalidDataFormat);
            }
            if (count <= 0)
            {
                throw new CommonException(Argument_Error, MessageResources.InvalidDataFormat);
            }

            if (count > MaxCount)
            {
                throw new CommonException(Argument_Error, string.Format(MessageResources.RedPocket_MaxCount, MaxCount));
            }

            if (!string.IsNullOrWhiteSpace(message) && message.Length > 46)
            {
                throw new CommonException(Argument_Error, MessageResources.RedPocket_MaxMessage);
            }

            SecurityVerify.Verify(new PinVerifier(), SystemPlatform.FiiiPay, accountId.ToString(), userPIN, pin);

            var cryptoDAC = new CryptocurrencyDAC();
            var priceDAC  = new PriceInfoDAC();

            var crypto = cryptoDAC.GetById(cryptoId);

            if (crypto == null)
            {
                throw new SystemErrorException();
            }

            if (!crypto.Status.HasFlag(Foundation.Entities.Enum.CryptoStatus.RedPocket) || crypto.Enable == 0)
            {
                throw new CommonException(ReasonCode.CURRENCY_FORBIDDEN, MessageResources.CurrencyForbidden);
            }

            var min = crypto.DecimalPlace == 8 ? 0.00000001M : crypto.DecimalPlace == 6 ? 0.000001M : 0.00000001M;

            var minAmount = count * min;

            if (amount < minAmount)
            {
                throw new CommonException(Push_MinAmount, string.Format(MessageResources.RedPocket_MinAmount, minAmount, crypto.Code));
            }

            var price = priceDAC.GetPriceByName("USD", crypto.Code);

            var max       = crypto.DecimalPlace == 8 ? 999999999.999999999M : crypto.DecimalPlace == 6 ? 999999999.999999M : 999999999.999999999M;
            var maxAmount = Math.Round(MaxAmount / price, crypto.DecimalPlace);

            if (count > 1)
            {
                maxAmount = Math.Round(MaxAmount * count / price, crypto.DecimalPlace);
            }

            if (amount >= max || Math.Round(amount, crypto.DecimalPlace) > maxAmount)
            {
                throw new CommonException(Argument_Error, string.Format(MessageResources.RedPocket_MaxAmount, maxAmount, crypto.Code));
            }

            var userWalletDAC          = new UserWalletDAC();
            var redPocketDAC           = new RedPocketDAC();
            var userWalletStatementDAC = new UserWalletStatementDAC();
            var userTransactionDAC     = new UserTransactionDAC();

            var wallet = userWalletDAC.GetByAccountId(accountId, cryptoId);

            if (wallet == null || wallet.Balance < amount)
            {
                throw new CommonException(ReasonCode.INSUFFICIENT_BALANCE, MessageResources.InsufficientBalance);
            }

            var fiatAmount = price * amount;

            using (var scope = new TransactionScope())
            {
                try
                {
                    var redPocket = new RedPocket
                    {
                        AccountId      = accountId,
                        Status         = RedPocketStatus.Actived,
                        PassCode       = GeneralPassCode(),
                        CryptoCode     = crypto.Code,
                        Amount         = amount,
                        Balance        = amount,
                        Count          = count,
                        RemainCount    = count,
                        Message        = message,
                        Timestamp      = DateTime.UtcNow,
                        ExpirationDate = DateTime.UtcNow.AddMinutes(_expried),
                        CryptoId       = cryptoId,
                        OrderNo        = IdentityHelper.OrderNo(),
                        FiatAmount     = fiatAmount <= 0 ? 0M : Math.Round(fiatAmount, 8)
                    };

                    var redPocketId = redPocketDAC.Insert(redPocket);
                    userTransactionDAC.Insert(new UserTransaction
                    {
                        Id         = Guid.NewGuid(),
                        AccountId  = accountId,
                        CryptoId   = redPocket.CryptoId,
                        CryptoCode = redPocket.CryptoCode,
                        Type       = UserTransactionType.PushRedPocket,
                        DetailId   = redPocketId.ToString(),
                        Status     = (byte)redPocket.Status,
                        Timestamp  = redPocket.Timestamp,
                        Amount     = redPocket.Amount,
                        OrderNo    = redPocket.OrderNo
                    });

                    userWalletDAC.Decrease(wallet.Id, amount);
                    userWalletStatementDAC.Insert(new UserWalletStatement
                    {
                        WalletId      = wallet.Id,
                        Balance       = wallet.Balance - amount,
                        Amount        = 0 - amount,
                        FrozenAmount  = 0,
                        FrozenBalance = wallet.FrozenBalance,
                        Action        = "Push Red Pocket",
                        Timestamp     = DateTime.UtcNow
                    });

                    QueueHelper.DelaySender.Send("FiiiPay_RedPocket", redPocketId);

                    scope.Complete();

                    return(redPocket);
                }
                catch (Exception ex)
                {
                    _log.Error(ex);

                    throw new SystemErrorException();
                }
            }
        }
示例#5
0
        public TransferOM Transfer(UserAccount account, TransferIM im)
        {
            SecurityVerify.Verify(new PinVerifier(), SystemPlatform.FiiiPay, account.Id.ToString(), account.Pin, im.Pin);
            if (account.L1VerifyStatus != VerifyStatus.Certified)
            {
                throw new ApplicationException();
            }
            if (account.IsAllowTransfer.HasValue && !account.IsAllowTransfer.Value)
            {
                throw new CommonException(ReasonCode.TRANSFER_FORBIDDEN, MessageResources.TransferForbidden);
            }
            var toAccount = new UserAccountDAC().GetByCountryIdAndCellphone(im.ToCountryId, im.ToCellphone);

            if (toAccount == null)
            {
                throw new CommonException(ReasonCode.ACCOUNT_NOT_EXISTS, MessageResources.AccountNotExist);
            }
            if (toAccount.IsAllowTransfer.HasValue && !toAccount.IsAllowTransfer.Value)
            {
                throw new CommonException(ReasonCode.TRANSFER_FORBIDDEN, MessageResources.ToAccountTransferForbidden);
            }
            if (im.Amount >= Convert.ToDecimal(Math.Pow(10, 11)))
            {
                throw new CommonException(ReasonCode.TRANSFER_AMOUNT_OVERFLOW, MessageResources.TransferAmountOverflow);
            }
            var currency = new CryptocurrencyDAC().GetById(im.CoinId);

            if (!currency.Status.HasFlag(CryptoStatus.Transfer) || currency.Enable == 0)
            {
                throw new CommonException(ReasonCode.CURRENCY_FORBIDDEN, MessageResources.CurrencyForbidden);
            }
            if (im.Amount < (decimal)Math.Pow(10, -currency.DecimalPlace))
            {
                throw new CommonException(ReasonCode.TRANSFER_AMOUNT_OVERFLOW, MessageResources.TransferAmountTooSmall);
            }
            var decimalDigits = im.Amount.ToString().Length - im.Amount.ToString().IndexOf('.') - 1;

            if (decimalDigits > currency.DecimalPlace)
            {
                throw new CommonException(ReasonCode.TRANSFER_AMOUNT_OVERFLOW, MessageResources.TransferAmountOverflow);
            }

            if (account.Id == toAccount.Id)
            {
                throw new CommonException(ReasonCode.TRANSFER_TO_SELF, MessageResources.TransferToSelf);
            }

            var uwComponent = new UserWalletComponent();

            var toWallet = uwComponent.GetUserWallet(toAccount.Id, im.CoinId);

            if (toWallet == null)
            {
                toWallet = uwComponent.GenerateWallet(toAccount.Id, currency.Id);
            }

            var      country      = new CountryComponent().GetById(im.ToCountryId);
            DateTime dtCreateTime = DateTime.UtcNow;

            var fromWallet = uwComponent.GetUserWallet(account.Id, im.CoinId);

            if (fromWallet.Balance < im.Amount)
            {
                throw new CommonException(ReasonCode.TRANSFER_BALANCE_LOW, MessageResources.TransferBalanceLow);
            }

            UserTransfer transfer = new UserTransfer
            {
                Timestamp         = dtCreateTime,
                OrderNo           = CreateOrderno(),
                FromUserAccountId = account.Id,
                FromUserWalletId  = fromWallet.Id,
                CoinId            = currency.Id,
                CoinCode          = currency.Code,
                ToUserAccountId   = toAccount.Id,
                ToUserWalletId    = toWallet.Id,
                Amount            = im.Amount,
                Status            = (byte)TransactionStatus.Confirmed
            };

            var uwDAC  = new UserWalletDAC();
            var uwsDAC = new UserWalletStatementDAC();
            var utDAC  = new UserTransactionDAC();

            //var pushComponent = new FiiiPayPushComponent();
            using (var scope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, new TimeSpan(0, 0, 1, 30)))
            {
                transfer.Id = new UserTransferDAC().Insert(transfer);

                utDAC.Insert(new UserTransaction
                {
                    Id         = Guid.NewGuid(),
                    AccountId  = transfer.FromUserAccountId,
                    CryptoId   = transfer.CoinId,
                    CryptoCode = transfer.CoinCode,
                    Type       = UserTransactionType.TransferOut,
                    DetailId   = transfer.Id.ToString(),
                    Status     = transfer.Status,
                    Timestamp  = dtCreateTime,
                    Amount     = transfer.Amount,
                    OrderNo    = transfer.OrderNo
                });

                utDAC.Insert(new UserTransaction
                {
                    Id         = Guid.NewGuid(),
                    AccountId  = transfer.ToUserAccountId,
                    CryptoId   = transfer.CoinId,
                    CryptoCode = transfer.CoinCode,
                    Type       = UserTransactionType.TransferIn,
                    DetailId   = transfer.Id.ToString(),
                    Status     = transfer.Status,
                    Timestamp  = dtCreateTime,
                    Amount     = transfer.Amount,
                    OrderNo    = transfer.OrderNo
                });

                uwDAC.Decrease(fromWallet.Id, transfer.Amount);
                uwDAC.Increase(toWallet.Id, transfer.Amount);

                uwsDAC.Insert(new UserWalletStatement
                {
                    WalletId      = fromWallet.Id,
                    Action        = UserWalletStatementAction.TansferOut,
                    Amount        = -transfer.Amount,
                    Balance       = fromWallet.Balance - transfer.Amount,
                    FrozenAmount  = 0,
                    FrozenBalance = fromWallet.FrozenBalance,
                    Timestamp     = dtCreateTime
                });

                uwsDAC.Insert(new UserWalletStatement
                {
                    WalletId      = toWallet.Id,
                    Action        = UserWalletStatementAction.TansferIn,
                    Amount        = transfer.Amount,
                    Balance       = toWallet.Balance + transfer.Amount,
                    FrozenAmount  = 0,
                    FrozenBalance = toWallet.FrozenBalance,
                    Timestamp     = dtCreateTime
                });

                scope.Complete();
            }

            RabbitMQSender.SendMessage("UserTransferOutFiiiPay", transfer.Id);
            RabbitMQSender.SendMessage("UserTransferIntoFiiiPay", transfer.Id);
            //pushComponent.PushTransferOut(transfer.Id);
            //pushComponent.PushTransferInto(transfer.Id);

            return(new TransferOM
            {
                Timestamp = dtCreateTime.ToUnixTime().ToString(),
                TracingId = transfer.Id,
                TracingNo = transfer.OrderNo,
                AccountName = country.PhoneCode + " " + toAccount.Cellphone
            });
        }