private void SetParts(BuildShapeContext context)
        {
            var tempPartTemp = context.ContentItem.As <TeamPart>();

            if (tempPartTemp != null)
            {
                this.teamPart = tempPartTemp;
            }

            var tempBusinessUnitPart = context.ContentItem.As <BusinessUnitPart>();

            if (tempBusinessUnitPart != null)
            {
                this.businessUnitPart = tempBusinessUnitPart;
            }

            var tempTicketPart = context.ContentItem.As <TicketPart>();

            if (tempTicketPart != null)
            {
                this.ticketPart = tempTicketPart;
            }

            if (this.contentItem == null)
            {
                this.contentItem = context.ContentItem;
            }

            var contentItemPermissionPart = context.ContentItem.As <ContentItemPermissionPart>();

            if (contentItemPermissionPart != null)
            {
                this.permissionParts.Add(contentItemPermissionPart);
            }
        }
Пример #2
0
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            var            records     = this.GetData().ToList();
            TicketPart     ticketPart  = workflowContext.Content.As <TicketPart>();
            CRMCommentPart commentPart = workflowContext.Content.As <CRMCommentPart>();

            if (ticketPart == null)
            {
                if (commentPart == null)
                {
                    this.Logger.Debug("ContentItem mismatch: Expexting TicketPart");
                    return(new[] { T("Failed") });
                }
                else
                {
                    var contentPart = this.contentManager.Get(commentPart.Record.CRMCommentsPartRecord.ContentItemRecord.Id);
                    ticketPart = contentPart.As <TicketPart>();
                }
            }

            var record = this.GetFromTicket(ticketPart);

            if (record == null)
            {
                this.Logger.Debug("TicketPart doesn't have any " + BasicDataRecordName);
                return(new[] { T(this.UnknownValue) });
            }

            return(new[] { this.T(record.Name) });
        }
Пример #3
0
        protected DriverResult DetailDisplay(MilestonePart part, dynamic shapeHelper)
        {
            List <DriverResult> shapes = new List <DriverResult>();

            EditMilestoneViewModel model = this.Convert(part);

            shapes.Add(ContentShape("Parts_Milestone_Data", () => shapeHelper.Parts_Milestone_Data(Model: model)));

            var memberShapes = this.GetMilestoneMembers(part.Id, "Pinboard", false).ToList();

            memberShapes.ForEach(c =>
            {
                ContentItem contentItem = c.ContentItem;
                TicketPart ticket       = contentItem.As <TicketPart>();
                c.StatusId = ticket.Record.StatusRecord != null ? (int?)ticket.Record.StatusRecord.Id : null;
            });

            dynamic ticketsModel = new ExpandoObject();

            ticketsModel.Part  = part;
            ticketsModel.Items = memberShapes;

            // we want to represent the tickets in a table where there is a column for each status.
            var statusRecords = this.basicDataService.GetStatusRecords().ToList();

            ticketsModel.StatusRecords = statusRecords;

            shapes.Add(ContentShape("Parts_Milestone_Tickets", () => shapeHelper.Parts_Milestone_Tickets(Model: JsonConvert.SerializeObject(ticketsModel))));

            return(this.Combined(shapes.ToArray()));
        }
        private void Copy(project_task source, TicketPart destination, TicketContext context)
        {
            destination.Record.Title       = source.name;
            destination.Record.Description = source.description;

            // priority
            if (!string.IsNullOrEmpty(source.priority))
            {
                var priority = context.Priorities.FirstOrDefault(c => c.Name.ToLower().Trim() == source.priority.ToLower().Trim());
                if (priority != null)
                {
                    destination.PriorityRecord = new PriorityRecord {
                        Id = priority.Id
                    };
                }
            }

            // status
            if (!string.IsNullOrEmpty(source.status))
            {
                var status = context.StatusList.FirstOrDefault(c => c.Name.ToLower().Trim() == source.status.ToLower().Trim());
                if (status != null)
                {
                    destination.StatusRecord = new StatusRecord {
                        Id = status.Id
                    };
                }
            }
        }
        private void Copy(TicketPart source, ContentItemPermissionPart sourcePermissionPart, task destination, TicketContext context)
        {
            destination.name     = source.Record.Title.Length > 50 ? source.Record.Title.Substring(0, 50) : source.Record.Title;
            destination.date_due = source.Record.DueDate;

            // status
            if (source.Record.StatusRecord != null)
            {
                var status = context.StatusList.FirstOrDefault(c => c.Id == source.Record.StatusRecord.Id);
                if (status != null)
                {
                    destination.status = status.Name;
                }
            }

            // priority
            if (source.Record.PriorityRecord != null)
            {
                var priority = context.Priorities.FirstOrDefault(c => c.Id == source.Record.PriorityRecord.Id);
                if (priority != null)
                {
                    destination.priority = priority.Name;
                }
            }

            CommonPart commonPart = source.As <CommonPart>();

            if (commonPart != null && commonPart.ModifiedUtc.HasValue)
            {
                destination.date_modified = commonPart.ModifiedUtc;
            }

            destination.assigned_user_id = this.GetAssigneeUserExternalId(sourcePermissionPart);
            destination.created_by       = this.GetOwnerUserExternalId(commonPart);
        }
Пример #6
0
        private string GetCreatedTicketDescription(TicketPart ticket)
        {
            string ticketIdAndTitle        = this.GetTicketIdAndTitle(ticket.Record);
            string createTicketDescription = string.Format(
                "{0} '{1}'",
                T("Creates a new Ticket").Text,
                ticketIdAndTitle);

            if (ticket.Record.Parent != null)
            {
                var parentTicket = this.ticketRepository.Table.FirstOrDefault(c => c.Id == ticket.Record.Parent.Id);
                if (parentTicket != null)
                {
                    createTicketDescription = string.Format(
                        "Creates a sub ticket '{0}' for '{1}'",
                        this.GetTicketIdAndTitle(parentTicket),
                        ticketIdAndTitle);
                }
            }

            string relatedContentItemString = string.Empty;

            if (ticket.Record.RelatedContentItem != null)
            {
                var relatedContentItem = this.services.ContentManager.Get(ticket.Record.RelatedContentItem.Id);
                relatedContentItemString = string.Format(" {0} {1}", this.T("for").Text, CRMHelper.GetContentItemTitle(relatedContentItem));
            }

            return(string.Format("{0}{1}", createTicketDescription, relatedContentItemString));
        }
Пример #7
0
        public AttachToProjectHandler(IRepository <AttachToProjectPartRecord> repository, IContentManager contentManager)
        {
            Filters.Add(StorageFilter.For(repository));

            this.OnIndexing <AttachToProjectPart>((context, part) =>
            {
                string projectId = part.Record.Project != null ? part.Record.Project.Id.ToString(CultureInfo.InvariantCulture) : TicketPart.NullValueForIntegers;
                context.DocumentIndex
                .Add(AttachToProjectPart.ProjectIdFieldName, projectId).Store();

                context.DocumentIndex.Add("type", part.ContentItem.ContentType.ToLower(CultureInfo.InvariantCulture));
            });

            this.OnPublishing <AttachToProjectPart>((context, part) =>
            {
                // refresh the AttachToProjectPart of the child items
                TicketPart ticketPart = part.As <TicketPart>();
                if (ticketPart != null && ticketPart.Record.SubTickets != null && ticketPart.Record.SubTickets.Count > 0)
                {
                    var childTickets = contentManager.GetMany <AttachToProjectPart>(
                        ticketPart.Record.SubTickets.Select(c => c.Id),
                        VersionOptions.Published,
                        new QueryHints().ExpandParts <AttachToProjectPart>());

                    foreach (var childTicket in childTickets)
                    {
                        childTicket.Record.Project = part.Record.Project != null ? new ProjectPartRecord {
                            Id = part.Record.Project.Id
                        } : null;
                        contentManager.Publish(childTicket.ContentItem);
                    }
                }
            });
        }
Пример #8
0
        protected override void OnDisplay(ContentItem contentItem, dynamic model)
        {
            TicketPart ticketPart = contentItem.As <TicketPart>();

            if (ticketPart.Record.RelatedContentItem != null)
            {
                var        relatedContentItem = this.contentManager.Get(ticketPart.Record.RelatedContentItem.Id, VersionOptions.AllVersions);
                TitlePart  titlePart          = relatedContentItem.As <TitlePart>();
                CommonPart commonPart         = relatedContentItem.As <CommonPart>();

                if (titlePart != null && commonPart != null)
                {
                    model.RelatedContentItem = new
                    {
                        Owner       = commonPart.Owner,
                        Title       = titlePart.Title,
                        Id          = relatedContentItem.Id,
                        ContentType = relatedContentItem.ContentType
                    };
                }
            }

            model.IsCurrentUserCustomer          = this.crmContentOwnershipService.IsCurrentUserCustomer();
            model.CurrentUserCanEditContent      = this.crmContentOwnershipService.CurrentUserCanEditContent(contentItem);
            model.CurrentUserCanChangePermission = this.crmContentOwnershipService.CurrentUserCanChangePermission(contentItem, new ModelStateDictionary());
        }
        private bool IsSyncingTicketValid(CopyOrchardTasksToSuiteViewModel.TaskIdentifiers item, SuiteCRMTaskPart ticket, out SuiteCRMProjectPart projectPart)
        {
            projectPart = null;

            if (ticket == null)
            {
                return(false);
            }

            var suiteCRMTaskPart = ticket.As <SuiteCRMTaskPart>();

            if (suiteCRMTaskPart == null)
            {
                return(false);
            }

            TicketPart ticketPart = ticket.As <TicketPart>();

            if (ticketPart == null)
            {
                return(false);
            }

            if (!item.SyncSubTasks && ticketPart.Record.Parent != null)
            {
                return(false);
            }

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

            if (item.IsProjectTask && (attachToProjectPart == null || attachToProjectPart.Record.Project == null))
            {
                return(false);
            }

            if (item.IsProjectTask)
            {
                var project = this.services.ContentManager.Get(attachToProjectPart.Record.Project.Id);

                if (project == null)
                {
                    return(false);
                }

                projectPart = project.As <SuiteCRMProjectPart>();

                if (string.IsNullOrEmpty(projectPart.ExternalId))
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #10
0
        protected DriverResult DisplaySyncOptions(SuiteCRMTaskPart part, string displayType, dynamic shapeHelper)
        {
            if (displayType != "Detail")
            {
                return(null);
            }

            if (!this.contentOwnershipService.IsCurrentUserOperator())
            {
                return(null);
            }

            var setting = services.WorkContext.CurrentSite.As <SuiteCRMSettingPart>();

            if (setting == null)
            {
                return(null);
            }

            string  taskType            = part.TaskType ?? SuiteCRMTaskPart.SuiteCRMProjectTaskTypeValue;
            var     attachToProjectPart = part.As <AttachToProjectPart>();
            dynamic model = new ExpandoObject();

            model.LastSyncTime    = part.LastSyncTime;
            model.ExternalId      = part.ExternalId;
            model.TaskId          = part.Id;
            model.IsProjectTask   = attachToProjectPart != null && attachToProjectPart.Record.Project != null;
            model.SuiteCRMAddress = (!string.IsNullOrEmpty(setting.WebAddress) && !string.IsNullOrEmpty(part.ExternalId)) ?
                                    Helper.GetTaskAddressInSuiteCRM(this.services, part.ExternalId, taskType) :
                                    string.Empty;

            var context = this.workContextAccessor.GetContext();

            Helper.RenderSyncDialogs(context, shapeHelper, model);

            TicketPart ticketPart = part.As <TicketPart>();

            if (displayType == "Detail" && ticketPart.Record.RequestingUser != null)
            {
                var reporterUser = this.services.ContentManager.Get <IUser>(ticketPart.Record.RequestingUser.Id);
                var contact      = this.suiteCRMDataService.GetContact(reporterUser.Email);
                if (contact != null)
                {
                    model.ContactUrl = Helper.GetContactAddressInSuiteCRM(this.services, contact.bean_id);
                }
            }

            return(ContentShape("Parts_SuiteCRMTask",
                                () => shapeHelper.Parts_SuiteCRMTask(
                                    Model: model
                                    )));
        }
Пример #11
0
        protected override ServiceRecord GetFromTicket(TicketPart ticketPart)
        {
            var record = ticketPart.Record.Service;

            if (record == null)
            {
                return(null);
            }
            else
            {
                var records = this.basicDataService.GetServices().ToList();
                return(records.FirstOrDefault(c => c.Id == record.Id));
            }
        }
        protected int?GetParentProjectId(AttachToProjectPart part)
        {
            // Check whether the given contentItem is a Ticket
            int?       parentProjectId = null;
            TicketPart ticketPart      = part.As <TicketPart>();

            if (ticketPart != null && ticketPart.Record.Parent != null)
            {
                // if the parent has a milestone, then the current ticket belongs to that milestone too
                var parent = this.services.ContentManager.Get(ticketPart.Record.Parent.Id, VersionOptions.Published, new QueryHints().ExpandParts <AttachToProjectPart>());
                var parentAttachToProject = parent.As <AttachToProjectPart>();
                parentProjectId = parentAttachToProject.Record.Project != null ? (int?)parentAttachToProject.Record.Project.Id : null;
            }

            return(parentProjectId);
        }
Пример #13
0
        /// <summary>
        /// One of the reasons we have a different Action for creating a child ticket, is setting the properties related to the Parent ticket such as
        /// Parent_Id and AttachToProjectId for the child ticket
        /// </summary>
        /// <param name="parentTicketId"></param>
        /// <returns></returns>
        public ActionResult CreateChildTicket(int parentTicketId)
        {
            var contentItem = this.contentManager.New(this.ControllerContentType);

            var parentTicketContentItem = this.contentManager.Get(parentTicketId, VersionOptions.Published, new QueryHints().ExpandParts <TicketPart, AttachToProjectPart>());

            if (parentTicketContentItem != null &&
                parentTicketContentItem.ContentType == "Ticket" &&
                this.crmContentOwnershipService.CurrentUserCanViewContent(parentTicketContentItem))
            {
                TicketPart ticket       = contentItem.As <TicketPart>();
                TicketPart parentTicket = parentTicketContentItem.As <TicketPart>();
                ticket.Record.Parent = parentTicket.Record;

                AttachToProjectPart attachToProjectPart = contentItem.As <AttachToProjectPart>();
                if (attachToProjectPart != null)
                {
                    var parentAttachToProject = parentTicketContentItem.As <AttachToProjectPart>();
                    if (parentAttachToProject.Record.Project != null)
                    {
                        attachToProjectPart.Record.Project = new ProjectPartRecord
                        {
                            Id = parentAttachToProject.Record.Project.Id
                        };
                    }
                }
            }

            if (!this.crmContentOwnershipService.IsCurrentUserOperator())
            {
                return(new HttpUnauthorizedResult());
            }

            dynamic model = this.contentManager.BuildEditor(contentItem);

            if (!string.IsNullOrEmpty(this.EditMetadataType))
            {
                model.Metadata.Type = this.EditMetadataType;
            }

            this.OnCreated(model);

            return(this.CreateActionResultBasedOnAjaxRequest(model, "Create", "Create", string.Empty));
        }
Пример #14
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteStartObject();
            TicketPart contentPart = value as TicketPart;
            var        record      = contentPart.Record;

            // dynamic  object corresponding to TicketPartRecord
            dynamic dynamicRecord = new JObject();

            // Basic data
            dynamicRecord.Status         = this.Copy(record.StatusRecord);
            dynamicRecord.TicketType     = this.Copy(record.TicketType);
            dynamicRecord.PriorityRecord = this.Copy(record.PriorityRecord);
            dynamicRecord.Service        = this.Copy(record.Service);
            dynamicRecord.Description    = record.Description;
            dynamicRecord.Title          = record.Title;
            dynamicRecord.SourceId       = record.SourceId;
            dynamicRecord.SourceData     = record.SourceData;
            dynamicRecord.Identity       = null;
            if (record.Identity != null)
            {
                dynamicRecord.Identity = new JObject();
                dynamicRecord.Identity.Add("Id", record.Identity.Id);
            }

            if (record.RequestingUser != null)
            {
                dynamicRecord.RequestingUser = new JObject();
                dynamicRecord.Id             = record.RequestingUser.Id;
                dynamicRecord.UserName       = record.RequestingUser.UserName;
            }

            dynamicRecord.DueDate = record.DueDate;

            Utility.WriteProperty("Record", dynamicRecord, writer, serializer);

            this.WriteCommonFields(writer, contentPart, serializer);

            // StatusTimes
            Utility.WriteArray("StatusTimes", contentPart.StatusTimes, writer, serializer);

            writer.WriteEnd();
        }
Пример #15
0
        private TicketPart GetTicketPart(EvaluateContext context)
        {
            ContentItem contentItem = (ContentItem)context.Data["Content"];
            TicketPart  ticketPart  = contentItem.As <TicketPart>();

            if (ticketPart == null)
            {
                CRMCommentPart crmComment = contentItem.As <CRMCommentPart>();
                if (crmComment == null)
                {
                    return(null);
                }
                else
                {
                    return(this.contentManager.Get <TicketPart>(crmComment.Record.CRMCommentsPartRecord.ContentItemRecord.Id));
                }
            }

            return(ticketPart);
        }
Пример #16
0
        protected override void OnCreating(ContentItem contentItem)
        {
            CreateModel createModel = new CreateModel();

            this.TryUpdateModel(createModel, "TicketPart");

            if (createModel.RelatedContentItemId.HasValue)
            {
                TicketPart ticketPart = contentItem.As <TicketPart>();

                if (ticketPart == null)
                {
                    return;
                }

                ticketPart.Record.RelatedContentItem = new ContentManagement.Records.ContentItemRecord {
                    Id = createModel.RelatedContentItemId.Value
                };
            }

            base.OnCreating(contentItem);
        }
Пример #17
0
        public static string GetContentItemTitle(ContentItem contentItem)
        {
            TicketPart ticketPart = contentItem.As <TicketPart>();

            if (ticketPart != null)
            {
                string title    = ticketPart.Record.Title;
                string identity = ticketPart.Record.Identity != null?
                                  ticketPart.Record.Identity.Id.ToString(CultureInfo.InvariantCulture) :
                                      string.Empty;

                return(string.Format(CultureInfo.CurrentUICulture, "{0} - {1}", identity, title));
            }

            TitlePart titlePart = contentItem.As <TitlePart>();

            if (titlePart != null)
            {
                return(titlePart.Title);
            }

            return(contentItem.ContentType + " " + contentItem.Id.ToString(CultureInfo.InvariantCulture));
        }
        public AttachToMilestoneHandler(IRepository <AttachToMilestonePartRecord> repository, IContentManager contentManager)
        {
            Filters.Add(StorageFilter.For(repository));

            this.OnPublishing <AttachToMilestonePart>((context, part) =>
            {
                // refresh the milestone of the child items
                TicketPart ticketPart = part.As <TicketPart>();
                if (ticketPart != null && ticketPart.Record.SubTickets != null && ticketPart.Record.SubTickets.Count > 0)
                {
                    var childTickets = contentManager.GetMany <AttachToMilestonePart>(
                        ticketPart.Record.SubTickets.Select(c => c.Id),
                        VersionOptions.Published,
                        new QueryHints().ExpandParts <AttachToMilestonePart>());

                    foreach (var childTicket in childTickets)
                    {
                        childTicket.Record.MilestoneId = part.Record.MilestoneId;
                        contentManager.Publish(childTicket.ContentItem);
                    }
                }
            });
        }
Пример #19
0
        private void UpdateIndex(IndexContentContext context, TicketPart part)
        {
            Func <IBasicDataRecord, string> getValue = (c) => c != null?c.Id.ToString(CultureInfo.InvariantCulture) : string.Empty;

            // service
            string service = getValue(part.Record.Service);

            string type = getValue(part.Record.TicketType);

            // identity
            string identity = part.Record.Identity != null?part.Record.Identity.Id.ToString(CultureInfo.InvariantCulture) : TicketPart.NullValueForIntegers;

            context.DocumentIndex
            .Add(TicketPart.TitleFieldName, part.Record.Title).Analyze().Store()
            .Add(TicketPart.TypeFieldName, type).Store()
            .Add(TicketPart.ServiceFieldName, service).Store()
            .Add(TicketPart.IdentityFieldName, identity).Store()
            .Add("type", "ticket").Store()
            .Add(TicketPart.DescriptionFieldName, part.Record.Description).Analyze().Store();

            // Priority
            if (part.Record.PriorityRecord != null)
            {
                context.DocumentIndex.Add(TicketPart.PriorityFieldName, part.PriorityRecord.Id.ToString(CultureInfo.InvariantCulture)).Store();
                var priorityRecord = basicDataService.GetPriorities().FirstOrDefault(c => c.Id == part.PriorityRecord.Id);

                if (priorityRecord != null)
                {
                    context.DocumentIndex.Add(TicketPart.PriorityOrderFieldName, priorityRecord.OrderId.ToString(CultureInfo.InvariantCulture)).Store();
                }
            }
            else
            {
                context.DocumentIndex.Add(TicketPart.PriorityFieldName, TicketPart.NullValueForIntegers).Store();
                context.DocumentIndex.Add(TicketPart.PriorityOrderFieldName, TicketPart.NullValueForIntegers).Store();
            }

            // status
            if (part.Record.StatusRecord != null)
            {
                context.DocumentIndex.Add(TicketPart.StatusFieldName, part.StatusRecord.Id.ToString(CultureInfo.InvariantCulture)).Store();
                var statusRecord = basicDataService.GetStatusRecords().FirstOrDefault(c => c.Id == part.StatusRecord.Id);

                if (statusRecord != null)
                {
                    context.DocumentIndex.Add(TicketPart.StatusOrderFieldName, statusRecord.OrderId.ToString(CultureInfo.InvariantCulture)).Store();
                }
            }
            else
            {
                context.DocumentIndex.Add(TicketPart.StatusFieldName, TicketPart.NullValueForIntegers).Store();
                context.DocumentIndex.Add(TicketPart.StatusOrderFieldName, TicketPart.NullValueForIntegers).Store();
            }

            // DueDate
            if (part.Record.DueDate != null)
            {
                context.DocumentIndex.Add(TicketPart.DueDateFieldName, part.Record.DueDate.Value).Store();
            }

            // requesting User
            if (part.Record.RequestingUser != null)
            {
                context.DocumentIndex.Add(TicketPart.RequestingUserFieldName, part.Record.RequestingUser.Id.ToString(CultureInfo.InvariantCulture)).Store();
            }
            else
            {
                context.DocumentIndex.Add(TicketPart.RequestingUserFieldName, string.Empty).Store();
            }

            // RelatedContentItem
            if (part.Record.RelatedContentItem != null)
            {
                context.DocumentIndex.Add(TicketPart.RelatedContentItemIdFieldName, part.Record.RelatedContentItem.Id.ToString(CultureInfo.InvariantCulture)).Store();
            }
            else
            {
                context.DocumentIndex.Add(TicketPart.RelatedContentItemIdFieldName, string.Empty).Store();
            }
        }
Пример #20
0
 protected abstract TBasicData GetFromTicket(TicketPart ticketPart);
Пример #21
0
        private void SetPermissions(WorkflowContext workflowContext, ActivityContext activityContext, ContentItem ticket, TicketPart ticketPart)
        {
            // Permission
            var contentPermissionPart = ticket.As <ContentItemPermissionPart>();

            contentPermissionPart.Record.Ticket = ticketPart.Record;

            // EditableBy
            string editableBy           = activityContext.GetState <string>("EditableBy");
            List <UserPartRecord> users = new List <UserPartRecord>();

            if (!string.IsNullOrEmpty(editableBy))
            {
                var usernames = editableBy.Split(',').Select(c => c.Trim().ToLower()).ToArray();
                users = this.userRepository.Table.Where(c => usernames.Contains(c.UserName)).ToList();

                // remove redundants
                users = users.GroupBy(c => c.Id).Select(c => c.First()).ToList();
                foreach (var user in users)
                {
                    var permissionRecord = new ContentItemPermissionDetailRecord
                    {
                        AccessType = ContentItemPermissionAccessTypes.SharedForEdit,
                        User       = new UserPartRecord {
                            Id = user.Id
                        },
                        ContentItemPermissionPartRecord = contentPermissionPart.Record
                    };
                    this.contentOwnershipHelper.Create(permissionRecord, ticket, false);
                }
            }

            // businessUnit
            string groupId = activityContext.GetState <string>("GroupId");

            if (!string.IsNullOrEmpty(groupId))
            {
                var targetContentItemPermissionViewModel = Converter.DecodeGroupId(groupId);

                if (targetContentItemPermissionViewModel.BusinessUnitId.HasValue)
                {
                    var permissionRecord = new ContentItemPermissionDetailRecord
                    {
                        AccessType   = ContentItemPermissionAccessTypes.Assignee,
                        BusinessUnit = new BusinessUnitPartRecord {
                            Id = targetContentItemPermissionViewModel.BusinessUnitId.Value
                        },
                        ContentItemPermissionPartRecord = contentPermissionPart.Record
                    };

                    this.contentOwnershipHelper.Create(permissionRecord, ticket, false);
                    contentPermissionPart.Record.HasOwner = true;
                }
                else if (targetContentItemPermissionViewModel.TeamId.HasValue)
                {
                    var permissionRecord = new ContentItemPermissionDetailRecord
                    {
                        AccessType = ContentItemPermissionAccessTypes.Assignee,
                        Team       = new TeamPartRecord {
                            Id = targetContentItemPermissionViewModel.TeamId.Value
                        },
                        ContentItemPermissionPartRecord = contentPermissionPart.Record
                    };

                    this.contentOwnershipHelper.Create(permissionRecord, ticket, false);
                    contentPermissionPart.Record.HasOwner = true;
                }
            }
            else
            {
                // user
                int?userId = GetValueFromActivityContext(activityContext, CreateTicketActivityForm.SelectedUserId);
                if (userId != null && !users.Any(c => c.Id == userId.Value))
                {
                    var permissionRecord = new ContentItemPermissionDetailRecord
                    {
                        AccessType = ContentItemPermissionAccessTypes.Assignee,
                        User       = new UserPartRecord {
                            Id = userId.Value
                        },
                        ContentItemPermissionPartRecord = contentPermissionPart.Record
                    };

                    contentPermissionPart.Record.HasOwner = true;
                    this.contentOwnershipHelper.Create(permissionRecord, ticket, false);
                }
            }
        }
Пример #22
0
        public ActionResult QuickUpdate(TicketQuickUpdateViewModel model, string displyType)
        {
            if (!this.crmContentOwnershipService.IsCurrentUserOperator() && !this.crmContentOwnershipService.IsCurrentUserCustomer())
            {
                return(new HttpUnauthorizedResult());
            }

            if (model.Ids.Count == 0)
            {
                this.ModelState.AddModelError("Ids", "The model must contains minimum one contentItem.Id");
            }

            var tickets = this.contentManager.GetMany <TicketPart>(model.Ids, VersionOptions.DraftRequired, new QueryHints().ExpandRecords(new[] { "TicketPartRecord", "ContentItemPermissionPartRecord" })).ToList();

            if (tickets.Count != model.Ids.Count)
            {
                return(HttpNotFound());
            }

            bool afterUpdateUserStillCanChangeOwnership = true;

            if (ModelState.IsValid)
            {
                foreach (var ticket in tickets)
                {
                    var contentItem = ticket.ContentItem;

                    var context = new UpdateContentContext(contentItem);

                    this.Handlers.Invoke(handler => handler.Updating(context), Logger);

                    if (contentItem == null)
                    {
                        return(HttpNotFound());
                    }

                    if (!this.IsEditAuthorized(contentItem))
                    {
                        this.ModelState.AddModelError("Ids", T("You don't have right access to change these items").Text);
                        return(this.CreateActionResultBasedOnAjaxRequest(null, null));
                    }

                    dynamic snapshot = this.streamService.TakeSnapshot(contentItem);

                    if (model.UpdateBusinessUnitId || model.UpdateTeamId || model.UpdateUserId)
                    {
                        PostedEditOwnerViewModel postedEditOwnerViewModel = new PostedEditOwnerViewModel();
                        postedEditOwnerViewModel.UserId = model.UpdateUserId ? model.UserId : null;

                        if (model.BusinessUnitId.HasValue)
                        {
                            postedEditOwnerViewModel.GroupId = model.UpdateBusinessUnitId ?
                                                               "BusinessUnit:" + model.BusinessUnitId.Value.ToString(CultureInfo.InvariantCulture) : string.Empty;
                        }

                        if (model.UpdateTeamId && model.TeamId.HasValue)
                        {
                            postedEditOwnerViewModel.GroupId = "Team:" + model.TeamId.Value.ToString(CultureInfo.InvariantCulture);
                        }

                        this.EditOwner(contentItem, postedEditOwnerViewModel, false, false);
                        afterUpdateUserStillCanChangeOwnership = this.crmContentOwnershipService.CurrentUserIsContentItemAssignee(contentItem) || this.services.Authorizer.Authorize(Permissions.AdvancedOperatorPermission);
                    }

                    TicketPart ticketPart = contentItem.As <TicketPart>();

                    // Title
                    if (!string.IsNullOrEmpty(model.Title))
                    {
                        ticketPart.Record.Title = model.Title;
                    }

                    // Description
                    if (model.UpdateDescription)
                    {
                        ticketPart.Record.Description = model.Description;
                    }

                    // Priority
                    if (model.PriorityId.HasValue)
                    {
                        ticketPart.Record.PriorityRecord = new PriorityRecord {
                            Id = model.PriorityId.Value
                        };
                    }
                    else if (model.UpdatePriority)
                    {
                        ticketPart.Record.PriorityRecord = null;
                    }

                    // serviceId
                    if (model.ServiceId.HasValue)
                    {
                        ticketPart.Record.Service = new ServiceRecord {
                            Id = model.ServiceId.Value
                        };
                    }
                    else if (model.UpdateServiceId)
                    {
                        ticketPart.Record.Service = null;
                    }

                    // statusId
                    if (model.StatusId.HasValue)
                    {
                        ticketPart.Record.StatusRecord = new StatusRecord {
                            Id = model.StatusId.Value
                        };
                    }
                    else if (model.UpdateStatusId)
                    {
                        ticketPart.Record.StatusRecord = null;
                    }

                    // TicketTypeId
                    if (model.TypeId.HasValue)
                    {
                        ticketPart.Record.TicketType = new TicketTypeRecord {
                            Id = model.TypeId.Value
                        };
                    }
                    else if (model.UpdateTypeId)
                    {
                        ticketPart.Record.TicketType = null;
                    }

                    // DueDate
                    if (model.DueDate.HasValue)
                    {
                        ticketPart.Record.DueDate = model.DueDate.Value;
                    }
                    else if (model.UpdateDueDate)
                    {
                        ticketPart.Record.DueDate = null;
                    }

                    this.Handlers.Invoke(handler => handler.Updated(context), Logger);

                    contentManager.Publish(contentItem);

                    this.streamService.WriteChangesToStreamActivity(contentItem, snapshot, StreamWriters.TicketStreamWriter);
                    var documentIndex = this.indexProvider.New(contentItem.Id);
                    this.contentManager.Index(contentItem, documentIndex);
                    this.indexProvider.Store(TicketController.SearchIndexName, documentIndex);
                }
            }

            bool isAjaxRequest = Request.IsAjaxRequest();

            if (isAjaxRequest)
            {
                displyType = string.IsNullOrEmpty(displyType) ? "Summary" : displyType;
                List <dynamic> shapes = new List <dynamic>();

                foreach (var contentItem in tickets)
                {
                    var shape = this.contentManager.BuildDisplay(tickets[0].ContentItem, displayType: displyType);
                    shapes.Add(shape);
                }

                var data = new
                {
                    Tickets = Newtonsoft.Json.JsonConvert.SerializeObject(shapes),
                    ChangeOwnershipIsPossible = afterUpdateUserStillCanChangeOwnership
                };

                AjaxMessageViewModel ajaxMessageModel = new AjaxMessageViewModel {
                    Id = tickets[0].ContentItem.Id, IsDone = ModelState.IsValid, Data = data
                };

                foreach (var item in ModelState)
                {
                    ajaxMessageModel.Errors.AddRange(item.Value.Errors.Select(c => new KeyValuePair <string, string>(item.Key, c.Exception != null ? c.Exception.Message : c.ErrorMessage)).Where(c => !string.IsNullOrEmpty(c.Value)));
                }

                return(this.Json(ajaxMessageModel, JsonRequestBehavior.AllowGet));
            }
            else if (!string.IsNullOrEmpty(model.returnUrl))
            {
                return(this.Redirect(model.returnUrl));
            }
            else
            {
                return(this.RedirectToAction("Edit", new RouteValueDictionary {
                    { "Id", tickets[0].ContentItem.Id }
                }));
            }
        }
        private void CopyOrchardTicketsToSuiteCRM(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");
            }

            var orchardTickets = this.searchTicketService.SearchByDatabase(new PagerParametersWithSortFields()
            {
                PageSize = 0
            }, new PostedTicketSearchViewModel {
                ProjectId = syncSettings.OrchardCollaborationProjectId
            });
            List <project_task> suiteCRMTasks = new List <project_task>();

            if (!string.IsNullOrEmpty(syncSettings.SuiteCRMId))
            {
                suiteCRMTasks.AddRange(context.ProjectTaskUnitOfWork.GetProjectTasks(syncSettings.SuiteCRMId));
            }

            foreach (var ticket in orchardTickets)
            {
                var suiteCRMTaskPart = ticket.As <SuiteCRMTaskPart>();

                if (suiteCRMTaskPart == null)
                {
                    continue;
                }

                TicketPart ticketPart = ticket.As <TicketPart>();
                ContentItemPermissionPart permissionPart = ticket.As <ContentItemPermissionPart>();

                if (ticketPart == null)
                {
                    continue;
                }

                if (!syncSettings.SyncSubTasks && ticketPart.Record.Parent != null)
                {
                    continue;
                }

                project_task suiteCRMProjectTask = null;

                if (!string.IsNullOrEmpty(suiteCRMTaskPart.ExternalId))
                {
                    suiteCRMProjectTask = suiteCRMTasks.FirstOrDefault(c => c.id == suiteCRMTaskPart.ExternalId);
                }

                if (suiteCRMProjectTask == null)
                {
                    suiteCRMProjectTask            = new project_task();
                    suiteCRMProjectTask.project_id = syncSettings.SuiteCRMId;
                    context.ProjectTaskUnitOfWork.Add(suiteCRMProjectTask);
                }

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

                suiteCRMTaskPart.ExternalId   = suiteCRMProjectTask.id;
                suiteCRMTaskPart.LastSyncTime = DateTime.UtcNow;
                suiteCRMTaskPart.TaskType     = SuiteCRMTaskPart.SuiteCRMProjectTaskTypeValue;
                this.services.ContentManager.Publish(ticket.ContentItem);
            }
        }
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            TicketPart ticketPart = workflowContext.Content.As <TicketPart>();

            if (!workflowContext.Tokens.ContainsKey("Permission"))
            {
                this.Logger.Debug("There is no Permission among the tokens");
                return(new[] { T("Failed") });
            }

            ContentItemPermissionDetailRecord permission = (ContentItemPermissionDetailRecord)workflowContext.Tokens["Permission"];

            if (permission == null)
            {
                this.Logger.Debug("There is no Permission among the tokens");
                return(new[] { T("Failed") });
            }

            if (ticketPart == null)
            {
                this.Logger.Debug("ContentItem mismatch: Expexting TicketPart");
                return(new[] { T("Failed") });
            }

            // setup tokenizer
            Dictionary <string, object> temp = new Dictionary <string, object>();

            temp.Add(ActivityTokenProvider.PermissionDetailKey, permission);
            var titlePart = ticketPart.As <TitlePart>();

            if (titlePart != null)
            {
                temp.Add(ActivityTokenProvider.TitkeKey, titlePart);
            }

            CRMCommentPart commentPart = workflowContext.Content.As <CRMCommentPart>();

            if (commentPart != null)
            {
                temp.Add(ActivityTokenProvider.CRMCommentKey, commentPart);
            }

            string emailTemplateIdString = activityContext.GetState <string>(EmailTemplateActivityForm.EmailTemplateIdFieldName);
            int    emailTemplateId;

            if (!int.TryParse(emailTemplateIdString, out emailTemplateId))
            {
                this.Logger.Debug("There is no email Template for new Tickets");
                return(new[] { T("Failed") });
            }

            var ticketEmailTemplate = this.emailTemplateRepository.Table.First(c => c.Id == emailTemplateId);

            if (ticketEmailTemplate == null)
            {
                this.Logger.Debug("There is no email Template for new Tickets");
                return(new[] { T("Failed") });
            }

            var queued   = activityContext.GetState <bool>("Queued");
            var priority = activityContext.GetState <int>("Priority");

            var recipients = this.GetRecipients(permission);

            foreach (var recipient in recipients.Where(c => !string.IsNullOrEmpty(c.Email)))
            {
                temp.Add(ActivityTokenProvider.UserKey, recipient);
                string body    = this.tokenizer.Replace(ticketEmailTemplate.Body, temp);
                string subject = this.tokenizer.Replace(ticketEmailTemplate.Subject, temp);
                this.SendEmail(subject, body, recipient.Email, queued, priority);
            }

            return(new[] { T("Done") });
        }
        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);
        }
Пример #26
0
        protected DriverResult GanttChartDisplay(MilestonePart part, dynamic shapeHelper)
        {
            List <DriverResult> shapes = new List <DriverResult>();

            EditMilestoneViewModel model = this.Convert(part);

            shapes.Add(ContentShape("Parts_Milestone_Data", () => shapeHelper.Parts_Milestone_Data(Model: model)));

            var memberShapes = this.GetMilestoneMembers(part.Id, "GanttChart", false).ToList();

            memberShapes.ForEach(c =>
            {
                ContentItem contentItem = c.ContentItem;
                TicketPart ticket       = contentItem.As <TicketPart>();
                c.StatusId = ticket.Record.StatusRecord != null ? (int?)ticket.Record.StatusRecord.Id : null;
            });

            dynamic ticketsModel = new ExpandoObject();

            ticketsModel.Milestone = model;

            List <dynamic> months = new List <dynamic>();

            List <DateTime> daysInDateTime = new List <DateTime>();

            // List of days in milestone
            if (model.Start.HasValue && model.End.HasValue && model.Start.Value < model.End.Value)
            {
                for (var day = model.Start.Value.Date; day <= model.End.Value.Date; day = day.AddDays(1))
                {
                    daysInDateTime.Add(CRMHelper.SetSiteTimeZone(this.services.WorkContext, day));
                }
            }

            var monthNames = new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

            var monthsInDayTime = daysInDateTime.GroupBy(c => new { c.Year, c.Month });

            foreach (var item in monthsInDayTime)
            {
                List <string> days  = new List <string>();
                dynamic       month = new ExpandoObject();
                month.Month = item.Key.Month;
                month.Year  = item.Key.Year;
                month.Name  = T(monthNames[item.Key.Month - 1]).Text;
                months.Add(month);

                foreach (var day in item)
                {
                    daysInDateTime.Add(day);
                    days.Add(day.ToString("yyyy-MM-dd"));
                }

                month.Days = days;
            }

            ticketsModel.Months = months;
            ticketsModel.Items  = memberShapes;
            ticketsModel.Today  = CRMHelper.SetSiteTimeZone(this.services.WorkContext, DateTime.UtcNow).ToString("yyyy-MM-dd");

            // we want to represent the tickets in a table where there is a column for each status.
            var statusRecords = this.basicDataService.GetStatusRecords().ToList();

            statusRecords.Insert(0, new StatusRecord {
                Id = 0, OrderId = 0, Name = T("No Status").Text
            });
            ticketsModel.StatusRecords = statusRecords;

            shapes.Add(ContentShape("Parts_Milestone_GanttChart", () => shapeHelper.Parts_Milestone_GanttChart(Model: JsonConvert.SerializeObject(ticketsModel))));

            return(this.Combined(shapes.ToArray()));
        }
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            TicketPart                ticketPart      = workflowContext.Content.As <TicketPart>();
            CRMCommentPart            commentPart     = workflowContext.Content.As <CRMCommentPart>();
            ContentItemPermissionPart permissionsPart = workflowContext.Content.As <ContentItemPermissionPart>();

            if (ticketPart == null)
            {
                if (commentPart == null)
                {
                    this.Logger.Debug("ContentItem mismatch: Expexting TicketPart");
                    return(new[] { T("Failed") });
                }
                else
                {
                    var contentPart = this.contentManager.Get(commentPart.Record.CRMCommentsPartRecord.ContentItemRecord.Id);
                    ticketPart      = contentPart.As <TicketPart>();
                    permissionsPart = contentPart.As <ContentItemPermissionPart>();
                }
            }

            if (permissionsPart == null)
            {
                this.Logger.Debug("ContentItem mismatch: Expexting ContentItemPermissionPart ");
                return(new[] { T("Failed") });
            }

            // setup tokenizer
            Dictionary <string, object> temp = new Dictionary <string, object>();

            temp.Add("Content", workflowContext.Content);
            var titlePart = ticketPart.As <TitlePart>();

            // read email template Id
            string emailTemplateIdString = activityContext.GetState <string>(EmailTemplateActivityForm.EmailTemplateIdFieldName);
            int    emailTemplateId;

            if (!int.TryParse(emailTemplateIdString, out emailTemplateId))
            {
                this.Logger.Debug("There is no email Template for new Tickets");
                return(new[] { T("Failed") });
            }

            bool sendToRequestingUser  = this.GetBooleanValue(activityContext, EmailTemplateActivityForm.SentToRequestingUserFieldName);
            bool sendToOwner           = this.GetBooleanValue(activityContext, EmailTemplateActivityForm.SentToOwnerFieldName);
            bool sendToSharedWithUsers = this.GetBooleanValue(activityContext, EmailTemplateActivityForm.SentToSharedUsersFieldName);

            var ticketEmailTemplate = this.emailTemplateRepository.Table.First(c => c.Id == emailTemplateId);

            if (ticketEmailTemplate == null)
            {
                this.Logger.Debug("There is no email Template for new Tickets");
                return(new[] { T("Failed") });
            }

            var queued   = activityContext.GetState <bool>("Queued");
            var priority = activityContext.GetState <int>("Priority");

            List <UserPartRecord> recipients = new List <UserPartRecord>();

            if (permissionsPart.Record.Items != null)
            {
                foreach (var permission in permissionsPart.Record.Items)
                {
                    if (permission.AccessType == ContentItemPermissionAccessTypes.Assignee && sendToOwner)
                    {
                        recipients.AddRange(this.GetRecipients(permission));
                    }
                    else if (sendToSharedWithUsers)
                    {
                        recipients.AddRange(this.GetRecipients(permission));
                    }
                }
            }

            if (sendToRequestingUser)
            {
                var record = ticketPart.Record;
                if (record.RequestingUser != null)
                {
                    recipients.Add(record.RequestingUser);
                }
                else if (record.SourceId == TicketSourceTypes.Email &&
                         !string.IsNullOrEmpty(record.SourceData))
                {
                    dynamic sender = JObject.Parse(record.SourceData);
                    string  email  = sender.Email;
                    string  name   = sender.Name;
                    recipients.Add(new UserPartRecord {
                        Email = email, UserName = name
                    });
                }
            }

            // filter the redundent items
            recipients = recipients.GroupBy(c => c.Id).Select(c => c.First()).ToList();

            foreach (var recipient in recipients.Where(c => !string.IsNullOrEmpty(c.Email)))
            {
                temp[ActivityTokenProvider.UserKey] = recipient;
                string body    = this.tokenizer.Replace(ticketEmailTemplate.Body, temp);
                string subject = this.tokenizer.Replace(ticketEmailTemplate.Subject, temp);
                this.SendEmail(subject, body, recipient.Email, queued, priority);
            }

            return(new[] { T("Done") });
        }
        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;
            }
        }