Exemple #1
0
        public async Task <IActionResult> NewUnit(NewUnitView model, IFormCollection form, CancellationToken cancellationToken)
        {
            model.Types = await _unitsService.GetUnitTypesForDepartmentAsync(DepartmentId);

            model.Stations = await _departmentGroupsService.GetAllStationGroupsForDepartmentAsync(DepartmentId);

            if ((await _unitsService.GetUnitByNameDepartmentIdAsync(DepartmentId, model.Unit.Name)) != null)
            {
                ModelState.AddModelError("Name", "Unit with that name already exists.");
            }

            var unitRoleNames = (from object key in form.Keys where key.ToString().StartsWith("unitRole_") select form[key.ToString()]).ToList();

            if (ModelState.IsValid)
            {
                model.Unit.DepartmentId = DepartmentId;

                if (model.Unit.StationGroupId.HasValue && model.Unit.StationGroupId.Value == 0)
                {
                    model.Unit.StationGroupId = null;
                }

                model.Unit = await _unitsService.SaveUnitAsync(model.Unit, cancellationToken);

                var roles = new List <UnitRole>();
                if (unitRoleNames.Count > 0)
                {
                    foreach (var roleName in unitRoleNames)
                    {
                        var role = new UnitRole();
                        role.Name   = roleName;
                        role.UnitId = model.Unit.UnitId;

                        roles.Add(role);
                    }
                }

                if (roles.Count > 0)
                {
                    await _unitsService.SetRolesForUnitAsync(model.Unit.UnitId, roles, cancellationToken);
                }

                var auditEvent = new AuditEvent();
                auditEvent.DepartmentId = DepartmentId;
                auditEvent.UserId       = UserId;
                auditEvent.Type         = AuditLogTypes.UnitAdded;
                auditEvent.After        = model.Unit.CloneJson();
                _eventAggregator.SendMessage <AuditEvent>(auditEvent);

                _eventAggregator.SendMessage <UnitAddedEvent>(new UnitAddedEvent()
                {
                    DepartmentId = DepartmentId, Unit = model.Unit
                });

                return(RedirectToAction("Index"));
            }

            return(View(model));
        }