Exemplo n.º 1
0
        /// <summary>
        ///     创建分润参数
        /// </summary>
        /// <param name="shareAamount"></param>
        /// <param name="triggerUser">触发用户</param>
        /// <param name="shareUser"></param>
        /// <param name="moneyType">分润金额到账账户类型</param>
        /// <param name="config">分润维度配置数据</param>
        /// <param name="parameter">分润触发通用参数</param>
        /// <param name="shareLevel"></param>
        public static FenRunResultParameter Create(decimal shareAamount, User triggerUser, User shareUser,
                                                   MoneyTypeConfig moneyType, ShareBaseConfig config, TaskParameter parameter, long shareLevel = 0)
        {
            parameter.TryGetValue("OrderId", out long orderId);
            parameter.TryGetValue("OrderSerial", out string orderSerial);
            var Order = new InvoiceOrder
            {
                Id     = orderId,
                Serial = orderSerial,
                Amount = shareAamount
            };

            //替换分润描述
            var summary = config.TemplateRule.LoggerTemplate.Replace("{OrderUserName}", triggerUser.UserName)
                          .Replace("{ShareUserNickName}", triggerUser.Name).Replace("{ShareUserRealName}", triggerUser.Name)
                          .Replace("{GainerUserName}", shareUser.UserName).Replace("{GainerNickName}", shareUser.Name)
                          .Replace("{GainerRealName}", shareUser.Name)
                          .Replace("{OrderSerial}", orderSerial).Replace("{AccountName}", moneyType.Name)
                          .Replace("{ShareUserAmount}", triggerUser.ToString())
                          .Replace("{DividendAmount}", shareAamount.ToString());

            return(new FenRunResultParameter
            {
                Amount = shareAamount,
                ModuleName = "招商奖", //读取配置的的名称,未实现

                //分润记录信息
                ShareStatus = FenRunStatus.Success,
                ShareLevel = shareLevel,
                UserRemark = string.Empty,
                Summary = summary,
                ExtraDate = "额外数据",

                //模块信息
                ModuleConfigId = config.Id,
                //BonusId = config.BonusId,
                ModuleTypeName = config.GetType().Name,
                TriggerType = config.TriggerType,

                //触发用户
                TriggerGradeId = config.ShareUser.ShareUserGradeId,
                TriggerUserTypeId = config.ShareUser.ShareUserTypeId,
                TriggerUserId = triggerUser.Id,
                OrderUserName = triggerUser.GetUserName(),

                //获得分润的用户
                ReceiveUserId = shareUser.Id,
                ReceiveUserName = shareUser.GetUserName(),

                //订单信息
                Order = Order,

                //财务信息
                MoneyTypeId = moneyType.Id,
                BillStatus = BillStatus.Success
            });
        }
Exemplo n.º 2
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.º 3
0
        /// <summary>
        ///     /// 执行队列
        ///     执行TaskQueue中的队列
        ///     Executes the task.
        /// </summary>
        /// <typeparam name="TParameter"></typeparam>
        /// <param name="moduleType"></param>
        /// <param name="taskQueue"></param>
        /// <param name="parameter"></param>
        public void ExecuteQueue <TParameter>(Type moduleType, TaskQueue taskQueue, TParameter parameter)
            where TParameter : class
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            if (moduleType == null)
            {
                throw new ArgumentNullException(nameof(moduleType));
            }

            var taskModuleAttribute = moduleType.GetTypeInfo().GetAttribute <TaskModuleAttribute>();

            if (taskModuleAttribute == null)
            {
                throw new ArgumentNullException(nameof(moduleType));
            }

            // 如果模块Id不相同退出
            if (taskModuleAttribute.Id != taskQueue.ModuleId)
            {
                return;
            }

            //从数据库中获取所有分润模块
            var modules = _taskModuleFactory.CreateModules(moduleType);

            if (modules.Count() <= 0)
            {
                return;
            }

            // 参数处理
            var taskParameter = new TaskParameter();
            var propertyList  = GetOrCreatePropertyCache <TParameter>();

            foreach (var item in propertyList)
            {
                taskParameter.AddValue(item.Key.Name, item.Value(parameter));
            }

            var taskMessage = new TaskMessage
            {
                Type       = moduleType.FullName,
                ModuleId   = taskModuleAttribute.Id,
                ModuleName = taskModuleAttribute.Name
            };
            IList <ITaskResult> resultList = new List <ITaskResult>();
            var success = false;

            foreach (var item in modules)
            {
                taskParameter.TryGetValue("QueueId", out long queueId);
                try
                {
                    var result = item.Execute(taskParameter);
                    if (result != null)
                    {
                        if (result.Status == ResultStatus.Success && result.Result.Count() > 0)
                        {
                            resultList.AddRange(result.Result);
                            success = true;
                        }
                        else
                        {
                            var taskQueueUpdate = Ioc.Resolve <ITaskQueueService>().GetSingle(taskQueue.Id);
                            // 将操作记录更新到数据
                            taskMessage.Message        = result.Message;
                            taskQueueUpdate.Status     = QueueStatus.Error;
                            taskQueueUpdate.Message    = $"升级队列失败,.message{taskMessage.Message}";
                            taskQueueUpdate.HandleTime = DateTime.Now;
                            Ioc.Resolve <ITaskQueueService>().Update(taskQueueUpdate);
                            _logger.LogWarning(result.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //执行出错,将错误写入到数据库中
                    var taskQueueUpdate = Ioc.Resolve <ITaskQueueService>().GetSingle(taskQueue.Id);
                    taskMessage.Message        = $"升级队列失败执行出错{moduleType}:{ex.Message}";
                    taskQueueUpdate.Status     = QueueStatus.Error;
                    taskQueueUpdate.Message    = $"{taskMessage.Message}";
                    taskQueueUpdate.HandleTime = DateTime.Now;
                    Ioc.Resolve <ITaskQueueService>().Update(taskQueueUpdate);
                }
            }

            var repositoryContext = Ioc.Resolve <IUserRepository>().RepositoryContext;
            IList <UserGradeChangeResult> gradeResultList = new List <UserGradeChangeResult>();

            foreach (var graderesult in resultList)
            {
                if (graderesult is UserGradeChangeResult)
                {
                    gradeResultList.Add((UserGradeChangeResult)graderesult);
                }
            }

            // 更新分润结果,财务结果到数据库
            Ioc.Resolve <IShareOrderRepository>().UpdateUpgradeTaskResult(gradeResultList);

            if (success)
            {
                //更新成功
                var taskQueueUpdate = Ioc.Resolve <ITaskQueueService>().GetSingle(taskQueue.Id);
                taskQueueUpdate.Status         = QueueStatus.Handled;
                taskQueueUpdate.Message        = "success";
                taskQueueUpdate.HandleTime     = DateTime.Now;
                taskQueueUpdate.ExecutionTimes = taskQueue.ExecutionTimes + 1;
                Ioc.Resolve <ITaskQueueService>().Update(taskQueueUpdate);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        ///     开始执行task任务,包括会员升级,分润等
        ///     Executes the task.
        /// </summary>
        /// <typeparam name="TParameter">The type of the t parameter.</typeparam>
        /// <param name="moduleType">The type.</param>
        /// <param name="parameter">参数</param>
        /// <param name="shareOrder"></param>
        /// <returns>ServiceResult.</returns>
        public void ExecuteTask <TParameter>(Type moduleType, ShareOrder shareOrder, TParameter parameter)
            where TParameter : class
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            if (moduleType == null)
            {
                throw new ArgumentNullException(nameof(moduleType));
            }

            var taskModuleAttribute = moduleType.GetTypeInfo().GetAttribute <TaskModuleAttribute>();

            if (taskModuleAttribute == null)
            {
                throw new ArgumentNullException(nameof(moduleType));
            }

            //从数据库中获取所有分润模块
            var modules = _taskModuleFactory.CreateModules(moduleType);

            if (modules.Count() <= 0)
            {
                return;
            }

            // 参数处理
            var taskParameter = new TaskParameter();
            var propertyList  = GetOrCreatePropertyCache <TParameter>();

            foreach (var item in propertyList)
            {
                taskParameter.AddValue(item.Key.Name, item.Value(parameter));
            }

            var taskMessage = new TaskMessage
            {
                Type       = moduleType.FullName,
                ModuleId   = taskModuleAttribute.Id,
                ModuleName = taskModuleAttribute.Name
            };
            IList <ITaskResult> resultList = new List <ITaskResult>();

            foreach (var item in modules)
            {
                // 通过动态类型获取配置属性
                var configuration = ((dynamic)item).Configuration;
                var triggerType   = (TriggerType)configuration.TriggerType;
                if (triggerType != shareOrder.TriggerType)
                {
                    continue;
                }

                taskMessage.ConfigName = (string)configuration.Name;
                taskParameter.TryGetValue("ShareOrderId", out long ShareOrderId);
                try
                {
                    var result = item.Execute(taskParameter);
                    if (result != null)
                    {
                        if (result.Status == ResultStatus.Success && result.Result.Count() > 0)
                        {
                            resultList.AddRange(result.Result);
                        }
                        else
                        {
                            // 将操作记录更新到数据
                            taskMessage.Message = result.Message;
                            Ioc.Resolve <IShareOrderService>()
                            .AddTaskMessage(ShareOrderId, taskMessage);
                            _logger.LogWarning(result.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //执行出错,将错误写入到数据库中
                    taskMessage.Message = $"DefaultTaskActuator.Execute执行出错{moduleType}:{ex.Message}";
                    Ioc.Resolve <IShareOrderService>().AddTaskMessage(ShareOrderId, taskMessage);
                }
            }

            //更新执行次数
            var repositoryContext = Ioc.Resolve <IShareOrderRepository>();

            repositoryContext.UpdateExcuteCount(shareOrder.Id, modules.Count());

            if (resultList.Count > 0)
            {
                var shareOrderNative = Ioc.Resolve <IShareOrderService>()
                                       .GetSingleNative(shareOrder.Id);
                if (shareOrderNative.Status == ShareOrderStatus.Pending)
                {
                    UpdateTaskPriceResult(resultList);
                }
            }
        }
Exemplo n.º 5
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.º 6
0
        /// <summary>
        /// 生成订单
        /// </summary>
        /// <param name="shareAmount">分润金额</param>
        /// <param name="orderUser">下单用户</param>
        /// <param name="shareUser">收益用户</param>
        /// <param name="parameter">参数</param>
        /// <param name="config">分润配置</param>
        /// <param name="resultList"></param>
        /// <param name="configName"></param>
        protected void CreateResultList(decimal shareAmount, User orderUser, User shareUser, TaskParameter parameter, ShareBaseConfig config, IList <ITaskResult> resultList, string configName = "")
        {
            //如果分润金额小于等于0,则退出
            if (shareAmount > 0 && shareUser != null)
            {
                if (shareUser.Status == Alabo.Domains.Enums.Status.Normal)
                {
                    parameter.TryGetValue("OrderId", out long orderId);

                    // 如果限制供应商购买过的店铺
                    // 检查该会员是否购买过该店铺的商品,核对User_TypeUser表
                    if (Configuration.ProductRule.IsLimitStoreBuy)
                    {
                        //TODO 重构
                        //// 如果是订单用户
                        //if (TriggerType == TriggerType.Order) {
                        //    var order = Ioc.Resolve<IOrderService>().GetSingle(orderId);
                        //    if (order != null) {
                        //        var storeUser = Ioc.Resolve<ITypeUserService>()
                        //            .GetStoreUser(order.StoreId, shareUser.Id);
                        //        if (storeUser == null) {
                        //            //分润用户不是该店铺的用户 退出
                        //            return;
                        //            // ExecuteResult<ITaskResult>.Cancel($"分润用户不是该店铺的用户");
                        //        }
                        //    }
                        //}
                    }

                    var moneyTypes = Resolve <IAutoConfigService>().GetList <MoneyTypeConfig>(r => r.Status == Alabo.Domains.Enums.Status.Normal);
                    foreach (var rule in Configuration.RuleItems)
                    {
                        var ruleAmount    = shareAmount * rule.Ratio;
                        var ruleMoneyType = moneyTypes.FirstOrDefault(r => r.Id == rule.MoneyTypeId);
                        if (ruleMoneyType == null)
                        {
                            continue;
                            //ExecuteResult<ITaskResult>.Cancel($"资产分润规则设置错误,货币类型Id{ruleMoneyType.Id}");
                        }

                        var shareResult = new ShareResult {
                            OrderUser       = orderUser,
                            ShareUser       = shareUser,
                            ShareOrder      = base.ShareOrder,
                            Amount          = ruleAmount,
                            MoneyTypeId     = rule.MoneyTypeId,
                            ModuleConfigId  = config.Id,
                            ModuleId        = config.ModuleId,
                            SmsNotification = config.TemplateRule.SmsNotification
                        };
                        //描述
                        shareResult.Intro = Configuration.TemplateRule.LoggerTemplate.Replace("{OrderUserName}", orderUser.GetUserName())
                                            .Replace("{ShareUserName}", shareUser.GetUserName())
                                            .Replace("{ConfigName}", configName)
                                            .Replace("{AccountName}", ruleMoneyType.Name)
                                            .Replace("{OrderId}", orderId.ToString())
                                            .Replace("{OrderPrice}", base.ShareOrder.Amount.ToString("F2"))
                                            .Replace("{ShareAmount}", ruleAmount.ToString("F2"));

                        //短信内容
                        shareResult.SmsIntro = Configuration.TemplateRule.LoggerTemplate.Replace("{OrderUserName}", orderUser.GetUserName())
                                               .Replace("{ShareUserName}", shareUser.GetUserName())
                                               .Replace("{ConfigName}", configName)
                                               .Replace("{AccountName}", ruleMoneyType.Name)
                                               .Replace("{OrderId}", orderId.ToString())
                                               .Replace("{OrderPrice}", base.ShareOrder.Amount.ToString("F2"))
                                               .Replace("{ShareAmount}", ruleAmount.ToString("F2"));

                        var queueResult = new TaskQueueResult <ITaskResult>(Context)
                        {
                            ShareResult = shareResult
                        };
                        resultList.Add(queueResult);
                    }
                }
            }
        }