private void CopySuiteCRMTasksToOrchardTickets(TicketContext context, CopyOrchardProjectToSuiteViewModel.ProjectIdentifiers syncSettings)
        {
            if (syncSettings.OrchardCollaborationProjectId == null)
            {
                throw new ArgumentNullException("OrchardCollaborationProjectId must not be null");
            }

            if (string.IsNullOrEmpty(syncSettings.SuiteCRMId))
            {
                throw new ArgumentNullException("SuiteCRMId must not be null");
            }

            List <project_task> suiteCRMTasks = context.ProjectTaskUnitOfWork.GetProjectTasks(syncSettings.SuiteCRMId).ToList();
            var orchardTickets = this.searchTicketService.SearchByDatabase(
                new PagerParametersWithSortFields()
            {
                PageSize = 0
            },
                new PostedTicketSearchViewModel {
                ProjectId = syncSettings.OrchardCollaborationProjectId
            })
                                 .Select(c => c.As <SuiteCRMTaskPart>())
                                 .Where(c => c != null)
                                 .ToList();

            foreach (var suiteCRMTask in suiteCRMTasks)
            {
                var     orchardTicket  = orchardTickets.FirstOrDefault(c => c.ExternalId == suiteCRMTask.id);
                dynamic ticketSnapshot = null;

                ContentItem ticketContentItem = null;
                bool        isNew             = false;
                if (orchardTicket == null)
                {
                    isNew             = true;
                    ticketContentItem = this.services.ContentManager.Create("Ticket");
                }
                else
                {
                    ticketContentItem = orchardTicket.ContentItem;
                    ticketSnapshot    = this.streamService.TakeSnapshot(ticketContentItem);
                }

                TicketPart          ticketPart          = ticketContentItem.As <TicketPart>();
                SuiteCRMTaskPart    taskPart            = ticketContentItem.As <SuiteCRMTaskPart>();
                AttachToProjectPart attachToProjectPart = ticketContentItem.As <AttachToProjectPart>();

                // the values will be overridde in case user doesn't care about update time (item.DoNotOverrideNewerValues == false) or
                // the target modified date is less than source modified date
                DateTime?  lastSuiteCRMChangeDate = suiteCRMTask.date_modified ?? suiteCRMTask.date_entered;
                CommonPart commonPart             = ticketPart.As <CommonPart>();
                if (!syncSettings.DoNotOverrideNewerValues ||
                    isNew ||
                    (lastSuiteCRMChangeDate.HasValue && commonPart.ModifiedUtc <= lastSuiteCRMChangeDate.Value))
                {
                    if (attachToProjectPart != null)
                    {
                        attachToProjectPart.Record.Project = new ProjectPartRecord {
                            Id = syncSettings.OrchardCollaborationProjectId.Value
                        };
                    }

                    this.Copy(suiteCRMTask, ticketPart, context);
                    this.services.ContentManager.Publish(ticketContentItem);
                    this.streamService.WriteChangesToStreamActivity(ticketContentItem, ticketSnapshot, null);
                }

                taskPart.ExternalId   = suiteCRMTask.id;
                taskPart.LastSyncTime = DateTime.UtcNow;
                taskPart.TaskType     = SuiteCRMTaskPart.SuiteCRMProjectTaskTypeValue;
            }
        }
        public IEnumerable <SuiteCRMTaskDetailViewModel> CopyOrchardTicketsToSuite(CopyOrchardTasksToSuiteViewModel model)
        {
            List <SuiteCRMTaskDetailViewModel> returnValue = new List <SuiteCRMTaskDetailViewModel>();

            using (var connection = Helper.GetConnection(this.services, this.Logger))
                using (SuiteCRMTaskUnitOfWork taskRepository = new SuiteCRMTaskUnitOfWork(connection))
                    using (SuiteCRMEmailAddressBeanUnitOfWork suiteCRMEmailAddressBeanUnitOfWork = new SuiteCRMEmailAddressBeanUnitOfWork(taskRepository))
                        using (SuiteCRMEmailAddressUnitOfWork suiteCRMEmailAddressUnitOfWork = new SuiteCRMEmailAddressUnitOfWork(taskRepository))
                            using (SuiteCRMProjectTaskUnitOfWork projectTasksRepository = new SuiteCRMProjectTaskUnitOfWork(taskRepository))
                                using (var suiteCRMTransaction = taskRepository.BeginTransaction())
                                {
                                    TicketContext context = new TicketContext();
                                    context.ProjectTaskUnitOfWork = projectTasksRepository;
                                    context.Priorities            = this.priorityRepository.Table.ToList();
                                    context.StatusList            = this.statusRepository.Table.ToList();

                                    try
                                    {
                                        var taskIds           = model.Tasks.Where(c => !string.IsNullOrEmpty(c.SuiteCRMId)).Select(c => c.SuiteCRMId).ToArray();
                                        var suiteTasks        = taskRepository.GetTasks(taskIds);
                                        var suiteProjectTasks = projectTasksRepository.GetTasks(taskIds);
                                        var orchardTickets    = this.services
                                                                .ContentManager
                                                                .GetMany <SuiteCRMTaskPart>(
                                            model.Tasks.Where(c => c.OrchardCollaborationTicketId.HasValue).Select(c => c.OrchardCollaborationTicketId.Value),
                                            VersionOptions.Published,
                                            new QueryHints().ExpandParts <TicketPart>());

                                        foreach (var item in model.Tasks)
                                        {
                                            if (item.OrchardCollaborationTicketId == null)
                                            {
                                                continue;
                                            }

                                            var ticket = orchardTickets.FirstOrDefault(c => c.Id == item.OrchardCollaborationTicketId.Value);

                                            var        suiteCRMTaskPart = ticket.As <SuiteCRMTaskPart>();
                                            TicketPart ticketPart       = ticket.As <TicketPart>();
                                            ContentItemPermissionPart permissionPart      = ticket.As <ContentItemPermissionPart>();
                                            AttachToProjectPart       attachToProjectPart = ticket.As <AttachToProjectPart>();
                                            SuiteCRMProjectPart       projectPart         = null;

                                            if (!this.IsSyncingTicketValid(item, ticket, out projectPart))
                                            {
                                                continue;
                                            }

                                            project_task suiteCRMProjectTask = null;
                                            task         suiteCRMTask        = null;

                                            if (!string.IsNullOrEmpty(suiteCRMTaskPart.ExternalId) && item.IsProjectTask)
                                            {
                                                suiteCRMProjectTask = suiteProjectTasks.FirstOrDefault(c => c.id == suiteCRMTaskPart.ExternalId);
                                            }

                                            if (!string.IsNullOrEmpty(suiteCRMTaskPart.ExternalId) && !item.IsProjectTask)
                                            {
                                                suiteCRMTask = suiteTasks.FirstOrDefault(c => c.id == suiteCRMTaskPart.ExternalId);
                                            }

                                            if (suiteCRMProjectTask == null && item.IsProjectTask)
                                            {
                                                suiteCRMProjectTask            = new project_task();
                                                suiteCRMProjectTask.project_id = item.SuiteCRMId;
                                                projectTasksRepository.Add(suiteCRMProjectTask);
                                            }

                                            if (suiteCRMTask == null && !item.IsProjectTask)
                                            {
                                                suiteCRMTask = new task();
                                                taskRepository.Add(suiteCRMTask);
                                            }

                                            CommonPart commonPart = ticketPart.As <CommonPart>();
                                            DateTime?  lastOrchardTicketChangeDate = commonPart.ModifiedUtc ?? commonPart.CreatedUtc;
                                            if (suiteCRMProjectTask != null &&
                                                (
                                                    !item.DoNotOverrideNewerValues ||
                                                    suiteCRMProjectTask.date_modified == null ||
                                                    (lastOrchardTicketChangeDate.HasValue &&
                                                     suiteCRMProjectTask.date_modified.Value <= lastOrchardTicketChangeDate.Value)
                                                ))
                                            {
                                                this.Copy(ticketPart, permissionPart, suiteCRMProjectTask, context);
                                                suiteCRMProjectTask.project_id = projectPart.ExternalId;
                                                projectTasksRepository.Save();
                                            }

                                            if (suiteCRMTask != null &&
                                                (
                                                    !item.DoNotOverrideNewerValues ||
                                                    suiteCRMTask.date_modified == null ||
                                                    (lastOrchardTicketChangeDate.HasValue &&
                                                     suiteCRMTask.date_modified.Value <= lastOrchardTicketChangeDate.Value)
                                                ))
                                            {
                                                this.Copy(ticketPart, permissionPart, suiteCRMTask, context);

                                                // set  contact
                                                if (string.IsNullOrEmpty(suiteCRMTask.created_by) && commonPart.Owner != null)
                                                {
                                                    var emailAddress = suiteCRMEmailAddressUnitOfWork.GetByEmail(commonPart.Owner.Email);
                                                    if (emailAddress != null)
                                                    {
                                                        var contact = suiteCRMEmailAddressBeanUnitOfWork.GetBeanIdOfEmailAddress(Helper.ContactsModuleName, new[] { emailAddress.id }).FirstOrDefault();

                                                        if (contact != null)
                                                        {
                                                            suiteCRMTask.parent_id   = contact.id;
                                                            suiteCRMTask.parent_type = Helper.ContactsModuleName;
                                                        }
                                                    }
                                                }

                                                projectTasksRepository.Save();
                                            }

                                            suiteCRMTaskPart.ExternalId   = item.IsProjectTask ? suiteCRMProjectTask.id : suiteCRMTask.id;
                                            suiteCRMTaskPart.LastSyncTime = DateTime.UtcNow;
                                            suiteCRMTaskPart.TaskType     = item.IsProjectTask ? SuiteCRMTaskPart.SuiteCRMProjectTaskTypeValue : SuiteCRMTaskPart.SuiteCRMTaskTypeValue;
                                            this.services.ContentManager.Publish(ticket.ContentItem);

                                            SuiteCRMTaskDetailViewModel returnValueItem = new SuiteCRMTaskDetailViewModel();
                                            returnValueItem.OrchardCollaborationTicket = ticket.ContentItem;
                                            returnValueItem.IsSync         = true;
                                            returnValueItem.IsProjectTask  = item.IsProjectTask;
                                            returnValueItem.LastSyncTime   = suiteCRMTaskPart.LastSyncTime;
                                            returnValueItem.SuiteCRMTaskId = suiteCRMTaskPart.ExternalId;
                                            returnValue.Add(returnValueItem);
                                        }

                                        suiteCRMTransaction.Commit();
                                    }
                                    catch (Exception ex)
                                    {
                                        suiteCRMTransaction.Rollback();
                                        throw ex;
                                    }
                                }

            return(returnValue);
        }
예제 #3
0
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            ContentItem contentItem = workflowContext.Content.ContentItem;

            var ticket = this.contentManager.New("Ticket");

            this.contentManager.Create(ticket, VersionOptions.Draft);
            var ticketPart = ticket.As <TicketPart>();

            var parentTicket = contentItem.As <TicketPart>();

            if (parentTicket != null)
            {
                ticketPart.Record.Parent = parentTicket.Record;
            }

            // requesting user
            if (parentTicket != null)
            {
                ticketPart.Record.RequestingUser = parentTicket.Record.RequestingUser;
            }
            else if (contentItem != null)
            {
                var commonPart = contentItem.As <CommonPart>();
                if (commonPart != null && commonPart.Record.OwnerId != default(int))
                {
                    ticketPart.Record.RequestingUser = new UserPartRecord {
                        Id = commonPart.Record.OwnerId
                    };
                }
            }

            // service
            int?serviceId = GetValueFromActivityContext(activityContext, CreateTicketActivityForm.ServiceId);

            if (serviceId.HasValue)
            {
                ticketPart.Record.Service = new ServiceRecord {
                    Id = serviceId.Value
                };
            }

            // status
            int?statusId = GetValueFromActivityContext(activityContext, CreateTicketActivityForm.StatusId);

            if (statusId.HasValue)
            {
                ticketPart.Record.StatusRecord = new StatusRecord {
                    Id = statusId.Value
                };
            }

            // Project
            AttachToProjectPart attachToProjectPart = ticket.As <AttachToProjectPart>();

            if (attachToProjectPart != null)
            {
                int?projectId = GetValueFromActivityContext(activityContext, CreateTicketActivityForm.ProjectId);
                if (projectId.HasValue)
                {
                    attachToProjectPart.Record.Project = new ProjectPartRecord {
                        Id = projectId.Value
                    };
                }
            }

            // priority
            int?priorityId = GetValueFromActivityContext(activityContext, CreateTicketActivityForm.PriorityId);

            if (priorityId.HasValue)
            {
                ticketPart.Record.PriorityRecord = new PriorityRecord {
                    Id = priorityId.Value
                };
            }

            // Due date
            int?dueDateDays = GetValueFromActivityContext(activityContext, CreateTicketActivityForm.DueDateId);

            if (dueDateDays.HasValue)
            {
                ticketPart.Record.DueDate = DateTime.UtcNow.AddDays(dueDateDays.Value);
            }

            // Title
            string title = activityContext.GetState <string>(CreateTicketActivityForm.TicketTitle);

            if (!string.IsNullOrEmpty(title))
            {
                title = title.Length > 100 ?
                        title.Substring(0, 100) :
                        title;
            }
            ticketPart.Record.Title = title;

            // Description
            string description = activityContext.GetState <string>(CreateTicketActivityForm.TicketDescription);

            if (!string.IsNullOrEmpty(description))
            {
                description = description.Length > 3000 ?
                              description.Substring(0, 3000) :
                              description;
            }

            ticketPart.Record.Description = description;

            // Received email is not a RelatedContentItem
            if (contentItem.ContentType != IMAPEmailPart.ContentItemTypeName)
            {
                ticketPart.Record.RelatedContentItem = workflowContext.Content.ContentItem.Record;
            }

            // Identity
            var identityRecord = new TicketIdentityRecord();

            this.ticketIdentityRecordRepository.Create(identityRecord);
            ticketPart.Record.Identity = identityRecord;

            // Permission
            this.SetPermissions(workflowContext, activityContext, ticket, ticketPart);

            this.AddEmailAttachmentAndRequestingUser(workflowContext, activityContext, ticket);

            this.contentManager.Publish(ticket);
            this.activityStreamService.WriteChangesToStreamActivity(ticket, null, true, StreamWriters.TicketStreamWriter);

            return(new[] { T("Done") });
        }
예제 #4
0
        public ContentItem CreateProjectMenu(ProjectPart project)
        {
            var editUrl = this.urlHelper.Action("Edit", "Project", new { id = project.Id, area = "Orchard.CRM.Project" });

            // if editUrl is null, it means the routes are not existed yet, so all menu items will br crap, then the creation of the menu must be postponed to the first load of the project
            if (string.IsNullOrEmpty(editUrl))
            {
                return(null);
            }

            // create menu
            var menu = this.menuService.Create(string.Format("Project-{0} --'{1}'", project.Id.ToString(CultureInfo.InvariantCulture), project.Record.Title));

            project.MenuId = menu.Id;

            var         contentManger   = this.services.ContentManager;
            ContentItem menuContentItem = contentManger.Create(ContentTypes.ProjectMenuContentType);

            // update AttachToProjectPart
            AttachToProjectPart attachToProjectPart = menuContentItem.As <AttachToProjectPart>();

            attachToProjectPart.Record.Project = project.Record;

            // update MenuWidgetPart
            MenuWidgetPart menuWidgetPart = menuContentItem.As <MenuWidgetPart>();

            menuWidgetPart.AddHomePage       = false;
            menuWidgetPart.Breadcrumb        = false;
            menuWidgetPart.MenuContentItemId = menu.Id;

            // create menu items
            Action <string, LocalizedString> createMenu = (url, localizedText) =>
            {
                var menuItemPart = contentManger.Create <MenuItemPart>("MenuItem");
                menuItemPart.Url = url;

                var menuPart = menuItemPart.As <MenuPart>();
                menuPart.MenuPosition = Position.GetNext(this.navigationManager.BuildMenu(menu));
                menuPart.MenuText     = localizedText.Text;
                menuPart.Menu         = menu;

                contentManger.Publish(menuItemPart.ContentItem);
            };

            Action <ContentItem, string> createProjectSubPartListUrl = (contentItem, title) =>
            {
                var url = this.urlHelper.Action("Display", "Item", new { id = contentItem.Id, area = "Orchard.CRM.Core" });
                createMenu(url, T(title));
            };

            var targetContentItems = contentManger.HqlQuery().ForType(new[]
            {
                ContentTypes.ProjectWikiContentType,
                ContentTypes.ProjectTicketsContentType,
                ContentTypes.ProjectDiscussionsContentType,
                ContentTypes.ProjectActivityStreamType,
                ContentTypes.ProjectProjectionContentType
            }).Where(c => c.ContentPartRecord <AttachToProjectPartRecord>(), d => d.Eq("Project.Id", project.Id)).List();

            foreach (var contentItem in targetContentItems)
            {
                string title = string.Empty;
                if (contentItem.ContentType == ContentTypes.ProjectWikiContentType)
                {
                    title = "Wiki";
                }
                else
                {
                    TitlePart titlePart = contentItem.As <TitlePart>();
                    title = titlePart.Title;

                    if (string.IsNullOrEmpty(title))
                    {
                        switch (contentItem.ContentType)
                        {
                        case ContentTypes.ProjectTicketsContentType:
                            title = T("Tickets").Text;
                            break;

                        case ContentTypes.ProjectDiscussionsContentType:
                            title = T("Discussion").Text;
                            // version 2.1 creates two discussion for each project. Because of it, we have to apply this hack to prevent creation of two menus.
                            ProjectionWithDynamicSortPart projectionWithDynamicSortPart = contentItem.As <ProjectionWithDynamicSortPart>();
                            if (projectionWithDynamicSortPart.Record.QueryPartRecord == null)
                            {
                                continue;
                            }
                            break;

                        case ContentTypes.ProjectActivityStreamType:
                            title = T("Activity Stream").Text;
                            break;
                        }
                    }
                }

                createProjectSubPartListUrl(contentItem, title);
            }

            // Create link to backlog
            var backLogItem = contentManger
                              .HqlQuery()
                              .ForType(ContentTypes.MilestoneContentType)
                              .Where(c => c.ContentPartRecord <AttachToProjectPartRecord>(), d => d.Eq("Project.Id", project.Id))
                              .List()
                              .FirstOrDefault(c => c.As <MilestonePart>().IsBacklog);

            if (backLogItem != null)
            {
                createProjectSubPartListUrl(backLogItem, T("Backlog").Text);
            }


            // edit project
            editUrl = this.urlHelper.Action("Edit", "Project", new { id = project.Id, area = "Orchard.CRM.Project" });
            createMenu(editUrl, T("Edit"));

            // Project People
            var peopleUrl = this.urlHelper.Action("Edit", "ProjectItemsOwnership", new { ids = project.Id, area = "Orchard.CRM.Project" });

            createMenu(peopleUrl, T("People"));

            this.services.ContentManager.Publish(menuContentItem);

            return(menuContentItem);
        }
        public void Evaluate(EvaluateContext context)
        {
            // AttachToProject
            context.For(ProjectTokenProvider.AttachToProjectKey, () => this.GetPart <AttachToProjectPart>(context))
            .Token("ProjectId", c =>
            {
                AttachToProjectPart attachToProjectPart = this.GetPart <AttachToProjectPart>(context);
                var container = this.GetPart <CommonPart>(context).Container;
                AttachToProjectPart attachToProjectPartInContainer = null;
                if (container != null)
                {
                    attachToProjectPartInContainer = container.As <AttachToProjectPart>();
                }

                if (attachToProjectPart != null)
                {
                    return(attachToProjectPart.Record.Project.Id.ToString(CultureInfo.InvariantCulture));
                }

                if (attachToProjectPartInContainer != null)
                {
                    return(attachToProjectPartInContainer.Record.Project.Id.ToString(CultureInfo.InvariantCulture));
                }

                return(string.Empty);
            });

            // Project
            context.For(ProjectTokenProvider.ProjectKey, () => this.GetPart <ProjectPart>(context))
            .Token("ProjectId", c =>
            {
                ProjectPart projectPart = this.GetPart <ProjectPart>(context);
                AttachToProjectPart attachToProjectPart = this.GetPart <AttachToProjectPart>(context);
                var container = this.GetPart <CommonPart>(context).Container;
                AttachToProjectPart attachToProjectPartInContainer = null;
                ProjectPart projectPartInContainer = null;

                if (container != null)
                {
                    attachToProjectPartInContainer = container.As <AttachToProjectPart>();
                    projectPartInContainer         = container.As <ProjectPart>();
                }

                // Priority is as follows:
                // first checking projectPart in the ContentItem
                // then checking for availability of ProjectPart in the container
                // If there is no ProjectPart, repeat the same process for AttachToProjectPart
                if (projectPart != null)
                {
                    return(projectPart.Record.Id.ToString(CultureInfo.InvariantCulture));
                }
                else if (projectPartInContainer != null)
                {
                    return(projectPartInContainer.Record.Id.ToString(CultureInfo.InvariantCulture));
                }
                else if (attachToProjectPart != null)
                {
                    return(attachToProjectPart.Record.Project.Id.ToString(CultureInfo.InvariantCulture));
                }
                else if (attachToProjectPartInContainer != null)
                {
                    return(attachToProjectPartInContainer.Record.Project.Id.ToString(CultureInfo.InvariantCulture));
                }
                else
                {
                    return(string.Empty);
                }
            });
        }