Exemplo n.º 1
0
        public ApiResult <AutoPreview> Preview(string id, string type)
        {
            //check
            if (type.IsNullOrEmpty() || type == "undefined")
            {
                return(ApiResult.Failure <AutoPreview>("类型不能为空"));
            }

            if (id.IsNullOrEmpty())
            {
                return(ApiResult.Failure <AutoPreview>("id不能为空"));
            }

            var typeIntance = type.GetTypeByName();
            var find        = type.GetInstanceByName();

            if (find == null || typeIntance == null)
            {
                return(ApiResult.Failure <AutoPreview>($"类型不存在,请确认{type}输入是否正确"));
            }

            //entity
            if (find is IEntity)
            {
                var obj         = Dynamics.DynamicService.ResolveMethod(typeIntance.Name, "GetViewById", id);
                var autoPreview = AutoPreviewMapping.Convert(obj);
                return(ApiResult.Success(autoPreview));
            }

            //Auto preview
            if (find is IAutoPreview set)
            {
                var autoPreview = set.GetPreview(id, AutoModel);
                return(ApiResult.Success(autoPreview));
            }

            return(ApiResult.Success(AutoPreviewMapping.Convert(find.GetType().FullName)));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Add([FromForm] ApiAppData data)
        {
            string fileName = "";

            if (data.file != null)
            {
                var fileExName = data.file.FileName.Substring(data.file.FileName.LastIndexOf("."));
                fileName = Guid.NewGuid().ToString("N") + fileExName;
                var saveFile = Path.Combine(Ptilopsis.Config.Get().AppZipPath, fileName);
                using (FileStream fs = System.IO.File.Create(saveFile))
                {
                    await data.file.CopyToAsync(fs);

                    fs.Flush();
                }
            }

            //储存对象
            PtiApp app = new PtiApp()
            {
                Name          = data.name,
                ZipFile       = fileName,
                DefaultRunCmd = data.runCmd,
                Description   = data.description,
                CreateDate    = DateTime.Now
            };

            app.Id = MD5Helper.getMd5Hash(app.Name);

            if (AppManager.Get().AddApp(app))
            {
                return(ApiResult.OK());
            }
            else
            {
                return(ApiResult.Failure("程序添加失败"));
            }
        }
Exemplo n.º 3
0
        public ApiResult SaveOrderAddress([FromBody] AddressInput parameter)
        {
            if (parameter == null)
            {
                return(ApiResult.Failure("所在地区不能为空"));
            }

            var regex = RegexHelper.ChinaMobile.IsMatch(parameter.Mobile);

            if (!regex)
            {
                return(ApiResult.Failure("联系电话格式不正确"));
            }

            if (parameter.Mobile.IsNullOrEmpty())
            {
                return(ApiResult.Failure("联系电话不能为空"));
            }

            if (parameter.Address.IsNullOrEmpty())
            {
                return(ApiResult.Failure("详细地址不能为空"));
            }

            if (parameter.Name.IsNullOrEmpty())
            {
                return(ApiResult.Failure("收货人姓名不能为空"));
            }

            if (!this.IsFormValid())
            {
                return(ApiResult.Failure(this.FormInvalidReason(), MessageCodes.ParameterValidationFailure));
            }

            var serviceResult = Resolve <IUserAddressService>().SaveOrderAddress(parameter);

            return(ToResult(serviceResult));
        }
Exemplo n.º 4
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            // api接口可以匿名访问,不需要任何安全措施
            if (context.Filters.OfType <IAllowAnonymousFilter>().Any())
            {
                return;
            }
            //基础api接口权限检查
            var token = GetAccessToken();

            if (token.Status != ResultStatus.Success)
            {
                context.Result = new JsonResult(ApiResult.Failure(token.Message, token.MessageCode));
            }
            // 用户权限检查,比如管理员、会员、供应商等权限的检查
            token = UserAccessToken(context);
            if (token.Status != ResultStatus.Success)
            {
                context.Result = new JsonResult(ApiResult.Failure(token.Message, token.MessageCode));
            }

            base.OnActionExecuting(context);
        }
Exemplo n.º 5
0
        public ApiResult <List <KeyValue> > Preview([FromQuery] PreviewInput parameter)
        {
            if (!this.IsFormValid())
            {
                return(ApiResult.Failure <List <KeyValue> >(this.FormInvalidReason(),
                                                            MessageCodes.ParameterValidationFailure));
            }

            var view = Resolve <IRewardService>().GetRewardView(parameter.Id.ConvertToLong());

            if (view == null)
            {
                return(ApiResult.Failure <List <KeyValue> >("该分润记录不存在!"));
            }
            //var result = view.Reward.ToKeyValues();
            var result = AutoMapping.SetValue <RewardPriviewOutput>(view.Reward);

            result.MoneyTypeName = view.MoneyTypeName;
            //result.StatusName = view.Status.GetDisplayName();
            result.OrderUserName = view.OrderUser.UserName;

            return(ApiResult.Success(result.ToKeyValues()));
        }
Exemplo n.º 6
0
        public ApiResult FindPayPassword([FromBody] FindPasswordInput parameter)
        {
            if (!this.IsFormValid())
            {
                return(ApiResult.Failure(this.FormInvalidReason(), MessageCodes.ParameterValidationFailure));
            }

            parameter.UserName = parameter.Mobile;
            if (!Resolve <IOpenService>().CheckVerifiyCode(parameter.Mobile, parameter.MobileVerifiyCode.ConvertToLong())
                )
            {
                return(ApiResult.Failure("手机验证码错误", MessageCodes.ParameterValidationFailure));
            }

            var result = Resolve <IUserDetailService>().FindPayPassword(parameter);

            if (!result.Succeeded)
            {
                return(ApiResult.Failure(result.ToString(), MessageCodes.ParameterValidationFailure));
            }

            return(ApiResult.Success("支付密码修改成功"));
        }
Exemplo n.º 7
0
        private static async Task <ApiResult> InvokeAsync(this HttpClient @this, HttpRequestMessage request,
                                                          Func <HttpClient, HttpRequestMessage, CancellationToken, Task <HttpResponseMessage> > invocation, CancellationToken cancellationToken)
        {
            @this.ThrowIfNull(typeof(HttpClient).Name.ToLower());
            request.ThrowIfNull(nameof(request));
            invocation.ThrowIfNull(nameof(invocation));
            cancellationToken.ThrowIfNull(nameof(cancellationToken));

            ApiResult apiResult;

            try
            {
                var response = await invocation(@this, request, cancellationToken);

                apiResult = await response.ToApiResult(request);
            }
            catch (Exception e)
            {
                apiResult = ApiResult.Failure(request, e);
            }

            return(apiResult);
        }
Exemplo n.º 8
0
        public ApiResult ToExcel([FromQuery] string type)
        {
            AutoModel.Query = Query;
            var dataResult = Resolve <IAutoTableService>().Table(type, QueryDictionary().ToJsons(), AutoModel);

            if (!dataResult.Item1.Succeeded)
            {
                return(ApiResult.Failure(dataResult.Item1.ErrorMessages.ToString()));
            }

            var modelType = type.GetTypeByName();

            if (type.IsNullOrEmpty() || type == "undefined")
            {
                return(ApiResult.Failure(new { File = "" }, "失败: 类型不能为空"));
            }

            var autoTable = dataResult.Item2;

            try {
                var result = Resolve <IAdminTableService>().ToExcel(modelType, autoTable.Result);

                var index = result.Item2.LastIndexOf(@"\wwwroot\");
                if (index < 0)
                {
                    return(ApiResult.Failure(new { File = "" }, "失败: 文件生成失败"));
                }

                var fileBytes = System.IO.File.ReadAllBytes(result.Item2);
                var file      = File(fileBytes, "application/x-msdownload", result.Item3);

                var path = $"{result.Item2.Substring(index)}".Replace(@"\", "/");
                return(ApiResult.Success(path));
            } catch (Exception ex) {
                return(ApiResult.Failure(new { File = "" }, ex.Message));
            }
        }
Exemplo n.º 9
0
        public ApiResult GetStoreOrdersToExcel(StoreOrdersToExcel model)
        {
            var webSite = Resolve <IAutoConfigService>().GetValue <WebSiteConfig>();
            var store   = Resolve <IStoreService>().GetSingle(u => u.UserId == model.UserId);

            if (store == null)
            {
                return(ApiResult.Failure("非法操作"));
            }

            var query = new ExpressionQuery <Order>
            {
                PageIndex = 1,
                PageSize  = 15
            };

            //  query.And(u => u.StoreId == store.Id);
            query.And(u => u.OrderStatus == model.Status);
            var view   = Resolve <IOrderService>().GetPagedList(query);
            var orders = new List <Order>();

            foreach (var item in view)
            {
                TimeSpan ts = DateTime.Now.Subtract(item.CreateTime);
                if (ts.Days < model.Days)
                {
                    orders.Add(item);
                }
            }

            view.Result = orders;
            var modelType = "Order".GetTypeByName();
            var result    = Resolve <IAdminTableService>().ToExcel(modelType, view);
            var url       = webSite.ApiImagesUrl + "/wwwroot/excel/" + result.Item3;

            return(ApiResult.Success(url));
        }
Exemplo n.º 10
0
        public ApiResult <List <KeyValue> > QueryField(string type)
        {
            var find = type.GetAllPropertys();

            if (find == null)
            {
                return(ApiResult.Failure <List <KeyValue> >("类型不存在"));
            }

            var list = new List <KeyValue>();

            foreach (var item in find)
            {
                if (item.Property.PropertyType == typeof(decimal) ||
                    item.Property.PropertyType == typeof(Enum) ||
                    item.Property.PropertyType.BaseType == typeof(Enum) ||
                    item.Property.PropertyType == typeof(int) ||
                    item.Property.PropertyType == typeof(long) ||
                    item.Property.PropertyType == typeof(short))
                {
                    if (item.Property.Name == "Id")
                    {
                        continue;
                    }

                    var key = new KeyValue {
                        Name  = $"{item.DisplayAttribute.Name}({item.Property.Name})",
                        Value = item.Property.Name,
                        Key   = item.Property.Name
                    };

                    list.Add(key);
                }
            }

            return(ApiResult.Success(list));
        }
Exemplo n.º 11
0
        public IHttpActionResult LogOn([FromBody] LoginRequest request)
        {
            var result = _service.LogOn(request);

            if (result.Success)
            {
                var account = ((OpResult <Account>)result).Result;

                string token;

                if (string.IsNullOrWhiteSpace(account.EmailVerificationCode))
                {
                    token = CreateFullyAuthorizedToken(request.UserName);
                }
                else
                {
                    token = CreateEmailVerificationRequiredToken(request.UserName);
                }

                return(Json(ApiResult.Success(new { jwt = token })));
            }

            return(Json(ApiResult.Failure(result.Errors)));
        }
Exemplo n.º 12
0
        public ApiResult <List <KeyValue> > All(string type)
        {
            var find = type.GetAllPropertys();

            if (find == null)
            {
                return(ApiResult.Failure <List <KeyValue> >("类型不存在"));
            }

            var list = new List <KeyValue>();

            foreach (var item in find)
            {
                var key = new KeyValue {
                    Name  = $"{item.DisplayAttribute.Name}({item.Property.Name})",
                    Value = item.Property.Name,
                    Key   = item.Property.Name
                };

                list.Add(key);
            }

            return(ApiResult.Success(list));
        }
Exemplo n.º 13
0
        public ApiResult <Coupon> GetCouponView([FromQuery] string id = "")
        {
            var view = new Coupon();

            if (!this.IsFormValid())
            {
                return(ApiResult.Failure <Coupon>(this.FormInvalidReason(), MessageCodes.ParameterValidationFailure));
            }

            if (!string.IsNullOrEmpty(id) && !id.Equals("undefined"))
            {
                view = Resolve <ICouponService>().GetSingle(id.ToObjectId());
                if (view != null)
                {
                    if (view.StartPeriodOfValidity.ToString() != "0001/1/1 0:00:00" ||
                        view.EndPeriodOfValidity.ToString() != "0001/1/1 0:00:00")
                    {
                        view.AfterDays = -1;
                    }
                }
            }

            return(ApiResult.Success(view));
        }
Exemplo n.º 14
0
        public ApiResult <AutoPreview> Preview([FromQuery] PreviewInput parameter)
        {
            if (!this.IsFormValid())
            {
                return(ApiResult.Failure <AutoPreview>(this.FormInvalidReason(),
                                                       MessageCodes.ParameterValidationFailure));
            }

            var userOutPut = Resolve <IUserDetailService>().GetUserOutput(parameter.Id.ConvertToLong());

            if (userOutPut == null)
            {
                return(ApiResult.Failure <AutoPreview>("用户不存在或者已经删除!"));
            }

            //if (!(userOutPut.ParentId == parameter.LoginUserId || userOutPut.Id == parameter.LoginUserId)) {
            //    return ApiResult.Failure<List<KeyValue>>("对不起您无权查看!");
            //}
            //var result = userOutPut.ToKeyValues();

            return(ApiResult.Success(new AutoPreview {
                KeyValues = userOutPut.ToKeyValues()
            }));
        }
Exemplo n.º 15
0
        public async Task <ApiResult> VerifyApiKey(string username, string apikey)
        {
            ApiResult apiresult = new ApiResult();

            if (String.IsNullOrWhiteSpace(username))
            {
                return(apiresult.Failure("Invalid Username."));
            }
            if (apikey?.Length != HashUtils.APIKeyLength256)
            {
                return(apiresult.Failure("Invalid APIKey."));
            }
            if (this.UserContext == null)
            {
                return(apiresult.Failure("You do not have permission to perform this action."));
            }
            if (!this.UserContext.IsVerifiedLogin)
            {
                return(apiresult.Failure("Login Credentials Expired. Try Relogging In."));
            }

            DBLogin dbLogin;

            try {
                dbLogin = await DBLogin.SP_Account_Login_GetAsync(WebAppContext.Factory, username, apikey).ConfigureAwait(false);
            } catch (Exception ex) { return(apiresult.Failure(ex)); }

            if (dbLogin != null && HashUtils.VerifyHashMatch256(apikey, dbLogin.UserName, dbLogin.APIKeyHash))
            {
                apiresult.Success("Is Valid ApiKey");
            }
            else
            {
                apiresult.Failure("ApiKey is Invalid");
            }

            return(apiresult);
        }
Exemplo n.º 16
0
        public ApiResult <ProductDetailView> Show(long id, long userId = 0)
        {
            ObjectCache.Remove("ApiProduct_" + id);
            return(ObjectCache.GetOrSet(() =>
            {
                var result = Resolve <IProductService>().Show(id, userId);
                if (result.Item1.Succeeded)
                {
                    var productDetail = result.Item2.MapTo <ProductDetailView>();
                    var config = Resolve <IAutoConfigService>().GetValue <MemberDiscountConfig>();
                    if ((AutoModel?.BasicUser?.Id ?? 0) != 0)
                    {
                        userId = AutoModel.BasicUser.Id;
                    }

                    var loginUser = Resolve <IUserService>().GetSingle(userId);
                    var isAdmin = Resolve <IUserService>().IsAdmin(userId);
                    productDetail.IsFrontShowPrice = true;

                    productDetail.DisplayPrice = Resolve <IProductService>()
                                                 .GetDisplayPrice(productDetail.Price, productDetail.PriceStyleId, 0M);
                    if (productDetail?.ProductExtensions?.ProductSkus?.Count > 0)
                    {
                        productDetail.ProductExtensions.ProductSkus.Foreach(x =>
                                                                            x.DisplayPrice = Resolve <IProductService>()
                                                                                             .GetDisplayPrice(productDetail.Price, productDetail.PriceStyleId, 0M));
                    }
                    //bniuniu 不进行该判断
                    StringValues isTenant = string.Empty;

                    if (Request.Headers.TryGetValue("zk-tenant", out isTenant))
                    {
                        var tenant = Resolve <IUserService>().GetSingle(s => s.Mobile == isTenant.FirstOrDefault());
                        //如果有租户头 判断是否为空 ,如果不为空则表示有值
                        //if (isTenant.Where(s => !(string.IsNullOrEmpty(s) || s == "null"||s== "[object Null]")).Count() <= 0)
                        if (tenant == null)     //不是租户 则判断是否显示价格
                        {
                            if (loginUser == null)
                            {
                                productDetail.IsFrontShowPrice = false;
                                productDetail.PriceAlterText = config.PriceAlterText;
                            }
                            else if (!isAdmin && loginUser.GradeId ==
                                     Guid.Parse("72BE65E6-3000-414D-972E-1A3D4A366000"))
                            {
                                productDetail.IsFrontShowPrice = config.IsFrontShowPrice;
                                productDetail.PriceAlterText = config.PriceAlterText;
                            }
                        }
                    }
                    else
                    {
                        //如果没有该头部 直接判断
                        if (loginUser == null)
                        {
                            //未登录直接不允许查看
                            productDetail.IsFrontShowPrice = false;
                            productDetail.PriceAlterText = config.PriceAlterText;
                        }
                        else if (!isAdmin && loginUser.GradeId ==
                                 Guid.Parse("72BE65E6-3000-414D-972E-1A3D4A366000"))
                        {
                            //如果不是管理员 且 会员等级为免费会员
                            productDetail.IsFrontShowPrice = config.IsFrontShowPrice;
                            productDetail.PriceAlterText = config.PriceAlterText;
                        }
                    }

                    return ApiResult.Success(productDetail);
                }

                return ApiResult.Failure <ProductDetailView>(result.Item1.ToString());
            }, "ApiProduct_" + id).Value);
        }
Exemplo n.º 17
0
        public ApiResult SendRaw(string mobile, string message)
        {
            //验证手机
            if (!CheckMobile(mobile))
            {
                return(ApiResult.Failure());
            }
            //验证消息是否为空
            if (string.IsNullOrWhiteSpace(message))
            {
                throw new ArgumentNullException(nameof(message));
            }

            //先使用v2
            var res = Ioc.Resolve <ISmsService>().Sent(mobile, message);

            if (res.Code.ToUpper().Equal("SUCCESS"))
            {
                return(ApiResult.Success());
            }
            //记录错误
            Ioc.Resolve <ITableService>().Log($"V2=>{mobile},{message};res=>{res.ToJson()}", LogsLevel.Error);
            //如果发送不成功尝试使用V1版本
            // 循环发送五次,确保发送率更高

            ////令牌未获取
            //if (_serverAuthenticationManager.Token == null || _serverAuthenticationManager.Token.Token.IsNullOrEmpty()) {
            //    var msg = "短信发送失败,未授权" + mobile + message;
            //    Ioc.Resolve<ITableService>().Log(msg, LogsLevel.Warning);
            //    // 重新授权一次,反正授权失败
            //    Authentication();
            //    BaseService();
            //}

            ////令牌过期
            //if (_serverAuthenticationManager.Token.ExpiresTime < DateTime.Now) {
            //    var msg = "短信发送失败,授权已过期" + mobile + message;
            //    Ioc.Resolve<ITableService>().Log(msg, LogsLevel.Warning);
            //    //令牌过期 重新授权一次
            //    Authentication();
            //    BaseService();
            //}

            ////如果两次判断令牌还没 则直接返回
            //if (_serverAuthenticationManager.Token == null || _serverAuthenticationManager.Token.Token.IsNullOrEmpty())
            //    return ApiResult.Failure();
            //var count = 0;
            //while (count < 5) {
            //    count++;
            //    //发送
            //    var result = _messageApiClient.SendRaw(_serverAuthenticationManager.Token.Token, mobile, message,
            //        HttpWeb.Ip);
            //    if (result.Status != ResultStatus.Success) {
            //        var msg =
            //            $"授权服务端短信发送失败:发送次数{count},{result.Message},_serverAuthenticationManager.Token.:{_serverAuthenticationManager.Token},_serverAuthenticationManager.Token.Token:{_serverAuthenticationManager.Token.Token}";
            //        Ioc.Resolve<ITableService>().Log(msg, LogsLevel.Error);
            //    } else {
            //        return ApiResult.Success();
            //    }
            //}

            return(ApiResult.Failure());
        }
Exemplo n.º 18
0
        public ApiResult UpdatePassword([FromBody] ViewAdminEdit view)
        {
            var passwordInput = new PasswordInput {
                Password        = view.Password,
                ConfirmPassword = view.ConfirmPassword,
                UserId          = view.EditUserId
            };

            var editUser = Resolve <IUserService>().GetSingle(view.EditUserId);

            if (editUser == null)
            {
                return(ApiResult.Failure("要编辑的用户ID对应用户信息不存在"));
            }

            view.User = editUser;

            //修改登录密码
            if (view.Type == 1)
            {
                passwordInput.Type = PasswordType.LoginPassword;
                var reuslt = Resolve <IUserDetailService>().ChangePassword(passwordInput, false);
                if (reuslt.Succeeded)
                {
                    Resolve <IUserService>()
                    .Log($"管理员修改会员的登录密码,会员ID为{view.User.Id},会员名{view.User.UserName},姓名{view.User.Name}");
                    if (view.SendPassword)
                    {
                        //  _messageManager.AddRawQueue(view.User.Mobile,
                        //    $"管理员已成功修改了您的登录密码,新的登录密码为{view.Password},请尽快登录系统,并修改登录密码");
                    }
                }
                else
                {
                    return(ApiResult.Failure("服务异常:登录密码修改失败,请稍后在试"));
                }
            }

            if (view.Type == 2)
            {
                passwordInput.Type = PasswordType.PayPassword;
                var reuslt = Resolve <IUserDetailService>().ChangePassword(passwordInput, false);
                if (reuslt.Succeeded)
                {
                    Resolve <IUserService>().Log(
                        $"管理员修改会员的支付密码,会员ID为{view.User.Id},会员名{view.User.UserName},姓名{view.User.Name}"
                        );
                    if (view.SendPassword)
                    {
                        //  _messageManager.AddRawQueue(view.User.Mobile,
                        //   $"管理员已成功修改了您的支付密码,新的登录密码为{view.Password},请尽快登录系统,并修改支付密码");
                    }
                }
                else
                {
                    return(ApiResult.Failure("服务异常:支付密码修改失败,请稍后在试" + reuslt));
                }
            }

            return(ApiResult.Success("密码修改成功"));
        }
Exemplo n.º 19
0
        public ApiResult Save([FromBody] CategoryView view)
        {
            //如果id为空就判断是否存在
            if (view.Id != Guid.Empty)
            {
                //判断重复
                var confrim = Resolve <ICategoryService>()
                              .Count(s => s.Name == view.Name && s.PartentId != view.PartentId);
                if (confrim > 0)
                {
                    return(ApiResult.Failure("已存在同名类目!"));
                }
            }
            else
            {
                //判断重复
                var confrim = Resolve <ICategoryService>().Count(s => s.Name == view.Name);
                if (confrim > 0)
                {
                    return(ApiResult.Failure("已存在同名类目!"));
                }
            }

            //销售属性
            var saleDistinct = view.SalePropertys.GroupBy(p => new { p.Name }).Select(g => g.First()).ToList();

            if (saleDistinct.Count() < view.SalePropertys.Count)
            {
                return(ApiResult.Failure("已存在同名销售属性!"));
            }

            foreach (var item in view.SalePropertys)
            {
                ///销售属性值
                var saleItemDistinct = item.Values.GroupBy(p => new { p.ValueName }).Select(g => g.First()).ToList();
                if (saleItemDistinct.Count() < item.Values.Count)
                {
                    return(ApiResult.Failure("已存在同名销售属性值!"));
                }
            }

            //商品参数
            var displayDistinct = view.DisplayPropertys.GroupBy(p => new { p.Name }).Select(g => g.First()).ToList();

            if (displayDistinct.Count() < view.DisplayPropertys.Count)
            {
                return(ApiResult.Failure("已存在同名商品参数!"));
            }

            foreach (var item in view.DisplayPropertys)
            {
                ///销售属性值
                var saleItemDistinct = item.Values.GroupBy(p => new { p.ValueName }).Select(g => g.First()).ToList();
                if (saleItemDistinct.Count() < item.Values.Count)
                {
                    return(ApiResult.Failure("已存在同名商品参数值!"));
                }
            }

            var valAdd      = new List <CategoryPropertyValue>();
            var valDel      = new List <CategoryPropertyValue>();
            var valUpd      = new List <CategoryPropertyValue>();
            var propertyDel = new List <CategoryProperty>();
            var catetory    = new Category();

            // CreateNew
            if (view.Id == Guid.Empty)
            {
                catetory = new Category
                {
                    Name      = view.Name,
                    PartentId = view.PartentId,
                    SortOrder = view.SortOrder
                };
                Resolve <ICategoryService>().Add(catetory);
            }
            else
            {
                catetory           = Resolve <ICategoryService>().GetSingle(view.Id);
                catetory.Name      = view.Name;
                catetory.PartentId = view.PartentId;
                catetory.SortOrder = view.SortOrder;
                Resolve <ICategoryService>().Update(catetory);
            }

            // CreateNew
            if (view.Id == Guid.Empty)
            {
                var property = new CategoryProperty();

                foreach (var saleProp in view.SalePropertys)
                {
                    property = ProcessProp(catetory, saleProp);

                    foreach (var vi in saleProp.Values)
                    {
                        ValueProcess(property, vi, valAdd);
                    }
                }

                foreach (var dispProp in view.DisplayPropertys)
                {
                    property = ProcessDispProp(catetory, dispProp);

                    foreach (var vi in dispProp.Values)
                    {
                        ValueProcess(property, vi, valAdd);
                    }
                }
            }
            else // Update Exist
            {
                // var catetory = Resolve<ICategoryService>().GetSingle(view.Id);
                catetory.Name      = view.Name;
                catetory.PartentId = view.PartentId;
                catetory.SortOrder = view.SortOrder;
                Resolve <ICategoryService>().Update(catetory);


                var propertyIdList = catetory.SalePropertys?.Select(x => x.Id.ToString());
                //需要删除的销售属性
                var delSalePropertyIdList = propertyIdList.Except(view.SalePropertys.Select(x => x.Id.ToString()));
                var delSalePropertyList   =
                    Resolve <ICategoryPropertyService>().GetList(string.Join(',', delSalePropertyIdList));
                propertyDel.AddRange(delSalePropertyList);
                //需要删除的商品参数
                var delDisplayPropertyIdList = catetory.DisplayPropertys?.Select(s => s.Id.ToString())
                                               .Except(view.DisplayPropertys.Select(x => x.Id.ToString()));
                var delDisplayPropertyList = Resolve <ICategoryPropertyService>()
                                             .GetList(string.Join(',', delDisplayPropertyIdList));
                propertyDel.AddRange(delDisplayPropertyList);


                var property = new CategoryProperty();

                foreach (var saleProp in view.SalePropertys)
                {
                    var loadIdList = Resolve <ICategoryPropertyValueService>().GetList(x => x.PropertyId == saleProp.Id)
                                     .Select(x => x.Id.ToString());
                    var delIdList = loadIdList.Except(saleProp.Values.Select(x => x.Id.ToString()));
                    var delList   = Resolve <ICategoryPropertyValueService>().GetList(string.Join(',', delIdList));
                    valDel.AddRange(delList);

                    property = ProcessProp(catetory, saleProp);

                    foreach (var vi in saleProp.Values)
                    {
                        ValueProcess(property, vi, valAdd, valUpd, delIdList);
                    }
                }

                foreach (var dispProp in view.DisplayPropertys)
                {
                    var loadIdList = Resolve <ICategoryPropertyValueService>().GetList(x => x.PropertyId == dispProp.Id)
                                     .Select(x => x.Id.ToString());
                    var delIdList = loadIdList.Except(dispProp.Values.Select(x => x.Id.ToString()));
                    var delList   = Resolve <ICategoryPropertyValueService>().GetList(string.Join(',', delIdList));
                    valDel.AddRange(delList);

                    property = ProcessDispProp(catetory, dispProp);

                    foreach (var vi in dispProp.Values)
                    {
                        ValueProcess(property, vi, valAdd, valUpd, delIdList);
                    }
                }
            }

            //先删除属性值
            Resolve <ICategoryPropertyValueService>().DeleteMany(valDel.Select(x => x.Id));
            //再删除属性
            Resolve <ICategoryPropertyService>().DeleteMany(propertyDel.Select(x => x.Id));
            // Resolve<ICategoryPropertyValueService>().DeleteMany(valDel.Select(x => x.Id));
            foreach (var item in valUpd)
            {
                Resolve <ICategoryPropertyValueService>().Update(item);
            }

            Resolve <ICategoryPropertyValueService>().AddMany(valAdd);

            return(ApiResult.Success("保存成功!"));
        }
Exemplo n.º 20
0
        public ApiResult <List <KeyValue> > GetKeyValue([FromQuery] string type)
        {
            if (type.IsNullOrEmpty() || type == "undefined")
            {
                return(ApiResult.Failure <List <KeyValue> >("类型不能为空"));
            }

            if (type == "IAutoTable")
            {
                return(ApiResult.Success(Resolve <IAutoUIService>().AutoTableKeyValues()));
            }

            if (type == "IAutoForm")
            {
                return(ApiResult.Success(Resolve <IAutoUIService>().AutoFormKeyValues()));
            }

            if (type == "IAutoList")
            {
                return(ApiResult.Success(Resolve <IAutoUIService>().AutoListKeyValues()));
            }

            if (type == "IAutoPreview")
            {
                return(ApiResult.Success(Resolve <IAutoUIService>().AutoPreviewKeyValues()));
            }

            if (type == "IAutoNews")
            {
                return(ApiResult.Success(Resolve <IAutoUIService>().AutoNewsKeyValues()));
            }

            if (type == "IAutoArticle")
            {
                return(ApiResult.Success(Resolve <IAutoUIService>().AutoArticleKeyValues()));
            }

            if (type == "IAutoReport")
            {
                return(ApiResult.Success(Resolve <IAutoUIService>().AutoReportKeyValues()));
            }

            if (type == "IAutoFaq")
            {
                return(ApiResult.Success(Resolve <IAutoUIService>().AutoFaqsKeyValues()));
            }

            if (type == "IAutoImage")
            {
                return(ApiResult.Success(Resolve <IAutoUIService>().AutoImagesKeyValues()));
            }

            if (type == "IAutoIndex")
            {
                return(ApiResult.Success(Resolve <IAutoUIService>().AutoIndexKeyValues()));
            }

            if (type == "IAutoIntro")
            {
                return(ApiResult.Success(Resolve <IAutoUIService>().AutoIntroKeyValues()));
            }

            if (type == "IAutoTask")
            {
                return(ApiResult.Success(Resolve <IAutoUIService>().AutoTaskKeyValues()));
            }

            if (type == "IAutoVideo")
            {
                return(ApiResult.Success(Resolve <IAutoUIService>().AutoVideoKeyValues()));
            }

            if (type == "CatalogEntity")
            {
                return(ApiResult.Success(Resolve <ITableService>().CatalogEntityKeyValues()));
            }

            if (type == "SqlServcieCatalogEntity")
            {
                return(ApiResult.Success(Resolve <ITableService>().SqlServcieCatalogEntityKeyValues()));
            }

            if (type == "MongodbCatalogEntity")
            {
                return(ApiResult.Success(Resolve <ITableService>().MongodbCatalogEntityKeyValues()));
            }

            var find = type.GetTypeByName();

            if (find == null)
            {
                return(ApiResult.Failure <List <KeyValue> >($"类型不存在,请确认{type}输入是否正确"));
            }

            var intances = type.GetInstanceByName();

            if (intances is IRelation)
            {
                var result = ServiceInterpreter.Eval <IEnumerable <KeyValue> >("IRelationService", "GetKeyValues2", type);
                return(ApiResult.Success(result.ToList()));
            }

            //enum
            if (find.IsEnum)
            {
                var keyValues = KeyValueExtesions.EnumToKeyValues(type);
                if (keyValues == null)
                {
                    return(ApiResult.Failure <List <KeyValue> >("枚举不存在"));
                }

                return(ApiResult.Success(keyValues.ToList()));
            }

            // auto config
            if (intances is IAutoConfig)
            {
                var configValue = Resolve <ITypeService>().GetAutoConfigDictionary(type);
                if (configValue == null)
                {
                    return(ApiResult.Failure <List <KeyValue> >($"{type}不存在"));
                }
                var keyValues = new List <KeyValue>();
                foreach (var item in configValue)
                {
                    keyValues.Add(new KeyValue {
                        Key = item.Key, Value = item.Value
                    });
                }
                return(ApiResult.Success(keyValues));
            }
            return(null);
        }
Exemplo n.º 21
0
 protected ApiResult <T> ApiResultFromModelErrors <T>()
 {
     return(ApiResult <T> .Failure(GetModelErrors()));
 }
Exemplo n.º 22
0
        public async Task <ApiResult> Process([FromBody] Refund parameter)
        {
            var order = Resolve <IOrderService>().GetSingle(parameter.OrderId);
            var pay   = Resolve <IPayService>().GetSingle(s => s.Id == order.PayId);

            pay.PayExtension = pay.Extensions.ToObject <PayExtension>();
            //先把微信金额原路退回

            var entity = Resolve <IRefundService>().GetByIdNoTracking(order.OrderExtension?.RefundInfo?.Id);

            if (entity == null)
            {
                return(await Task.FromResult(ApiResult.Failure("退款状态以异常!")));
            }

            if (pay.Amount < parameter.Amount) //退款金额不能大于支付金额
            {
                return(await Task.FromResult(ApiResult.Failure("退款金额不能大于订单金额!")));
            }
            //退款金额等于 手动退款的金额
            entity.Amount = parameter.Amount;
            //再更新订单状态和退货状态
            var refundFree = Resolve <IPayService>().Refund(ref pay, Convert.ToInt32(parameter.Amount * 100),
                                                            order.OrderExtension?.RefundInfo?.Id.ToString());

            //请求结果
            if (!refundFree.Item1.Succeeded)
            {
                return(ApiResult.Failure(
                           $"退款失败!refundFree.Item1:ErrorMessages=>{refundFree.Item1.ErrorMessages.Join()}/ReturnMessage=>{refundFree.Item1.ReturnMessage},refundFree.Item2:{refundFree.Item2}"));
            }
            //未发货
            if (order.OrderStatus == OrderStatus.AfterSale)
            {
                if (order.OrderExtension.RefundInfo.Process == RefundStatus.WaitSaleAllow)
                {
                    entity.Process = RefundStatus.Sucess;
                }
                else
                {
                    return(await Task.FromResult(ApiResult.Failure("售后状态已被更改,操作失败!")));
                }
            }
            else if (order.OrderStatus == OrderStatus.Refund)
            {
                //退款可以在 同意之后或者 直接退款,退款后直接完成
                if (order.OrderExtension.RefundInfo.Process == RefundStatus.BuyerApplyRefund)
                {
                    entity.Process = RefundStatus.Sucess;
                }
                else
                {
                    return(await Task.FromResult(ApiResult.Failure("售后状态已被更改,操作失败!")));
                }
            }
            else
            {
                return(await Task.FromResult(ApiResult.Failure("订单状态已更改,操作失败!")));
            }

            //退款完成后将更改订单状态
            order.OrderStatus = OrderStatus.Refunded;

            entity.ProcessMessage = parameter.ProcessMessage;

            var res = Resolve <IRefundService>().Update(entity);

            order.OrderExtension.RefundInfo = entity;
            order.Extension = order.OrderExtension.ToJsons();
            var update = Resolve <IOrderService>().Update(order);
            var result = res && update?ApiResult.Success() : ApiResult.Failure("退款失败!");

            return(await Task.FromResult(result));
        }
Exemplo n.º 23
0
        public ApiResult DetailEdit([FromBody] AccountViewIn view)
        {
            var chargeUser = Resolve <IUserService>().GetSingle(view.ChargeUserId);

            if (chargeUser == null)
            {
                return(ApiResult.Failure("对应编辑的用户ID不存在"));
            }

            view.User        = chargeUser;
            view.AccountList = Resolve <IAccountService>().GetUserAllAccount(chargeUser.Id);
            //view.UserId = chargeUser.Id;

            if (!this.IsFormValid())
            {
                return(ApiResult.Failure(string.Empty, this.FormInvalidReason()));
            }

            var loginUser = Resolve <IUserService>().GetUserDetail(view.UserId);

            if (loginUser.Status != Status.Normal)
            {
                return(ApiResult.Failure(string.Empty, "操作失败:您的账户不正常,不能进行资产操作"));
            }

            //var safePassword = HttpContext.Request.Form["SafePassWord"].ToString();
            if (view.AdminPayPassword.IsNullOrEmpty())
            {
                return(ApiResult.Failure(string.Empty, "操作失败:支付密码不能为空"));
            }

            if (loginUser.Detail.PayPassword != view.AdminPayPassword.ToMd5HashString())
            {
                return(ApiResult.Failure(string.Empty, "操作失败:支付密码不正确"));
            }

            var moneyType = Resolve <IAutoConfigService>().MoneyTypes().FirstOrDefault(r => r.Id == view.MoneyTypeId);

            if (moneyType == null)
            {
                return(ApiResult.Failure("操作失败:对应的货币类型不支持!"));
            }

            var result = ServiceResult.Success;

            if (view.ActionType == (int)FinanceActionType.Add)
            {
                if (view.Amount > 1000000)
                {
                    return(ApiResult.Failure("Amount", "资产增加单次金额不能超过100W"));
                }

                result = Resolve <IBillService>()
                         .Increase(chargeUser, moneyType, view.Amount, "管理员后台手动增加资产" + view.Remark);
            }

            if (view.ActionType == (int)FinanceActionType.Reduce)
            {
                result = Resolve <IBillService>().Reduce(chargeUser, moneyType, view.Amount, "管理员后台减少" + view.Remark);
            }

            if (view.ActionType == (int)FinanceActionType.Freeze)
            {
                result = Resolve <IBillService>().Treeze(chargeUser, moneyType, view.Amount, "管理员后台冻结" + view.Remark);
            }

            if (view.ActionType == (int)FinanceActionType.Unfreeze)
            {
                result = Resolve <IBillService>()
                         .DeductTreeze(chargeUser, moneyType, view.Amount, "管理员后台解结" + view.Remark);
            }

            if (!result.Succeeded)
            {
                return(ApiResult.Failure(string.Empty, result.ToString()));
            }

            Resolve <IAccountService>().Log(
                $@"管理员{AutoModel.BasicUser.UserName}{GetAcctionName(view.ActionType)}会员{chargeUser.UserName}的资产,账户为:{moneyType.Name},金额为:{view.Amount}"
                );
            //通知会员后台手动添加资产
            var userAccount = Resolve <IAccountService>().GetAccount(chargeUser.Id, moneyType.Id);
            IDictionary <string, string> parameter = new Dictionary <string, string>
            {
                { "accountName", moneyType.Name },
                { "account", view.Amount.ToString() },
                { "userName", chargeUser.UserName },
                { "balance", userAccount.Amount.ToString() },
                { "acctionname", GetAcctionName(view.ActionType) }
            };

            //   _messageManager.AddTemplateQueue(2001, chargeUser.Mobile, parameter);
            // _messageManager.AddTemplateQueue(2002, _messageManager.OpenMobile, parameter);

            return(ApiResult.Success($"{GetAcctionName(view.ActionType)}资产成功"));
        }
Exemplo n.º 24
0
        public ApiResult SendSms([FromBody] SmsInput input)
        {
            try
            {
                if (string.IsNullOrEmpty(input.Message))
                {
                    return(ApiResult.Failure("请输入message内容"));
                }
                if (input.Type == Sms.Enums.SmsType.Phone && string.IsNullOrEmpty(input.Phone))
                {
                    return(ApiResult.Failure("type为指定手机号码时,phone 不能为空"));
                }
                IList <SmsSend> phones = new List <SmsSend>();
                if (input.Type == Sms.Enums.SmsType.All)
                {
                    var users = Resolve <IUserService>().GetList();
                    if (Resolve <ApiStore.Sms.Services.ISmsSendService>().GetAll(SendState.Root).Count() <= 0)
                    {
                        var sendList = users.Select(s => new SmsSend
                        {
                            State      = SendState.Root,
                            Phone      = s.Mobile,
                            UserId     = s.Id,
                            UserName   = s.UserName,
                            CreateTime = DateTime.Now
                        }).ToList();
                        Resolve <ApiStore.Sms.Services.ISmsSendService>().Add(sendList);
                        phones = Resolve <ApiStore.Sms.Services.ISmsSendService>().GetAll(input.State);
                    }
                    else
                    {
                        phones = Resolve <ApiStore.Sms.Services.ISmsSendService>().GetAll(input.State);
                    }

                    //phones = users.Select(s => new SmsSend
                    //{
                    //    State = SendState.Root,
                    //    Phone = s.Mobile,
                    //    UserId=s.Id
                    //}).ToList();
                    //phones = input.Phone.Split(",").Select(s => new SmsSend
                    //{
                    //    State = SendState.Root,
                    //    Phone = s,
                    //}).ToList();
                }
                else
                {
                    phones = input.Phone.Split(",").Select(s => new SmsSend
                    {
                        State = SendState.Root,
                        Phone = s,
                    }).ToList();
                }
                for (int i = 1249; i < phones.Count; i++)
                {
                    if (!string.IsNullOrEmpty(input.Message))
                    {
                        //Task.Factory.StartNew(() =>
                        //{
                        var result = Resolve <ISmsService>().SendRaw(phones[i].Phone, input.Message);
                        if (result.Status == ResultStatus.Success)
                        {
                            phones[i].State = SendState.Success;
                            Resolve <ApiStore.Sms.Services.ISmsSendService>().Update(phones[i]);
                        }
                        else
                        {
                            phones[i].State = SendState.Fail;
                            Resolve <ApiStore.Sms.Services.ISmsSendService>().Update(phones[i]);
                        }
                        //});
                    }
                    //if (i % 50 == 0)
                    //{
                    Thread.Sleep(500);
                    //}
                    // i++;
                }
                return(ApiResult.Success("执行完毕"));
            }
            catch (Exception ex)
            {
                return(ApiResult.Failure(ex.Message));
            }
        }
Exemplo n.º 25
0
        public ApiResult Pay([FromBody] OrderEditPay orderEditPay)
        {
            var user = Resolve <IUserService>().GetUserDetail(orderEditPay.UserId);

            if (user == null)
            {
                return(ApiResult.Failure("用户已经不存在"));
            }

            if (user.Detail.PayPassword != orderEditPay.PayPassword.ToMd5HashString())
            {
                return(ApiResult.Failure("支付密码不正确"));
            }

            var order = Resolve <IOrderService>().GetSingle(r => r.Id == orderEditPay.OrderId);

            if (order == null)
            {
                return(ApiResult.Failure("订单不存在"));
            }

            if (order.OrderStatus != OrderStatus.WaitingBuyerPay)
            {
                return(ApiResult.Failure("订单已付款或关闭,请刷新"));
            }

            IList <Order> orderList = new List <Order>
            {
                order
            };

            var reduceMoneys = new List <OrderMoneyItem>();

            order.OrderExtension.ReduceAmounts.Foreach(r =>
            {
                reduceMoneys.Add(new OrderMoneyItem
                {
                    MoneyId     = r.MoneyTypeId,
                    MaxPayPrice = r.ForCashAmount
                });
            });
            var singlePayInput = new SinglePayInput
            {
                Orders       = orderList,
                User         = user,
                ReduceMoneys = reduceMoneys,
                IsAdminPay   = true
            };
            var payResult = Resolve <IOrderAdminService>().AddSinglePay(singlePayInput);

            if (!payResult.Item1.Succeeded)
            {
                return(ApiResult.Failure(payResult.Item1.ToString()));
            }

            var payInput = AutoMapping.SetValue <PayInput>(payResult.Item2);

            payInput.LoginUserId = user.Id;
            payInput.PayId       = payResult.Item2.Id;

            var result = Resolve <IPayService>().Pay(payInput);

            if (!result.Item1.Succeeded)
            {
                return(ApiResult.Failure(result.ToString()));
            }

            return(ApiResult.Success("支付成功!"));
        }
Exemplo n.º 26
0
 public static ApiResult <T> ToApiResult <T>(this ValidationException @this)
 {
     return(ApiResult.Failure <T>(@this));
 }
Exemplo n.º 27
0
 public ApiResult BatchDelete([FromBody] string ids)
 {
     return(ApiResult.Failure("改类型不支持api 接口删除"));
 }
Exemplo n.º 28
0
        public ApiResult <EventInfo> EventUpdate(long EventID, EventInput input)
        {
            //TODO: Verify Event belongs to user if updating. Right now anyone can update any event.
            var apiresult = new ApiResult <EventInfo>();

            if (UserContext == null)
            {
                return(apiresult.Failure("Must be logged in."));
            }
            if (!UserContext.IsVerifiedLogin)
            {
                return(apiresult.Failure("Insufficient account permissions."));
            }

            if (EventID <= 0)
            {
                return(apiresult.Failure("Invalid ID"));
            }
            DBEventFeedItemExtended existing = null;

            try {
                existing = Factory.EventManager.EventGetByID(EventID);
                if (existing == null)
                {
                    return(apiresult.Failure("Event Does not exist."));
                }
            } catch (Exception ex) { return(apiresult.Failure(ex)); }


            if (input == null)
            {
                return(apiresult.Failure("Input is null."));
            }
            if (input.Title != null && existing.Title != input.Title)
            {
                existing.Title = input.Title;
            }
            if (input.Caption != null && existing.Caption != input.Caption)
            {
                existing.Caption = input.Caption;
            }
            if (input.Description != null && existing.Details != input.Description)
            {
                existing.Details = input.Description;
            }
            if (input.EventTypeID > 0 && existing.EventTypeID != input.EventTypeID)
            {
                existing.EventTypeID = input.EventTypeID;
            }
            if (input.DateStart != default && existing.DateStart != input.DateStart)
            {
                existing.DateStart = input.DateStart;
            }
            if (input.DateEnd != default && existing.DateEnd != input.DateEnd)
            {
                existing.DateEnd = input.DateEnd;
            }

            //TODO sanitize Title, Caption, and Description to be free of javascript
            if (existing.Title.CountAlphaNumeric() <= 5)
            {
                return(apiresult.Failure("Title to short."));
            }
            if (existing.Caption.CountAlphaNumeric() <= 8)
            {
                return(apiresult.Failure("Caption to short."));
            }
            if (existing.DateStart.ToUniversalTime() < DateTime.UtcNow)
            {
                apiresult.Failure("DateStart in the past.");
                if (UserContext.IsAdmin)
                {
                    apiresult.AppendMessage("(AdminOverride)");
                }
                else
                {
                    return(apiresult);
                }
            }
            if (existing.DateEnd.ToUniversalTime() < input.DateStart.ToUniversalTime())
            {
                return(apiresult.Failure("DateEnd is before DateStart"));
            }
            if (existing.DateStart.AddDays(14).ToUniversalTime() < input.DateEnd.ToUniversalTime())
            {
                return(apiresult.Failure("Events cannot last longer than 2 weeks."));
            }


            DBEventType eventType = Factory.EventTypeManager[existing.EventTypeID];

            if (eventType == null)
            {
                return(apiresult.Failure("EventType does not exist."));
            }


            List <DBTag> newTags     = null;
            List <DBTag> removedTags = null;

            DBTag[] eventTags = null;

            if (input.Tags != null && input.Tags.Length > 0)
            {
                DBTag[] previousTags = existing.TagIds.Select(x => Factory.TagManager[x]).ToArray();
                existing.TagIds = new long[input.Tags.Length];
                eventTags       = new DBTag[input.Tags.Length];
                newTags         = new List <DBTag>();
                removedTags     = new List <DBTag>();

                for (int i = 0; i < input.Tags.Length; i++)
                {
                    DBTag tag = eventTags[i] = Factory.TagManager[input.Tags[i]];
                    if (tag == null)
                    {
                        return(apiresult.Failure("Invalid Tag: " + input.Tags[i].ToString()));
                    }
                    existing.TagIds[i] = tag.TagID;
                    if (Array.IndexOf(previousTags, tag) == -1)
                    {
                        newTags.Add(tag);
                    }
                }
                for (int i = 0; i < previousTags.Length; i++)
                {
                    DBTag tag = previousTags[i];
                    if (Array.IndexOf(eventTags, tag) == -1)
                    {
                        removedTags.Add(tag);
                    }
                }
            }
            else
            {
                eventTags = new DBTag[existing.TagIds.Length];
                for (int i = 0; i < existing.TagIds.Length; i++)
                {
                    DBTag tag = Factory.TagManager[existing.TagIds[i]];
                    if (tag == null)
                    {
                        return(apiresult.Failure("Invalid Tag: " + input.Tags[i].ToString()));
                    }
                    eventTags[i] = tag;
                }
            }



            bool bLocChange = false;

            if (input.Location != null)
            {
                var loc = input.Location;
                if (loc.Name != null && existing.LocationName != loc.Name)
                {
                    existing.LocationName = loc.Name; bLocChange = true;
                }
                if (loc.AddressLine != null && existing.AddressLine != loc.AddressLine)
                {
                    existing.AddressLine = loc.AddressLine; bLocChange = true;
                }
                if (loc.Locality != null && existing.Locality != loc.Name)
                {
                    existing.Locality = loc.Locality; bLocChange = true;
                }
                if (loc.PostalCode != null && existing.PostalCode != loc.PostalCode)
                {
                    existing.PostalCode = loc.PostalCode; bLocChange = true;
                }
                if (loc.AdminDistrict != null && existing.AdminDistrict != loc.Name)
                {
                    existing.AdminDistrict = loc.AdminDistrict; bLocChange = true;
                }
                if (loc.CountryRegion != null && existing.CountryRegion != loc.CountryRegion)
                {
                    existing.CountryRegion = loc.CountryRegion; bLocChange = true;
                }

                if (bLocChange)
                {
                    LocationNode.CountryRegionNode oCountry = Factory.LocationManager.QueryCachedCountries(existing.CountryRegion).FirstOrDefault();
                    if (oCountry == null)
                    {
                        return(apiresult.Failure("Invalid Country"));
                    }

                    LocationNode.AdminDistrictNode oState = Factory.LocationManager.QueryCachedStates(existing.AdminDistrict).FirstOrDefault();
                    if (oState == null)
                    {
                        return(apiresult.Failure("Invalid State"));
                    }

                    if (existing.PostalCode.CountAlphaNumeric() < 3)
                    {
                        return(apiresult.Failure("Invalid PostalCode"));
                    }
                    if (oCountry.Abbreviation == "USA")
                    {
                        LocationNode.PostalCodeNode oZip = Factory.LocationManager.QueryCachedPostalCodes(existing.PostalCode).FirstOrDefault();
                        if (oZip == null)
                        {
                            return(apiresult.Failure("Invalid PostalCode"));
                        }
                    }

                    if (existing.Locality.CountAlphaNumeric() < 3)
                    {
                        return(apiresult.Failure("Invalid City"));
                    }
                }
            }

            StreetAddress address = new StreetAddress()
            {
                ParentLocationID = existing.ParentLocationID,
                LocationID       = existing.LocationID,
                Name             = existing.LocationName,
                AddressLine      = existing.AddressLine,
                Locality         = existing.Locality,
                AdminDistrict    = existing.AdminDistrict,
                PostalCode       = existing.PostalCode,
                CountryRegion    = existing.CountryRegion
            };

            if (bLocChange)
            {
                try {
                    address = new StreetAddress(Factory.LocationManager.GetOrCreateDBLocation(address));
                } catch (Exception ex) { return(apiresult.Failure(ex)); }
            }

            try {
                Factory.EventManager.UpdateEvent(EventID, existing.EventTypeID, existing.DateStart, existing.DateEnd, UserContext.AccountID, existing.LocationID, existing.Title, existing.Caption, existing.Details);
                EventInfo info = new EventInfo()
                {
                    EventID      = existing.EventID,
                    DateStart    = existing.DateStart,
                    DateEnd      = existing.DateEnd,
                    Title        = existing.Title,
                    Caption      = existing.Title,
                    EventTypeID  = existing.EventTypeID,
                    EventType    = eventType,
                    LocationID   = existing.LocationID,
                    LocationName = address.Name,
                    AddressLine  = Helpers.FormatAddress(null, address.AddressLine, address.Locality, address.AdminDistrict, address.PostalCode, address.CountryRegion),
                    AccountID    = existing.AccountID,
                    Host         = String.IsNullOrWhiteSpace(UserContext.UserDisplayName) ? UserContext.UserName : UserContext.UserDisplayName,
                    Tags         = eventTags,
                    Details      = existing.Details
                };

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                if (newTags != null)
                {
                    for (int i = 0; i < newTags.Count; i++)
                    {
                        Factory.TagManager.LinkTagToEvent(info.EventID, newTags[i].TagID);
                    }
                }
                if (removedTags != null)
                {
                    for (int i = 0; i < removedTags.Count; i++)
                    {
                        Factory.TagManager.RemoveTagFromEvent(info.EventID, removedTags[i].TagID);
                    }
                }
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                return(apiresult.Success(info));
            } catch (Exception ex) {
                return(apiresult.Failure(ex));
            }
        }
Exemplo n.º 29
0
        public ApiResult <EventInfo> EventCreate(EventInput input)
        {
            var apiresult = new ApiResult <EventInfo>();

            if (UserContext == null)
            {
                return(apiresult.Failure("Must be logged in."));
            }
            if (!UserContext.IsVerifiedLogin)
            {
                return(apiresult.Failure("Insufficient account permissions."));
            }

            if (input == null)
            {
                return(apiresult.Failure("Bad Post. Input is null."));
            }
            if (input.Location == null)
            {
                return(apiresult.Failure("Location Invalid"));
            }
            //TODO sanitize Title, Caption, and Description to be free of javascript
            if (input.Title.CountAlphaNumeric() <= 5)
            {
                return(apiresult.Failure("Title to short."));
            }
            if (input.Caption.CountAlphaNumeric() <= 8)
            {
                return(apiresult.Failure("Caption to short."));
            }
            if (input.DateStart.ToUniversalTime() < DateTime.UtcNow)
            {
                return(apiresult.Failure("DateStart in the past."));
            }
            if (input.DateEnd.ToUniversalTime() < input.DateStart.ToUniversalTime())
            {
                return(apiresult.Failure("DateEnd is before DateStart"));
            }
            if (input.DateStart.AddDays(14).ToUniversalTime() < input.DateEnd.ToUniversalTime())
            {
                return(apiresult.Failure("Events cannot last longer than 2 weeks."));
            }



            DBEventType eventType = Factory.EventTypeManager[input.EventTypeID];

            if (eventType == null)
            {
                return(apiresult.Failure("EventType does not exist."));
            }

            if (input.Tags == null || input.Tags.Length == 0)
            {
                return(apiresult.Failure("Include at least one EventTag."));
            }
            DBTag[] eventTags = new DBTag[input.Tags.Length];
            for (int i = 0; i < input.Tags.Length; i++)
            {
                DBTag tag = Factory.TagManager[input.Tags[i]];
                if (tag == null)
                {
                    return(apiresult.Failure("Invalid Tag: " + input.Tags[i].ToString()));
                }
                eventTags[i] = tag;
            }

            LocationNode.CountryRegionNode oCountry = Factory.LocationManager.QueryCachedCountries(input.Location.CountryRegion).FirstOrDefault();
            if (oCountry == null)
            {
                return(apiresult.Failure("Invalid Country"));
            }

            LocationNode.AdminDistrictNode oState = Factory.LocationManager.QueryCachedStates(input.Location.AdminDistrict).FirstOrDefault();
            if (oState == null)
            {
                return(apiresult.Failure("Invalid State"));
            }

            if (input.Location.PostalCode.CountAlphaNumeric() < 3)
            {
                return(apiresult.Failure("Invalid PostalCode"));
            }
            if (oCountry.Abbreviation == "USA")
            {
                LocationNode.PostalCodeNode oZip = Factory.LocationManager.QueryCachedPostalCodes(input.Location.PostalCode).FirstOrDefault();
                if (oZip == null)
                {
                    return(apiresult.Failure("Invalid PostalCode"));
                }
            }

            if (input.Location.Locality.CountAlphaNumeric() < 3)
            {
                return(apiresult.Failure("Invalid City"));
            }


            try {
                StreetAddress   address     = new StreetAddress(Factory.LocationManager.GetOrCreateDBLocation(input.Location));
                DBEventFeedItem dbEventItem = Factory.EventManager.CreateEvent(eventType.EventTypeID, input.DateStart, input.DateEnd, UserContext.AccountID, address.LocationID.UnBox(), input.Title, input.Caption, input.Description);
                EventInfo       info        = new EventInfo()
                {
                    EventID      = dbEventItem.EventID,
                    DateStart    = dbEventItem.DateStart,
                    DateEnd      = dbEventItem.DateEnd,
                    Title        = dbEventItem.Title,
                    Caption      = dbEventItem.Title,
                    EventTypeID  = dbEventItem.EventTypeID,
                    EventType    = eventType,
                    LocationID   = dbEventItem.LocationID,
                    LocationName = address.Name,
                    AddressLine  = Helpers.FormatAddress(null, address.AddressLine, address.Locality, address.AdminDistrict, address.PostalCode, address.CountryRegion),
                    AccountID    = dbEventItem.AccountID,
                    Host         = String.IsNullOrWhiteSpace(UserContext.UserDisplayName) ? UserContext.UserName : UserContext.UserDisplayName,
                    Tags         = eventTags,
                    Details      = input.Description
                };

                for (int i = 0; i < eventTags.Length; i++)
                {
                    DBTag tag = eventTags[i];
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                    Factory.TagManager.LinkTagToEvent(info.EventID, tag.TagID);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                }

                return(apiresult.Success(info));
            } catch (Exception ex) {
                return(apiresult.Failure(ex));
            }
        }
Exemplo n.º 30
0
        public ApiResult Delete([FromBody] AutoConfigDelete entity)
        {
            if (entity == null)
            {
                return(ApiResult.Failure("参数不能为空"));
            }

            if (entity.Type.IsNullOrEmpty())
            {
                return(ApiResult.Failure("类型不能为空"));
            }

            var type = entity.Type.GetTypeByName();

            if (type == null)
            {
                return(ApiResult.Failure("类型不存在"));
            }

            var attr = type.GetTypeInfo().GetAttribute <ClassPropertyAttribute>();
            var configDescription = new ClassDescription(type.GetTypeInfo());

            if (attr != null && !string.IsNullOrEmpty(attr.Validator) && FilterSQLScript(attr.Validator) == 0)
            {
                var script      = string.Format(attr.Validator, entity.Id);
                var isValidated = Resolve <IAutoConfigService>().Check(script);
                if (isValidated)
                {
                    return(ApiResult.Failure("删除失败" + attr.ValidateMessage));
                }
            }

            var    list       = Resolve <IAutoConfigService>().GetObjectList(type);
            object deleteItem = null;

            foreach (var item in list)
            {
                if (item.GetType().GetProperty("Id").GetValue(item).ToGuid() == entity.Id.ToGuid())
                {
                    if (type.GetTypeInfo().BaseType.Name == "BaseGradeConfig")
                    {
                        if (item.GetType().GetProperty("IsDefault").GetValue(item).ToBoolean())
                        {
                            continue;
                        }
                    }

                    deleteItem = item;
                    break;
                }
            }

            if (deleteItem != null)
            {
                list.Remove(deleteItem);
            }

            var config = Resolve <IAutoConfigService>().GetConfig(type.FullName);

            config.Value = JsonConvert.SerializeObject(list);
            Resolve <IAutoConfigService>().AddOrUpdate(config);
            Resolve <IAutoConfigService>().Log($"成功删除配置,IAutoConfig配置类型为:{type.GetTypeInfo().Name},配置ID:{entity.Id}");

            return(ApiResult.Success("删除成功"));
        }