/// <summary>
 ///     获取指定的用户编号和账户编号下面的所有Campaign对象集合
 /// </summary>
 /// <param name="userId">用户编号</param>
 /// <param name="accountId">账户编号</param>
 /// <returns>返回执行后的结果</returns>
 public IExecuteResult GetCampaigns(uint userId, ulong accountId)
 {
     if (userId == 0)
     {
         return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal user id!"));
     }
     if (accountId == 0)
     {
         return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal account id!"));
     }
     try
     {
         //获取参数的值
         object[] parameterValues = new object[] { accountId, userId };
         //验证CampaignId和AccountId从属关系
         DataTable dt = _slaveDB.SpExecuteTable(SpName.SpGetCampaigns, ParametersObject.GetCampaigns, parameterValues);
         if (dt.Rows.Count <= 0)
         {
             return(ExecuteResult.Fail(SystemErrors.NotFound, SpName.SpGetCampaigns + ":Executed count = 0"));
         }
         Campaign[] campaigns = new Campaign[dt.Rows.Count];
         for (int i = 0; i < dt.Rows.Count; i++)
         {
             campaigns[i] = _convertor.ConvertToDomain(dt.Rows[i]);
         }
         return(ExecuteResult.Succeed(campaigns));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
     }
 }
 /// <summary>
 ///     根据指定的编号获取一个Campaign
 /// </summary>
 /// <param name="userId">用户编号</param>
 /// <param name="accountId">账户编号</param>
 /// <param name="campaignId">Campaign编号</param>
 /// <returns>返回执行后的结果</returns>
 public IExecuteResult GetCampainById(uint userId, ulong accountId, ulong campaignId)
 {
     if (userId == 0)
     {
         return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal user id!"));
     }
     if (accountId == 0)
     {
         return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal account id!"));
     }
     if (campaignId == 0)
     {
         return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal campaign id!"));
     }
     try
     {
         //获取参数的值
         object[] parameterValues = new object[] { campaignId, accountId, userId };
         //验证CampaignId和AccountId从属关系
         DataTable dt = _slaveDB.SpExecuteTable(SpName.SpGetCampaignByCampaignId, ParametersObject.GetCampaignByCampaignId, parameterValues);
         if (dt.Rows.Count <= 0)
         {
             return(ExecuteResult.Fail(SystemErrors.NotFound, SpName.SpGetCampaignByCampaignId + ":Executed count = 0"));
         }
         Campaign campaign = _convertor.ConvertToDomain(dt.Rows[0]);//ConverterFactory.GetCampaignConverter().PackToDomainObject(dt.Rows[0]);
         return(ExecuteResult.Succeed(campaign));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
     }
 }
 /// <summary>
 ///     根据指定编号获取一个简单Campagin实体
 /// </summary>
 /// <param name="userId">用户编号</param>
 /// <param name="campaignId">广告活动编号</param>
 /// <returns>返回执行后的结果</returns>
 public IExecuteResult <CampaignSimpleData> GetCampaignSimpleById(uint userId, ulong campaignId)
 {
     if (userId == 0)
     {
         return(ExecuteResult <CampaignSimpleData> .Fail(SystemErrors.Malformed, "#Illegal user id"));
     }
     if (campaignId == 0)
     {
         return(ExecuteResult <CampaignSimpleData> .Fail(SystemErrors.Malformed, "#Illegal campaignId id"));
     }
     try
     {
         //获取参数的值
         object[]  parameterValues = new object[] { campaignId, userId };
         DataTable dt = _slaveDB.SpExecuteTable(SpName.SpGetCampaignSimpleByCampaignId, new[] { "CampaignID", "Creator" }, parameterValues);
         if (dt.Rows.Count == 0)
         {
             return(ExecuteResult <CampaignSimpleData> .Fail(SystemErrors.NotFound, SpName.SpGetCampaignSimpleByCampaignId + ":Executed count = 0"));
         }
         CampaignSimpleData campaign = _convertorSimple.ConvertToDomain(dt.Rows[0]);
         return(ExecuteResult <CampaignSimpleData> .Succeed(campaign));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult <CampaignSimpleData> .Fail(SystemErrors.Unknown, ex.Message));
     }
 }
Exemplo n.º 4
0
        /// <summary>
        ///     获得发送邮件的日志
        /// </summary>
        /// <returns>返回的结果(DataSet)</returns>
        public IExecuteResult GetSendEmailLog()
        {
            try
            {
                //获取参数的值
                object[] parameterValues = new object[] { };
                DataSet  ds = _masterDB.SpExecuteDataSet(SpName.SpBuildEmailLog, ParametersObject.SpBuildEmailLog, parameterValues);
                if (ds == null)
                {
                    return(ExecuteResult.Fail(SystemErrors.Unknown, "Return DataSet is Null"));
                }
                if (ds.Tables.Count == 0)
                {
                    return(ExecuteResult.Fail(SystemErrors.Unknown, "Not Return DataTable"));
                }
                if (ds.Tables.Count != 2)
                {
                    return(ExecuteResult.Fail(SystemErrors.Unknown, "Not Return 2 Tables"));
                }

                return(ExecuteResult.Succeed(ds));
            }
            catch (Exception ex)
            {
                _tracing.Error(ex, null);
                return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
            }
        }
Exemplo n.º 5
0
 /// <summary>
 ///     检查指定活动下是否存在不具有启动资格的广告组信息
 /// </summary>
 /// <param name="campaignId">活动编号</param>
 /// <returns>返回执行结果</returns>
 public IExecuteResult <SimpleAdGroup[]> CheckRunStatusByCampaignId(ulong campaignId)
 {
     try
     {
         //获取参数的值
         object[] parameterValues = new object[] { campaignId };
         //验证CampaignId和AccountId从属关系
         DataTable dt = _slaveDB.SpExecuteTable(SpName.SpCheckRunStatusByCampaignId, ParametersObject.CheckRunStatusByCampaignId, parameterValues);
         if (dt.Rows.Count <= 0)
         {
             return(ExecuteResult <SimpleAdGroup[]> .Succeed(null));
         }
         SimpleAdGroup[] tags = new SimpleAdGroup[dt.Rows.Count];
         for (int i = 0; i < dt.Rows.Count; i++)
         {
             tags[i] = _otherConvertor.ConvertToDomain(dt.Rows[i]);
         }
         return(ExecuteResult <SimpleAdGroup[]> .Succeed(tags));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult <SimpleAdGroup[]> .Fail(SystemErrors.Unknown, ex.Message));
     }
 }
Exemplo n.º 6
0
        public ExecuteResult Update()
        {
            if (ChangeAmount == 0)
            {
                return(ExecuteResult.Success());
            }

            try
            {
                var findAccount = Ioc.Resolve <IAccountService>().GetAccount(AccountId);
                if (findAccount == null)
                {
                    return(ExecuteResult.Fail($"not found account when UserId={UserId} and AccountId={AccountId}"));
                }

                findAccount.Amount += ChangeAmount;
                if (ChangeAmount > 0)
                {
                    findAccount.HistoryAmount += ChangeAmount;
                }

                Ioc.Resolve <IAccountService>().Update(findAccount);
                //decimal historyChangeAmount = ChangeAmount > 0 ? ChangeAmount : 0;
                //string sql = $"update [Asset_Account] set [Amount]=[Amount]+{ChangeAmount}, [HistoryAmount]=[HistoryAmount]+{historyChangeAmount} where [UserId]={UserId} and [Id]={AccountId}";
                //Alabo.Helpers.Ioc.Resolve<IUserRepository>().RepositoryContext.ExecuteNonQuery(sql);
                return(ExecuteResult.Success());
            }
            catch (Exception e)
            {
                return(ExecuteResult.Error(e));
            }
        }
Exemplo n.º 7
0
 public IExecuteResult GetValue(CoinTypes coinType, PlatformTypes platformType)
 {
     try
     {
         KeyParse keyParse = new KeyParse {
             CoinType = coinType, PlatformType = platformType
         };
         string key     = keyParse.ToString();
         string content = m_Cache[key] as string;
         if (content == null)
         {
             CacheItemPolicy policy = new CacheItemPolicy();
             policy.AbsoluteExpiration = DateTime.Now.AddMilliseconds(25000);
             IExecuteResult <Ticker> result = _remoteApiService.GetDataFromDataBase(key);
             if (result.State != ExecuteResults.Succeed)
             {
                 return(ExecuteResult.Fail(SystemErrors.Unknown, null));
             }
             content = result.GetResult().ToString();
             m_Cache.Set(key, content, policy);
         }
         return(ExecuteResult.Succeed(JsonConvert.DeserializeObject <Ticker>(content)));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult.Fail(SystemErrors.NotFound, null));
     }
 }
Exemplo n.º 8
0
 /// <summary>
 ///     从数据库中获取Ticker数据
 /// </summary>
 public IExecuteResult <Ticker> GetDataFromDataBase(string key)
 {
     try
     {
         KeyParse keyParse;
         KeyParse.TryParse(key, out keyParse);
         CoinTypes     coinType     = keyParse.CoinType;
         PlatformTypes platformType = keyParse.PlatformType;
         string        sqlStr       = string.Format("SELECT * FROM `coin`.`trades` WHERE `CoinId` ={0} AND `PlatformId` = {1} ORDER BY `NowTime` DESC LIMIT 1"
                                                    , (int)coinType, (int)platformType);
         DataTable dt = QueryData(sqlStr);
         if (dt == null || dt.Rows.Count == 0)
         {
             return(ExecuteResult <Ticker> .Fail(SystemErrors.Unknown, "没有获取到数据"));
         }
         Ticker ticker = new Ticker
         {
             BuyPrice  = double.Parse(dt.Rows[0]["BuyPrice"].ToString()),
             SellPrice = double.Parse(dt.Rows[0]["SellPrice"].ToString()),
             HignPrice = double.Parse(dt.Rows[0]["HighPrice"].ToString()),
             LowPrice  = double.Parse(dt.Rows[0]["LowPrice"].ToString()),
             LastPrice = double.Parse(dt.Rows[0]["LastPrice"].ToString()),
             Vol       = double.Parse(dt.Rows[0]["TradeVol"].ToString())
         };
         //Tradescs tradesc = new Tradescs(coinType, ticker, platformType, ((MySqlDateTime)dt.Rows[0]["NowTime"]).GetDateTime());
         return(ExecuteResult <Ticker> .Succeed(ticker));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult <Ticker> .Fail(SystemErrors.Unknown, ex.Message));
     }
 }
Exemplo n.º 9
0
 /// <summary>
 ///     修改账户类型(目前只对自投放开放)
 /// </summary>
 /// <param name="userId">用户ID</param>
 /// <param name="accountId">账户ID</param>
 /// <param name="typeId">类型ID *自投放默认为3</param>
 /// <returns>结果</returns>
 public IExecuteResult UpdateAccountType(uint userId, uint accountId, uint typeId = 3)
 {
     if (userId == 0)
     {
         return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal user id."));
     }
     if (accountId == 0)
     {
         return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal account id."));
     }
     try
     {
         // 获取参数的值 自投放
         object[] parameterValues = new object[] { accountId, typeId, userId };
         int      count           = _masterDB.SpExecuteNonQuery(SpName.SpUpdateAccountType, ParametersObject.SpUpdateAccountType, parameterValues);
         return(count == 0
                       ? ExecuteResult.Fail(SystemErrors.NotFound, SpName.SpUpdateAccountType + ":Executed count = 0")
                       : ExecuteResult.Succeed(true));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
     }
 }
Exemplo n.º 10
0
        public ExecuteResult Update()
        {
            try
            {
                if (_taskActuator == null)
                {
                    return(ExecuteResult.Cancel("task actuator is null."));
                }

                if (_taskManager == null)
                {
                    return(ExecuteResult.Cancel("task manager is null."));
                }

                if (ModuleId == Guid.Empty)
                {
                    return(ExecuteResult.Cancel("module is is empty, return."));
                }

                if (!_taskManager.ContainsModuleId(ModuleId))
                {
                    return(ExecuteResult.Fail($"module with id {ModuleId} not found."));
                }
                // 注释可能出现出错
                // _taskActuator.ExecuteTaskAndUpdateResults(ModuleId, Parameter);
                return(ExecuteResult.Success());
            }
            catch (Exception e)
            {
                return(ExecuteResult.Error(e));
            }
        }
Exemplo n.º 11
0
 /// <summary>
 ///     新建AccountId与CustomId的关系在OA中
 /// </summary>
 /// <param name="userId">用户ID</param>
 /// <param name="accountId">账户ID</param>
 /// <param name="customId">广告主ID</param>
 /// <returns>结果</returns>
 public IExecuteResult CreateCustomerRel(uint userId, uint accountId, ushort customId)
 {
     if (userId == 0)
     {
         return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal user id."));
     }
     if (accountId == 0)
     {
         return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal account id."));
     }
     try
     {
         //获取参数的值
         object[] parameterValues = new object[] { accountId, customId, userId };
         int      count           = _masterDB.SpExecuteNonQuery(SpName.SpOA_AddCustomerRelationship, ParametersObject.SpAddCustomerRelationship, parameterValues);
         return(count == 0
                       ? ExecuteResult.Fail(SystemErrors.NotFound, SpName.SpOA_AddCustomerRelationship + ":Executed count = 0")
                       : ExecuteResult.Succeed(true));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
     }
 }
Exemplo n.º 12
0
        /// <summary>
        ///     根据指定编号异步获取Ticker对象的操作
        /// </summary>
        /// <param name="coinType">币种编号</param>
        /// <param name="platformType">平台编号</param>
        /// <returns>返回执行结果</returns>
        public async Task <IExecuteResult> GetTickerAsync(CoinTypes coinType, PlatformTypes platformType)
        {
            MetadataMessageTransaction transaction = SystemWorker.Instance.CreateMetadataTransaction("CoinAPI");
            MetadataContainer          reqMsg      = new MetadataContainer();

            reqMsg.SetAttribute(0x00, new MessageIdentityValueStored(new MessageIdentity
            {
                ProtocolId = 1,
                ServiceId  = 0,
                DetailsId  = 0
            }));
            reqMsg.SetAttribute(0x0F, new ByteValueStored((byte)coinType));
            reqMsg.SetAttribute(0x10, new ByteValueStored((byte)platformType));
            TaskCompletionSource <IExecuteResult> completionSource = new TaskCompletionSource <IExecuteResult>();
            Task <IExecuteResult> task = completionSource.Task;

            transaction.ResponseArrived += delegate(object sender, LightSingleArgEventArgs <MetadataContainer> e)
            {
                MetadataContainer rspMsg = e.Target;
                completionSource.SetResult((!rspMsg.IsAttibuteExsits(0x0A))
                             ? (rspMsg.GetAttribute(0x0F).GetValue <ResourceBlock>() == null
                                 ? ExecuteResult.Succeed(null)
                                 : ExecuteResult.Succeed(ConverterFactory.GetTickerConverter().ConvertToDomainObject(rspMsg.GetAttribute(0x0F).GetValue <ResourceBlock>())))
                             : ExecuteResult.Fail(rspMsg.GetAttribute(0x0A).GetValue <byte>(), rspMsg.GetAttribute(0x0B).GetValue <string>()));
            };
            transaction.Timeout += delegate { completionSource.SetResult(ExecuteResult.Fail(SystemErrors.Timeout, string.Format("[Async Handle] Transaction: {0} execute timeout!", transaction.Identity))); };
            transaction.Failed  += delegate { completionSource.SetResult(ExecuteResult.Fail(SystemErrors.Unknown, string.Format("[Async Handle] Transaction: {0} execute failed!", transaction.Identity))); };
            transaction.SendRequest(reqMsg);
            return(await task);
        }
Exemplo n.º 13
0
 /// <summary>
 ///     获取指定活动下的所有标签编号
 /// </summary>
 /// <param name="campaignId">活动编号</param>
 /// <returns>返回执行结果</returns>
 public IExecuteResult <ushort[]> GetTagIdByCampaignId(ulong campaignId)
 {
     try
     {
         //获取参数的值
         object[] parameterValues = new object[] { campaignId };
         //验证CampaignId和AccountId从属关系
         DataTable dt = _slaveDB.SpExecuteTable(SpName.SpGetTagIdByCampaignId, ParametersObject.GetTagIdByCampaignId, parameterValues);
         if (dt.Rows.Count <= 0)
         {
             return(ExecuteResult <ushort[]> .Succeed(null));
         }
         ushort[] tags = new ushort[dt.Rows.Count];
         for (int i = 0; i < dt.Rows.Count; i++)
         {
             tags[i] = ushort.Parse(dt.Rows[i]["Id"].ToString());
         }
         return(ExecuteResult <ushort[]> .Succeed(tags));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult <ushort[]> .Fail(SystemErrors.Unknown, ex.Message));
     }
 }
Exemplo n.º 14
0
 /// <summary>
 ///     根据指定编号获取一个AdGroup实体
 /// </summary>
 /// <param name="userId">用户编号</param>
 /// <param name="adgroupId">广告组编号</param>
 /// <returns>返回执行后的结果</returns>
 public IExecuteResult <AdGroupSimpleData> GetAdGroupSimpleById(uint userId, ulong adgroupId)
 {
     if (userId == 0)
     {
         return(ExecuteResult <AdGroupSimpleData> .Fail(SystemErrors.Malformed, "#Illegal user id"));
     }
     if (adgroupId == 0)
     {
         return(ExecuteResult <AdGroupSimpleData> .Fail(SystemErrors.Malformed, "#Illegal adgroup id"));
     }
     try
     {
         //获取参数的值
         object[]  parameterValues = new object[] { adgroupId, userId };
         DataTable dt = _slaveDB.SpExecuteTable(SpName.SpGetAdGroupSimpleByAdGroupId, ParametersObject.GetAdGroupSimpleById, parameterValues);
         if (dt.Rows.Count == 0)
         {
             return(ExecuteResult <AdGroupSimpleData> .Fail(SystemErrors.NotFound, SpName.SpGetAdGroupSimpleByAdGroupId + ":Executed count = 0"));
         }
         AdGroupSimpleData adGroup = _convertorSimplle.ConvertToDomain(dt.Rows[0]);
         return(ExecuteResult <AdGroupSimpleData> .Succeed(adGroup));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult <AdGroupSimpleData> .Fail(SystemErrors.Unknown, ex.Message));
     }
 }
Exemplo n.º 15
0
        /// <summary>
        /// 创建Campaign
        /// </summary>
        /// <param name="userId">当前用户Id</param>
        /// <param name="campaign">要创建的Campaign对象</param>
        /// <returns>
        ///     <para>1. 如果userid=0, 则返回执行失败</para>
        ///     <para>2. 如果执行成功,则返回CampaignId</para>
        ///     <para>3. 如果插入异常,则返回未知异常</para>
        /// </returns>
        /// <exception cref="ArgumentNullException">参数不能为空</exception>
        public IExecuteResult Create(uint userId, Campaign campaign)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException("campaign");
            }
            if (userId == 0)
            {
                return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal user id!"));
            }
            try
            {
                //验证CampaignId和AccountId从属关系
                DataTable dt = _slaveDB.SpExecuteTable(SpName.SpIsNotExistByAccountId, new[] { "AccountId", "Creator" }, new object[] { campaign.AccountId, userId });
                if (dt.Rows.Count == 0)
                {
                    return(ExecuteResult.Fail(SystemErrors.NotFound, SpName.SpIsNotExistByAccountId + ":Executed count = 0"));
                }

                //创建一条Campaign的信息
                dt = _masterDB.SpExecuteTable(SpName.SpAddCampaign
                                              , ParametersObject.CreateNewCampaign
                                              , new object[]
                {
                    campaign.AccountId
                    , campaign.MediaTypeId
                    , campaign.Name
                    , campaign.DailyBudget
                    , campaign.BidType
                    , campaign.StartDate
                    , campaign.EndDate
                    , campaign.DeliveryRemainingAd
                    , campaign.Status
                    , userId
                    , campaign.Targeting
                    , campaign.WaterMark
                    , campaign.MoreDayBudget
                    , campaign.IsMoreDaysBudget
                    , campaign.IsAutoTransform
                    , campaign.IsConfine
                    , campaign.IsAutoActivation
                    , campaign.ActivationType
                    , campaign.AdUrl
                    , campaign.UdidType
                    , campaign.AppleStore
                    , campaign.AdSource
                });
                if (dt.Rows.Count == 0)
                {
                    return(ExecuteResult.Fail(SystemErrors.NotFound, SpName.SpAddCampaign + ":Executed count = 0"));
                }
                return(ExecuteResult.Succeed((ulong)(long)dt.Rows[0]["CampaignID"]));
            }
            catch (Exception ex)
            {
                _tracing.Error(ex, null);
                return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
            }
        }
Exemplo n.º 16
0
        public ExecuteResult Update()
        {
            var currentTime = DateTime.Now;
            var moneyType   = Ioc.Resolve <IAutoConfigService>()
                              .GetList <MoneyTypeConfig>()
                              .FirstOrDefault(e => e.Id == Parameter.MoneyTypeId);

            if (moneyType == null)
            {
                return(ExecuteResult.Fail($"未找到MoneyTypeId为{Parameter.MoneyTypeId}的货币类型."));
            }

            var userAccount   = Ioc.Resolve <IAccountService>().GetAccount(Parameter.ReceiveUserId, moneyType.Id);
            var invoiceReward = new Reward
            {
                AfterAmount = userAccount.Amount,
                CreateTime  = currentTime,

                ModuleId    = Parameter.ModuleId,
                MoneyTypeId = moneyType.Id,

                Amount = Parameter.Amount,
                //Remark = Parameter.Remark,
                UserId = Parameter.ReceiveUserId,

                Intro = Parameter.Summary,
                //TriggerType = Parameter.TriggerType,
                ModuleConfigId = Parameter.ModuleConfigId
            };

            if (Parameter.Order != null)
            {
                invoiceReward.OrderId = Parameter.Order.Id;
            }

            Ioc.Resolve <IRewardService>().AddOrUpdate(invoiceReward);
            var invoiceBill = new Bill
            {
                Type = BillActionType.FenRun,

                AfterAmount = userAccount.Amount,
                Amount      = Parameter.Amount,

                CreateTime = currentTime,

                Flow  = Parameter.Amount >= 0 ? AccountFlow.Income : AccountFlow.Spending,
                Intro = Parameter.Summary,

                MoneyTypeId = moneyType.Id,

                //Remark = Parameter.Remark,
                UserId      = Parameter.ReceiveUserId,
                OtherUserId = Parameter.TriggerUserId
            };

            Ioc.Resolve <IBillService>().Add(invoiceBill);
            return(ExecuteResult.Success());
        }
Exemplo n.º 17
0
        /// <summary>
        /// 检查分润会员,得到收益的会员
        /// 可以在插入数据看的时候,检查
        /// </summary>
        /// <param name="userId">会员Id</param>
        /// <param name="shareUser">The share 会员.</param>

        public virtual ExecuteResult <ITaskResult[]> GetShareUser(long userId, out User shareUser)
        {
            shareUser = null;
            var _shareUser = Alabo.Helpers.Ioc.Resolve <IUserService>().GetSingle(userId);

            if (_shareUser == null)
            {
                return(ExecuteResult <ITaskResult[]> .Fail($"the shareuser is null.with userid {userId}"));
            }
            //检查分润会员的状态
            if (_shareUser.Status != Alabo.Domains.Enums.Status.Normal)
            {
                return(ExecuteResult <ITaskResult[]> .Fail($"the shareuser status is not normal .with userid {userId}"));
            }
            //检查分润订单用户类型
            if (Configuration.ShareUser.IsLimitShareUserType)
            {
                if (!Configuration.ShareUser.ShareUserTypeId.IsGuidNullOrEmpty())
                {
                    if (Configuration.ShareUser.ShareUserTypeId == Guid.Parse("71BE65E6-3A64-414D-972E-1A3D4A365000"))
                    {
                        //如果是会员,检查会员等级
                        if (Configuration.ShareUser.IsLimitShareUserGrade)
                        {
                            if (Configuration.ShareUser.ShareUserGradeId != _shareUser.GradeId)
                            {
                                return(ExecuteResult <ITaskResult[]> .Fail($"user with id {userId} not match UserGradeid:{Configuration.ShareUser.ShareUserTypeId}, exit module")); //会员等级不符合grade要求,直接退出
                            }
                        }
                    }
                    else
                    {
                        ////检查用户类型
                        //var userType = Alabo.Helpers.Ioc.Resolve<IUserTypeService>().GetSingle(userId, Configuration.ShareUser.ShareUserTypeId);
                        //if (userType == null) {
                        //    return ExecuteResult<ITaskResult[]>.Fail($"share user with id {userId} has not  userType:{Configuration.ShareUser.ShareUserTypeId}, exit module"); //该会员不存在该类型的用户类型
                        //} else {
                        //    //检查用户类型等级
                        //    if (Configuration.ShareUser.IsLimitShareUserGrade) {
                        //        if (Configuration.ShareUser.ShareUserGradeId != userType.GradeId) {
                        //            return ExecuteResult<ITaskResult[]>.Fail($"share userType with UserId {userId} not match UserTypeGradeid:{Configuration.ShareUser.ShareUserTypeId}, exit module"); //会员等级不符合grade要求,直接退出
                        //        }
                        //    }
                        //}
                    }
                }
                else
                {
                    return(ExecuteResult <ITaskResult[]> .Fail($"ShareUserTypeId is null")); //userTypeId 为空
                }
            }
            shareUser = _shareUser;

            return(ExecuteResult <ITaskResult[]> .Success());
        }
        /// <summary>
        ///     执行一个KAE系统命令
        /// </summary>
        /// <param name="msg">执行命令的请求消息</param>
        /// <param name="stateLogger">KAE宿主状态记录器实例</param>
        /// <returns>返回操作的结果</returns>
        public IExecuteResult Execute(MetadataContainer msg, IKAEStateLogger stateLogger)
        {
            Guid kppUniqueId = msg.GetAttributeAsType <Guid>(0x03);

            if (kppUniqueId == Guid.Empty)
            {
                return(ExecuteResult.Fail((byte)KAEErrorCodes.IllegalArgument, string.Empty));
            }
            //stateLogger.Log(string.Format("#[Retrieving KPP Info] #KAE application: {0}, Internal un-rsp count: {1}", kppUniqueId, APPExecuter.Application.UnRspCount));
            //return ExecuteResult.Succeed(APPExecuter.Application.UnRspCount.ToString());
            throw new NotImplementedException();
        }
Exemplo n.º 19
0
        public ExecuteResult Update()
        {
            var repositoryContext = Ioc.Resolve <IUserRepository>().RepositoryContext;
            var transaction       = repositoryContext.BeginNativeDbTransaction();

            try
            {
                var sql = "";
                foreach (var item in RuleItems)
                {
                    var addAmount = item.Ratio * Amount;
                    sql =
                        $"update Asset_Account set Amount=Amount+{addAmount}, HistoryAmount=HistoryAmount+{addAmount}, ModifiedTime=GetDate() where MoneyTypeId='{item.MoneyTypeId}' and UserId={UserId}";
                    if (repositoryContext.ExecuteNonQuery(transaction, sql) <= 0)
                    {
                        return(ExecuteResult.Fail($"sql script:\"{sql}\" execute with 0 line update."));
                    }
                    //此处继续加入Share_Reward与Asset_Bill表的记录
                    sql =
                        @"insert into Share_Reward(AfterAcount, ConfirmTime, CreateTime, ExtraDate, Fee, FenRunDate, Intro, IsAccount, [Level], ModifiedTime, ModuleId, ModuleName, MoneyTypeId, MoneyTypeName, OrderId,OrderPrice, OrderSerial, OrderUserId, OrderUserNick, Price, Remark, Serial, SortOrder, State, Status, UserId, UserNikeName, TriggerType, ModuleConfigId, BonusId)
                        values(@afteracount, GETDATE(), GETDATE(), '', 0, GETDATE(), @intro, 1, 0, GETDATE(), @moduleid, @modulename, @moneytypeid, @moneytypename, 0, 0, '', 0, '', 0, NULL, '', 1000, 3, 0, @userid, @usernickname, @triggertype, @moduleconfigid, @bonusid)";
                    IList <DbParameter> parameterList = new List <DbParameter>
                    {
                        repositoryContext.CreateParameter("@afteracount", Parameter.Amount),
                        repositoryContext.CreateParameter("@intro", Parameter.Summary),
                        repositoryContext.CreateParameter("@moduleid", Parameter.ModuleId),
                        repositoryContext.CreateParameter("@modulename", Parameter.ModuleName),
                        repositoryContext.CreateParameter("@moneytypeid", Parameter.MoneyTypeId),
                        repositoryContext.CreateParameter("@moneytypename", ""),
                        repositoryContext.CreateParameter("@userid", Parameter.ReceiveUserId),
                        repositoryContext.CreateParameter("@usernickname", Parameter.ReceiveUserName),
                        repositoryContext.CreateParameter("@triggertype", Parameter.TriggerType),
                        repositoryContext.CreateParameter("@moduleconfigid", Parameter.ModuleConfigId),
                        repositoryContext.CreateParameter("@bonusid", Parameter.BonusId)
                    };
                    repositoryContext.ExecuteNonQuery(transaction, sql, parameterList.ToArray());
                }

                transaction.Commit();
            }
            catch
            {
                transaction.Rollback();
                throw;
            }
            finally
            {
                transaction.Dispose();
            }

            return(ExecuteResult.Success());
        }
Exemplo n.º 20
0
        /// <summary>
        ///     从OKcoin平台获取Ticker数据
        /// </summary>
        public IExecuteResult GetLTCTickerFromOkCoin()
        {
            try
            {
                string         responseText = null;
                HttpWebRequest request      = (HttpWebRequest)WebRequest.Create("https://www.okcoin.com/api/ticker.do?symbol=ltc_cny");
                request.Method = "Get";
                request.Headers.Clear();
                request.ContentType   = "application/json; charset=UTF-8";
                request.ContentLength = 0;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream stream = response.GetResponseStream();
                    if (stream != null)
                    {
                        StreamReader read = null;
                        using (read = new StreamReader(stream, Encoding.UTF8))
                            responseText += read.ReadToEnd();
                    }
                }
                JObject o      = (JObject)JsonConvert.DeserializeObject(responseText);
                Ticker  ticker = new Ticker
                {
                    BuyPrice  = double.Parse(o["ticker"]["buy"].ToString()),
                    HignPrice = double.Parse(o["ticker"]["high"].ToString()),
                    LastPrice = double.Parse(o["ticker"]["last"].ToString()),
                    LowPrice  = double.Parse(o["ticker"]["low"].ToString()),
                    SellPrice = double.Parse(o["ticker"]["sell"].ToString()),
                    Vol       = double.Parse(o["ticker"]["vol"].ToString()),
                };

                string sqlStr = string.Format("INSERT INTO `coin`.`trades`(`CoinId`,`PlatformId`,`BuyPrice`,`SellPrice`,`HighPrice`,`LowPrice`,`TradeVol`,`NowTime`,`LastPrice`)VALUE({0},{1},{2},{3},{4},{5},{6},{7},{8})",
                                              (int)CoinTypes.LTC, (int)PlatformTypes.OKCoin, ticker.BuyPrice, ticker.SellPrice, ticker.HignPrice, ticker.LowPrice, ticker.Vol, string.Format("'{0}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), ticker.LastPrice);

                int count = InsertData(sqlStr);
                if (count == 0)
                {
                    return(ExecuteResult.Fail(SystemErrors.Unknown, "插入数据库时出错"));
                }
                return(ExecuteResult.Succeed(ticker));
            }
            catch (Exception ex)
            {
                _tracing.Error(ex, null);
                return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
            }
        }
Exemplo n.º 21
0
        /// <summary>
        ///    执行相应的KAE系统命令
        /// </summary>
        /// <param name="msg">系统请求消息</param>
        /// <param name="logger">状态记录器实例</param>
        /// <returns>返回执行后的结果</returns>
        public static IExecuteResult Execute(MetadataContainer msg, IKAEStateLogger logger)
        {
            MessageIdentity   messageIdentity = msg.GetAttributeAsType <MessageIdentity>(0x00);
            IKAESystemCommand command;

            if (!_commands.TryGetValue(messageIdentity, out command))
            {
                return(ExecuteResult.Fail((byte)KAEErrorCodes.NotSupportedCommand, string.Format("#Not supported system command protocol: {0}", messageIdentity)));
            }
            try { return(command.Execute(msg, logger)); }
            catch (Exception ex)
            {
                logger.Log(string.Format("#Occured an unhandled exception while executing a system level KAE command. #Command msg struct: {0}. \r\n#Error: {1}", msg, ex.Message));
                _tracing.Error(ex, null);
                return(ExecuteResult.Fail((byte)KAEErrorCodes.Unknown, ex.Message));
            }
        }
Exemplo n.º 22
0
 /// <summary>
 ///     新增日志
 /// </summary>
 /// <param name="className">类名称</param>
 /// <param name="createTime">建立时间</param>
 /// <param name="serviceName">服务名称</param>
 /// <param name="processInfo">过程日志详细信息</param>
 /// <param name="processLevel">过程日志级别</param>
 /// <param name="processDetail">过程日志详细</param>
 /// <param name="processTrace">过程日志堆栈信息</param>
 /// <returns>执行结果</returns>
 public IExecuteResult Create(string className, DateTime createTime, string serviceName, string processInfo, byte processLevel, string processDetail, string processTrace)
 {
     try
     {
         //获取参数的值
         object[] parameterValues = new object[] { className, createTime, serviceName, processInfo, processLevel, processDetail, processTrace };
         ulong    logId           = _masterDB.SpExecuteScalar <ulong>(SpName.SpAddLog, ParametersObject.SpAddLog, parameterValues);
         if (logId == 0)
         {
             return(ExecuteResult.Fail(SystemErrors.Unknown, "#LogId is 0"));
         }
         return(ExecuteResult.Succeed(logId));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
     }
 }
Exemplo n.º 23
0
        /// <summary>
        ///     获得发送质量圆环邮件的日志
        /// </summary>
        /// <param name="fatherTid">父级tid</param>
        /// <returns>返回的结果(DataTable)</returns>
        public IExecuteResult GetSendQualityRingDetailLog(string fatherTid)
        {
            try
            {
                //获取参数的值
                object[]  parameterValues = new object[] { fatherTid };
                DataTable dt = _masterDB.SpExecuteTable(SpName.SpBuildQualityRingDetailLog, ParametersObject.SpBuildQualityRingDetailLog, parameterValues);
                if (dt == null)
                {
                    return(ExecuteResult.Fail(SystemErrors.Unknown, "#Return DataTable is Null"));
                }

                return(ExecuteResult.Succeed(dt));
            }
            catch (Exception ex)
            {
                _tracing.Error(ex, null);
                return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
            }
        }
Exemplo n.º 24
0
        /// <summary>
        ///     检查分润会员,得到收益的会员
        ///     可以在插入数据看的时候,检查
        /// </summary>
        /// <param name="userId">会员Id</param>
        /// <param name="shareUser">The share 会员.</param>
        public virtual ExecuteResult <ITaskResult[]> GetShareUser(long userId, out User shareUser)
        {
            shareUser = null;
            var _shareUser = Ioc.Resolve <IUserService>().GetSingle(userId);

            if (_shareUser == null)
            {
                return(ExecuteResult <ITaskResult[]> .Cancel($"the shareuser is null.with userid {userId}"));
            }
            //检查分润会员的状态
            if (_shareUser.Status != Status.Normal)
            {
                return(ExecuteResult <ITaskResult[]> .Fail($"the shareuser status is not normal .with userid {userId}"));
            }
            //检查分润订单用户类型
            if (Configuration.ShareUser.IsLimitShareUserType)
            {
                if (!Configuration.ShareUser.ShareUserTypeId.IsGuidNullOrEmpty())
                {
                    if (Configuration.ShareUser.ShareUserTypeId == Guid.Parse("71BE65E6-3A64-414D-972E-1A3D4A365000"))
                    {
                        //如果是会员,检查会员等级
                        if (Configuration.ShareUser.IsLimitShareUserGrade)
                        {
                            if (Configuration.ShareUser.ShareUserGradeId != _shareUser.GradeId)
                            {
                                return(ExecuteResult <ITaskResult[]> .Fail(
                                           $"user with id {userId} not match UserGradeid:{Configuration.ShareUser.ShareUserTypeId}, exit module")); //会员等级不符合grade要求,直接退出
                            }
                        }
                    }
                }
                else
                {
                    return(ExecuteResult <ITaskResult[]> .Fail("ShareUserTypeId is null")); //userTypeId 为空
                }
            }

            shareUser = _shareUser;
            return(ExecuteResult <ITaskResult[]> .Success());
        }
Exemplo n.º 25
0
        /// <summary>
        ///     根据ID更改物料状态
        /// </summary>
        /// <param name="accountId">账户id</param>
        /// <param name="groupIds">主键IDs</param>
        /// <param name="status">状态</param>
        /// <returns>返回执行后的结果</returns>
        public IExecuteResult UpdateStatusByIds(ulong accountId, ulong[] groupIds, AdStatus status)
        {
            if (groupIds == null || groupIds.Length == 0)
            {
                return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal groupId"));
            }
            try
            {
                object[] parameterValues;

                StringBuilder sGroup = new StringBuilder();
                foreach (ulong groupId in groupIds)
                {
                    sGroup.Append(groupId).Append(',');
                }
                string groupString = sGroup.ToString().TrimEnd(',');
                //获取参数的值
                parameterValues = new object[] { accountId, groupString };
                //验证CampaignId和AccountId从属关系
                uint selectCount = _slaveDB.SpExecuteScalar <uint>(SpName.SpIsNotExistByAccountIdAndGroupId,
                                                                   ParametersObject.IsNotExistByAccountIdAndGroupId,
                                                                   parameterValues);
                if (selectCount != groupIds.Length)
                {
                    return(ExecuteResult.Fail(SystemErrors.NotFound, SpName.SpIsNotExistByAccountIdAndGroupId + ":Executed count = 0 #Paramate [AccountId] is " + accountId + " [GroupId] is " + groupString));
                }

                //获取参数的值
                parameterValues = new object[] { groupString, status, 0 };
                _masterDB.SpExecuteTable(SpName.SpUpdateGroupsStatus, ParametersObject.UpdateGroupsStatus, parameterValues);
                return(ExecuteResult.Succeed(true));
            }
            catch (Exception ex)
            {
                _tracing.Error(ex, null);
                return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
            }
        }
Exemplo n.º 26
0
 /// <summary>
 ///     获得账户列表信息
 /// </summary>
 /// <param name="accountId">账户ID</param>
 /// <returns>执行结果</returns>
 public IExecuteResult GetAccountTypeByAccountId(ulong accountId)
 {
     if (accountId == 0)
     {
         return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal account id."));
     }
     try
     {
         // account type.
         DataTable accountTypeDt = _slaveDB.SpExecuteTable(SpName.SpGetAccountTypeFromAccountDetail, ParametersObject.GetAccountTypeFromAccountDetail, new[] { accountId });
         if (accountTypeDt.Rows.Count == 0)
         {
             return(ExecuteResult.Fail(SystemErrors.NotFound, "#There isn't any accout accords current condition: AccountId: " + accountId));
         }
         AccountTypes accountTypes = (AccountTypes)byte.Parse(accountTypeDt.Rows[0]["AccountTypeID"].ToString());
         return(ExecuteResult.Succeed(accountTypes));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
     }
 }
Exemplo n.º 27
0
        /// <summary>
        ///     对module配置与参数进行基础验证,子类重写后需要显式调用并判定返回值,如返回值不为Success,则不再执行子类后续逻辑
        /// </summary>
        /// <param name="parameter">参数</param>
        public override ExecuteResult <ITaskResult[]> Execute(TaskParameter parameter)
        {
            var baseResult = base.Execute(parameter);

            if (baseResult.Status != ResultStatus.Success)
            {
                return(baseResult);
            }

            if (parameter.TryGetValue(TriggerTypeKey, out int triggerType))
            {
                TriggerType = (TriggerType)triggerType;
                if (Configuration.TriggerType != TriggerType) //触发类型与配置的触发类型不一致,直接退出
                {
                    return(ExecuteResult <ITaskResult[]> .Cancel(
                               $"模块实际触发类型{triggerType}与模块设置的触发类型{Configuration.TriggerType}不一致,退出模块."));
                }
            }
            else
            {
                TriggerType = Configuration.TriggerType;
            }

            // 触发类型为会员注册
            if (TriggerType == TriggerType.UserReg)
            {
                parameter.TryGetValue(FenRunAmountKey, out decimal amount);
                BaseFenRunAmount = amount;
                if (BaseFenRunAmount <= 0)
                {
                    return(ExecuteResult <ITaskResult[]> .Cancel($"分润基数价格获取为0. BaseFenRunAmount={BaseFenRunAmount}"));
                }
            }

            // 触发类型为会员升级
            if (TriggerType == TriggerType.UserUpgrade)
            {
                parameter.TryGetValue(FenRunAmountKey, out decimal amount);
                BaseFenRunAmount = amount;
                if (BaseFenRunAmount <= 0)
                {
                    return(ExecuteResult <ITaskResult[]> .Cancel(
                               $"分润基数价格获取为0. BaseFenRunAmount={BaseFenRunAmount},会员Id为{ShareOrder.UserId}"));
                }
            }

            // TODO 2019年9月24日 触发类型为商城购物
            if (TriggerType == TriggerType.Order)
            {
                ////获取价格基数
                //if (parameter.TryGetValue("OrderId", out long orderId)) {
                //    // 获取符合条件的商品 价格依赖范围 所有商品 按所属商品线选择 按所属商城选择
                //    var effectiveOrderProductListAll = GetEffectiveOrderProduct(orderId);
                //    if (effectiveOrderProductListAll == null || effectiveOrderProductListAll.Count == 0) {
                //        return ExecuteResult<ITaskResult[]>.Cancel($"没有符合的产品可分润,退出模块.");
                //    }
                //    var effectiveOrderProductList = new List<OrderProduct>();

                //    // 商品单价限制

                //    if (Configuration.PriceLimitType == PriceLimitType.ProductPrice) {
                //        foreach (var productItem in effectiveOrderProductListAll) {
                //            if (productItem.Amount > Configuration.BaseRule.MaxAmount && Configuration.BaseRule.MaxAmount > 0) {
                //                continue;
                //            }
                //            if (productItem.Amount < Configuration.BaseRule.MinimumAmount && Configuration.BaseRule.MinimumAmount > 0) {
                //                continue;
                //            }
                //            effectiveOrderProductList.Add(productItem);
                //        }
                //    } else {
                //        effectiveOrderProductList = effectiveOrderProductListAll;
                //    }

                //    //如果价格模式为销售价,则触发金额为有效的商品实际售价之和
                //    if (Configuration.ProductRule.AmountType == PriceType.Price) {
                //        // 根据实际支付方式获取价格 (PaymentAmount为人民币支付的价格)
                //        BaseFenRunAmount = effectiveOrderProductList.Sum(e => e.PaymentAmount);
                //    }
                //    //如果价格模式为分润价,则触发金额为有效的商品分润价之和
                //    if (Configuration.ProductRule.AmountType == PriceType.FenRun) {
                //        BaseFenRunAmount = effectiveOrderProductList.Sum(e => e.FenRunAmount);
                //    }
                //    //如果价格模式为商品数 :有效商品数量之和
                //    if (Configuration.ProductRule.AmountType == PriceType.ProductNum) {
                //        BaseFenRunAmount = effectiveOrderProductList.Sum(e => e.Count);
                //    }
                //    //如果价格模式为商品数 :有效商品数量之和
                //    if (Configuration.ProductRule.AmountType == PriceType.OrderNum) {
                //        BaseFenRunAmount = 1;
                //    }
                //    //如果价格模式为服务费
                //    if (Configuration.ProductRule.AmountType == PriceType.OrderFeeAmount) {
                //        BaseFenRunAmount = effectiveOrderProductList.Sum(e => e.OrderProductExtension?.OrderAmount?.FeeAmount).ConvertToDecimal();
                //    }
                //}

                //OrderId = orderId;
                //if (BaseFenRunAmount <= 0) {
                //    return ExecuteResult<ITaskResult[]>.Cancel($"分润基数价格获取为0. BaseFenRunAmount={BaseFenRunAmount},订单id为{OrderId}");
                //}
            }

            // 触发类型为内部连锁
            if (TriggerType == TriggerType.Chain)
            {
                if (!parameter.TryGetValue(DefaultAmountKey, out decimal amount))
                {
                    amount = 0;
                }

                BaseFenRunAmount = amount;
            }

            // 触发类型为其他、提现、充值,订单金额为ShareOrder的Amount
            if (TriggerType == TriggerType.Other || TriggerType == TriggerType.WithDraw ||
                TriggerType == TriggerType.Recharge)
            {
                parameter.TryGetValue(FenRunAmountKey, out decimal amount);
                BaseFenRunAmount = amount;
                if (BaseFenRunAmount <= 0)
                {
                    return(ExecuteResult <ITaskResult[]> .Cancel($"分润基数价格获取为0. BaseFenRunAmount={BaseFenRunAmount}"));
                }
            }

            if (!parameter.TryGetValue("ShareOrderId", out long shareOrderId))
            {
                return(ExecuteResult <ITaskResult[]> .Fail("分润订单ShareOrderId未找到."));
            }
            // 线程停止3s中,重新读取数据库,保证ShardeOdeer状态正确,不重复触发
            //Thread.Sleep(TimeSpan.FromSeconds(3));
            var shareOrder = Resolve <IShareOrderService>().GetSingleNative(shareOrderId);

            if (shareOrder == null)
            {
                return(ExecuteResult <ITaskResult[]> .Fail("分润订单未找到."));
            }
            // TODO 2019年9月24日 重构 商城模式
            //if (shareOrder.Status != ShareOrderStatus.Pending) {
            //    return ExecuteResult<ITaskResult[]>.Fail("分润订单原生查询,状态不正常.");
            //}

            var teamConfig = Resolve <IAutoConfigService>().GetValue <TeamConfig>();

            TeamLevel = teamConfig.TeamLevel;
            return(ExecuteResult <ITaskResult[]> .Success());
        }
Exemplo n.º 28
0
        /// <summary>
        ///     Executes the specified parameter.
        /// </summary>
        /// <param name="parameter">参数</param>
        public override ExecuteResult <ITaskResult[]> Execute(TaskParameter parameter)
        {
            if (Configuration == null)
            {
                return(ExecuteResult <ITaskResult[]> .Fail("configuration is null."));
            }
            //进行参数判断
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            //判断通用交易订单
            if (!parameter.TryGetValue("ShareOrderId", out long shareOrderId))
            {
                return(ExecuteResult <ITaskResult[]> .Fail("分润订单ShareOrderId未找到."));
            }

            var shareOrder = Ioc.Resolve <IShareOrderService>().GetSingle(r => r.Id == shareOrderId);

            if (shareOrder == null)
            {
                return(ExecuteResult <ITaskResult[]> .Fail($"分润订单为空,shareorder with id {shareOrderId} is null."));
            }

            if (shareOrder.Status != ShareOrderStatus.Pending)
            {
                return(ExecuteResult <ITaskResult[]> .Fail("分润订单状态不是代理状态,不触发分润."));
            }

            if (shareOrder.Amount <= 0)
            {
                return(ExecuteResult <ITaskResult[]> .Fail("分润订单金额小于0,shareorder with amount is less than zero"));
            }

            if (Configuration.PriceLimitType == PriceLimitType.OrderPrice)
            {
                if (shareOrder.Amount > Configuration.BaseRule.MaxAmount && Configuration.BaseRule.MaxAmount > 0)
                {
                    return(ExecuteResult <ITaskResult[]> .Fail(
                               $"分润订单金额{shareOrder.Amount} > 最大触发金额{Configuration.BaseRule.MinimumAmount}, 退出模块"));
                }

                if (shareOrder.Amount < Configuration.BaseRule.MinimumAmount && Configuration.BaseRule.MinimumAmount > 0
                    )
                {
                    return(ExecuteResult <ITaskResult[]> .Fail(
                               $"分润订单金额{shareOrder.Amount} <= 最小触发金额{Configuration.BaseRule.MinimumAmount}, 退出模块"));
                }
            }

            ShareOrder = shareOrder;

            //判断交易用户
            var user = Ioc.Resolve <IUserService>().GetSingle(shareOrder.UserId);

            if (user == null)
            {
                return(ExecuteResult <ITaskResult[]> .Fail(
                           $"shareorder with id {shareOrderId} ,shareorder user is null."));
            }

            ShareOrderUser = user;
            //检查分润用户
            var gradeResult = CheckOrderUserTypeAndGrade();

            if (gradeResult.Status != ResultStatus.Success)
            {
                return(gradeResult);
            }

            //检查分润比例
            var distriRatio = Configuration.DistriRatio.Split(',');

            if (distriRatio == null || distriRatio.Length == 0)
            {
                return(ExecuteResult <ITaskResult[]> .Cancel("模块需要设置分润比例但未设置."));
            }

            Ratios = distriRatio.ToList();
            return(ExecuteResult <ITaskResult[]> .Success());
        }
Exemplo n.º 29
0
 protected ExecuteResult <ITaskResult[]> FailAndLogError(string message)
 {
     Logger.LogError(message);
     return(ExecuteResult <ITaskResult[]> .Fail(message));
 }
Exemplo n.º 30
0
        /// <summary>
        ///     创建一个新的AdGroup
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <param name="accountId">账户编号</param>
        /// <param name="adGroup">需要被创建的AdGroup</param>
        /// <returns>返回执行后的结果</returns>
        /// <exception cref="ArgumentNullException">参数不能为空</exception>
        public IExecuteResult Create(uint userId, ulong accountId, AdGroup adGroup)
        {
            if (adGroup == null)
            {
                throw new ArgumentNullException("adGroup");
            }
            try
            {
                //获取参数的值
                object[] parameterValues = new object[] { accountId, adGroup.CampaignId, userId };

                //验证CampaignId和AccountId从属关系
                DataTable dt = _slaveDB.SpExecuteTable(SpName.SpIsNotExistByAccountIdAndCampaignId, ParametersObject.IsNotExistByAccountIdAndCampaignId, parameterValues);
                if (dt.Rows.Count == 0)
                {
                    return(ExecuteResult.Fail(SystemErrors.NotFound, SpName.SpIsNotExistByAccountIdAndCampaignId + ":Executed count = 0"));
                }
                //check publish id.
                if (!string.IsNullOrEmpty(adGroup.PublishId))
                {
                    string[] subIds = adGroup.PublishId.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string subId in subIds)
                    {
                        dt = _slaveDB.SpExecuteTable(SpName.SpGetAppByPublishId, ParametersObject.GetAppByPublishId, new object[] { subId });
                        if (dt.Rows.Count == 0)
                        {
                            return(ExecuteResult.Fail(SystemErrors.NotFound, string.Format("#There isn't any records indicated that this publish id: {0} is valid.", subId)));
                        }
                    }
                }

                //获取参数的值
                parameterValues = new object[]
                {
                    adGroup.CampaignId
                    , accountId
                    , adGroup.MediaTypeId
                    , adGroup.Name
                    , Math.Round(adGroup.BidPrice, 2)
                    , adGroup.PricePolicy.DevPrice
                    , adGroup.Status
                    , adGroup.DeliveryMode
                    , adGroup.Weight
                    , userId
                    , adGroup.Targetings.FrequencyTargeting.MaxClicksEveryDayByDevice
                    , adGroup.Targetings.FrequencyTargeting.MaxImpressionsEveryDayByDevice
                    , adGroup.Targetings.FrequencyTargeting.MaxClicksSevenDaysByDevice
                    , adGroup.Targetings.FrequencyTargeting.MaxImpressionsSevenDaysByDevice
                    , adGroup.Targetings.FrequencyTargeting.MaxClicksEveryDay
                    , adGroup.Targetings.FrequencyTargeting.MaxImpressionsEveryDay
                    , adGroup.Targetings.FrequencyTargeting.MaxClicksPutIn
                    , adGroup.Targetings.FrequencyTargeting.MaxImpressionsPutIn
                    , adGroup.ITunesAppId
                    , adGroup.ActionType
                    , adGroup.ContentType.AdContentId
                    , adGroup.Targetings.TimeTargeting
                    , adGroup.ThirdpartyPlatformId
                    , adGroup.DeviceCategory
                    , adGroup.NetworkTypes
                    , adGroup.Targetings.DeviceTargeting.GetCatagoryString()
                    , adGroup.Targetings.DeviceTargeting.GetSDKString()
                    , adGroup.Targetings.DeviceTargeting.GetOSString()
                    , adGroup.Targetings.DeviceTargeting.GetOpString()
                    , adGroup.Targetings.DeviceTargeting.GetAppString()
                    , adGroup.ITunesAppCategoryId
                    , adGroup.CPAPrice
                    , adGroup.MaxImpressions
                    , adGroup.MaxClicks
                    , adGroup.MaxPerUserImpressions
                    , adGroup.PublishId
                    , adGroup.Targetings.TagTargeting.GetData(UserTagDirectionTypes.Forward) == null ? null : adGroup.Targetings.TagTargeting.GetData(UserTagDirectionTypes.Forward).Concat()
                    , adGroup.Targetings.TagTargeting.GetData(UserTagDirectionTypes.Backward) == null ? null : adGroup.Targetings.TagTargeting.GetData(UserTagDirectionTypes.Backward).Concat()
                    , adGroup.ITunesBundleId
                    , adGroup.DisplayType
                };
                //创建一条Campaign的信息
                dt = _masterDB.SpExecuteTable(SpName.SpAddAdGroup
                                              , ParametersObject.CreateNewAdGroup
                                              , parameterValues);
                if (dt.Rows.Count == 0)
                {
                    return(ExecuteResult.Fail(SystemErrors.NotFound, SpName.SpAddAdGroup + ":Executed count = 0"));
                }
                return(ExecuteResult.Succeed((ulong)(long)dt.Rows[0]["GroupID"]));
            }
            catch (Exception ex)
            {
                _tracing.Error(ex, null);
                return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
            }
        }