public ActionResult <bool> UpdateEnterprise(int id, [FromBody] EnterpriseModel enterprise)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    foreach (var state in ModelState)
                    {
                        if (state.Key == nameof(enterprise.Name) && state.Value.Errors.Count > 0)
                        {
                            return(BadRequest(state.Value.Errors));
                        }
                    }
                }

                return(Ok(service.UpdateEnterprise(id, enterprise)));
            }
            catch (NotFoundException ex)
            {
                return(NotFound(ex.Message));
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
            }
        }
Exemple #2
0
        /// <summary>
        /// 模型数据改变
        /// </summary>
        /// <param name="obj"></param>
        private void dataChanged(EnterpriseModel enterpriseModel)
        {
            getPageData(pageRepuestParams.PageIndex, pageRepuestParams.PageSize);
            var tmpModel = EnterpriseInfoList.FirstOrDefault(a => a.Id == enterpriseModel.Id);

            this.EnterpriseInfo = EnterpriseInfoList.FirstOrDefault();
        }
Exemple #3
0
 public ActionResult Create(EnterpriseModel Model)
 {
     Model.Key = Helpers.Pinyin.Convert(Model.Title);
     DB.Enterprises.Add(Model);
     DB.SaveChanges();
     return(Content(Model.ID.ToString()));
 }
Exemple #4
0
        public Guid InsertEnterprise(EnterpriseModel enterprise)
        {
            Guid id = Guid.NewGuid();

            if (enterprise == null)
            {
                throw new NullReferenceException();
            }

            using (AppTourEntities data = new AppTourEntities())
            {
                ENTERPRISE _new = new ENTERPRISE
                {
                    ID            = id,
                    NAME          = enterprise.Name,
                    DESCRIPTION   = enterprise.Description,
                    CREATION_DATE = DateTime.Now,
                    UPDATE_DATE   = DateTime.Now
                };

                data.ENTERPRISE.AddObject(_new);
                data.SaveChanges();
            }

            return(id);
        }
Exemple #5
0
        public void CreateEnterpriseTest()
        {
            var model      = new EnterpriseModel(context);
            var enterprise = model.CreateEnterprise("Fantasia", "123456000132");

            Assert.True(enterprise.Id != 0, "Falha ao inserir uma nova empresa");
        }
Exemple #6
0
 public void DeleteEnterprise(EnterpriseModel enterprise)
 {
     if (enterprise == null)
     {
         throw new ArgumentNullException();
     }
     using (AppTourEntities data = new AppTourEntities())
     {
         ENTERPRISE current = data.ENTERPRISE.Where(p => p.ID == enterprise.Id).SingleOrDefault();
         if (current != null)
         {
             try
             {
                 data.DeleteObject(current);
                 data.SaveChanges();
             }
             catch (UpdateException ex)
             {
                 if (ex.InnerException != null)
                 {
                     throw new UpdateException(ex.InnerException.Message);
                 }
                 throw;
             }
             catch (Exception e)
             {
                 if (e.InnerException != null)
                 {
                     throw new Exception(e.InnerException.Message);
                 }
                 throw;
             }
         }
     }
 }
Exemple #7
0
        public void UpdateEnterprise(EnterpriseModel enterprise)
        {
            using (AppTourEntities data = new AppTourEntities())
            {
                ENTERPRISE current = data.ENTERPRISE.Where(x => enterprise.Id == x.ID).SingleOrDefault();
                if (current != null)
                {
                    try
                    {
                        current.NAME          = enterprise.Name;
                        current.DESCRIPTION   = enterprise.Description;
                        current.CREATION_DATE = enterprise.CreationDate;
                        current.UPDATE_DATE   = DateTime.Now;

                        data.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        if (e.InnerException != null)
                        {
                            throw new Exception(e.InnerException.Message);
                        }
                        throw;
                    }
                }
            }
        }
Exemple #8
0
        public EnterpriseModel CreateEnterprise(EnterpriseModel newEnterprise)
        {
            var enterpriseEntity    = mapper.Map <EnterpriseEntity>(newEnterprise);
            var newEnterpriseEntity = repository.CreateEnterprise(enterpriseEntity);

            return(mapper.Map <EnterpriseModel>(newEnterpriseEntity));
        }
Exemple #9
0
        private void UpdateEnterprise(EnterpriseModel enterprise)
        {
            var culture        = MvcApplication.GetCurrentCulture();
            var nativeLanguage = Monscierge.Utilities.Translation.GetLanguageFromCulture(culture);

            if (enterprise != null)
            {
                Rp.ExecuteAction(() =>
                {
                    var dbEnterprise = (from e in ProxylessContext.Enterprises.Where(e2 => e2.IsActive)
                                        where e.PKID == enterprise.PKID
                                        select e).FirstOrDefault();

                    if (dbEnterprise != null)
                    {
                        if (dbEnterprise.DescriptionLanguage.Equals(nativeLanguage, StringComparison.InvariantCultureIgnoreCase))
                        {
                            dbEnterprise.Description = enterprise.Description;
                        }
                        else
                        {
                            dbEnterprise.LocalizedDescription =
                                Localization.SetLocalizedText(dbEnterprise.LocalizedDescription, nativeLanguage,
                                                              enterprise.Description);
                        }
                        dbEnterprise.FacebookUrl = enterprise.FacebookUrl;
                        dbEnterprise.Name        = enterprise.Name;
                        dbEnterprise.TwitterUrl  = enterprise.TwitterUrl;
                        dbEnterprise.URL         = enterprise.WebsiteUrl;
                    }
                });
            }
        }
Exemple #10
0
        public bool UpdateEnterprise(int id, EnterpriseModel enterprise)
        {
            GetEnterprise(id);
            enterprise.Id = id;

            repository.UpdateEnterprise(mapper.Map <EnterpriseEntity>(enterprise));
            return(true);
        }
Exemple #11
0
        /// <summary>
        /// 执行导出命令
        /// </summary>
        private async void OnExecuteExportCommand()
        {
            var window       = (MetroWindow)Application.Current.MainWindow;
            var dialogResult = await window.ShowMessageAsync("数据导出"
                                                             , "确定要从磁盘中导出企业信息数据吗?"
                                                             , MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings()
            {
                AffirmativeButtonText = "是", NegativeButtonText = "否"
            });

            if (dialogResult == MessageDialogResult.Affirmative)
            {
                string filePath = "";
                System.Windows.Forms.SaveFileDialog openFileDialog = new System.Windows.Forms.SaveFileDialog();
                openFileDialog.FileName = "企业信息" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss") + ".xls";
                if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)//注意,此处一定要手动引入System.Window.Forms空间,否则你如果使用默认的DialogResult会发现没有OK属性
                {
                    filePath = openFileDialog.FileName;
                }
                if (string.IsNullOrEmpty(filePath))
                {
                    Application.Current.Resources["UiMessage"] = "数据导出失败,选择存储路径为空!";
                    return;
                }
                if (EnterpriseInfoList.Any())
                {
                    try
                    {
                        EnterpriseModel model           = new EnterpriseModel();
                        List <string>   displayNameList = model.GetDisplayName();
                        DataTable       dataTable       = EnterpriseInfoList.ToDataTable <EnterpriseModel>(displayNameList);
                        //filePath += @"\企业信息" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss") + ".xls";
                        NPOIHelper.Export(dataTable, "企业信息", filePath);
                    }
                    catch (Exception ex)
                    {
                        Application.Current.Resources["UiMessage"] = "数据导出失败!" + ex.ToString();
                    }

                    if (File.Exists(filePath))
                    {
                        Application.Current.Resources["UiMessage"] = "数据导出已完成!";
                    }
                    else
                    {
                        Application.Current.Resources["UiMessage"] = "数据导出失败!";
                    }
                }
                else
                {
                    Application.Current.Resources["UiMessage"] = "数据导出失败,无数据!";
                }
            }
        }
Exemple #12
0
        public EnterpriseModel GetEnterpriseRecommendationForEdit(int deviceId, int enterpriseId, int?enterpriseLocationId)
        {
            EnterpriseModel enterprise = null;

            RootRepository.SecurityRepository.AssertDevicePermissions(deviceId);

            enterprise =
                Rp.ExecuteAction(() => (from e in ProxylessContext.Enterprises.Where(e2 => e2.IsActive && e2.PKID == enterpriseId)
                                        let el =
                                            e.EnterpriseLocations.Where(el2 => !enterpriseLocationId.HasValue || el2.PKID == enterpriseLocationId.Value)
                                            let ecm = e.EnterpriseCategoryMaps
                                                      let hboem =
                                                ecm.SelectMany(
                                                    ecm2 =>
                                                    ecm2.HotelBestOfEnterpriseMaps.Where(hboem2 => hboem2.IsActive && hboem2.FKDevice == deviceId)
                                                    .OrderBy(hboem2 => hboem2.Ordinal))
                                                let hboelm = hboem.SelectMany(hboem2 => hboem2.HotelBestOfEnterpriseLocationMaps)
                                                             let blem = e.BlackListEnterpriseMaps.Where(blem2 => blem2.IsActive && blem2.FKDevice == deviceId)
                                                                        let blelm =
                                                    el.SelectMany(
                                                        el2 =>
                                                        el2.BlackListEnterpriseLocationMaps.Where(
                                                            blelm2 => blelm2.IsActive && blelm2.Hotel.Devices.Any(d => d.PKID == deviceId)))
                                                    select new EnterpriseModel
            {
                Blacklisted = blem.Any(),
                EnterpriseLocations = (from el2 in el
                                       let c = ProxylessContext.Countries.FirstOrDefault(c2 => c2.IsActive && c2.ISOCountryCode == el2.Country)
                                               where !hboelm.Any() ||
                                               hboelm.Select(hboelm2 => hboelm2.FKEnterpriseLocation).Contains(el2.PKID)
                                               select new EnterpriseLocationModel
                {
                    Blacklisted = blelm.Select(blelm2 => blelm2.FKEnterpriseLocation).Contains(el2.PKID),
                    PKID = el2.PKID,
                    RecommendedCategories = (from hboelm2 in hboelm
                                             select new OrderModel
                    {
                        Key = hboelm2.HotelBestOfEnterpriseMap.EnterpriseCategoryMap.CategoryMap.ChildCategory.PKID,
                        Order = hboelm2.Ordinal
                    })
                }),
                PKID = e.PKID,
                RecommendedCategories = (from hboem2 in hboem
                                         select new OrderModel
                {
                    Key = hboem2.EnterpriseCategoryMap.CategoryMap.ChildCategory.PKID,
                    Order = hboem2.Ordinal
                })
            })).FirstOrDefault();

            return(enterprise);
        }
Exemple #13
0
        public void UpdateEnterprise(int deviceId, EnterpriseModel enterprise, EnterpriseLocationModel enterpriseLocation)
        {
            if (enterprise != null)
            {
                RootRepository.SecurityRepository.AssertDevicePermissions(deviceId);

                UpdateEnterprise(enterprise);
                UpdateEnterpriseLocation(enterpriseLocation);

                Rp.ExecuteAction(
                    () => ProxylessContext.LogValidationFailSaveChanges(RootRepository.SecurityRepository.AuditLogUserId));
            }
        }
        static void Main(string[] args)
        {
            string path = @"C:\Users\T.I\Desktop\tt.txt";

            ExtractData extractData = new ExtractData(path);

            Enterprise      enterprise = new Enterprise();
            EnterpriseModel e          = enterprise.Getdata(extractData.DataFromHeader());

            Console.WriteLine($"CNPJ: {e.Cnpj}");
            Console.WriteLine($"Código da SEFIP: {e.SefipCode}");
            Console.WriteLine($"Mês de Competência: {e.CompetenceMonth}");
            Console.WriteLine($"Ano de Competencia: {e.CompetenceYear}");
        }
Exemple #15
0
 public ActionResult EditPost(EnterpriseModel enterprise, Guid enterpriseID)
 {
     if (enterpriseID == null)
     {
         return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
     }
     if (new RoadFlow.Platform.EnterpriseAndEnterpriseTaxBLL().ManageUpdate(enterprise, enterpriseID) > 0)
     {
         ViewBag.Success = true;
     }
     else
     {
         ModelState.AddModelError("", "更新失败。");
     }
     return(View(EditInit(enterpriseID)));
 }
Exemple #16
0
        public JsonNetResult GetEnterpriseForEdit(int deviceId, int enterpriseId, int?enterpriseLocationId)
        {
            var hotel = ConnectCmsRepository.HotelRepository.GetHotelFromDevice(deviceId);

            EnterpriseModel enterprise = null;

            if (hotel != null)
            {
                var location = hotel.Location;

                if (location != null)
                {
                    enterprise = ConnectCmsRepository.EnterpriseRepository.GetEnterpriseForEdit(deviceId, enterpriseId, enterpriseLocationId, location.Latitude, location.Longitude, hotel.RadiusInMeters);
                }
            }

            return(JsonNet(enterprise ?? new EnterpriseModel()));
        }
Exemple #17
0
        public void CannotCreateEnterpriseWithoutNameTest()
        {
            var model = new EnterpriseModel(context);

            Assert.Throws <BusinessException>(() =>
            {
                model.CreateEnterprise("", "123123213213");
            });

            Assert.Throws <BusinessException>(() =>
            {
                model.CreateEnterprise(" ", "123123213213");
            });

            Assert.Throws <BusinessException>(() =>
            {
                model.CreateEnterprise(null, "123123213213");
            });
        }
Exemple #18
0
        public void CannotCreateEnterpriseWithoutCNPJTest()
        {
            var model = new EnterpriseModel(context);

            Assert.Throws <BusinessException>(() =>
            {
                model.CreateEnterprise("teste", "");
            });

            Assert.Throws <BusinessException>(() =>
            {
                model.CreateEnterprise("teste", " ");
            });

            Assert.Throws <BusinessException>(() =>
            {
                model.CreateEnterprise("teste", null);
            });
        }
Exemple #19
0
 public ActionResult Edit(EnterpriseModel enterprise)
 {
     if (enterprise.IsValid)
     {
         try
         {
             service.UpdateEnterprise(enterprise);
             return(RedirectToAction("Index"));
         }
         catch (Exception e)
         {
             ModelState.AddModelError("", e.Message);
         }
     }
     else
     {
         ModelState.AddModelError("", enterprise.Error);
     }
     return(View(enterprise));
 }
Exemple #20
0
        private void SendEnterpriseEmail(User user, string activationCode, Company company)
        {
            var license = company.Licenses.FirstOrDefault();
            var days    = (int)Math.Round(license.Return(x => x.ExpiryDate.Subtract(DateTime.Today), new TimeSpan(45, 0, 0, 0)).TotalDays);

            var model = new EnterpriseModel(this.Settings)
            {
                CompanyName       = company.CompanyName,
                MailSubject       = Emails.TrialSubject,
                TrialContactEmail = (string)this.Settings.TrialContactEmail,
                TrialDays         = days,
                UserName          = user.Email,
                FirstName         = user.FirstName,
                ActivationCode    = activationCode,
                ExpirationDate    = license.Return(x => x.ExpiryDate.ToShortDateString(), string.Empty),
            };
            var bcced = new List <MailAddress>
            {
                new MailAddress(this.Settings.TrialContactEmail),
                new MailAddress(Common.JacquieEmail, Common.JacquieName)
            };

            bool sentSuccessfully = this.MailModel.SendEmailSync(
                user.FirstName,
                user.Email,
                Emails.TrialSubject,
                model,
                Common.AppEmailName,
                Common.AppEmail,
                bcced: bcced);

            this.SaveHistory(
                sentSuccessfully,
                user.FirstName,
                user.Email,
                Emails.TrialSubject,
                model,
                Common.AppEmailName,
                Common.AppEmail,
                bcced: bcced);
        }
        public ActionResult <EnterpriseModel> CreateEnterprise([FromBody] EnterpriseModel enterprise)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var newEnterprise = service.CreateEnterprise(enterprise);
                return(Created($"/api/Enterprises/{newEnterprise.Id}", newEnterprise));
            }
            catch (NotFoundException ex)
            {
                return(NotFound(ex.Message));
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));;
            }
        }
Exemple #22
0
        public async Task <EnterpriseModel> EnterpriseGet(int id)
        {
            try
            {
                var enterpriseModel = new EnterpriseModel();
                enterpriseModel.Employees = new List <EmployeeModel>();
                using (var ctx = new dbPumox())
                {
                    var ent = await ctx.Enterprises.Where(x => x.Id == id).FirstOrDefaultAsync();

                    enterpriseModel = EnterpriseModelMapper.MapEnterprise(ent);
                }

                return(enterpriseModel);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(null);
            }
        }
Exemple #23
0
        public static EnterpriseModel MapEnterprise(Enterprise enterprise)
        {
            try
            {
                if (enterprise == null)
                {
                    return(null);
                }

                var model = new EnterpriseModel();
                model.Id   = enterprise.Id;
                model.Name = enterprise.Name;
                model.EstablishmentYear = enterprise.EstablishmentYear;
                model.Employees         = MapEmployeeList(enterprise.Employees);

                return(model);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #24
0
 public ActionResult Create(EnterpriseModel enterprise)
 {
     if (ModelState.IsValid)
     {
         try
         {
             if (enterprise.IsValid)
             {
                 service.InsertEnterprise(enterprise);
             }
             else
             {
                 ModelState.AddModelError("", enterprise.Error);
                 return(View("Create", enterprise));
             }
         }
         catch (Exception e)
         {
             ModelState.AddModelError("", e.Message);
             return(View("Create", enterprise));
         }
     }
     return(RedirectToAction("Index"));
 }
Exemple #25
0
        public ActionResult Delete(Guid id, EnterpriseModel enterprise)
        {
            if (id == enterprise.Id)
            {
                try
                {
                    service.DeleteEnterprise(enterprise);
                    return(RedirectToAction("Index"));
                }
                catch (UpdateException)
                {
                    enterprise = service.GetEnterprise(id);
                    ViewData.Add(new KeyValuePair <string, object>(ViewRes.Enterprise.Erro + ':', ViewRes.Enterprise.UpdateException));
                }
                catch (Exception e)
                {
                    enterprise = service.GetEnterprise(id);
                    ModelState.AddModelError("", e.Message);
                    ViewData.Add(new KeyValuePair <string, object>(ViewRes.Enterprise.Erro + ':', ViewRes.Enterprise.UpdateException));
                }
            }

            return(View("Delete", enterprise));
        }
Exemple #26
0
        /// <summary>
        /// 执行导入命令
        /// </summary>
        private async void OnExecuteImportCommand()
        {
            var window       = (MetroWindow)Application.Current.MainWindow;
            var dialogResult = await window.ShowMessageAsync("数据导入"
                                                             , "确定要导入企业信息数据到磁盘中吗?将会删除磁盘中原有数据"
                                                             , MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings()
            {
                AffirmativeButtonText = "是", NegativeButtonText = "否"
            });

            if (dialogResult == MessageDialogResult.Affirmative)
            {
                string filePath = "";
                System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
                if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)//注意,此处一定要手动引入System.Window.Forms空间,否则你如果使用默认的DialogResult会发现没有OK属性
                {
                    filePath = openFileDialog.FileName;
                }
                if (string.IsNullOrEmpty(filePath))
                {
                    Application.Current.Resources["UiMessage"] = "数据导入失败,选择存储路径为空!";
                    return;
                }
                if (EnterpriseInfoList.Any())
                {
                    try
                    {
                        EnterpriseModel           model       = new EnterpriseModel();
                        Dictionary <String, Type> filedNameDc = model.GetFiledNameAndType();
                        DataTable dt    = NPOIHelper.Import(filePath);
                        DataTable dtNew = new DataTable();
                        foreach (var kvp in filedNameDc)
                        {
                            dtNew.Columns.Add(kvp.Key, kvp.Value);
                        }
                        object[] values = new object[filedNameDc.Count];
                        foreach (DataRow row in dt.Rows)
                        {
                            for (int i = 0; i < dtNew.Columns.Count; i++)
                            {
                                values[i] = row[i];
                            }
                            dtNew.Rows.Add(values);
                        }
                        List <EnterpriseModel> enterpriseModels = dtNew.DataTableToList <EnterpriseModel>();
                    }
                    catch (Exception ex)
                    {
                        Application.Current.Resources["UiMessage"] = "数据导入失败!" + ex.ToString();
                    }

                    if (File.Exists(filePath))
                    {
                        Application.Current.Resources["UiMessage"] = "数据导入已完成!";
                    }
                    else
                    {
                        Application.Current.Resources["UiMessage"] = "数据导入失败!";
                    }
                }
                else
                {
                    Application.Current.Resources["UiMessage"] = "数据导入失败,无数据!";
                }
            }
        }
Exemple #27
0
        public List <EnterpriseModel> GetSearchBingEnterprises(float?hotelLatitude, float?hotelLongitude, float radiusInKilometers, string text, EnterpriseSearchSortTypes sortType, string culture, IEnumerable <string> excludeBingIds = null)
        {
            List <EnterpriseModel> enterprises = new List <EnterpriseModel>();

            if (hotelLatitude.HasValue && hotelLongitude.HasValue)
            {
                var bingAppId       = GetBingAppId();
                var enUsCultureInfo = new CultureInfo("en-US");
                var latitude        = hotelLatitude.Value;
                var longitude       = hotelLongitude.Value;

                var searchRequest = new Bing.Search.SearchRequest()
                {
                    Credentials = new Bing.Search.Credentials()
                    {
                        ApplicationId = bingAppId
                    },
                    Culture       = FormatCulture(culture),
                    SearchOptions = new Bing.Search.SearchOptions()
                    {
                        Count       = 20,
                        ListingType = Bing.Search.ListingType.Business,
                        Radius      = radiusInKilometers,
                        SortOrder   = Bing.Search.SortOrder.Popularity
                    },
                    StructuredQuery = new Bing.Search.StructuredSearchQuery()
                    {
                        Location = latitude.ToString(enUsCultureInfo) + ", " + longitude.ToString(enUsCultureInfo),
                        Keyword  = text
                    },
                    UserProfile = new Bing.Search.UserProfile()
                    {
                        CurrentLocation = new Bing.Search.UserLocation()
                        {
                            Latitude  = latitude,
                            Longitude = longitude
                        }
                    }
                };

                var searchServiceService = new Bing.Search.SearchServiceClient("BasicHttpBinding_ISearchService");
                var searchResponse       = searchServiceService.Search(searchRequest);

                if (searchResponse != null &&
                    searchResponse.ResultSets != null && searchResponse.ResultSets.Count() > 0 &&
                    searchResponse.ResultSets[0].Results != null && searchResponse.ResultSets[0].Results.Count() > 0)
                {
                    Bing.Search.Address address;
                    Bing.Search.BusinessSearchResult businessSearchResult;
                    EnterpriseLocationModel          enterpriseLocation;
                    EnterpriseModel             enterprise;
                    Bing.Search.GeocodeLocation geocodeLocation;

                    foreach (Bing.Search.SearchResultBase searchResultBase in searchResponse.ResultSets[0].Results)
                    {
                        if (searchResultBase is Bing.Search.BusinessSearchResult &&
                            searchResultBase.LocationData != null &&
                            searchResultBase.LocationData.Locations != null && searchResultBase.LocationData.Locations.Count > 0)
                        {
                            businessSearchResult = searchResultBase as Bing.Search.BusinessSearchResult;

                            if (excludeBingIds == null || !excludeBingIds.Contains(businessSearchResult.Id))
                            {
                                enterprise = new EnterpriseModel()
                                {
                                    EnterpriseLocations = new List <EnterpriseLocationModel>(),
                                    Name       = businessSearchResult.Name,
                                    WebsiteUrl = businessSearchResult.Website != null?businessSearchResult.Website.ToString() : null
                                };

                                enterpriseLocation = new EnterpriseLocationModel()
                                {
                                    BingId               = businessSearchResult.Id,
                                    Blacklisted          = false,
                                    DistanceInKilometers = businessSearchResult.Distance,
                                    LocalHours           = businessSearchResult.AdditionalProperties.ContainsKey("HoursOfOperation") ? businessSearchResult.AdditionalProperties["HoursOfOperation"].ToString().ToLower() : null,
                                    Phone = businessSearchResult.PhoneNumber
                                };

                                geocodeLocation = searchResultBase.LocationData.Locations.FirstOrDefault();

                                address = businessSearchResult.Address;

                                if (address != null)
                                {
                                    enterpriseLocation.Location = new LocationModel()
                                    {
                                        Address1       = address.AddressLine,
                                        City           = address.PostalTown ?? address.Locality,
                                        ISOCountryCode = address.CountryRegion,
                                        PostalCode     = address.PostalCode,
                                        ISOStateCode   = address.AdminDistrict
                                    };

                                    if (geocodeLocation.Latitude != 0 && geocodeLocation.Longitude != 0)
                                    {
                                        enterpriseLocation.Location.Latitude = ( float )geocodeLocation.Latitude;
                                    }
                                    enterpriseLocation.Location.Longitude = ( float )geocodeLocation.Longitude;

                                    enterpriseLocation.PhoneISOCountryCode = enterpriseLocation.Location.ISOCountryCode;
                                }

                                // TODO: JD: Get culture
                                enterpriseLocation.TranslatedHours.Add("EN", enterpriseLocation.LocalHours);

                                ((List <EnterpriseLocationModel>)enterprise.EnterpriseLocations).Add(enterpriseLocation);

                                enterprises.Add(enterprise);
                            }
                        }
                    }
                }

                if (enterprises.Any())
                {
                    switch (sortType)
                    {
                    case EnterpriseSearchSortTypes.ALAPHABETICAL:
                        enterprises = enterprises.OrderBy(e => e.Name).ThenBy(e => e.EnterpriseLocations.Min(el => el.DistanceInMeters)).ToList();

                        break;

                    case EnterpriseSearchSortTypes.NEAREST:
                        enterprises = enterprises.OrderBy(e => e.EnterpriseLocations.Min(el => el.DistanceInMeters)).ToList();

                        break;
                    }
                }
            }

            return(enterprises);
        }
        public ActionResult Edit(int id, ProjectModel Model, string EnterpriseName, string CustomerName)
        {
            var project = DB.Projects.Find(id);

            project.ZoneID         = Model.ZoneID;
            project.ActualPayments = Model.ActualPayments;
            project.Begin          = Model.Begin;
            project.End            = Model.End;
            project.EnterpriseID   = Model.EnterpriseID;
            project.Hint           = Model.Hint;
            project.Description    = Model.Description;
            project.InvoicePrice   = Model.InvoicePrice;
            project.InvoiceSN      = Model.InvoiceSN;
            project.InvoiceTime    = Model.InvoiceTime;
            project.Ordering       = Model.Ordering;
            project.Priority       = Model.Priority;
            project.Charge         = Model.Charge;
            project.ChargeTime     = Model.ChargeTime;
            project.SignTime       = Model.SignTime;
            project.InvoicePrice   = Model.InvoicePrice;
            project.CustomerID     = Model.CustomerID;
            project.Title          = Model.Title;
            project.Status         = Model.Status;
            project.Brand          = Model.Brand;
            project.Log           += string.Format("[{0}] {1}({2}) 修改了项目\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm"), CurrentUser.Name, CurrentUser.Username);
            if (Model.Status == ProjectStatus.Completed)
            {
                project.Percent = 1;
            }
            project.PayMethod = Model.PayMethod;
            if (project.ProductID != Model.ProductID)
            {
                if (Model.ProductID != null)
                {
                    project.ProductID = Model.ProductID;
                    var product = DB.Products.Find(Model.ProductID);
                    project.AwardAllocRatioCache = product.Category.AwardAllocRatio;
                    project.SaleAllocRatioCache  = product.Category.SaleAllocRatio;
                    project.TaxRatioCache        = product.Category.TaxRatio;
                }
                else
                {
                    project.AwardAllocRatioCache = null;
                    project.SaleAllocRatioCache  = null;
                    project.TaxRatioCache        = null;
                }
            }
            if (!string.IsNullOrEmpty(EnterpriseName))
            {
                if (project.Enterprise == null || project.Enterprise != null && !EnterpriseName.Contains(project.Enterprise.Title) && EnterpriseName != project.Enterprise.Title)
                {
                    var tmp = (from e in DB.Enterprises where e.Title == EnterpriseName select e).ToList();
                    if (tmp.Count > 0)
                    {
                        EnterpriseModel enterprise = (EnterpriseModel)tmp[0];
                        enterprise.Title = EnterpriseName;
                        enterprise.Key   = Helpers.Pinyin.Convert(EnterpriseName);
                        enterprise.Phone = (Model.Phone == null ? "" : Model.Phone);
                        // enterprise.Brand = Model.Brand;
                        //
                        project.EnterpriseID = enterprise.ID;
                        try
                        {
                            DB.SaveChanges();
                        }
                        catch (DbEntityValidationException dbEx)
                        {
                            throw dbEx;
                        }
                    }
                    else
                    {
                        var e = new EnterpriseModel
                        {
                            Level       = EnterpriseLevel.D,
                            Key         = Helpers.Pinyin.Convert(EnterpriseName),
                            Title       = (EnterpriseName == null ? "" : EnterpriseName),
                            Phone       = (Model.Phone == null ? "" : Model.Phone),
                            Address     = "Null",
                            SalesVolume = "Null",
                            Scale       = "Null",
                            Hint        = "Null",
                            Fax         = "Null",
                            Property    = "Null",
                            Type        = "Null",
                            Website     = "Null",
                            Zip         = "Null"
                        };
                        DB.Enterprises.Add(e);
                        try
                        {
                            DB.SaveChanges();
                        }
                        catch (DbEntityValidationException dbEx)
                        {
                            throw dbEx;
                        }
                        project.EnterpriseID = e.ID;
                    }
                }
                else
                {
                    if (project.EnterpriseID != null)
                    {
                        EnterpriseModel enterprise = DB.Enterprises.Find(project.EnterpriseID);
                        enterprise.Title = EnterpriseName;
                        enterprise.Key   = Helpers.Pinyin.Convert(EnterpriseName);
                        enterprise.Phone = (Model.Phone == null ? "" : Model.Phone);
                        //enterprise.Brand = Model.Brand;
                        try
                        {
                            DB.SaveChanges();
                        }
                        catch (DbEntityValidationException dbEx)
                        {
                            throw dbEx;
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(CustomerName))
            {
                if (project.CustomerID == null || project.CustomerID != null && !CustomerName.Contains(project.Customer.Name) && CustomerName != project.Customer.Name)
                {
                    var tmp = (from e in DB.Customers where e.Name == CustomerName select e).ToList();
                    if (tmp.Count > 0)
                    {
                        CustomerModel customer = (CustomerModel)tmp[0];
                        customer.Name  = CustomerName;
                        customer.Email = (Model.Email == null ? "" : Model.Email);
                        customer.Phone = (Model.Phone == null ? "" : Model.Phone);
                        customer.Tel   = (Model.Tel == null ? "" : Model.Tel);
                        //
                        project.CustomerID = customer.ID;
                        try
                        {
                            DB.SaveChanges();
                        }
                        catch (DbEntityValidationException dbEx)
                        {
                            throw dbEx;
                        }
                    }
                    else
                    {
                        if (project.EnterpriseID.HasValue)
                        {
                            var c = new CustomerModel
                            {
                                Name         = CustomerName,
                                Sex          = Sex.Male,
                                Email        = (Model.Email == null ? "" : Model.Email),
                                Birthday     = DateTime.Now,
                                EnterpriseID = project.EnterpriseID.Value,
                                Hint         = "Null",
                                Fax          = "Null",
                                Phone        = (Model.Phone == null ? "" : Model.Phone),
                                QQ           = "Null",
                                Tel          = (Model.Tel == null ? "" : Model.Tel),
                                WeChat       = "Null",
                                Position     = "Null"
                            };
                            DB.Customers.Add(c);
                            try
                            {
                                DB.SaveChanges();
                            }
                            catch (DbEntityValidationException dbEx)
                            {
                                throw dbEx;
                            }
                            project.CustomerID = c.ID;
                        }
                    }
                }
                else
                {
                    if (project.CustomerID != null)
                    {
                        CustomerModel customer = DB.Customers.Find(project.CustomerID);
                        customer.Name  = CustomerName;
                        customer.Email = (Model.Email == null ? "" : Model.Email);
                        customer.Phone = (Model.Phone == null ? "" : Model.Phone);
                        customer.Tel   = (Model.Tel == null ? "" : Model.Tel);
                        try
                        {
                            DB.SaveChanges();
                        }
                        catch (DbEntityValidationException dbEx)
                        {
                            throw dbEx;
                        }
                    }
                }
            }
            try
            {
                DB.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                throw dbEx;
            }
            return(RedirectToAction("Show", "Project", new { id = id }));
        }
Exemple #29
0
        public EnterpriseModel GetEnterpriseTipForEdit(int deviceId, int enterpriseId, int?enterpriseLocationId)
        {
            EnterpriseModel enterprise = null;

            RootRepository.SecurityRepository.AssertDevicePermissions(deviceId);

            var culture = "en-US";

            var nativeLanguage = culture.Substring(0, 2).ToUpper();

            enterprise =
                Rp.ExecuteAction(() => (from e in ProxylessContext.Enterprises.Where(e2 => e2.IsActive && e2.PKID == enterpriseId)
                                        let el =
                                            e.EnterpriseLocations.Where(
                                                el2 => el2.IsActive && (!enterpriseLocationId.HasValue || el2.PKID == enterpriseLocationId.Value))
                                            let it =
                                                e.InsiderTips.Where(
                                                    it2 =>
                                                    it2.Hotel.HotelDetail.IsActive &&
                                                    it2.Hotel.Devices.Where(d => d.DeviceDetail.IsActive).Select(d => d.PKID).Contains(deviceId) && it2.IsActive)
                                                select new EnterpriseModel
            {
                EnterpriseLocations = (from el2 in el
                                       let c = ProxylessContext.Countries.FirstOrDefault(c2 => c2.IsActive && c2.ISOCountryCode == el2.Country)
                                               let s = ProxylessContext.States.FirstOrDefault(s => s.IsActive && s.FKCountry == c.PKID)
                                                       select new EnterpriseLocationModel
                {
                    Location = new LocationModel
                    {
                        Address1 = el2.Address1,
                        Address2 = el2.Address2,
                        City = el2.City,
                        Country = c,
                        PostalCode = el2.PostalCode,
                        State = s,
                    },
                    PKID = el2.PKID,
                    Tips = (from it2 in it
                            let cu = it2.ContactUser
                                     where it2.FKEnterpriseLocation.HasValue &&
                                     it2.FKEnterpriseLocation.Value == el2.PKID
                                     select new TipModel
                    {
                        ContactUser = new ContactUserModel
                        {
                            Name = cu.ContactUserName,
                            PKID = cu.PKID
                        },
                        LastModified = it2.TipDateTime,
                        LocalTip = it2.Tip,
                        LocalTipLanguage =
                            it2.TipLanguage != null && it2.TipLanguage != string.Empty ? it2.TipLanguage : nativeLanguage,
                        LocalTipXml = it2.LocalizedTip,
                        PKID = it2.PKID
                    })
                }),
                PKID = e.PKID,
                Tips = (from it2 in it
                        let cu = it2.ContactUser
                                 where !it2.FKEnterpriseLocation.HasValue
                                 select new TipModel
                {
                    ContactUser = new ContactUserModel
                    {
                        Name = cu.ContactUserName,
                        PKID = cu.PKID
                    },
                    LastModified = it2.TipDateTime,
                    LocalTip = it2.Tip,
                    LocalTipLanguage = it2.TipLanguage != null && it2.TipLanguage != string.Empty ? it2.TipLanguage : nativeLanguage,
                    LocalTipXml = it2.LocalizedTip,
                    PKID = it2.PKID
                })
            })).FirstOrDefault();

            if (enterprise != null)
            {
                enterprise.Tips.ForEach(t => t.Tip = Localization.GetLocalizedText(t.LocalTip, t.LocalTipXml, t.LocalTipLanguage, nativeLanguage));
                enterprise.EnterpriseLocations.ForEach(
                    el => el.Tips.ForEach(t => t.Tip = Localization.GetLocalizedText(t.LocalTip, t.LocalTipXml, t.LocalTipLanguage, nativeLanguage)));
            }

            return(enterprise);
        }
Exemple #30
0
        public EnterpriseModel GetEnterpriseForEdit(int deviceId, int enterpriseId, int?enterpriseLocationId,
                                                    float?hotelLatitude, float?hotelLongitude, float radiusInMeters)
        {
            EnterpriseModel enterprise = null;

            var hotelPoint = GeographyUtils.GetPointFromLatitudeAndLongitude(hotelLatitude, hotelLongitude);

            if (hotelPoint != null)
            {
                RootRepository.SecurityRepository.AssertDevicePermissions(deviceId);

                // TODO: JD: Culture.
                var culture = MvcApplication.GetCurrentCulture();

                var nativeLanguage = culture.Substring(0, 2).ToUpper();

                var item =
                    Rp.ExecuteAction(
                        () => (from e in ProxylessContext.Enterprises.Where(e2 => e2.IsActive && e2.PKID == enterpriseId)
                               let eim = e.EnterpriseImageMaps.Where(eim2 => eim2.IsActive)
                                         let el = e.EnterpriseLocations.Where(el2 => el2.IsActive && (!enterpriseLocationId.HasValue || el2.PKID == enterpriseLocationId.Value))
                                                  let ecm = e.EnterpriseCategoryMaps
                                                            let fecm = ecm.FirstOrDefault()
                                                                       let cm = ecm.Where(ecm2 => ecm2.CategoryMap.IsActive).Select(ecm2 => ecm2.CategoryMap)
                                                                                let fcm = cm.FirstOrDefault()
                                                                                          let hcm = cm.SelectMany(cm2 => cm2.HotelCategoryMaps.Where(hcm2 => hcm2.IsActive && hcm2.FKDevice == deviceId))
                                                                                                    let fhcm = hcm.OrderBy(hcm2 => hcm2.Ordinal).FirstOrDefault()
                                                                                                               let hboem = ecm.SelectMany(ecm2 => ecm2.HotelBestOfEnterpriseMaps.Where(hboem2 => hboem2.IsActive && hboem2.FKDevice == deviceId).OrderBy(hboem2 => hboem2.Ordinal))
                                                                                                                           let hboelm = hboem.SelectMany(hboem2 => hboem2.HotelBestOfEnterpriseLocationMaps)
                                                                                                                                        select new
                {
                    CMImage = fcm.Image,
                    ECMImage = fecm.Image,
                    Enterprise = new EnterpriseModel
                    {
                        EnterpriseLocations = (from el2 in el
                                               let c = ProxylessContext.Countries.FirstOrDefault(c2 => c2.IsActive && c2.ISOCountryCode == el2.Country)
                                                       let s =
                                                   ProxylessContext.States.FirstOrDefault(
                                                       s2 => s2.IsActive && s2.ISOStateCode == el2.State && s2.FKCountry == c.PKID)
                                                   select new EnterpriseLocationModel
                        {
                            BingId = el2.BingId,
                            DistanceInMeters = el2.Coordinates.Distance(hotelPoint),
                            HourType = el2.HourType,
                            LocalHours = el2.Hours,
                            LocalHoursLanguage = !string.IsNullOrEmpty(el2.HoursLanguage) ? el2.HoursLanguage : nativeLanguage,
                            LocalHoursXml = el2.LocalizedHours,
                            Location = new LocationModel
                            {
                                Address1 = el2.Address1,
                                Address2 = el2.Address2,
                                City = el2.City,
                                Country = c,
                                Latitude = el2.Latitude,
                                Longitude = el2.Longitude,
                                PostalCode = el2.PostalCode,
                                State = s
                            },
                            Phone = el2.Phone,
                            PhoneISOCountryCode = el2.PhoneISOCountryCode,
                            PKID = el2.PKID,
                            Recommended = hboelm.Any(hboelm2 => hboelm2.FKEnterpriseLocation == el2.PKID)
                        }),
                        LocalDescription = e.Description,
                        LocalDescriptionLanguage =
                            e.DescriptionLanguage != null && e.DescriptionLanguage != string.Empty
                                                                                                ? e.DescriptionLanguage
                                                                                                : nativeLanguage,
                        LocalDescriptionXml = e.LocalizedDescription,
                        Name = e.Name,
                        PKID = e.PKID,
                        Recommended = hboem.Any() && !hboelm.Any()
                    },
                    EnterpriseImages = eim.Select(eim2 => eim2.Image),
                    HCMImage = fhcm.Image,
                })).FirstOrDefault();

                if (item != null && item.Enterprise != null)
                {
                    if (item.EnterpriseImages != null)
                    {
                        foreach (var customImage in item.EnterpriseImages)
                        {
                            ((List <ImageModel>)item.Enterprise.Images).Add(new ImageModel(customImage));
                        }
                    }

                    if (item.CMImage != null)
                    {
                        item.Enterprise.ListItemImage = new ImageModel(item.CMImage);
                    }

                    if (item.HCMImage != null)
                    {
                        item.Enterprise.ListItemImage = new ImageModel(item.HCMImage);
                    }

                    if (item.ECMImage != null)
                    {
                        item.Enterprise.ListItemImage = new ImageModel(item.ECMImage);
                    }

                    ((List <ImageModel>)item.Enterprise.Images).Insert(0, item.Enterprise.ListItemImage);

                    item.Enterprise.Description = Localization.GetLocalizedText(item.Enterprise.LocalDescription,
                                                                                item.Enterprise.LocalDescriptionXml, item.Enterprise.LocalDescriptionLanguage, nativeLanguage);
                    item.Enterprise.EnterpriseLocations.ForEach(
                        el => el.Hours = Localization.GetLocalizedText(el.LocalHours, el.LocalHoursXml, el.LocalHoursLanguage, nativeLanguage));

                    enterprise = item.Enterprise;
                }
            }

            return(enterprise);
        }