Ejemplo n.º 1
0
        public void Handle(CreateEmailAddress command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // load person
            var person = command.Person ?? _entities.Get <Person>()
                         .EagerLoad(_entities, new Expression <Func <Person, object> >[]
            {
                x => x.Emails,
            })
                         .Single(x => x.RevisionId == command.PersonId);

            // override IsDefault when person has no default email
            var isDefault = command.IsDefault || !person.Emails.Any(x => x.IsDefault);

            // clear previous default email
            if (isDefault)
            {
                foreach (var email in person.Emails.Where(x => x.IsDefault))
                {
                    _updateEmail.Handle(new UpdateEmailAddress(email)
                    {
                        NoCommit    = true,
                        IsDefault   = false,
                        IsConfirmed = email.IsConfirmed,
                        IsFromSaml  = email.IsFromSaml,
                        Value       = email.Value,
                    });
                }
            }

            // create email address entity
            var entity = new EmailAddress
            {
                IsConfirmed = command.IsConfirmed,
                IsDefault   = isDefault,
                Value       = command.Value,
                Number      = person.Emails.NextNumber(),
                Person      = person,
                IsFromSaml  = command.IsFromSaml,
            };

            person.Emails.Add(entity);

            // log audit
            var audit = new CommandEvent
            {
                RaisedBy = Thread.CurrentPrincipal.Identity.Name,
                Name     = command.GetType().FullName,
                Value    = JsonConvert.SerializeObject(new
                {
                    command.PersonId,
                    command.Value,
                    command.IsConfirmed,
                    IsDefault = isDefault,
                    command.IsFromSaml,
                }),
                NewState = entity.ToJsonAudit(),
            };

            _entities.Create(audit);

            // store
            if (!command.NoCommit)
            {
                _entities.SaveChanges();
            }

            command.CreatedEmailAddress       = entity;
            command.CreatedEmailAddressNumber = entity.Number;
        }