Ejemplo n.º 1
0
        /// <summary>
        /// 获取电话客服列表
        /// 若需要获取完整客服列表,还需要查询Mastersetting表获取相关数据
        /// </summary>
        /// <param name="isZH"></param>
        /// <returns></returns>
        public Dictionary <string, List <string> > GetCustomerService(bool isZH)
        {
            var dic = new Dictionary <string, List <string> >();
            //var countries = GetList(isZH);

            //var strList = countries.Select(country => $"{country.CustomerService}({(isZH ? country.Name_CN : country.Name)})").ToList();

            //dic.Add("Phone", strList);

            var CustomerServices = new MasterSettingDAC().SelectByGroup("CustomerService");

            if (CustomerServices != null)
            {
                foreach (var masterSetting in CustomerServices)
                {
                    if (!dic.ContainsKey(masterSetting.Name))
                    {
                        dic.Add(masterSetting.Name, new List <string> {
                            masterSetting.Value
                        });
                    }
                    else
                    {
                        dic[masterSetting.Name].Add(masterSetting.Value);
                    }
                }
            }

            return(dic);
        }
Ejemplo n.º 2
0
        public MerchantWithdrawalMasterSettingDTO GetMerchantWithdrawalMasterSetting()
        {
            var msList = new MasterSettingDAC().SelectByGroup("MerchantWithdrawal");

            return(new MerchantWithdrawalMasterSettingDTO
            {
                PerTxLimit = Convert.ToDecimal(msList.FirstOrDefault(e => e.Name == "Withdrawal_PerTx_Limit_Merchant_NotVerified")?.Value),
                PerDayLimit = Convert.ToDecimal(msList.FirstOrDefault(e => e.Name == "Withdrawal_PerDay_Limit_Merchant_NotVerified")?.Value),
                PerMonthLimit = Convert.ToDecimal(msList.FirstOrDefault(e => e.Name == "Withdrawal_PerMonth_Limit_Merchant_NotVerified")?.Value),

                PerTxLimit1 = Convert.ToDecimal(msList.FirstOrDefault(e => e.Name == "Withdrawal_PerTx_Limit_Merchant_Lv1Verified")?.Value),
                PerDayLimit1 = Convert.ToDecimal(msList.FirstOrDefault(e => e.Name == "Withdrawal_PerDay_Limit_Merchant_Lv1Verified")?.Value),
                PerMonthLimit1 = Convert.ToDecimal(msList.FirstOrDefault(e => e.Name == "Withdrawal_PerMonth_Limit_Merchant_Lv1Verified")?.Value),

                PerTxLimit2 = Convert.ToDecimal(msList.FirstOrDefault(e => e.Name == "Withdrawal_PerTx_Limit_Merchant_Lv2Verified")?.Value),
                PerDayLimit2 = Convert.ToDecimal(msList.FirstOrDefault(e => e.Name == "Withdrawal_PerDay_Limit_Merchant_Lv2Verified")?.Value),
                PerMonthLimit2 = Convert.ToDecimal(msList.FirstOrDefault(e => e.Name == "Withdrawal_PerMonth_Limit_Merchant_Lv2Verified")?.Value),

                ToOutsideMinAmount = Convert.ToDecimal(msList.FirstOrDefault(e => e.Name == "Withdrawal_MinAmount")?.Value),
                ToUserMinAmount = Convert.ToDecimal(msList.FirstOrDefault(e => e.Name == "MerchantWithdrawal_ToUser_MinAmount")?.Value),

                ToUserHandleFeeTier = Convert.ToDecimal(msList.FirstOrDefault(e => e.Name == "MerchantWithdrawal_ToUser")?.Value),
                ToMerchantHandleFeeTier = Convert.ToDecimal(msList.FirstOrDefault(e => e.Name == "MerchantWithdrawal_ToMerchant")?.Value)
            });
        }
Ejemplo n.º 3
0
        public SaveResult Reward(Guid id, int userId, string userName)
        {
            var settingCollection = new MasterSettingDAC().SelectByGroup("InviteReward");
            var inviteMoney       = decimal.Parse(settingCollection.Where(item => item.Name == "Invite_Reward_Amount").Select(item => item.Value).FirstOrDefault());

            var uwComponent = new UserWalletBLL();
            var uwsDAC      = new UserWalletStatementDAC();
            var uwDAC       = new UserWalletDAC();

            var cryptoId     = new CryptocurrencyDAC().GetByCode("FIII").Id;
            var inviteWallet = uwComponent.GetUserWallet(id, cryptoId);

            if (inviteWallet == null)
            {
                inviteWallet = uwComponent.GenerateWallet(id, cryptoId);
            }

            var adoResult = FiiiPayDB.DB.Ado.UseTran(() =>
            {
                //解冻奖励
                uwDAC.Increase(inviteWallet.Id, inviteMoney);
                //插入奖励流水
                uwsDAC.Insert(new UserWalletStatement
                {
                    WalletId  = inviteWallet.Id,
                    Action    = UserWalletStatementAction.Invite,
                    Amount    = inviteMoney,
                    Balance   = inviteWallet.Balance + inviteMoney,
                    Timestamp = DateTime.UtcNow,
                    Remark    = "BO Reward"
                });
            });
            ActionLog actionLog = new ActionLog();

            actionLog.IPAddress  = GetClientIPAddress();
            actionLog.AccountId  = userId;
            actionLog.CreateTime = DateTime.UtcNow;
            actionLog.ModuleCode = typeof(UserManageBLL).FullName + ".Reward";
            actionLog.Username   = userName;
            actionLog.LogContent = "Reward " + id + " Fiii:" + inviteMoney;
            new ActionLogBLL().Create(actionLog);


            return(new SaveResult(true, "Save Success"));
        }
Ejemplo n.º 4
0
        public TransactionFeeRateOM TransactionFeeRate(int coinId, string address, string tag)
        {
            var  userWalletDAC     = new UserWalletDAC();
            var  merchantWalletDAC = new MerchantWalletDAC();
            var  coin             = new CryptocurrencyDAC().GetById(coinId);
            var  mastSettings     = new MasterSettingDAC().SelectByGroup("UserWithdrawal");
            var  isUserWallet     = userWalletDAC.IsUserWalletAddress(address);
            var  isMerchantWallet = merchantWalletDAC.IsMerchantWalletAddress(address);
            bool isFiiiAccount    = isUserWallet || isMerchantWallet;

            if (isFiiiAccount)
            {
                var userWallet = userWalletDAC.GetByAddressAndCrypto(coinId, address, tag);
                var result     = new TransactionFeeRateOM
                {
                    CryptoAddressType  = CryptoAddressType.FiiiPay,
                    TransactionFee     = "0",
                    TransactionFeeRate = mastSettings.First(e => e.Name == "UserWithdrawal_ToUser").Value
                };
                if (userWallet != null)
                {
                    return(result);
                }

                var merchantWallet = merchantWalletDAC.GetByAddressAndCrypto(coinId, address, tag);
                if (merchantWallet != null)
                {
                    result.CryptoAddressType = CryptoAddressType.FiiiPOS;
                    return(result);
                }

                result.CryptoAddressType = CryptoAddressType.InsideWithError;
                return(result);
            }
            else
            {
                return(new TransactionFeeRateOM
                {
                    CryptoAddressType = CryptoAddressType.Outside,
                    TransactionFee = (coin.Withdrawal_Fee ?? 0).ToString(CultureInfo.InvariantCulture),
                    TransactionFeeRate = (coin.Withdrawal_Tier ?? 0).ToString(CultureInfo.InvariantCulture)
                });
            }
        }
Ejemplo n.º 5
0
        public IEnumerable <BillerCryptoItemOM> GetBillerCryptoCurrency(UserAccount user, string fiatCurrency)
        {
            var dac      = new MasterSettingDAC();
            var discount = dac.SelectByGroup("BillerMaxAmount").First(item =>
                                                                      item.Name.Equals("DiscountRate", StringComparison.CurrentCultureIgnoreCase));

            var coins = new UserWalletComponent().ListForDepositAndWithdrawal(user, fiatCurrency).List;

            var priceInfoDict = new PriceInfoDAC().GetByCurrencyId(new CurrenciesDAC().GetByCode(fiatCurrency).ID).ToDictionary(item => item.CryptoID);

            foreach (var item in coins)
            {
                var model = new BillerCryptoItemOM()
                {
                    Code           = item.Code,
                    Id             = item.Id,
                    Name           = item.Name,
                    CryptoEnable   = item.CryptoEnable,
                    DecimalPlace   = item.DecimalPlace,
                    FiatBalance    = item.FiatBalance,
                    FrozenBalance  = item.FrozenBalance,
                    IconUrl        = item.IconUrl,
                    NewStatus      = item.NewStatus,
                    UseableBalance = item.UseableBalance,
                    ExchangeRate   = priceInfoDict.ContainsKey(item.Id) ? priceInfoDict[item.Id].Price.ToString(4) : 0.ToString()
                };
                if (item.Code.Equals("fiii", StringComparison.InvariantCultureIgnoreCase))
                {
                    model.Discount = decimal.Parse(discount.Value).ToString();
                    yield return(model);
                }
                else
                {
                    model.Discount = "0";
                    yield return(model);
                }
            }
        }
Ejemplo n.º 6
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 });
            //}
        }
        public SignonDTO Signup(int countryId, string cellphone, string merchantAccount, string merchantName, string posSn, string invitationCode, string pin)
        {
            SecurityVerify.Verify <FiiiPosSignUpVerify>(new CustomVerifier("FiiiPosSignUp"), SystemPlatform.FiiiPOS, $"{countryId}:{cellphone}", (model) =>
            {
                return(model.CellphoneVerified);
            });

            var country = new CountryComponent().GetById(countryId);

            if (country == null)
            {
                throw new CommonException(10000, Resources.国家不存在);
            }
            var cacheKey = $"{countryId}{cellphone}";
            var verifier = new FiiiPosRegisterVerifier();
            var dic      = verifier.GetRegisterModel(SystemPlatform.FiiiPOS, cacheKey, false);

            MerchantAccount excistAccount = new MerchantAccountDAC().GetByUsername(merchantAccount);

            if (excistAccount != null)
            {
                throw new CommonException(ReasonCode.ACCOUNT_EXISTS, Resources.帐号已存在);
            }

            UserAccount inviterAccount = new UserAccount();

            if (!string.IsNullOrEmpty(invitationCode))
            {
                inviterAccount = new UserAccountDAC().GetUserAccountByInviteCode(invitationCode);
                if (inviterAccount == null)
                {
                    throw new CommonException(ReasonCode.INVITORCODE_NOT_EXISTS, Resources.邀请码不存在);
                }
            }

            var posDac = new POSDAC();
            var pos    = posDac.GetInactivedBySn(posSn);

            if (pos == null)
            {
                throw new CommonException(ReasonCode.POSSN_ERROR, Resources.SN码不存在);
            }

            var merchantMS = new MasterSettingDAC().SelectByGroup("Merchant");

            Guid            beInvitedAccountId = Guid.NewGuid();
            MerchantAccount account            = new MerchantAccount
            {
                CountryId        = countryId,
                Cellphone        = cellphone,
                Username         = merchantAccount,
                MerchantName     = merchantName,
                PIN              = PasswordHasher.HashPassword(pin),
                Id               = beInvitedAccountId,
                POSId            = pos.Id,
                IsVerifiedEmail  = false,
                PhoneCode        = dic["PhoneCode"],
                RegistrationDate = DateTime.UtcNow,
                Status           = AccountStatus.Active,
                SecretKey        = beInvitedAccountId.ToString(),
                FiatCurrency     = dic["FiatCurrency"],
                Markup           = Convert.ToDecimal(merchantMS.First(e => e.Name == "Merchant_Markup").Value),
                Receivables_Tier = Convert.ToDecimal(merchantMS.First(e => e.Name == "Merchant_TransactionFee").Value),
                //默认开启手机验证
                ValidationFlag = (byte)ValidationFlag.Cellphone,
                InvitationCode = invitationCode
            };

            POSMerchantBindRecord posBindRecord = new POSMerchantBindRecord
            {
                POSId            = pos.Id,
                SN               = pos.Sn,
                MerchantId       = account.Id,
                MerchantUsername = merchantAccount,
                BindTime         = DateTime.UtcNow,
                BindStatus       = (byte)POSBindStatus.Binded
            };

            MerchantProfile profile = new MerchantProfile
            {
                MerchantId     = account.Id,
                Country        = account.CountryId,
                Cellphone      = account.Cellphone,
                L1VerifyStatus = VerifyStatus.Uncertified,
                L2VerifyStatus = VerifyStatus.Uncertified
            };

            MerchantProfileAgent agent = new MerchantProfileAgent();
            bool addProfileResult      = agent.AddMerchant(profile);

            if (!addProfileResult)
            {
                throw new CommonException(ReasonCode.GENERAL_ERROR, "Add merchant profile error.");
            }
            int recordId = default(int);

            try
            {
                using (var scope = new TransactionScope())
                {
                    posDac.ActivePOS(pos);
                    new MerchantAccountDAC().Insert(account);
                    recordId = new POSMerchantBindRecordDAC().Insert(posBindRecord);
                    if (!string.IsNullOrEmpty(invitationCode))
                    {
                        BindInviter(posSn, beInvitedAccountId, inviterAccount.Id, invitationCode);
                    }

                    scope.Complete();
                }
            }
            catch (Exception ex)
            {
                agent.RemoveMerchantById(profile);

                //LogHelper.Error(ex);
                throw;
            }

            if (!string.IsNullOrEmpty(invitationCode))
            {
                RabbitMQSender.SendMessage("InvitePosBindSuccess", new Tuple <Guid, long>(inviterAccount.Id, recordId));
            }

            verifier.DeleteCacheModel(SystemPlatform.FiiiPOS, cacheKey);

            return(GetAccessToken(pos, account));
        }
Ejemplo n.º 8
0
        public PreWithdrawOM PreWithdraw(UserAccount user, int cryptoId)
        {
            var crypto = new CryptocurrencyDAC().GetById(cryptoId);

            var exchangeRate = GetMarketPrice(user.CountryId, crypto.Code, "USD");
            var wallet       = new UserWalletDAC().GetByAccountId(user.Id, cryptoId) ?? new UserWalletComponent().GenerateWallet(user.Id, cryptoId);
            //var profile = new UserProfileAgent().GetUserProfile(user.Id);

            var mastSettings = new MasterSettingDAC().SelectByGroup("UserWithdrawal");

            var Withdrawal_PerTx_Limit_User_NotVerified    = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerTx_Limit_User_NotVerified").Value) / exchangeRate;
            var Withdrawal_PerDay_Limit_User_NotVerified   = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerDay_Limit_User_NotVerified").Value) / exchangeRate;
            var Withdrawal_PerMonth_Limit_User_NotVerified = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerMonth_Limit_User_NotVerified").Value) / exchangeRate;

            var Withdrawal_PerTx_Limit_User_Lv1Verified    = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerTx_Limit_User_Lv1Verified").Value) / exchangeRate;
            var Withdrawal_PerDay_Limit_User_Lv1Verified   = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerDay_Limit_User_Lv1Verified").Value) / exchangeRate;
            var Withdrawal_PerMonth_Limit_User_Lv1Verified = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerMonth_Limit_User_Lv1Verified").Value) / exchangeRate;

            var Withdrawal_PerTx_Limit_User_Lv2Verified    = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerTx_Limit_User_Lv2Verified").Value) / exchangeRate;
            var Withdrawal_PerDay_Limit_User_Lv2Verified   = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerDay_Limit_User_Lv2Verified").Value) / exchangeRate;
            var Withdrawal_PerMonth_Limit_User_Lv2Verified = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerMonth_Limit_User_Lv2Verified").Value) / exchangeRate;

            var MinAmount = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_MinAmount").Value) / exchangeRate;

            var om = new PreWithdrawOM();

            om.Lv1Verified = user.L1VerifyStatus == VerifyStatus.Certified;
            om.Lv2Verified = user.L2VerifyStatus == VerifyStatus.Certified;

            om.Code    = crypto.Code;
            om.NeedTag = crypto.NeedTag;

            om.DecimalPlace = crypto.DecimalPlace;

            //余额
            om.UseableBalance = wallet.Balance.ToString(crypto.DecimalPlace);

            //最小提币量
            om.MinAmount = MinAmount.ToString(crypto.DecimalPlace);

            // to fiiipay min withdraw amount
            var toFiiiPayMinWithdrawAmount = GetToFiiiPayMinAmount(Convert.ToDecimal(mastSettings.First(e => e.Name == "UserWithdrawal_ToUser_MinAmount").Value), exchangeRate, crypto.DecimalPlace);

            om.ToFiiiPayMinWithdrawalAmount = toFiiiPayMinWithdrawAmount.ToString(crypto.DecimalPlace);


            var     dac               = new UserWithdrawalDAC();
            var     today             = DateTime.UtcNow.Date;
            decimal dailyWithdrawal   = dac.DailyWithdrawal(user.Id, cryptoId, today);
            decimal monthlyWithdrawal = dac.MonthlyWithdrawal(user.Id, cryptoId, new DateTime(today.Year, today.Month, 1));

            if (user.L1VerifyStatus == VerifyStatus.Certified && user.L2VerifyStatus == VerifyStatus.Certified)
            {
                om.PerTxLimit    = Withdrawal_PerTx_Limit_User_Lv2Verified.ToString(crypto.DecimalPlace);
                om.PerDayLimit   = Withdrawal_PerDay_Limit_User_Lv2Verified.ToString(crypto.DecimalPlace);
                om.PerMonthLimit = Withdrawal_PerMonth_Limit_User_Lv2Verified.ToString(crypto.DecimalPlace);
            }
            else if (user.L1VerifyStatus == VerifyStatus.Certified && user.L2VerifyStatus != VerifyStatus.Certified)
            {
                om.PerTxLimit    = Withdrawal_PerTx_Limit_User_Lv1Verified.ToString(crypto.DecimalPlace);
                om.PerDayLimit   = Withdrawal_PerDay_Limit_User_Lv1Verified.ToString(crypto.DecimalPlace);
                om.PerMonthLimit = Withdrawal_PerMonth_Limit_User_Lv1Verified.ToString(crypto.DecimalPlace);
            }
            else if (user.L1VerifyStatus != VerifyStatus.Certified && user.L2VerifyStatus != VerifyStatus.Certified)
            {
                om.PerTxLimit    = Withdrawal_PerTx_Limit_User_NotVerified.ToString(crypto.DecimalPlace);
                om.PerDayLimit   = Withdrawal_PerDay_Limit_User_NotVerified.ToString(crypto.DecimalPlace);
                om.PerMonthLimit = Withdrawal_PerMonth_Limit_User_NotVerified.ToString(crypto.DecimalPlace);
            }

            om.PerTxUsable = om.PerTxLimit;
            //当月可用限额小于当日可用限额时,当月可用限额更新为当日可用限额。
            decimal dayUsable   = Convert.ToDecimal(om.PerDayLimit) - dailyWithdrawal;
            decimal monthUsable = Convert.ToDecimal(om.PerMonthLimit) - monthlyWithdrawal;

            dayUsable = Math.Min(dayUsable, monthUsable);

            om.PerDayUsable   = Math.Max(0, dayUsable).ToString(crypto.DecimalPlace);
            om.PerMonthUsable = Math.Max(0, monthUsable).ToString(crypto.DecimalPlace);

            om.PerTxLimitIfLv1Veried    = Withdrawal_PerTx_Limit_User_Lv1Verified.ToString(crypto.DecimalPlace);
            om.PerDayLimitIfLv1Veried   = Withdrawal_PerDay_Limit_User_Lv1Verified.ToString(crypto.DecimalPlace);
            om.PerMonthLimitIfLv1Veried = Withdrawal_PerMonth_Limit_User_Lv1Verified.ToString(crypto.DecimalPlace);

            om.PerTxLimitIfLv2Veried    = Withdrawal_PerTx_Limit_User_Lv2Verified.ToString(crypto.DecimalPlace);
            om.PerDayLimitIfLv2Veried   = Withdrawal_PerDay_Limit_User_Lv2Verified.ToString(crypto.DecimalPlace);
            om.PerMonthLimitIfLv2Veried = Withdrawal_PerMonth_Limit_User_Lv2Verified.ToString(crypto.DecimalPlace);

            return(om);
        }
Ejemplo n.º 9
0
        private WithdrawOM WithdrawalToUserAccount(UserWallet fromWallet, UserWithdrawal fromWithdraw, UserWallet toWallet)
        {
            var         mastSettings = new MasterSettingDAC().SelectByGroup("UserWithdrawal");
            UserDeposit model        = new UserDeposit();

            using (var scope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 0, 1, 30)))
            {
                fromWithdraw.Status        = TransactionStatus.Confirmed;
                fromWithdraw.TransactionId = toWallet.UserAccountId.ToString("N");
                fromWithdraw.SelfPlatform  = true;//平台内提币
                fromWithdraw.Id            = new UserWithdrawalDAC().Create(fromWithdraw);

                new UserTransactionDAC().Insert(new UserTransaction
                {
                    Id         = Guid.NewGuid(),
                    AccountId  = fromWithdraw.UserAccountId,
                    CryptoId   = fromWallet.CryptoId,
                    CryptoCode = fromWallet.CryptoCode,
                    Type       = UserTransactionType.Withdrawal,
                    DetailId   = fromWithdraw.Id.ToString(),
                    Status     = (byte)fromWithdraw.Status,
                    Timestamp  = fromWithdraw.Timestamp,
                    Amount     = fromWithdraw.Amount,
                    OrderNo    = fromWithdraw.OrderNo
                });

                var fromWithdrawFee = new UserWithdrawalFee
                {
                    Amount       = fromWithdraw.Amount,
                    WithdrawalId = fromWithdraw.Id,
                    Fee          = fromWithdraw.Amount *
                                   Convert.ToDecimal(mastSettings.First(e => e.Name == "UserWithdrawal_ToUser").Value),
                    Timestamp = DateTime.UtcNow
                };

                new UserWithdrawalFeeDAC().Create(fromWithdrawFee);

                new UserWalletDAC().Decrease(fromWallet.Id, fromWithdraw.Amount);

                new UserWalletStatementDAC().Insert(new UserWalletStatement
                {
                    WalletId      = fromWallet.Id,
                    Action        = MerchantWalletStatementAction.Withdrawal,
                    Amount        = -fromWithdraw.Amount,
                    Balance       = fromWallet.Balance - fromWithdraw.Amount,
                    FrozenAmount  = 0,
                    FrozenBalance = fromWallet.FrozenBalance,
                    Timestamp     = DateTime.UtcNow
                });

                //充币
                var amount = fromWithdraw.Amount - fromWithdrawFee.Fee;
                if (amount <= 0)
                {
                    throw new CommonException(ReasonCode.GENERAL_ERROR, MessageResources.ArrivalAmountError);
                }

                new UserWalletDAC().Increase(toWallet.Id, amount);
                new UserWalletStatementDAC().Insert(new UserWalletStatement
                {
                    WalletId      = toWallet.Id,
                    Action        = UserWalletStatementAction.Deposit,
                    Amount        = amount,
                    Balance       = toWallet.Balance + amount,
                    FrozenAmount  = 0,
                    FrozenBalance = toWallet.FrozenBalance,
                    Timestamp     = DateTime.UtcNow
                });

                model = new UserDepositDAC().Insert(new UserDeposit
                {
                    UserAccountId = toWallet.UserAccountId,
                    UserWalletId  = toWallet.Id,
                    FromAddress   = fromWallet.Address,
                    FromTag       = fromWallet.Tag,
                    ToAddress     = toWallet.Address,
                    ToTag         = toWallet.Tag,
                    Amount        = amount,
                    Status        = TransactionStatus.Confirmed,
                    Timestamp     = DateTime.UtcNow,
                    OrderNo       = IdentityHelper.OrderNo(),
                    TransactionId = fromWallet.UserAccountId.ToString("N"),
                    SelfPlatform  = true,
                    CryptoCode    = fromWallet.CryptoCode
                });
                new UserTransactionDAC().Insert(new UserTransaction
                {
                    Id         = Guid.NewGuid(),
                    AccountId  = model.UserAccountId,
                    CryptoId   = fromWallet.CryptoId,
                    CryptoCode = fromWallet.CryptoCode,
                    Type       = UserTransactionType.Deposit,
                    DetailId   = model.Id.ToString(),
                    Status     = (byte)model.Status,
                    Timestamp  = model.Timestamp,
                    Amount     = model.Amount,
                    OrderNo    = model.OrderNo
                });

                scope.Complete();
            }

            UserMSMQ.PubUserWithdrawCompleted(fromWithdraw.Id, 0);
            UserMSMQ.PubUserDeposit(model.Id, 0);

            return(new WithdrawOM
            {
                OrderId = fromWithdraw.Id,
                OrderNo = fromWithdraw.OrderNo,
                Timestamp = fromWithdraw.Timestamp.ToUnixTime().ToString()
            });
        }
Ejemplo n.º 10
0
        public WithdrawOM Withdraw(UserAccount user, WithdrawIM im, string clientIP)
        {
            SecurityVerify.Verify <WithdrawVerify>(new CustomVerifier("UserWithdraw"), SystemPlatform.FiiiPay, user.Id.ToString(), (model) =>
            {
                return(model.PinVerified && model.CombinedVerified);
            });


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

            var cryptocurrency = new CryptocurrencyDAC().GetById(im.CoinId);

            if (!cryptocurrency.Status.HasFlag(CryptoStatus.Withdrawal) || cryptocurrency.Enable == 0)
            {
                throw new CommonException(ReasonCode.CURRENCY_FORBIDDEN, MessageResources.CurrencyForbidden);
            }

            CryptoAddressValidation.ValidateAddress(cryptocurrency.Code, im.Address);
            if (!string.IsNullOrEmpty(im.Tag))
            {
                CryptoAddressValidation.ValidateTag(cryptocurrency.Code, im.Tag);
            }
            //else if (cryptocurrency.NeedTag)
            //{
            //    throw new CommonException(ReasonCode.NEED_INPUT_TAG, GeneralResources.EMNeedInputTag);
            //}

            if (im.Amount <= 0)
            {
                throw new ApplicationException(MessageResources.AmountGreater);
            }

            var IsAllowWithdrawal = user.IsAllowWithdrawal ?? true;

            if (!IsAllowWithdrawal)
            {
                throw new CommonException(ReasonCode.Not_Allow_Withdrawal, MessageResources.WithdrawalDisabled);
            }

            var fromWallet = new UserWalletDAC().GetByAccountId(user.Id, im.CoinId);


            //var profile = new UserProfileAgent().GetUserProfile(user.Id);

            //标准化这个金额,防止超过8位
            im.Amount = im.Amount.ToSpecificDecimal(cryptocurrency.DecimalPlace);

            var mastSettings = new MasterSettingDAC().SelectByGroup("UserWithdrawal");

            var Withdrawal_PerTx_Limit_User_NotVerified    = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerTx_Limit_User_NotVerified").Value);
            var Withdrawal_PerDay_Limit_User_NotVerified   = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerDay_Limit_User_NotVerified").Value);
            var Withdrawal_PerMonth_Limit_User_NotVerified = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerMonth_Limit_User_NotVerified").Value);

            var Withdrawal_PerTx_Limit_User_Lv1Verified    = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerTx_Limit_User_Lv1Verified").Value);
            var Withdrawal_PerDay_Limit_User_Lv1Verified   = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerDay_Limit_User_Lv1Verified").Value);
            var Withdrawal_PerMonth_Limit_User_Lv1Verified = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerMonth_Limit_User_Lv1Verified").Value);

            var Withdrawal_PerTx_Limit_User_Lv2Verified    = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerTx_Limit_User_Lv2Verified").Value);
            var Withdrawal_PerDay_Limit_User_Lv2Verified   = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerDay_Limit_User_Lv2Verified").Value);
            var Withdrawal_PerMonth_Limit_User_Lv2Verified = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_PerMonth_Limit_User_Lv2Verified").Value);

            var MinAmount = Convert.ToDecimal(mastSettings.First(e => e.Name == "Withdrawal_MinAmount").Value);

            var merchantWalletDac = new MerchantWalletDAC();
            var userWalletDac     = new UserWalletDAC();

            var isWithdrawToInside = (merchantWalletDac.IsMerchantWalletAddress(im.Address) || userWalletDac.IsUserWalletAddress(im.Address));

            if (isWithdrawToInside)
            {
                MinAmount = Convert.ToDecimal(mastSettings.First(e => e.Name == "UserWithdrawal_ToUser_MinAmount").Value);
            }

            var exchangeRate = GetMarketPrice(user.CountryId, cryptocurrency.Code, "USD");

            var _minAmount = (MinAmount / exchangeRate).ToSpecificDecimal(cryptocurrency.DecimalPlace);

            if (im.Amount < _minAmount)
            {
                throw new ApplicationException(MessageResources.MinWidrawalError);
            }

            var     withdrawalDAC     = new UserWithdrawalDAC();
            var     today             = DateTime.UtcNow.Date;
            decimal dailyWithdrawal   = withdrawalDAC.DailyWithdrawal(user.Id, im.CoinId, today);
            decimal monthlyWithdrawal = withdrawalDAC.MonthlyWithdrawal(user.Id, im.CoinId, new DateTime(today.Year, today.Month, 1));

            var PerDayLimit   = 0M;
            var PerMonthLimit = 0M;

            if (user.L1VerifyStatus == VerifyStatus.Certified && user.L2VerifyStatus == VerifyStatus.Certified)
            {
                PerDayLimit   = Withdrawal_PerDay_Limit_User_Lv2Verified;
                PerMonthLimit = Withdrawal_PerMonth_Limit_User_Lv2Verified;
            }
            else if (user.L1VerifyStatus == VerifyStatus.Certified && user.L2VerifyStatus != VerifyStatus.Certified)
            {
                PerDayLimit   = Withdrawal_PerDay_Limit_User_Lv1Verified;
                PerMonthLimit = Withdrawal_PerMonth_Limit_User_Lv1Verified;
            }
            else if (user.L1VerifyStatus != VerifyStatus.Certified && user.L2VerifyStatus != VerifyStatus.Certified)
            {
                PerDayLimit   = Withdrawal_PerDay_Limit_User_NotVerified;
                PerMonthLimit = Withdrawal_PerMonth_Limit_User_NotVerified;
            }
            if ((PerDayLimit / exchangeRate - dailyWithdrawal).ToSpecificDecimal(cryptocurrency.DecimalPlace) < im.Amount)
            {
                throw new ApplicationException(MessageResources.TodayWidrawalLimit);
            }
            if ((PerMonthLimit / exchangeRate - monthlyWithdrawal).ToSpecificDecimal(cryptocurrency.DecimalPlace) < im.Amount)
            {
                throw new ApplicationException(MessageResources.MonthWithdrawalLimit);
            }

            var fromWithdraw = new UserWithdrawal
            {
                UserAccountId = user.Id,
                UserWalletId  = fromWallet.Id,
                Address       = im.Address,
                Tag           = im.Tag,
                Amount        = im.Amount,
                Status        = TransactionStatus.UnSubmit,
                Timestamp     = DateTime.UtcNow,
                OrderNo       = IdentityHelper.OrderNo(),
                CryptoCode    = fromWallet.CryptoCode,
                CryptoId      = fromWallet.CryptoId
            };

            //是否是商户地址
            var toMerchantWallet = merchantWalletDac.GetByAddressAndCrypto(im.CoinId, im.Address, im.Tag);

            if (toMerchantWallet != null)
            {
                //if (toMerchantWallet.CryptoId != im.CoinId)
                //    throw new CommonException(ReasonCode.GENERAL_ERROR, GeneralResources.EMInvalidAddress);
                //return WithdrawalToMerchantAccount(fromWallet, fromWithdraw, fromWithdrawFee, toMerchantWallet, cryptocurrency);
                //042018
                throw new CommonException(ReasonCode.CAN_NOT_WITHDRAW_TO_FiiiPOS, MessageResources.FiiiPayCantWithdrawToFiiiPOS);
            }

            //是否是用户地址
            var toUserWallet = userWalletDac.GetByAddressAndCrypto(im.CoinId, im.Address, im.Tag);

            if (toUserWallet != null)
            {
                if (toUserWallet.UserAccountId == user.Id)
                {
                    throw new CommonException(ReasonCode.CANNOT_TRANSFER_TO_YOURSELF, MessageResources.WithdrawalToSelfError);
                }

                var toFiiiPayMinWithdrawAmount = GetToFiiiPayMinAmount(Convert.ToDecimal(mastSettings.First(e => e.Name == "UserWithdrawal_ToUser_MinAmount").Value), exchangeRate, cryptocurrency.DecimalPlace);
                if (im.Amount < toFiiiPayMinWithdrawAmount)
                {
                    throw new CommonException(10000, MessageResources.MinWidrawalError);
                }

                return(WithdrawalToUserAccount(fromWallet, fromWithdraw, toUserWallet));
            }

            var tier = cryptocurrency.Withdrawal_Tier ?? 0;
            var fee  = im.Amount * tier + (cryptocurrency.Withdrawal_Fee ?? 0);

            fee = fee.ToSpecificDecimal(cryptocurrency.DecimalPlace);
            var actualAmount = im.Amount - fee;

            if (fromWallet.Balance < im.Amount)
            {
                throw new CommonException(ReasonCode.INSUFFICIENT_BALANCE, MessageResources.InsufficientBalance);
            }
            if (actualAmount <= 0)
            {
                throw new CommonException(ReasonCode.GENERAL_ERROR, MessageResources.ArrivalAmountError);
            }

            //地址是FiiiPay的地址,但tag找不到
            if (cryptocurrency.NeedTag && isWithdrawToInside)
            {
                return(CancelWithdrawal(fromWithdraw));
            }

            ILog _logger = LogManager.GetLogger("LogicError");

            //如果都不是,向Finance申请提现

            //var agent = new FiiiFinanceAgent();

            var requestModel = new CreateWithdrawModel
            {
                AccountID        = user.Id,
                AccountType      = AccountTypeEnum.User,
                CryptoName       = cryptocurrency.Code,
                ReceivingAddress = im.Address,
                DestinationTag   = im.Tag,
                Amount           = actualAmount,
                IPAddress        = clientIP,
                TransactionFee   = fee
            };

            using (var scope = new TransactionScope())
            {
                try
                {
                    fromWithdraw.Id = withdrawalDAC.Create(fromWithdraw);
                    var fromWithdrawFee = new UserWithdrawalFee
                    {
                        Amount       = im.Amount,
                        Fee          = fee,
                        Timestamp    = DateTime.UtcNow,
                        WithdrawalId = fromWithdraw.Id
                    };

                    new UserTransactionDAC().Insert(new UserTransaction
                    {
                        Id         = Guid.NewGuid(),
                        AccountId  = fromWithdraw.UserAccountId,
                        CryptoId   = fromWithdraw.CryptoId,
                        CryptoCode = fromWithdraw.CryptoCode,
                        Type       = UserTransactionType.Withdrawal,
                        DetailId   = fromWithdraw.Id.ToString(),
                        Status     = (byte)fromWithdraw.Status,
                        Timestamp  = fromWithdraw.Timestamp,
                        Amount     = fromWithdraw.Amount,
                        OrderNo    = fromWithdraw.OrderNo
                    });

                    new UserWithdrawalFeeDAC().Create(fromWithdrawFee);

                    userWalletDac.Freeze(fromWallet.Id, im.Amount);

                    new UserWalletStatementDAC().Insert(new UserWalletStatement
                    {
                        WalletId      = fromWallet.Id,
                        Action        = UserWalletStatementAction.Withdrawal,
                        Amount        = 0 - im.Amount,
                        Balance       = fromWallet.Balance - im.Amount,
                        FrozenAmount  = im.Amount,
                        FrozenBalance = fromWallet.FrozenBalance + im.Amount,
                        Timestamp     = DateTime.UtcNow
                    });

                    requestModel.WithdrawalId = fromWithdraw.Id;
                    Framework.Queue.RabbitMQSender.SendMessage("WithdrawSubmit", requestModel);

                    scope.Complete();
                }
                catch (CommonException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    _logger.Info($"Withdraw CreateWithdrawRequest faild.WithdrawID:{fromWithdraw.Id},OrderNo:{fromWithdraw.OrderNo}.request Parameter - {requestModel}. Error message:{ex.Message}");
                    throw;
                }
            }

            return(new WithdrawOM
            {
                OrderId = fromWithdraw.Id,
                OrderNo = fromWithdraw.OrderNo,
                Timestamp = fromWithdraw.Timestamp.ToUnixTime().ToString()
            });
        }