コード例 #1
0
        public async Task <IActionResult> Post([FromBody] GroupDto dto)
        {
            var group = _mapper.Map <Group>(dto);
            await _groupService.AddAsync(group);

            return(Created("localhost", ""));
        }
コード例 #2
0
        public async Task <IActionResult> Create(GroupActionViewModel model)
        {
            if (ModelState.IsValid)
            {
                var username = User.Identity.Name;
                var user     = await _userManager.FindByNameAsync(username);

                var profile = await _profileService.GetProfileByUserId(user.Id);

                var groupDto = new GroupsDto
                {
                    ProfileId   = profile.Id,
                    Title       = model.Title,
                    Description = model.Description,
                    //Currency
                    CurrencyType = 933
                };

                await _groupService.AddAsync(groupDto);

                return(RedirectToAction("Index", "Group"));
            }

            return(View(model));
        }
コード例 #3
0
        public async Task <Person> UpdatePersonAsync(
            UpdatePersonRequest request,
            CancellationToken cancellationToken)
        {
            List <Guid> userGroups = request.Groups?.ToList() ?? new List <Guid>();

            if (request.NewGroups is { } newGroupNames&& newGroupNames.Any())
            {
                foreach (var newGroup in newGroupNames)
                {
                    Group?group = await _groupService.AddAsync(newGroup, cancellationToken);

                    userGroups.Add(group.Id);
                }
            }

            Person person = await _personStore.GetByIdAsnc(request.Id, cancellationToken);

            person.Name          = request.Name;
            person.Groups        = userGroups;
            person.ProfileFaceId = request.ProfileFaceId;
            person.DateOfBirth   = request.DateOfBirth?.Date;

            await _personStore.UpdateAsync(person, cancellationToken);

            await _bus.Publish(new PersonUpdatedMessage(person.Id, "Update"));

            return(person);
        }
コード例 #4
0
ファイル: PersonMutations.cs プロジェクト: lulzzz/magic-media
        public async Task <CreateGroupPayload> CreateGroupAsync(
            string name,
            CancellationToken cancellationToken)
        {
            Group group = await _groupService.AddAsync(name, cancellationToken);

            return(new CreateGroupPayload(group));
        }
コード例 #5
0
        public async Task <IActionResult> PostAsync(Group group)
        {
            group.Id          = Guid.NewGuid().ToString();
            group.CreatedBy   = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
            group.CreatedDate = DateTimeOffset.UtcNow.ToString("s");
            await _groupService.AddAsync(group);

            return(Ok(group.Id));
        }
コード例 #6
0
        public async Task <Result> Add(RegisterGroupModel registerGroupModel)
        {
            ValidationResult validationResult = _registerGroupValidator.Validate(registerGroupModel);

            if (!validationResult.IsValid)
            {
                _logger.LogWarning($"Invalid {typeof(RegisterGroupModel).Name} model");
                return(Result.Fail(validationResult.ToResultError()));
            }

            Result userExists = await _addUserService.UserExists(registerGroupModel.BaseUser);

            if (userExists.Success)
            {
                _logger.LogError($"User already exists");
                return(Result.Fail(USER_ALREADY_EXISTS));
            }

            AddGroupRequest addGroupRequest = new AddGroupRequest()
            {
                Name = registerGroupModel.GroupName
            };

            Result <IdStringModel> addGroupResult = await _groupService.AddAsync(addGroupRequest);

            if (addGroupResult.Failure)
            {
                return(Result.Fail(addGroupResult));
            }

            _logger.LogInformation($"Group added. ${addGroupResult.Value.Id}");

            Result <IdStringModel> addUserResult = await _addUserService.RegisterForGroup(registerGroupModel.BaseUser);

            if (addUserResult.Failure)
            {
                _logger.LogError($"Failed to add user. Removing group. GroupId {addGroupResult.Value.Id}");

                //TODO: remove group

                return(Result.Fail(addUserResult));
            }

            Result addGroupAdminRoleResult = await AddAdminRole(addUserResult.Value.Id, addGroupResult.Value.Id);

            if (addGroupAdminRoleResult.Failure)
            {
                _logger.LogError($"Failed to add user to group.");

                //TODO: remove group, user

                return(Result.Fail(addGroupAdminRoleResult));
            }

            return(Result.Ok());
        }
コード例 #7
0
        public async Task <IActionResult> Creat(CreateGroupDto createGroupDto)
        {
            var res = await _groupService.AddAsync(createGroupDto);

            if (!res.Sucess)
            {
                return(Conflict());
            }
            return(Ok(res.Data));
        }
コード例 #8
0
        public async Task <ActionResult> AddGroupAsync(GroupDto group)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            await _groupService.AddAsync(group);

            return(Ok());
        }
コード例 #9
0
        public async Task <IActionResult> AddGroup([FromBody] Group group, CancellationToken cancellationToken)
        {
            var addedGroup = await _groupsService.AddAsync(group, cancellationToken);

            if (addedGroup == null)
            {
                return(NotFound("No data found !"));
            }

            return(Ok(addedGroup));
        }
コード例 #10
0
        public async Task <HttpResponseMessage> PostAsync(Group group)
        {
            group.Id = Guid.NewGuid().ToString();
            var httpContext = _httpContextAccessor.HttpContext;

            group.CreatedBy   = httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
            group.CreatedDate = DateTimeOffset.UtcNow.ToString("s");
            await _groupService.AddAsync(group);

            return(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
        }
コード例 #11
0
 public async Task<IHttpActionResult> CreateGroup([FromBody]GroupDto group)
 {
     if (!ModelState.IsValid)
     {
         return BadRequest(ModelState);
     }
     var userId = User.Identity.GetUserId();
     group.OwnerUserId = userId;
     var result = await _groupService.AddAsync(group);
     await _userGroupService.AddAsync(userId, result.GroupId);
     return Created(Url.Request.RequestUri + "/" + result.GroupId, result);
 }
コード例 #12
0
        public async Task <ActionResult> Create(IFormCollection collection, GroupViewModel groupViewModel)
        {
            try
            {
                var group = mapper.Map <Group>(groupViewModel);
                await groupService.AddAsync(group);

                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception)
            {
                return(View());
            }
        }
コード例 #13
0
        public async Task <IActionResult> Add([FromBody] Group group)
        {
            try
            {
                var id = await _groupService.AddAsync(group);

                _logger.LogInformation("Added new class");

                return(Ok(id));
            }
            catch (BusinessLogicException ex)
            {
                _logger.LogError(ex.Message);
                return(BadRequest(ex.Message));
            }
        }
コード例 #14
0
        public async Task <IActionResult> Post([FromBody] GroupAddModel value)
        {
            var userId = _validateHelper.GetUserId(HttpContext);

            if (value != null && !value.Users.Any(u => u.Id.Equals(userId)))
            {
                return(Forbid());
            }

            var model = await _groupService.AddAsync(value);

            if (model == null)
            {
                return(BadRequest());
            }
            return(Ok(model));
        }
コード例 #15
0
        public async Task <IActionResult> AddOrUpdateGroup(
            [FromBody] GroupPostModel groupPostModel,
            [FromQuery] bool add = true)
        {
            var group = _groupMapper.Map(groupPostModel);

            if (add)
            {
                await _groupService.AddAsync(group);
            }
            else
            {
                await _groupService.UpdateAsync(group);
            }

            await _groupService.SetStudentsFromGroup(group.GroupId, (IReadOnlyCollection <int>) groupPostModel.Students);

            return(RedirectToAction("Index"));
        }
コード例 #16
0
        public async Task <IActionResult> CreateGroup(string name)
        {
            if (this.User.Identity == null)
            {
                return(NotFound());
            }
            if (!this.User.Identity.IsAuthenticated)
            {
                return(NotFound());
            }

            var admin = await userService.GetOrCreateAsync(this.User);

            var group = new Group()
            {
                Name = name, Admin = admin
            };

            group = await groupService.AddAsync(group);

            return(new JsonResult(group));
        }
コード例 #17
0
        public async Task <IActionResult> AddFirmAsync(GroupDTO groupDtO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.GetErrorMessage()));
            }
            else
            {
                _mapper = GroupMapping.GetMapper().CreateMapper();
                Group group       = _mapper.Map <GroupDTO, Group>(groupDtO);
                var   GroupResult = await _service.AddAsync(group);

                if (GroupResult.Success)
                {
                    return(Ok(GroupResult.Message));
                }
                else
                {
                    return(BadRequest(GroupResult.Message));
                }
            }
        }
コード例 #18
0
        public async Task <HttpResponseMessage> CreateGroup([FromBody] GroupViewModel group)
        {
            await _groupService.AddAsync(Mapper.Map <GroupDto>(group));

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
コード例 #19
0
        public async Task <IActionResult> AddAsync(GroupModel model, CancellationToken ct)
        {
            var group = await _groupService.AddAsync(model.ToServiceModel(), ct);

            return(CreatedAtAction(nameof(GetByIdAsync), new { id = group.Id }, group));
        }
コード例 #20
0
        private async void OnMessageReceived(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            try
            {
                if (e.Message.Chat.Type != ChatType.Group)
                {
                    return;
                }

                long chatId = e.Message.Chat.Id;

                var settings = _cashlogSettingsService.ReadSettings();

                /*if (chatId.ToString() != settings.AdminChatToken)
                 * {
                 *  _logger.Info($"{GetType().Name}: Произведена попытка использования бота в группе `{e.Message.Chat.Title}` ({chatId})");
                 *  await _client.SendTextMessageAsync(chatId, "Чтобы бот мог работать в этой группе обратитесь к @vsoff");
                 *  return;
                 * }*/

                // Получаем группу этого чата.
                Group group = await _groupService.GetByChatTokenAsync(chatId.ToString());

                // Если группы для этого чата нету, то создаём её.
                if (group == null)
                {
                    var admins = await _client.GetChatAdministratorsAsync(chatId);

                    var creator = admins.FirstOrDefault(x => x.Status == ChatMemberStatus.Creator);

                    if (creator == null)
                    {
                        _logger.Warning($"В группе {chatId} не был найден создатель");
                        return;
                    }

                    group = await _groupService.AddAsync(e.Message.Chat.Id.ToString(), creator.User.Id.ToString(), e.Message.Chat.Title ?? "Default chat name");
                }

                Customer[] customers = await _customerService.GetListAsync(group.Id);

                // Собираем всю информацию о пользователе и сообщении.
                UserMessageInfo userMessageInfo = new UserMessageInfo
                {
                    Group       = group,
                    Customers   = customers,
                    UserName    = e.Message.From.Username,
                    UserToken   = e.Message.From.Id.ToString(),
                    MessageType = Core.Models.MessageType.Unknown,
                    Message     = new MessageInfo
                    {
                        //e.Message.ReplyToMessage.MessageId
                        Token       = e.Message.MessageId.ToString(),
                        ReceiptInfo = null,
                        Text        = e.Message.Text,
                    }
                };

                // Дописываем дополнительную инфу.
                switch (e.Message.Type)
                {
                case MessageType.Photo:
                {
                    PhotoSize photoSize = e.Message.Photo.OrderByDescending(x => x.Width).First();
                    _logger.Trace($"{GetType().Name}: Получено фото чека с разрешением W:{photoSize.Width} H:{photoSize.Height}");

                    File file = await _client.GetFileAsync(photoSize.FileId);

                    // Скачиваем изображение.
                    byte[] imageBytes;
                    try
                    {
                        await using MemoryStream clientStream = new MemoryStream();
                        await _client.DownloadFileAsync(file.FilePath, clientStream);

                        imageBytes = clientStream.ToArray();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Ошибка во время скачки изображения с чеком из telegram", ex);
                    }

                    _logger.Trace($"{GetType().Name}: Получено изображение из потока размером {imageBytes.Length} байт");

                    var data = _receiptHandleService.ParsePhoto(imageBytes);
                    _logger.Trace(data == null ? $"{GetType().Name}: Не удалось распознать QR код на чеке" : $"{GetType().Name}: Данные с QR кода чека {data.RawData}");

                    userMessageInfo.Message.ReceiptInfo = data;
                    userMessageInfo.MessageType         = Core.Models.MessageType.QrCode;

                    break;
                }

                case MessageType.Text:
                {
                    userMessageInfo.MessageType = Core.Models.MessageType.Text;
                    break;
                }
                }

                // Уведомляем подписчиков о новом сообщении.
                OnMessage?.Invoke(this, userMessageInfo);
            }
            catch (Exception ex)
            {
                _logger.Error($"{GetType().Name}: Во время обработки полученного сообщения произошла ошибка", ex);
            }
        }
コード例 #21
0
 public async Task <Group> AddAsync(Group group, CancellationToken ct)
 {
     _logger.LogWarning($"### hello from {nameof(AddAsync)} ###");
     return(await _inner.AddAsync(group, ct));
 }