Exemplo n.º 1
0
 public void SetTask(EntityTask task, bool priorityCheck = true)
 {
     if (CurrentTask != null)
     {
         if (priorityCheck)
         {
             if (task.Priority > CurrentTask.Priority)
             {
                 CurrentTask.OnTaskEnd();
                 CurrentTask = task;
                 Entity.GetLoadedEntity()?.SpeechBubble.PushMessage("New task has higher priority : " + CurrentTask);
             }
         }
         else
         {
             CurrentTask.OnTaskEnd();
             CurrentTask = task;
             Entity.GetLoadedEntity()?.SpeechBubble.PushMessage("New task, skip priority check : " + CurrentTask);
         }
     }
     else
     {
         CurrentTask = task;
         Entity.GetLoadedEntity()?.SpeechBubble.PushMessage("No task, new task : " + CurrentTask);
     }
 }
Exemplo n.º 2
0
 private static void CheckTaskCronExpress(EntityTask entityTask)
 {
     if (!entityTask.CronExpress.IsValidateCronExpress())
     {
         throw new ArgumentException("Cron表达式不正确");
     }
 }
Exemplo n.º 3
0
        public async Task <EntityTask> AddTaskAsync(EntityTask entityTask)
        {
            CheckTaskCronExpress(entityTask);

            var taskRep     = GetRepositoryInstance <TableTask>();
            var checkResult = await taskRep.FindAsync(x => x.Name == entityTask.Name);

            if (checkResult != null)
            {
                throw new ArgumentException("该任务已存在,不能重复添加");
            }

            var groupInfo = await GroupService.GetGroupAsync(entityTask.GroupId);

            if (groupInfo == null)
            {
                throw new ArgumentException("该任务所属类别不存在");
            }

            var model  = entityTask.MapTo <TableTask>();
            var result = await taskRep.InsertAsync(model);

            if (!result)
            {
                throw new ArgumentException("任务新增失败");
            }
            entityTask.Id = model.Id;
            return(entityTask);
        }
Exemplo n.º 4
0
 public virtual void Tick()
 {
     Debug.BeginDeepProfile("internal_ai_tick");
     //Check if we need a new task
     if (CurrentTask == null || CurrentTask.IsComplete || CurrentTask.ShouldTaskEnd() || WorldManager.Instance.Time.TimeChange)
     {
         //if so, choose our idle task
         EntityTask task = ChooseIdleTask();
         if (task != null)
         {
             SetTask(task);
         }
     }
     if (CurrentTask != null)
     {
         if (CurrentTask.IsComplete || CurrentTask.ShouldTaskEnd() || WorldManager.Instance.Time.TimeChange)
         {
             Entity.GetLoadedEntity().SpeechBubble.PushMessage("Task " + CurrentTask + " complete");
             CurrentTask = null;
             EntityTask task = ChooseIdleTask();
             if (task != null)
             {
                 SetTask(task);
             }
         }
         else
         {
             CurrentTask.Tick();
         }
     }
     Debug.EndDeepProfile("internal_ai_tick");
 }
Exemplo n.º 5
0
 public void AddTask(EntityTask task)
 {
     using (MyContext db = new MyContext())
     {
         db.Tasks.Add(task);
         db.SaveChanges();
     }
 }
Exemplo n.º 6
0
 protected override void Context()
 {
     _applicationController = A.Fake <IApplicationController>();
     _executionContext      = A.Fake <IExecutionContext>();
     _entity          = A.Fake <IEntity>();
     _renamePresenter = A.Fake <IRenameObjectPresenter>();
     A.CallTo(() => _applicationController.Start <IRenameObjectPresenter>()).Returns(_renamePresenter);
     sut = new EntityTask(_applicationController, _executionContext);
 }
Exemplo n.º 7
0
        public async Task <ResponseModel> EditTaskAsync([FromBody] EntityTask entityTask)
        {
            if (entityTask.Id <= 0)
            {
                return(Fail(ErrorCodeEnum.ParamIsNullArgument));
            }
            var result = await TaskService.EditTaskAsync(entityTask);

            return(Success(result));
        }
 public HttpResponseMessage Put([FromBody] EntityTask task, int ID)
 {
     try
     {
         obj.UpdateTask(task, ID);
         return(Request.CreateResponse(HttpStatusCode.OK, "Record updated successfully"));
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
     }
 }
Exemplo n.º 9
0
    public void OnEntityLoad()
    {
        if (Entity == null)
        {
            return;
        }
        EntityTask task = ChooseIdleTask();

        if (task != null)
        {
            SetTask(task);
        }
    }
 public HttpResponseMessage POST([FromBody] EntityTask task)
 {
     try
     {
         obj.AddTask(task);
         var message = Request.CreateResponse(HttpStatusCode.Created, task);
         message.Headers.Location = new Uri(Request.RequestUri + task.taskId.ToString());
         return(message);
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
     }
 }
Exemplo n.º 11
0
 public virtual void Tick()
 {
     Debug.BeginDeepProfile("internal_ai_tick");
     //Check if we need a new task
     if (CurrentTask == null || CurrentTask.IsComplete)
     {
         //if so, choose our idle task
         CurrentTask = ChooseIdleTask();
     }
     if (CurrentTask != null)
     {
         CurrentTask.Tick();
     }
     Debug.EndDeepProfile("internal_ai_tick");
 }
        protected override void Context()
        {
            _applicationController = A.Fake <IApplicationController>();
            _executionContext      = A.Fake <IExecutionContext>();
            _entity = A.Fake <IEntity>();
            _renameObjectFactory = A.Fake <IRenameObjectDTOFactory>();
            _renamePresenter     = A.Fake <IRenameObjectPresenter>();
            A.CallTo(() => _applicationController.Start <IRenameObjectPresenter>()).Returns(_renamePresenter);
            sut = new EntityTask(_applicationController, _executionContext, _renameObjectFactory);

            _renameDTO = new RenameObjectDTO(_entity.Name);
            _renameDTO.AddUsedNames(new[] { "A", "B" });
            A.CallTo(() => _renameObjectFactory.CreateFor(_entity)).Returns(_renameDTO);
            A.CallTo(() => _executionContext.TypeFor <IObjectBase>(_entity)).Returns(ENT_TYPE);
        }
Exemplo n.º 13
0
        public void UpdateTask()
        {
            EntityTask       entTask       = new EntityTask();
            EntityUser       entUser       = new EntityUser();
            EntityProject    entProject    = new EntityProject();
            EntityParentTask entParentTask = new EntityParentTask();

            entTask.taskId      = 1;
            entTask.task        = "Updated Task";
            entTask.startDate   = DateTime.Now;
            entTask.endDate     = DateTime.Now;
            entTask.priority    = 1;
            entTask.isCompleted = false;
            entTask.user        = entUser;
            entTask.project     = entProject;
            entTask.parentTask  = entParentTask;

            BLProjectManager.UpdateTask(entTask, 1);
            NUnit.Framework.Assert.IsNotEmpty("1");
            NUnit.Framework.Assert.IsNotNull("1");
        }
Exemplo n.º 14
0
 public void SetTask(EntityTask task, bool priorityCheck = true)
 {
     if (CurrentTask != null)
     {
         if (priorityCheck)
         {
             if (task.Priority > CurrentTask.Priority)
             {
                 CurrentTask.OnTaskEnd();
                 CurrentTask = task;
             }
         }
         else
         {
             CurrentTask.OnTaskEnd();
             CurrentTask = task;
         }
     }
     else
     {
         CurrentTask = task;
     }
 }
Exemplo n.º 15
0
 public bool UpdateTask(EntityTask task, int ID)
 {
     using (MyContext db = new MyContext())
     {
         var entity = db.Tasks.FirstOrDefault(e => e.taskId == ID);
         if (entity == null)
         {
             return(false);
         }
         else
         {
             entity.task        = task.task;
             entity.parentTask  = task.parentTask;
             entity.priority    = task.priority;
             entity.startDate   = task.startDate;
             entity.endDate     = task.endDate;
             entity.isCompleted = task.isCompleted;
             entity.project     = task.project;
             db.SaveChanges();
             return(true);
         }
     }
 }
Exemplo n.º 16
0
        public async Task <EntityTask> EditTaskAsync(EntityTask entityTask)
        {
            CheckTaskCronExpress(entityTask);

            var taskRep     = GetRepositoryInstance <TableTask>();
            var checkResult = await taskRep.FindAsync(x => x.Name == entityTask.Name && x.Id != entityTask.Id);

            if (checkResult != null)
            {
                throw new ArgumentException("任务名称重复");
            }

            var groupInfo = await GroupService.GetGroupAsync(entityTask.GroupId);

            if (groupInfo == null)
            {
                throw new ArgumentException("该任务所属类别不存在");
            }
            var model = entityTask.MapTo <TableTask>();

            taskRep.Update(model);

            return(entityTask);
        }
Exemplo n.º 17
0
        public DataResponse Update(EntityTask entity)
        {
            var response = new DataResponse <EntityTask>();

            try
            {
                base.DBInit();

                entity.UpdatedOn = DateTime.UtcNow;

                #region Prepare model
                var model = DBEntity.Tasks.FirstOrDefault(a => a.Id == entity.TaskId);

                model.RequestedBy       = entity.CurrentUserId;
                model.Subject           = entity.Subject;
                model.PracticeId        = entity.PracticeId;
                model.TaskDescription   = entity.TaskDescription;
                model.PriorityTypeId    = entity.PriorityTypeId;
                model.TaskRequestTypeId = entity.TaskRequestTypeId;
                model.TargetDate        = entity.TargetDate;
                model.ClosingDate       = entity.ClosingDate;
                model.UpdatedOn         = entity.UpdatedOn;
                model.UpdatedBy         = entity.UpdatedBy;

                List <EntityNotification> notificationlist = new List <EntityNotification>();
                if (model.Status != entity.StatusId)
                {
                    model.Status = entity.StatusId;
                }
                //    notificationlist = model.TaskUsers.Where(a => a.UserId != entity.CurrentUserId).Select(a => new EntityNotification
                //    {
                //        UserId = a.UserId,
                //        Message = NotificationMessages.TaskStatusUpdateUserNotification
                //    }).ToList();

                //    if (model.CreatedBy != entity.CurrentUserId)
                //        notificationlist.Add(new EntityNotification
                //        {
                //            UserId = model.CreatedBy,
                //            Message = NotificationMessages.TaskStatusUpdateUserNotification
                //        });
                //}
                if (entity.AlertDate.HasValue)
                {
                    var modelItem = model.TaskUserAlerts.FirstOrDefault(a => a.UserId == entity.CurrentUserId);
                    if (modelItem != null)
                    {
                        DBEntity.Entry(modelItem).State = EntityState.Modified;

                        modelItem.AlertDate = entity.AlertDate.Value;
                        modelItem.Message   = entity.AlertMessage;
                        modelItem.UpdatedOn = entity.UpdatedOn;
                        modelItem.UpdatedBy = entity.UpdatedBy;
                    }
                    else
                    {
                        var taskUserAlerts = new Database.TaskUserAlert
                        {
                            TaskId    = model.Id,
                            UserId    = entity.CurrentUserId,
                            AlertDate = entity.AlertDate.Value,
                            Message   = entity.AlertMessage,
                            CreatedOn = entity.UpdatedOn.Value,
                            CreatedBy = entity.UpdatedBy.Value,
                        };
                        model.TaskUserAlerts.Add(taskUserAlerts);
                    }
                }

                //delete all previous assignments
                DBEntity.TaskUsers.Where(a => a.TaskId == model.Id).Delete();

                if (entity.AssignedTo > 0)
                {
                    model.TaskUsers.Add(new Database.TaskUser
                    {
                        UserId    = entity.AssignedTo,
                        IsWatcher = false,
                        CreatedOn = entity.UpdatedOn.Value,
                        CreatedBy = entity.UpdatedBy.Value
                    });

                    //    if (entity.CurrentUserId != entity.AssignedTo)
                    notificationlist.Add(new EntityNotification
                    {
                        UserId  = entity.AssignedTo,
                        Message = NotificationMessages.TaskUpdateUserNotification
                    });
                }

                if (entity.Watchers != null)
                {
                    foreach (var user in entity.Watchers)
                    {
                        model.TaskUsers.Add(new Database.TaskUser
                        {
                            UserId    = int.Parse(user),
                            IsWatcher = true,
                            CreatedOn = entity.UpdatedOn.Value,
                            CreatedBy = entity.UpdatedBy.Value
                        });

                        notificationlist.Add(new EntityNotification
                        {
                            UserId  = int.Parse(user),
                            Message = NotificationMessages.TaskUpdateUserNotification
                        });
                    }
                }

                notificationlist.Add(new EntityNotification
                {
                    UserId  = model.CreatedBy,
                    Message = NotificationMessages.TaskUpdateUserNotification
                });
                #endregion

                #region Delete removed files from db on update

                IEnumerable <int> incomingFileLists = null;
                IEnumerable <Database.TaskAttachment> existingFiles = null;

                if (entity.FilesList != null && entity.FilesList.Count() > 0)
                {
                    incomingFileLists = entity.FilesList.Select(a => a.Id);
                }
                if (incomingFileLists != null && incomingFileLists.Count() > 0)
                {
                    existingFiles = model.TaskAttachments.Where(a => !incomingFileLists.Contains(a.Id));
                }
                else
                {
                    existingFiles = model.TaskAttachments;
                }

                if (existingFiles.Count() > 0)
                {
                    foreach (var item in existingFiles)
                    {
                        item.IsActive = false;
                    }
                }

                #endregion

                if (base.DBSaveUpdate(model) > 0)
                {
                    #region Save Notification Data

                    new RepositoryNotification().Save(notificationlist, entity.CurrentUserId, model.Id, (int)NotificationTargetType.Task, (int)NotificationType.Normal, model.UpdatedBy.Value, entity.CreatedByName, model.UpdatedOn.Value, model.Subject);

                    #endregion

                    #region Save to Log
                    var objTask = new Database.Task
                    {
                        Id                = model.Id,
                        RequestedBy       = entity.CurrentUserId,
                        Subject           = model.Subject,
                        TaskDescription   = model.TaskDescription,
                        BusinessId        = model.BusinessId,
                        TaskRequestTypeId = model.TaskRequestTypeId,
                        ReferenceNumber   = model.ReferenceNumber,
                        PracticeId        = model.PracticeId,
                        PriorityTypeId    = model.PriorityTypeId,
                        TargetDate        = model.TargetDate,
                        ClosingDate       = model.ClosingDate,
                        IsActive          = model.IsActive,
                        Status            = model.Status,
                        TaskUsers         = model.TaskUsers,
                        TaskUserAlerts    = model.TaskUserAlerts,
                        User              = model.User,
                        CreatedOn         = model.UpdatedOn.Value,
                        CreatedBy         = model.UpdatedBy.Value
                    };

                    if (!SaveLog(objTask))
                    {
                        new Exception("Task log failed!  Task:" + entity.TaskId).Log();
                    }
                    #endregion

                    //return GetTaskById(model.Id, entity.CurrentUserId, entity.CurrentBusinessId);
                    return(new DataResponse {
                        Status = DataResponseStatus.OK, Id = model.Id
                    });
                }
                else
                {
                    response.CreateResponse(DataResponseStatus.InternalServerError);
                }
            }
            catch (Exception ex)
            {
                ex.Log();
            }
            finally
            {
                base.DBClose();
            }
            return(response);
        }
Exemplo n.º 18
0
        public DataResponse <EntityTask> Insert(EntityTask entity)
        {
            var response = new DataResponse <EntityTask>();

            try
            {
                base.DBInit();

                var model = new Database.Task
                {
                    RequestedBy       = entity.CurrentUserId,
                    Subject           = entity.Subject,
                    TaskDescription   = entity.TaskDescription,
                    BusinessId        = entity.CurrentBusinessId,
                    TaskRequestTypeId = entity.TaskRequestTypeId,
                    PracticeId        = entity.PracticeId,
                    PriorityTypeId    = entity.PriorityTypeId,
                    TargetDate        = entity.TargetDate,
                    ClosingDate       = entity.ClosingDate,
                    IsActive          = true,
                    Status            = (int)TaskStatuses.New,
                    CreatedOn         = entity.CreatedOn,
                    CreatedBy         = entity.CreatedBy,
                    UpdatedOn         = entity.UpdatedOn,
                    UpdatedBy         = entity.UpdatedBy
                };

                if (entity.AlertDate.HasValue)
                {
                    var taskUserAlerts = new List <Database.TaskUserAlert> {
                        new Database.TaskUserAlert
                        {
                            UserId    = entity.CurrentUserId,
                            AlertDate = entity.AlertDate.Value,
                            Message   = entity.AlertMessage,
                            CreatedOn = entity.CreatedOn,
                            CreatedBy = entity.CreatedBy,
                        }
                    };
                    model.TaskUserAlerts = taskUserAlerts;
                }
                var notificationlist = new List <EntityNotification>();

                if (entity.AssignedTo > 0)
                {
                    model.TaskUsers.Add(new Database.TaskUser
                    {
                        UserId    = entity.AssignedTo,
                        IsWatcher = false,
                        CreatedOn = entity.CreatedOn,
                        CreatedBy = entity.CreatedBy
                    });

                    notificationlist.Add(new EntityNotification
                    {
                        UserId  = entity.AssignedTo,
                        Message = NotificationMessages.TaskUserNotification
                    });
                }

                if (entity.Watchers != null)
                {
                    foreach (var user in entity.Watchers)
                    {
                        model.TaskUsers.Add(new Database.TaskUser
                        {
                            UserId    = int.Parse(user),
                            IsWatcher = true,
                            CreatedOn = entity.CreatedOn,
                            CreatedBy = entity.CreatedBy
                        });

                        notificationlist.Add(new EntityNotification
                        {
                            UserId  = int.Parse(user),
                            Message = NotificationMessages.TaskUserNotification
                        });
                    }
                }

                if (base.DBSave(model) > 0)
                {
                    #region Save Notification Data

                    new RepositoryNotification().Save(notificationlist, entity.CurrentUserId, model.Id, (int)NotificationTargetType.Task, (int)NotificationType.Normal, model.CreatedBy, entity.CreatedByName, model.CreatedOn, model.Subject);

                    #endregion

                    #region Save to Log

                    var objTask = new Database.Task
                    {
                        Id                = model.Id,
                        RequestedBy       = model.RequestedBy,
                        Subject           = model.Subject,
                        TaskDescription   = model.TaskDescription,
                        BusinessId        = model.BusinessId,
                        TaskRequestTypeId = model.TaskRequestTypeId,
                        ReferenceNumber   = model.ReferenceNumber,
                        PracticeId        = model.PracticeId,
                        PriorityTypeId    = model.PriorityTypeId,
                        TargetDate        = model.TargetDate,
                        ClosingDate       = model.ClosingDate,
                        IsActive          = model.IsActive,
                        Status            = model.Status,
                        TaskUsers         = model.TaskUsers,
                        TaskUserAlerts    = model.TaskUserAlerts,
                        User              = model.User,
                        CreatedOn         = model.CreatedOn,
                        CreatedBy         = model.CreatedBy
                    };

                    if (!SaveLog(objTask, "Created"))
                    {
                        new Exception("Task log failed!  Task:" + entity.TaskId).Log();
                    }

                    #endregion

                    return(GetTaskById(model.Id, entity.CurrentUserId, entity.CurrentBusinessId));
                }
                else
                {
                    response.CreateResponse(DataResponseStatus.InternalServerError);
                }
            }
            catch (Exception ex)
            {
                ex.Log();
            }
            finally
            {
                base.DBClose();
            }
            return(response);
        }
Exemplo n.º 19
0
    /// <summary>
    /// Called as a slow tick to update entities that aren't currently loaded.
    /// <br/> Used to update entities that are close to the player, but which are in different worlds. <br/>
    /// When the player is in the world, this consists of all entities in all subworlds who's entrances are in currently loaded chunks
    /// <br/>When the player is in a subworld, it is all the entities that were loaded previous to entering the subworld.
    /// <br/>Update allows entities to leave subworlds while they are not loaded (allowing pursuet).
    /// <br/>Also checks for the entities desired location (i.e, if they should be at work) and allows them to travel.
    /// </summary>
    public void UnloadedEntityTick()
    {
        Debug.Log("Unloaded update count: " + UnloadedUpdatableEntities.Count);
        int currentSubworldID = Subworld == null ? -1 : Subworld.SubworldID;

        //Iterate all entities
        foreach (int id in UnloadedUpdatableEntities)
        {
            //Get entity and its combat target
            Entity e = GetEntityFromID(id);

            Entity currentTarget = e.EntityAI.CombatAI.CurrentTarget;
            if (currentTarget != null)
            {
                Debug.Log(e + " is unloaded but has a target: " + currentTarget);
                Debug.Log(e + " attempting to follow " + currentTarget);
            }

            Subworld entWorld = e.GetSubworld();
            //Check if the current target is one the entity should be following
            if (currentTarget != null && currentTarget.CurrentSubworldID != e.CurrentSubworldID && currentTarget.IsLoaded)
            {
                if (entWorld != null)
                {
                    Debug.Log(e + " is leaving subworld, moving to subworld ID: " + "-1" + " pos:" + entWorld.ExternalEntrancePos);
                    //If we are currently in a subworld, then we assume we are attempting to leave the subworld (no nested sw)
                    MoveEntity(e, -1, entWorld.ExternalEntrancePos);
                }
                else
                {
                    entWorld = currentTarget.GetSubworld();
                    if (entWorld != null)
                    {
                        //If we are currently in a subworld, then we assume we are attempting to leave the subworld (no nested sw)
                        MoveEntity(e, entWorld.SubworldID, entWorld.InternalEntrancePos);
                    }
                }
            }
            else if (e is NPC)
            {
                //Get the NPC and its AI
                NPC            npc   = e as NPC;
                BasicNPCTaskAI npcAI = npc.EntityAI.TaskAI as BasicNPCTaskAI;

                if (!npcAI.HasTask || npcAI.CurrentTask.ShouldTaskEnd())
                {
                    //Check for a new task
                    EntityTask curTask = npcAI.ChooseIdleTask();
                    npcAI.SetTask(curTask);
                    if (curTask != null)
                    {
                        Debug.Log("HEREHEHREHERE");
                        //If the current task has a specified location
                        if (curTask.HasTaskLocation)
                        {
                            int taskWorld = curTask.Location.SubworldWorldID;
                            //Check if this entities task is in the currently loaded world.
                            //if this is the case, we should teleport the entity to this place
                            if (taskWorld == currentSubworldID)
                            {
                                Debug.Log("This should not happen...");
                                MoveEntity(e, taskWorld, curTask.Location.Position);
                                continue;
                            }
                            //If we are currently in the same world as the desired task, then we do not need to do anything
                            if (taskWorld == e.CurrentSubworldID)
                            {
                                continue;
                            }
                            //If the current task world is not loaded, and this entity is in an unloaded subworld, and will
                            //wish to travel to the target world
                            //The simplest example is an entity at home/work, who wishes to walk to a position in the main world.
                            if (e.CurrentSubworldID != -1 && taskWorld == -1)
                            {
                                Vec2i extPos = entWorld.ExternalEntrancePos;
                                if (EntityWithinDistanceOfPlayer(e, World.ChunkSize * 3))
                                {
                                    //We move the entity from the current subworld to the main world
                                    MoveEntity(e, taskWorld, extPos);
                                    Debug.Log("1");
                                }
                            }
                            else if (e.CurrentSubworldID != -1 && taskWorld != -1 && taskWorld != e.CurrentSubworldID)
                            {
                                //if the entity is currently in a subworld, and the task is in a different subworld
                                //We move first to the main world
                                Vec2i extPos = entWorld.ExternalEntrancePos;
                                if (EntityWithinDistanceOfPlayer(e, World.ChunkSize * 3))
                                {
                                    //We move the entity from the current subworld to the main world
                                    MoveEntity(e, taskWorld, extPos);
                                    Debug.Log("2");
                                }

                                //TODO - check if currently loaded world is main world, if so, move to entrance and travel (depending on distance to player)
                            }
                            else if (e.CurrentSubworldID == -1 && taskWorld != -1)
                            {
                                Debug.Log("3");
                            }
                        }
                    }
                }
            }
        }
        foreach (LoadedEntity le in LoadedEntities)
        {
            if (UnloadedUpdatableEntities.Contains(le.Entity.ID))
            {
                UnloadedUpdatableEntities.Remove(le.Entity.ID);
            }
        }
    }
Exemplo n.º 20
0
        private void SendEmailNotification(string returnUrl, int taskId)
        {
            var        repository = new RepositoryTask(); var objTask = repository.GetTaskById(taskId, CurrentUserId, CurrentBusinessId);
            EntityTask model         = objTask.Model;
            var        CreatedByName = CurrentUser.FirstName + " " + CurrentUser.LastName;
            var        ReturnUrl     = ConfigurationManager.AppSettings["BaseUrl"] + CurrentUser.BusinessName.Replace(" ", "-") + "#/tasks/" + model.ReferenceNumber;
            var        rootPath      = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
            var        Subject       = "Task " + model.ReferenceNumber + " - " + model.Subject + "";
            var        mail          = new GMEmail();
            string     toEmails      = null,
                       practiceName  = null,
                       priorityType  = null,
                       targetDate    = null,
                       status        = null;

            if (model.PracticeId.HasValue)
            {
                practiceName = new RepositoryLookups().GetPracticeNameById(model.PracticeId.Value);
            }
            if (model.PriorityTypeId.HasValue)
            {
                priorityType = EnumHelper.GetEnumName <TaskPriorities>(model.PriorityTypeId.Value);
            }
            targetDate = model.TargetDate.HasValue ? model.TargetDate.ToString() : "Not Set";
            var AssignedUsers = string.Join(",", model.AssignedUsersList.Select(a => a.Name));

            if (!string.IsNullOrEmpty(returnUrl))
            {
                returnUrl += model.ReferenceNumber;
            }

            if (model.StatusId.HasValue)
            {
                status = Regex.Replace(EnumHelper.GetEnumName <TaskStatuses>(model.StatusId.Value), "([A-Z]{1,2}|[0-9]+)", " $1").Trim();
            }

            if (CurrentUserId != model.RequestedUser.UserId)
            {
                var emailBody = TemplateManager.UpdateOrDeleteTask(rootPath, model.RequestedUser.Name, null, CreatedByName, model.Subject,
                                                                   targetDate, model.TaskDescription, practiceName, priorityType, status, ReturnUrl, false, CurrentBusinessId.Value, CurrentUser.RelativeUrl);
                mail.SendDynamicHTMLEmail(model.RequestedUser.Email, Subject, emailBody, CurrentUser.OtherEmails);
            }

            foreach (var item in model.AssignedUsersList)
            {
                if (item.UserId == CurrentUserId)
                {
                    continue;
                }

                toEmails = new RepositoryUserProfile().NotificationEnabledEmails(item.Email, "TSKSTATNFN");
                if (!string.IsNullOrEmpty(toEmails))
                {
                    var emailBody = TemplateManager.UpdateOrDeleteTask(rootPath, item.Name, null, CreatedByName, model.Subject,
                                                                       targetDate, model.TaskDescription, practiceName, priorityType, status, ReturnUrl, false, CurrentBusinessId.Value, CurrentUser.RelativeUrl);
                    mail.SendDynamicHTMLEmail(toEmails, Subject, emailBody, CurrentUser.OtherEmails);
                }
            }

            foreach (var item in model.WatchersList)
            {
                toEmails = new RepositoryUserProfile().NotificationEnabledEmails(item.Email, "TSKSTATNFN");
                if (!string.IsNullOrEmpty(toEmails))
                {
                    var emailBody = TemplateManager.UpdateOrDeleteTask(rootPath, item.Name, AssignedUsers, CreatedByName, model.Subject,
                                                                       targetDate, model.TaskDescription, practiceName, priorityType, status, ReturnUrl, true, CurrentBusinessId.Value, CurrentUser.RelativeUrl);
                    mail.SendDynamicHTMLEmail(toEmails, Subject, emailBody, CurrentUser.OtherEmails);
                }
            }
        }
Exemplo n.º 21
0
        public IHttpActionResult InsertTaskData(EntityTask model)
        {
            var response = new DataResponse <EntityTask>();
            var TaskId   = 0;

            if (ModelState.IsValid)
            {
                model.UpdatedBy         = model.CreatedBy = model.CurrentUserId = CurrentUserId;
                model.CurrentBusinessId = CurrentBusinessId;
                model.CreatedByName     = string.Format("{0} {1}", CurrentUser.FirstName, CurrentUser.LastName);

                if (model.TaskId > 0)
                {
                    var updateResponse = new RepositoryTask().Update(model);
                    if (updateResponse.Status == DataResponseStatus.OK)
                    {
                        TaskId = (int)updateResponse.Id;
                    }
                }
                else
                {
                    response = new RepositoryTask().Insert(model);
                    TaskId   = response.Model.TaskId;

                    #region Send email to users in assigned to and watchers list

                    try
                    {
                        var    rootPath     = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
                        var    ReturnUrl    = ConfigurationManager.AppSettings["PortalUrl"] + CurrentUser.BusinessName.Replace(" ", "-") + "#/tasks/" + response.Model.ReferenceNumber;
                        var    Subject      = "Task " + response.Model.ReferenceNumber + " - " + response.Model.Subject + "";
                        var    mail         = new GMEmail();
                        string toEmails     = null,
                               practiceName = null,
                               priorityType = null,
                               targetDate   = null;
                        if (model.PracticeId.HasValue)
                        {
                            practiceName = new RepositoryLookups().GetPracticeNameById(model.PracticeId.Value);
                        }
                        if (model.PriorityTypeId.HasValue)
                        {
                            priorityType = EnumHelper.GetEnumName <TaskPriorities>(model.PriorityTypeId.Value);
                        }
                        targetDate = model.TargetDate.HasValue ? model.TargetDate.ToString() : "Not Set";

                        foreach (var item in response.Model.AssignedUsersList)
                        {
                            if (item.UserId == CurrentUserId)
                            {
                                continue;
                            }

                            var emailBody = TemplateManager.NewTask(rootPath, item.Name, "", model.CreatedByName, model.Subject, targetDate, model.TaskDescription, practiceName, priorityType, ReturnUrl, false, CurrentBusinessId.Value, CurrentUser.RelativeUrl);
                            try
                            {
                                toEmails = new RepositoryUserProfile().NotificationEnabledEmails(item.Email, "TSKASSGN");
                                if (!string.IsNullOrEmpty(toEmails))
                                {
                                    mail.SendDynamicHTMLEmail(item.Email, Subject, emailBody, CurrentUser.OtherEmails);
                                }
                            }
                            catch (Exception ex)
                            {
                                ex.Log();
                            }
                        }

                        foreach (var item in response.Model.WatchersList)
                        {
                            if (item.UserId == CurrentUserId)
                            {
                                continue;
                            }

                            var AssignedUsers = string.Join(",", response.Model.AssignedUsersList.Select(a => a.Name));

                            var emailBody = TemplateManager.NewTask(rootPath, item.Name, AssignedUsers, model.CreatedByName, model.Subject, targetDate, model.TaskDescription, practiceName, priorityType, ReturnUrl, true, CurrentBusinessId.Value, CurrentUser.RelativeUrl);
                            try
                            {
                                toEmails = new RepositoryUserProfile().NotificationEnabledEmails(item.Email, "TSKCC");
                                if (!string.IsNullOrEmpty(toEmails))
                                {
                                    mail.SendDynamicHTMLEmail(item.Email, Subject, emailBody, CurrentUser.OtherEmails);
                                }
                            }
                            catch (Exception ex)
                            {
                                ex.Log();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ex.Log();
                    }

                    #endregion
                }

                #region Upload file

                if (model.Files != null && model.Files.Count > 0)
                {
                    List <string> FilesList = new List <string>();

                    foreach (var file in model.Files)
                    {
                        string FileName = SaveFile(file.Base64, file.FileName, TaskId);
                        FilesList.Add(FileName);
                    }

                    bool isImagesSaved = new RepositoryTask().SaveFiles(FilesList, TaskId, model.TaskId > 0);
                }

                #endregion

                response = new RepositoryTask().GetTaskById(TaskId, CurrentUserId, CurrentBusinessId, true);

                return(Ok <DataResponse>(response));
            }
            else
            {
                var errorList = ModelState.Where(a => a.Value.Errors.Any()).Select(s => new
                {
                    Key     = s.Key.Split('.').Last(),
                    Message = s.Value.Errors[0].ErrorMessage
                });
                return(Ok <dynamic>(new { Status = HttpStatusCode.BadRequest, Model = errorList }));
            }
        }
Exemplo n.º 22
0
        public async Task <ResponseModel> AddTaskAsync([FromBody] EntityTask entityTask)
        {
            var result = await TaskService.AddTaskAsync(entityTask);

            return(Success(result));
        }