static int ComputeAccessCapacity(Guid userId) { var accountCapacity = 0; BCT.Execute(d => { var boards = d.BulletinDb.Boards.ToArray(); // Сколько объявлений можно повесить на текущие аккаунты foreach (var board in boards) { var needPlaces = defaultCapacity; var boardAccesses = d.BulletinDb.Accesses.Where(q => !q.HasBlocked).Where(q => q.UserId == userId && q.BoardId == board.Id && (q.State == (int)FessooFramework.Objects.Data.DefaultState.Enable)).OrderBy(q => q.LastPublication).ToArray(); foreach (var access in boardAccesses) { var occupiedPlaces = d.BulletinDb.BulletinInstances.Count(q => q.BoardId == board.Id && q.AccessId == access.Id); if (occupiedPlaces < needPlaces) { accountCapacity += needPlaces - occupiedPlaces; } else if (needPlaces >= occupiedPlaces && !access.HasBlocked) { access.HasBlocked = true; access.StateEnum = FessooFramework.Objects.Data.DefaultState.Created; } } d.SaveChanges(); } }); return(accountCapacity); }
static IEnumerable <Bulletin> GetBulletinsForPublication(Guid userId) { var result = Enumerable.Empty <Bulletin>(); BCT.Execute(d => { var bulletins = d.BulletinDb.Bulletins.Where(q => q.UserId == userId).ToArray(); //Определяем опубликованные инстанции var bulletinIds = bulletins.Select(q => q.Id); var publicatedInstances = d.BulletinDb.BulletinInstances.Where(q => q.Url != null && bulletinIds.Any(qq => qq == q.BulletinId)).ToArray().Where(q => q.CreateDate.Date == DateTime.Today); //Определяем неопубликованные инстанции, которые в процесс публикации var unpublicatedInstances = d.BulletinDb.BulletinInstances.Where(q => q.Url == null && bulletinIds.Any(qq => qq == q.BulletinId)).ToArray().Where(q => q.CreateDate.Date == DateTime.Today); var unpublicatedInstanceIds = unpublicatedInstances.Select(q => q.Id); var instanceToPublicationIds = d.TempDB.Tasks.Where(q => q.Command == (int)TaskCommand.InstancePublication && q.State == 0 && unpublicatedInstanceIds.Any(qq => qq == q.InstanceId)).Select(q => q.InstanceId).ToArray(); var instancesToPublication = unpublicatedInstances.Where(q => instanceToPublicationIds.Any(qq => qq == q.Id)).ToArray(); // Пропускаем уже опубликованные или в стадии публикации буллетины var skippedBulletinIds = publicatedInstances.Concat(instancesToPublication).Select(q => q.BulletinId); result = bulletins.Where(q => skippedBulletinIds.All(qq => qq != q.Id)).ToArray(); }); return(result); }
///------------------------------------------------------------------------------------------------- /// <summary> Получает свободный доступ к борде для пользователя из инстанции буллетина </summary> /// /// <remarks> SV Milovanov, 12.02.2018. </remarks> /// /// <param name="userId"> Identifier for the user. </param> /// <param name="boardId"> Identifier for the board. </param> /// /// <returns> The free access. </returns> ///------------------------------------------------------------------------------------------------- public static AccessCache GetFreeAccess(Guid instanceId) { AccessCache result = null; BCT.Execute(d => { var dbInstance = d.BulletinDb.BulletinInstances.FirstOrDefault(q => q.Id == instanceId); var dbBoard = d.BulletinDb.Boards.FirstOrDefault(q => q.Id == dbInstance.BoardId); var boardId = dbBoard.Id; var dbBulletin = d.BulletinDb.Bulletins.FirstOrDefault(q => q.Id == dbInstance.BulletinId); var userId = dbBulletin.UserId; var accessId = dbInstance.AccessId; Access access; if (accessId == Guid.Empty) { access = d.BulletinDb.Accesses.FirstOrDefault(q => q.UserId == userId && q.BoardId == boardId); accessId = access.Id; } else { access = d.BulletinDb.Accesses.FirstOrDefault(q => q.Id == accessId); } result = new AccessCache { //Id = access.Id, Login = access.Login, Password = access.Password, BoardId = boardId }; }); return(result); }
static bool SendEmail(Email email) { var result = false; BCT.Execute((data) => { var mail = new MailMessage { IsBodyHtml = true, Subject = email.Title, Body = email.Body, From = new System.Net.Mail.MailAddress(senderEmail, senderName) }; using (var client = new System.Net.Mail.SmtpClient { Host = senderHost, Port = senderPort, EnableSsl = true, Credentials = new NetworkCredential(senderEmail, senderPassword), DeliveryMethod = SmtpDeliveryMethod.Network }) { mail.To.Add(email.Destination); client.Send(mail); ConsoleHelper.SendMessage("SendStatistics => Письмо отправлено"); } result = true; }); return(result); }
public static IEnumerable <Task> All() { var result = Enumerable.Empty <Task>(); BCT.Execute(d => { result = d.TempDB.Tasks.ToArray(); }); return(result); }
public static void GetAccessStatistics(Access access) { BCT.Execute(d => { TaskHelper.CreateAccessStatistics(access); }); }
/// <summary> /// Запускает задачи по сбору статистики для пользователя /// </summary> /// <param name="userId"></param> public static bool RunUserStatisticsTask(string userLogin) { var result = false; BCT.Execute(d => { var user = d.MainDb.UserAccesses.FirstOrDefault(q => q.Login == userLogin); if (user == null) { return; } var userId = user.Id; // Создаем задачи на сбор статистики с аккаунтов var accesses = d.BulletinDb.Accesses.Where(q => q.UserId == userId && q.State != (int)FessooFramework.Objects.Data.DefaultState.Created).ToArray(); foreach (var access in accesses) { TaskHelper.CreateAccessStatistics(access); } // Создаем задачи на сбор статистики с инстанций var bulletinIds = d.BulletinDb.Bulletins.Where(q => q.UserId == userId).Select(q => q.Id).ToArray(); var instances = d.BulletinDb.BulletinInstances.Where(q => bulletinIds.Contains(q.BulletinId) && q.Url != null).ToArray(); foreach (var instance in instances) { TaskHelper.CreateInstanceStatistics(userId, instance); } result = true; }); return(result); }
/// <summary> /// Собирает статистику по переадресации /// </summary> /// <param name="userId"></param> public static void GetCallsStatistics(Guid userId) { BCT.Execute(d => { var request = WebRequest.Create("https://onlinesim.ru/api/forwardingList.php?apikey=f02eb880d7930c4a6eec0b39bb893e36"); request.Timeout = 5000; request.ContentType = "application/json"; using (var response = (HttpWebResponse)request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { var json = reader.ReadToEnd(); var apiData = JObject.Parse(json); var array = apiData["forwardingList"]["data"].Children().ToList(); foreach (var a in array) { var call = new Call(); call.UserId = userId; call.VirtualNumber = a["number"].Value <string>(); call.ForwardNumber = a["forward_number"].Children().FirstOrDefault().Value <string>(); call.CallDate = a["created_at"].Value <DateTime>(); call.StateEnum = FessooFramework.Objects.Data.DefaultState.Created; } d.SaveChanges(); } } }); }
public static ProductCount GetProductStatisticsByPeriod(Guid userId, DateTime from, DateTime until) { var result = default(ProductCount); BCT.Execute(d => { var bulletins = d.BulletinDb.Bulletins.Where(q => q.UserId == userId).ToArray(); var bulletinIds = bulletins.Select(q => q.Id); var instances = d.BulletinDb.BulletinInstances.Where(q => q.Url != null && q.ActivationDate != null && bulletinIds.Any(qq => qq == q.BulletinId) && q.ActivationDate >= from && q.ActivationDate <= until).ToArray(); var bulletinCount = instances.GroupBy(q => q.BulletinId).Count(); var instanceCount = instances.Count(); result = new ProductCount { BulletinCount = bulletinCount, InstanceCount = instanceCount }; }); return(result); }
static void CreateNewAccesses(Guid userId, int needAccounts) { BCT.Execute(d => { var forwardingEnabled = false; var userSettings = d.BulletinDb.UserSettings.FirstOrDefault(q => q.UserId == userId); if (userSettings != null && userSettings.EnableForwarding) { forwardingEnabled = true; } var accessInTasks = d.TempDB.Tasks.Where(q => q.State == 0 && q.UserId == userId && q.Command == (int)TaskCommand.Registration).Select(q => q.AccessId).ToArray(); var accessCountInTasks = d.BulletinDb.Accesses.Count(q => q.UserId == userId && accessInTasks.Any(qq => qq == q.Id)); needAccounts -= accessCountInTasks; if (needAccounts <= 0) { return; } for (var i = 0; i < needAccounts; i++) { AccessTaskHelper.CreateAccess(userId, forwardingEnabled); } }); }
public override IEnumerable <EntityObject> CustomCollectionLoad(string code, string sessionUID = "", string hashUID = "", IEnumerable <EntityObject> obj = null, IEnumerable <Guid> id = null) { var result = Enumerable.Empty <EntityObject>(); BCT.Execute(c => { //Пока не заморачивался - передаётся базовый объект и требуется привести к типу var entities = Enumerable.Empty <BulletinTemplate>(); if (obj.Any()) { entities = obj.Select(q => (BulletinTemplate)q).ToArray(); } switch (code) { case "All": result = TemplateHelper.All().Where(q => q.IsIndividualSeller).OrderByDescending(q => q.Count).Take(100); break; case "MarkAsUsed": result = new[] { TemplateHelper.MarkAsUsed(entities.FirstOrDefault()) }; break; } }); return(result); }
public static IEnumerable <BulletinInstance> All() { var result = Enumerable.Empty <BulletinInstance>(); BCT.Execute(d => { result = d.BulletinDb.BulletinInstances.ToArray(); }); return(result); }
public override IEnumerable <TDataModel> _CacheSave <TDataModel>(IEnumerable <TDataModel> objs) { var result = Enumerable.Empty <TDataModel>(); BCT.Execute(d => { var access = objs.FirstOrDefault() as Access; var dbAccess = d.BulletinDb.Accesses.FirstOrDefault(q => q.Login == access.Login && q.Password == access.Password); if (dbAccess == null) { access.BoardId = d.BulletinDb.Boards.FirstOrDefault().Id; access.UserId = d.UserId; access.StateEnum = DefaultState.Created; d.SaveChanges(); } else { dbAccess.Login = access.Login; dbAccess.Password = access.Password; dbAccess.Views = access.Views; dbAccess.Calls = access.Calls; dbAccess.Messages = access.Messages; dbAccess.LastMessage = access.LastMessage; dbAccess.IsForwarding = access.IsForwarding; d.SaveChanges(); } result = new TDataModel[] { access as TDataModel }; }); return(result); }
public static BulletinPackage ToCache(BulletinInstance obj) { BulletinPackage result = null; BCT.Execute(d => { var groupSignature = GroupHelper.GetGroupSignature(obj.Id); var access = AccessHelper.GetFreeAccess(obj.Id); var valueFields = ValueFieldHelper.GetValueFields(obj.Id); var accessFields = AccessFieldHelper.GetAccessFields(obj.Id); var state = obj.State; result = new BulletinPackage { BulletinId = obj.BulletinId, BulletinInstanceId = obj.Id, Url = obj.Url, Signature = groupSignature, Access = access, ValueFields = valueFields, AccessFields = accessFields, State = state, Title = obj.Url, }; }); return(result); }
public override IEnumerable <EntityObject> _CollectionObjectLoad() { var workStates = new[] { (int)BulletinInstanceState.WaitPublication, (int)BulletinInstanceState.Unchecked, (int)BulletinInstanceState.OnModeration, (int)BulletinInstanceState.WaitRepublication, }; var result = Enumerable.Empty <EntityObject>(); BCT.Execute(c => { var id = c._SessionInfo.HashUID; var id2 = c._SessionInfo.SessionUID; if (id == "Engine") { result = c.BulletinDb.BulletinInstances .Where(q => workStates.Contains(q.State)).Take(1).ToArray(); } else { result = base._CollectionObjectLoad(); } }); return(result); }
static Bulletin AddAvitoByTemplate(Guid userId, BulletinTemplate template, string brand, string model, string modifier, string price, string groupHash) { var result = default(Bulletin); BCT.Execute(d => { var group = BCT.Context.BulletinDb.Groups.FirstOrDefault(q => q.Hash == groupHash); if (group == null) { ConsoleHelper.SendMessage($"AvitoPublicateBulletin => Группа с хэшем:{groupHash} не найдена"); return; } result = new Bulletin(); result.Brand = brand; result.Model = model; result.Modifier = modifier; result.GroupId = group.Id; result.Title = template.Title; result.Description = template.Description; result.Price = price; result.Images = template.Images; result.UserId = userId; result.StateEnum = BulletinState.Created; d.SaveChanges(); }); return(result); }
/// <summary> /// Перерасчитывает статистику для пользователя /// </summary> /// <param name="userId"></param> public static void ComputeUserStatistics(Guid userId) { BCT.Execute(d => { var bulletins = d.BulletinDb.Bulletins.Where(q => q.UserId == userId).ToArray(); foreach (var bulletin in bulletins) { var bulletinViews = d.BulletinDb.BulletinInstances.Count(q => q.BulletinId == bulletin.Id); bulletin.Views = bulletinViews; bulletin.StateEnum = bulletin.StateEnum; } d.SaveChanges(); var accesses = d.BulletinDb.Accesses.Where(q => q.UserId == userId && q.StateEnum != FessooFramework.Objects.Data.DefaultState.Disable).ToArray(); var totalViews = accesses.Sum(q => q.Views); var totalMessages = accesses.Sum(q => q.Messages); var totalCalls = accesses.Sum(q => q.Calls); var user = d.BulletinDb.UserStatistics.FirstOrDefault(q => q.UserId == userId); if (user == null) { user = new BulletinHub.Models.UserStatistics(); user.StateEnum = FessooFramework.Objects.Data.DefaultState.Created; } user.TotalViews = totalViews; user.TotalMessages = totalMessages; user.TotalCalls = totalCalls; d.SaveChanges(); }); }
///------------------------------------------------------------------------------------------------- /// <summary> Создает сигнатуру группы из хэша </summary> /// /// <remarks> SV Milovanov, 12.02.2018. </remarks> /// /// <param name="hash"> The hash. </param> /// /// <returns> The group signature. </returns> ///------------------------------------------------------------------------------------------------- public static GroupSignature GetGroupSignature(string hash) { GroupSignature result = null; BCT.Execute(data => { var group = data.BulletinDb.Groups.FirstOrDefault(q => q.Hash == hash); if (group != null) { var chosenCategories = new List <string>(); var groupedCategories = data.BulletinDb.GroupedCategories.Where(q => q.GroupId == group.Id).Select(q => q.CategoryId).ToArray(); var categories = data.BulletinDb.CategoryTemplates.Where(q => groupedCategories.Contains(q.Id)).ToArray(); var topCategory = categories.FirstOrDefault(q => q.ParentId == Guid.Empty); var nothandledCategories = categories.Where(q => q.Id != topCategory.Id).ToList(); var parentId = topCategory.Id; chosenCategories.Add(topCategory.Name); while (nothandledCategories.Count > 0) { for (var i = 0; i < nothandledCategories.Count; i++) { if (nothandledCategories[i].ParentId == parentId) { parentId = nothandledCategories[i].Id; chosenCategories.Add(nothandledCategories[i].Name); nothandledCategories.RemoveAt(i); break; } } } result = new GroupSignature(chosenCategories.ToArray()); } }); return(result); }
public static void GenerationClearData() { Console.WriteLine($"GenerationClearData execute start"); BCT.Execute(c => { //1. Проверка аккаунтов - на авторизацию и активность foreach (var access in c.BulletinDb.Accesses.Where(q => !q.HasBlocked).ToArray()) { access.GenerationCheckNext = null; access.StateEnum = access.StateEnum; } c.SaveChanges(); //2. Публикация инстанций объявлений foreach (var bulletin in c.BulletinDb.Bulletins.ToArray()) { bulletin.GenerationCheckNext = null; bulletin.StateEnum = bulletin.StateEnum; } c.SaveChanges(); //0. Сбор данных с аккаунта - сообщения и буллетины - //0. Редактирование существующих инстанций //0. Сбор аналитики по инстанциям //Clear tasks c.TempDB.Tasks.RemoveRange(c.TempDB.Tasks.ToArray()); c.SaveChanges(); }); Console.WriteLine($"GenerationClearData execute complete"); }
public static void ActivateAccess(Access access) { BCT.Execute(d => { TaskHelper.CreateActivateAccess(access); }); }
public static void GetInstanceStatistics(BulletinInstance instance) { BCT.Execute(d => { var bulletin = d.BulletinDb.Bulletins.FirstOrDefault(q => q.Id == instance.BulletinId); TaskHelper.CreateInstanceStatistics(bulletin.UserId, instance); }); }
public override ServiceMessage Execute(ServiceMessage data) { var result = default(ServiceMessage); BCT.Execute(c => { result = _Execute(data); }); return(result); }
public static BulletinTemplate MarkAsUsed(BulletinTemplate template) { BCT.Execute(c => { template.StateEnum = DefaultState.Disable; c.SaveChanges(); }); return(template); }
public static UserSettingsCache ToCache(UserSettings obj) { UserSettingsCache result = null; BCT.Execute(d => { }); return(result); }
static void CreatePublicationTasks(Bulletin bulletin, Guid templateId) { BCT.Execute(d => { var tasks = d.TempDB.Tasks.Where(q => (q.State == (int)BulletinHub.Entity.Data.TaskState.Created || q.State == (int)BulletinHub.Entity.Data.TaskState.Enabled) && q.BulletinId == bulletin.Id && q.Command == (int)BulletinHub.Entity.Data.TaskCommand.InstancePublication).ToArray(); if (tasks != null && tasks.Any()) { TaskHelper.Remove(tasks); } var instances = BulletinHub.Helpers.BulletinHelper.CreateInstance(bulletin, templateId); if (instances.Any()) { bulletin.SetGenerationCheck(); var datePublish = DateTime.Now.AddDays(1); var hasPublication = false; foreach (var instance in instances) { var access = BulletinEngine.Helpers.AccessHelper.GetFreeAccess(bulletin.UserId, instance.BoardId, instance.BulletinId); if (access == null) { ConsoleHelper.SendMessage($"AvitoPublicateBulletin => Не найден свободный доступ для буллетина {bulletin.Id}"); continue; } if (accessPublicationTime.ContainsKey(access.Id)) { var lastTime = accessPublicationTime[access.Id]; datePublish = lastTime.AddMinutes(30); accessPublicationTime[access.Id] = datePublish; } else { accessPublicationTime.Add(access.Id, datePublish); } instance.AccessId = access.Id; instance.StateEnum = instance.StateEnum; d.SaveChanges(); TaskHelper.CreateInstancePublication(bulletin.UserId, instance, datePublish); //var now = DateTime.Now; //var activationDate = now.Date.AddDays(1); //activationDate.Date.Subtract(now); //activationDate = activationDate.AddHours(3); //TaskHelper.CreateActivateInstance(bulletin.UserId, instance, activationDate); hasPublication = true; } if (hasPublication) { bulletin.DatePublication = datePublish; bulletin.StateEnum = bulletin.StateEnum; d.SaveChanges(); } } }); }
public static IEnumerable <BulletinTemplate> All() { var result = Enumerable.Empty <BulletinTemplate>(); BCT.Execute(c => { result = c.TempDB.BulletinTemplate.Where(q => q.State != (int)DefaultState.Disable).ToArray(); }); return(result); }
/// <summary> /// Создаем буллетину по шаблону, запускаем задачи на публикацию и активацию /// </summary> /// <param name="userLogin"></param> /// <param name="title"></param> public static void AutoPublicateBulletin(string userLogin, string brand, string model, string modifier, string price) { BCT.Execute(d => { //var bulletin = CreateBulletin(userLogin, brand, model, modifier, price); //if (bulletin == null) return; ////Запускаем задачи на публикацию и активацию //CreatePublicationTasks(bulletin); }); }
public static Bulletin AddAvito(Bulletin model) { BCT.Execute(c => { model.UserId = c.UserId; model.StateEnum = BulletinEngine.Entity.Data.BulletinState.Created; c.SaveChanges(); }); return(model); }
public static IEnumerable <Access> All() { var result = Enumerable.Empty <Access>(); BCT.Execute(c => { result = c.BulletinDb.Accesses.Where(q => q.UserId == c.UserId).ToArray(); }); return(result); }
public static Bulletin Edit(Bulletin bulletin) { BCT.Execute(d => { var instance = d.BulletinDb.BulletinInstances.FirstOrDefault(q => q.BulletinId == bulletin.Id); instance.StateEnum = BulletinInstanceState.Edited; d.SaveChanges(); }); return(bulletin); }