コード例 #1
0
        public async Task <IServiceResult <string> > Create(CreateOrderRequest input)
        {
            var getBasketResult = await _getBasketService.Get(input.BuyerId);

            if (getBasketResult.Status != ServiceResultStatus.Ok)
            {
                return(ServiceResult <string> .BadRequest("an error was eccured while fetching shopping basket data."));
            }

            var items = ((BasketItemDto[])getBasketResult.Value)
                        .Select(x => new OrderItem(x.ProductId, x.UnitPrice, x.Units, x.Discount));

            var order = new Order(input.BuyerId, items);

            var clearBasketResult = await _clearBasketService.Clear(order.BuyerId);

            if (clearBasketResult.Status != ServiceResultStatus.Ok)
            {
                return(ServiceResult <string> .BadRequest("an error was eccured while clearing shopping basket."));
            }

            await _orderRepository.InsertAsync(order);

            await _unitOfWork.CommitAsync();

            await _messagePublisher.PublishAsync(new OrderCreatedEvent(
                                                     order.Id,
                                                     order.BuyerId,
                                                     new Dictionary <int, double>(order.Items.Select(x => new KeyValuePair <int, double>(x.ProductId, x.Units)))));

            return(ServiceResult <string> .Ok(order.Id));
        }
コード例 #2
0
        public async Task <ServiceResult> AddAsync(AddUserContract user)
        {
            ServiceResult result = new ServiceResult();

            try
            {
                var check = await userRepository.GetCountAsync(userRepository.GetTable.Where(d => d.UserID.Equals(user.UserID)).AsQueryable());

                if (check == 0)
                {
                    tUser data = new tUser
                    {
                        UserID     = Guid.Parse(user.UserID.ToString()),
                        Password   = HelperMethod.encrypt(user.Password),
                        FirstName  = user.FirstName,
                        LastName   = user.LastName,
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now
                    };
                    var save = await userRepository.AddAsync(data);

                    result = save.status;
                }
                else
                {
                    result.BadRequest("REGISTERED_ALREADY");
                }
                return(result);
            }
            catch (Exception ex)
            {
                result.Error("ERROR", ex.Message);
            }
            return(result);
        }
        public override async Task <ServiceResult> Delete(int id)
        {
            var getPregledResult = await GetPregledForManipulation(id);

            if (!getPregledResult.Succeeded)
            {
                return(ServiceResult.WithStatusCode(getPregledResult.StatusCode, getPregledResult.Message));
            }

            var pregledFromDb = getPregledResult.Data as Pregled;

            if (pregledFromDb == null)
            {
                return(ServiceResult.NotFound());
            }

            if (await _dbContext.LekarskaUverenja.AnyAsync(x => x.PregledId == id))
            {
                return(ServiceResult.BadRequest("Ne mozete brisati pregled sve dok ima lekarskih uverenja povezanih sa ovim pregledom."));
            }

            await Task.Run(() =>
            {
                _dbContext.Remove(pregledFromDb);
            });

            await _dbContext.SaveChangesAsync();

            return(ServiceResult.NoContent());
        }
コード例 #4
0
        public async Task <ServiceResult> RemoveFromRoles(int id, KorisnickiNalogRolesUpsertDto request)
        {
            var korisnickiNalog = await _dbContext.KorisnickiNalozi.FindAsync(id);

            if (korisnickiNalog == null)
            {
                return(ServiceResult.NotFound($"Korisnicki nalog sa ID-em {id} nije pronadjen."));
            }

            var roleKorisnickiNalog = await _dbContext.RolesKorisnickiNalozi.FirstOrDefaultAsync(x =>
                                                                                                 x.RoleId == request.RoleId && korisnickiNalog.Id == x.KorisnickiNalogId);

            if (roleKorisnickiNalog == null)
            {
                return(ServiceResult.BadRequest($"Korisnik sa ID-em {id} ne poseduje role sa ID-em {request.RoleId}"));
            }

            await Task.Run(() =>
            {
                _dbContext.RolesKorisnickiNalozi.Remove(roleKorisnickiNalog);
            });

            await _dbContext.SaveChangesAsync();

            await _dbContext.Entry(korisnickiNalog).Collection(x => x.RolesKorisnickiNalog).LoadAsync();

            return(ServiceResult.OK(_mapper.Map <KorisnickiNalogDtoLL>(korisnickiNalog)));
        }
コード例 #5
0
        public async Task <ServiceResult> ChangePassword(string currentPassword, string newPassword)
        {
            if (string.IsNullOrWhiteSpace(currentPassword) || string.IsNullOrWhiteSpace(newPassword))
            {
                return(ServiceResult.BadRequest());
            }

            currentPassword = currentPassword.RemoveWhitespaces();
            newPassword     = newPassword.RemoveWhitespaces();

            var currentUser = await _authService.LoggedInUser();

            var userFromDb = await _dbContext.KorisnickiNalozi.FindAsync(currentUser.Id);

            var hashedCurrentPassword = _securityService.GenerateHash(userFromDb.PasswordSalt, currentPassword);

            if (userFromDb.PasswordHash != hashedCurrentPassword)
            {
                return(ServiceResult.BadRequest("Netačna trenutna lozinka"));
            }

            userFromDb.PasswordSalt = _securityService.GenerateSalt();
            var hash = _securityService.GenerateHash(userFromDb.PasswordSalt, newPassword);

            userFromDb.PasswordHash = hash;
            await _dbContext.SaveChangesAsync();

            return(ServiceResult.OK());
        }
コード例 #6
0
        public override async Task <ServiceResult> Delete(int id)
        {
            if (await _dbContext.ZahteviZaPregled.AnyAsync(x => x.UputnicaId == id))
            {
                return(ServiceResult.BadRequest("Ne mozete brisati uputnicu sve dok ima zahteva za pregled koji su referencirani na nju."));
            }

            var getUputnicaResult = await GetUputnicaForManipulation(id);

            if (!getUputnicaResult.Succeeded)
            {
                return(ServiceResult.WithStatusCode(getUputnicaResult.StatusCode, getUputnicaResult.Message));
            }

            var uputnicaFromDb = getUputnicaResult.Data as Uputnica;

            if (uputnicaFromDb == null)
            {
                return(ServiceResult.NotFound());
            }

            await Task.Run(() =>
            {
                _dbContext.Remove(uputnicaFromDb);
            });

            await _dbContext.SaveChangesAsync();

            return(ServiceResult.NoContent());
        }
コード例 #7
0
        public async Task <IServiceResult <int> > Create(CreateProductInput input)
        {
            if (await ValidateUnit(input))
            {
                return(ServiceResult <int> .BadRequest("unit is not exists."));
            }

            if (await ValidateCategory(input))
            {
                return(ServiceResult <int> .BadRequest("category is not exists."));
            }

            if (await ValidateWarehouse(input))
            {
                return(ServiceResult <int> .BadRequest("warehouse is not exists."));
            }

            var product = new Product(
                input.Name,
                input.Description,
                input.Stock,
                input.UnitId,
                input.WarehouseId,
                input.CategoryId);

            await _databaseContext.Products.AddAsync(product);

            await _databaseContext.SaveChangesAsync();

            await _messagePublisher.PublishAsync(new ProductCreatedEvent(product.Id, product.Name));

            return(ServiceResult <int> .Ok(product.Id));
        }
コード例 #8
0
        public override async Task <ServiceResult> Insert(KorisnickiNalogUpsertDto request)
        {
            if (await ValidateModel(request) is { } validationResult&& !validationResult.Succeeded)
            {
                return(ServiceResult.WithStatusCode(validationResult.StatusCode, validationResult.Message));
            }

            var korisnickiNalog = _mapper.Map <KorisnickiNalog>(request);

            if (request.ConfirmPassword != request.Password)
            {
                return(ServiceResult.BadRequest("Lozinke se ne podudaraju"));
            }

            korisnickiNalog.PasswordSalt = _securityService.GenerateSalt();
            korisnickiNalog.PasswordHash = _securityService.GenerateHash(korisnickiNalog.PasswordSalt, request.Password);

            korisnickiNalog.DateCreated = DateTime.Now;
            korisnickiNalog.LastOnline  = DateTime.Now;

            await _dbContext.KorisnickiNalozi.AddAsync(korisnickiNalog);

            await _dbContext.SaveChangesAsync();

            var roleType = RoleTypeManager.RoleTypeFromString(request.RoleType);

            if (roleType.HasValue)
            {
                await AddInRole(korisnickiNalog.Id, roleType.Value);
            }

            return(ServiceResult.OK(_mapper.Map <KorisnickiNalogDtoLL>(korisnickiNalog)));
        }
コード例 #9
0
        public async Task <IServiceResult> Update(UpdateOrderAddressRequest input)
        {
            var order = await _orderRepository.FindAsync(input.OrderId);

            if (order is null)
            {
                return(ServiceResult.NotFound());
            }

            var getAddressResponse = await _httpClient.GetAsync(ServiceRoute.GetAddressById(input.AddressId));

            if (!getAddressResponse.IsSuccessStatusCode)
            {
                return(ServiceResult.BadRequest("An error was eccured whiule fetching address from location service."));
            }

            var getAddressContent = await getAddressResponse.Content.ReadAsStringAsync();

            var address = JsonSerializer.Deserialize <AddressDto>(getAddressContent);

            order.UpdateLocation(
                address.Description,
                address.ZipCode,
                address.CityId,
                address.Longitude,
                address.Latitude);

            await _unitOfWork.CommitAsync();

            await _messagePublisher.PublishAsync(new OrderAddressUpdatedEvent(order.Id, address.CityId));

            return(ServiceResult.Ok());
        }
コード例 #10
0
        public override async Task <ServiceResult> Delete(int id)
        {
            if (await _dbContext.LicniPodaci.AnyAsync(x => x.GradId == id))
            {
                return(ServiceResult.BadRequest("Postoje licni podaci koji su referencirani na ovaj grad"));
            }

            return(await base.Delete(id));
        }
コード例 #11
0
        public override async Task <ServiceResult> Delete(int id)
        {
            if (await _dbContext.Gradovi.AnyAsync(x => x.DrzavaId == id))
            {
                return(ServiceResult.BadRequest("Postoje gradovi koji su referencirani na ovu drzavu"));
            }

            return(await base.Delete(id));
        }
コード例 #12
0
        public override async Task <ServiceResult> Delete(int id)
        {
            if (await _dbContext.RolesKorisnickiNalozi.AnyAsync(x => x.RoleId == id))
            {
                return(ServiceResult.BadRequest("Ne mozete izbrisati ovu rolu sve dok je dodijeljena nekom od korisnika"));
            }

            return(await base.Delete(id));
        }
コード例 #13
0
        public virtual async Task <ServiceResult> Get(TResourceParameters resourceParameters)
        {
            IQueryable <TEntity> result;

            if (resourceParameters != null)
            {
                if (ShouldEagerLoad(resourceParameters))
                {
                    //check prop and prop mapping
                    var propertyCheckResult = PropertyCheck <TDtoEagerLoaded>(resourceParameters.OrderBy);
                    if (!propertyCheckResult.Succeded)
                    {
                        return(ServiceResult.BadRequest(propertyCheckResult.Message));
                    }

                    result = GetWithEagerLoad();
                }
                else
                {
                    //check prop and prop mapping
                    var propertyCheckResult = PropertyCheck <TDto>(resourceParameters.OrderBy);
                    if (!propertyCheckResult.Succeded)
                    {
                        return(ServiceResult.BadRequest(propertyCheckResult.Message));
                    }
                    result = _dbContext.Set <TEntity>().AsQueryable();
                }
            }
            else
            {
                result = _dbContext.Set <TEntity>().AsQueryable();
            }

            var pagedResult = await FilterAndPrepare(result, resourceParameters) ?? new PagedList <TEntity>(new List <TEntity>(), 0, 0, 0);

            var serviceResultToReturn = new SequenceResult()
            {
                PaginationMetadata = new PaginationMetadata()
                {
                    CurrentPage = pagedResult.CurrentPage,
                    PageSize    = pagedResult.PageSize,
                    TotalCount  = pagedResult.TotalCount,
                    TotalPages  = pagedResult.TotalPages
                },
                Data        = PrepareDataForClient(pagedResult, resourceParameters: resourceParameters),
                HasNext     = pagedResult.HasNext,
                HasPrevious = pagedResult.HasPrevious
            };

            return(ServiceResult.OK(serviceResultToReturn));
        }
コード例 #14
0
        private async Task <ServiceResult> ValidateModel(KorisnickiNalogUpsertDto dto)
        {
            if (dto == null)
            {
                return(ServiceResult.BadRequest());
            }

            if (await _dbContext.KorisnickiNalozi.AnyAsync(x => x.Username.ToLower() == dto.Username.ToLower()))
            {
                return(ServiceResult.BadRequest($"Vec postoji korisnicki nalog koji koristi username {dto.Username}."));
            }

            return(ServiceResult.WithStatusCode(HttpStatusCode.OK));
        }
コード例 #15
0
        public ServiceResult <string> GetHome()
        {
            ++_numTimesCalled;

            if (_numTimesCalled > 3)
            {
                return(ServiceResult.BadRequest <string>("Dude. Really."));
            }
            if (_numTimesCalled > 1)
            {
                return(ServiceResult.Conflict <string>("I already told you we're up!"));
            }

            return(ServiceResult.Ok("Up and running!"));
        }
コード例 #16
0
        public async Task <ServiceResult> CheckPassword(string password)
        {
            var user = await _authService.LoggedInUser();

            if (user == null)
            {
                return(ServiceResult.Unauthorized());
            }

            if (user.PasswordHash == _securityService.GenerateHash(user.PasswordSalt, password))
            {
                return(ServiceResult.OK());
            }

            return(ServiceResult.BadRequest(Resources.IncorrectPassword));
        }
コード例 #17
0
        public async Task <ServiceResult> AccountLocked(string username, string password)
        {
            var user = await Authenticate(username, password);

            if (user == null)
            {
                return(ServiceResult.BadRequest("Korisnicki nalog nije pronadjen"));
            }

            if (user.LockedOut)
            {
                return(ServiceResult.WithStatusCode(HttpStatusCode.Locked));
            }

            return(ServiceResult.OK());
        }
コード例 #18
0
        public override async Task <ServiceResult> Delete(int id)
        {
            var getDoktorResult = await GetDoktor(id);

            if (!getDoktorResult.Succeeded)
            {
                return(ServiceResult.WithStatusCode(getDoktorResult.StatusCode, getDoktorResult.Message));
            }

            var doktorFromDb = getDoktorResult.doktor;

            if (!await _authService.CurrentUserIsInRoleAsync(RoleType.Administrator) && doktorFromDb.Radnik.KorisnickiNalogId != ((await _authService.LoggedInUser())?.Id ?? 0))
            {
                return(ServiceResult.Forbidden("Ne mozete vrsiti izmene na drugim profilima doktora."));
            }

            if (await _dbContext.Uputnice.AnyAsync(x => x.UputioDoktorId == doktorFromDb.Id || x.UpucenKodDoktoraId == doktorFromDb.Id))
            {
                return(ServiceResult.BadRequest("Ne mozete izbrisati profil doktora sve dok postoje uputnice koje su povezane sa ovim doktorom."));
            }

            if (await _dbContext.ZahteviZaPregled.AnyAsync(x => x.DoktorId == doktorFromDb.Id))
            {
                return(ServiceResult.BadRequest("Ne mozete izbrisati profil doktora sve dok postoje zahtevi za pregled kod ovog doktora."));
            }

            if (await _dbContext.Pregledi.AnyAsync(x => x.DoktorId == doktorFromDb.Id))
            {
                return(ServiceResult.BadRequest("Ne mozete izbrisati profil doktora sve dok postoje zakazani ili odradjeni pregledi koje je odradio ovaj doktor."));
            }

            if (await _dbContext.ZdravstvenaKnjizica.AnyAsync(x => x.DoktorId == doktorFromDb.Id))
            {
                return(ServiceResult.BadRequest("Ne mozete izbrisati profil doktora sve dok ima zdravstvenih knjizica koje su povezane sa ovim doktorom."));
            }

            await _radnikService.Delete(doktorFromDb.RadnikId);

            await Task.Run(() =>
            {
                _dbContext.Remove(doktorFromDb);
            });

            await _dbContext.SaveChangesAsync();

            return(ServiceResult.NoContent());
        }
コード例 #19
0
        public override async Task <ServiceResult> Insert(PregledUpsertDto dtoForCreation)
        {
            var doktor = await _authService.GetCurrentLoggedInDoktor();

            if (doktor == null)
            {
                return(ServiceResult.Forbidden("Samo doktori mogu kreirati novi pregled."));
            }
            if (await ValidateModel(dtoForCreation) is { } result&& !result.Succeeded)
            {
                return(ServiceResult.WithStatusCode(result.StatusCode, result.Message));
            }

            if (await _dbContext.Pregledi.AnyAsync(x => x.DatumPregleda == dtoForCreation.DatumPregleda))
            {
                return(ServiceResult.BadRequest($"Termin {dtoForCreation.DatumPregleda:g} je već zauzet"));
            }
            var entity = new Pregled
            {
                DoktorId          = doktor.Id,
                PacijentId        = dtoForCreation.PacijentId,
                ZahtevZaPregledId = dtoForCreation.ZahtevZaPregledId,
                DatumPregleda     = dtoForCreation.DatumPregleda,
                IsOdradjen        = false
            };

            var zahtevFromDb = await _dbContext.ZahteviZaPregled.FindAsync(dtoForCreation.ZahtevZaPregledId);

            zahtevFromDb.IsObradjen = true;

            await _dbContext.AddAsync(entity);

            await _dbContext.SaveChangesAsync();

            var pacijent = await _dbContext.Pacijenti
                           .Include(x => x.ZdravstvenaKnjizica)
                           .ThenInclude(x => x.LicniPodaci)
                           .FirstOrDefaultAsync(x => x.Id == entity.PacijentId);

            await AddAndTrainModel(new GodisteVrijemeIdModel
            {
                Godiste    = (uint)pacijent.ZdravstvenaKnjizica.LicniPodaci.DatumRodjenja.Year,
                VrijemeUid = GetVrijemeUid(entity.DatumPregleda.TimeOfDay.Minutes)
            });

            return(ServiceResult.OK(_mapper.Map <PregledDtoLL>(entity)));
        }
コード例 #20
0
        public override async Task <ServiceResult> Update(int id, KorisnickiNalogUpsertDto dtoForUpdate)
        {
            var korisnickiNalog = await _dbContext.KorisnickiNalozi.FindAsync(id);

            if (korisnickiNalog == null)
            {
                return(ServiceResult.NotFound("Korisnicki nalog nije pronadjen"));
            }

            if (await ValidateModel(dtoForUpdate) is { } validationResult&& !validationResult.Succeeded)
            {
                return(ServiceResult.WithStatusCode(validationResult.StatusCode, validationResult.Message));
            }

            _mapper.Map(dtoForUpdate, korisnickiNalog);

            if (!string.IsNullOrEmpty(dtoForUpdate.Password) && dtoForUpdate.Password != dtoForUpdate.ConfirmPassword)
            {
                return(ServiceResult.BadRequest("Lozinke se ne podudaraju"));
            }

            await Task.Run(() =>
            {
                korisnickiNalog.PasswordSalt = _securityService.GenerateSalt();
                korisnickiNalog.PasswordHash = _securityService.GenerateHash(korisnickiNalog.PasswordSalt, dtoForUpdate.Password);

                korisnickiNalog.DateCreated = DateTime.Now;
                korisnickiNalog.LastOnline  = DateTime.Now;

                _dbContext.KorisnickiNalozi.Update(korisnickiNalog);
            });

            var roleType = RoleTypeManager.RoleTypeFromString(dtoForUpdate.RoleType);

            if (roleType.HasValue)
            {
                await AddInRole(id, roleType.Value);
            }

            await _dbContext.SaveChangesAsync();

            //Load RoleKorisnickiNalog relations
            await _dbContext.Entry(korisnickiNalog).Collection(x => x.RolesKorisnickiNalog).LoadAsync();

            return(ServiceResult.OK(_mapper.Map <KorisnickiNalogDtoLL>(korisnickiNalog)));
        }
コード例 #21
0
        private async Task <ServiceResult> ValidateModel(UputnicaUpsertDto dto)
        {
            if (dto == null)
            {
                return(ServiceResult.BadRequest());
            }

            if (!await _dbContext.Doktori.AnyAsync(x => x.Id == dto.UpucenKodDoktoraId))
            {
                return(ServiceResult.NotFound($"Doktor sa ID-em {dto.UpucenKodDoktoraId} nije pronadjen."));
            }

            if (!await _dbContext.Pacijenti.AnyAsync(x => x.Id == dto.PacijentId))
            {
                return(ServiceResult.NotFound($"Pacijent sa ID-em {dto.PacijentId} nije pronadjen."));
            }

            return(ServiceResult.WithStatusCode(HttpStatusCode.OK));
        }
コード例 #22
0
        public async Task <IServiceResult> Delete(int id)
        {
            var warehouse = await _databaseContext.Warehouses.FindAsync(id);

            if (warehouse is null)
            {
                return(ServiceResult.NotFound());
            }

            if (await HasProduct(warehouse))
            {
                return(ServiceResult.BadRequest("warehouse contains some products"));
            }

            _databaseContext.Warehouses.Remove(warehouse);
            await _databaseContext.SaveChangesAsync();

            return(ServiceResult.Ok());
        }
コード例 #23
0
        public override async Task <ServiceResult> Delete(int id)
        {
            var entityFromDb = await _dbContext.ZdravstvenaStanja.FindAsync(id);

            if (entityFromDb == null)
            {
                return(ServiceResult.NotFound($"Zdravstveno stanje sa ID-em {id} nije pronadjeno"));
            }

            if (await _dbContext.LekarskaUverenja.AnyAsync(x => x.ZdravstvenoStanjeId == id))
            {
                return(ServiceResult.BadRequest("Ne mozete brisati zdravstveno stanje, sve dok ima lekarskih uverenja na kojima je referencirano"));
            }

            await Task.Run(() =>
            {
                _dbContext.Remove(entityFromDb);
            });

            await _dbContext.SaveChangesAsync();

            return(ServiceResult.NoContent());
        }
コード例 #24
0
        public override async Task <ServiceResult> Delete(int id)
        {
            var zdravstvenaKnjizicaFromDb = await _dbContext.ZdravstvenaKnjizica.FindAsync(id);

            if (zdravstvenaKnjizicaFromDb == null)
            {
                return(ServiceResult.NotFound($"Zdravstvena knjizica sa ID-em {id} nije pronadjena."));
            }

            if (await _dbContext.Pacijenti.AnyAsync(x => x.ZdravstvenaKnjizicaId == id))
            {
                return(ServiceResult.BadRequest($"Ne mozete izbrisati zdravstvenu knjizicu, jer postoji pacijent koji je koristi."));
            }

            await Task.Run(() =>
            {
                _dbContext.Remove(zdravstvenaKnjizicaFromDb.LicniPodaci);
                _dbContext.Remove(zdravstvenaKnjizicaFromDb);
            });

            await _dbContext.SaveChangesAsync();

            return(ServiceResult.NoContent());
        }
コード例 #25
0
        public async Task <IServiceResult> Delete(int id)
        {
            var category = await _databaseContext.ProductCategories.FindAsync(id);

            if (category is null)
            {
                return(ServiceResult.NotFound());
            }

            if (await HasChild(category))
            {
                return(ServiceResult.BadRequest("This category referenced by another categories."));
            }

            if (await HasProduct(category))
            {
                return(ServiceResult.BadRequest("This category referenced by another categories."));
            }

            _databaseContext.ProductCategories.Remove(category);
            await _databaseContext.SaveChangesAsync();

            return(ServiceResult.Ok());
        }
        /// <summary>
        /// Prevent data duplication
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="id">Pass ID of entity if validation is from Update method</param>
        /// <returns></returns>
        private async Task <ServiceResult> ValidateModel(LicniPodaciUpsertDto dto, int id = 0)
        {
            if (!await _dbContext.Gradovi.AnyAsync(x => x.Id == dto.GradId))
            {
                return(ServiceResult.NotFound($"Grad sa ID-em {dto.GradId} nije pronadjen"));
            }

            if (await _dbContext.LicniPodaci.AnyAsync(x => x.Id != id && x.JMBG == dto.JMBG))
            {
                return(ServiceResult.BadRequest("Vec postoji korisnik sa istim JMBG."));
            }

            if (await _dbContext.LicniPodaci.AnyAsync(x => x.Id != id && x.BrojTelefona == dto.BrojTelefona.Trim()))
            {
                return(ServiceResult.BadRequest($"Vec postoji korisnik koji koristi broj telefona -> {dto.BrojTelefona}"));
            }

            if (await _dbContext.LicniPodaci.AnyAsync(x => x.Id != id && x.EmailAddress == dto.EmailAddress.Trim()))
            {
                return(ServiceResult.BadRequest($"Vec postoji korisnik koji koristi e-mail adresu -> {dto.EmailAddress}"));
            }

            return(ServiceResult.WithStatusCode(HttpStatusCode.OK));
        }
        public override async Task <ServiceResult> Update(int id, LicniPodaciUpsertDto request)
        {
            if (!await _authService.IsAuthenticated())
            {
                return(ServiceResult.Unauthorized());
            }

            if (await ValidateModel(request, id) is { } validationResult&& !validationResult.Succeeded)
            {
                return(ServiceResult.WithStatusCode(validationResult.StatusCode, validationResult.Message));
            }

            var entity = await _dbContext.LicniPodaci.FindAsync(id);

            if (entity == null)
            {
                return(ServiceResult.NotFound("Licni podaci nisu pronadjeni"));
            }

            if (_authService.UserIsPacijent())
            {
                var pacijent = await _authService.GetCurrentLoggedInPacijent();

                if (pacijent == null)
                {
                    return(ServiceResult.BadRequest());
                }

                var korisnickiNalog = await _dbContext.KorisnickiNalozi.FindAsync(pacijent.KorisnickiNalogId);

                if (request.ProfilePicture != null && request.ProfilePicture.Any())
                {
                    if (entity.ProfilePicture != null && korisnickiNalog.FaceId != null && (!entity.ProfilePicture?.SequenceEqual(request.ProfilePicture) ?? false))
                    {
                        await _faceRecognitionService.AddFaceForUser(request.ProfilePicture, korisnickiNalog.Username, Guid.Parse(korisnickiNalog.FaceId), true);
                    }
                    else
                    {
                        var addedPersonId =
                            await _faceRecognitionService.AddFaceForUser(request.ProfilePicture, korisnickiNalog.Username);

                        korisnickiNalog.FaceId = addedPersonId?.ToString();

                        _dbContext.Update(korisnickiNalog);
                        await _dbContext.SaveChangesAsync();
                    }
                }
            }

            if (!_dbContext.Gradovi.Any(x => x.Id == request.GradId))
            {
                return(ServiceResult.NotFound($"Grad sa ID-em {request.GradId} nije pronadjen"));
            }
            await Task.Run(() =>
            {
                _mapper.Map(request, entity);

                _dbContext.LicniPodaci.Update(entity);
            });

            await _dbContext.SaveChangesAsync();

            return(new ServiceResult(_mapper.Map <LicniPodaciDto>(entity)));
        }
コード例 #28
0
        public async Task <ServiceResult> AutoScheduling()
        {
            var zahteviZaPoseteDanas = _dbContext.ZahteviZaPosetu
                                       .Include(x => x.PacijentNaLecenju)
                                       .Where(x => !x.IsObradjen)
                                       .ToList();

            if (!zahteviZaPoseteDanas.Any())
            {
                return(ServiceResult.BadRequest("Trenutno nema zahteva za posete"));
            }

            var maxBrojPosetiocaPoPacijentu = 2;
            var dnevniBrojTerminaZaPosete   = 2;

            var currentDate             = DateTime.Now.Date;
            var prviTerminPosetePocetak = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 14, 30, 0);

            var drugiTerminPosetePocetak = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 18, 0, 0);

            if (DateTime.Now >= drugiTerminPosetePocetak)
            {
                return(ServiceResult.BadRequest("Vrijeme današnjih poseta je isteklo"));
            }

            if (DateTime.Now >= prviTerminPosetePocetak)
            {
                dnevniBrojTerminaZaPosete = 1;
            }
            bool IsPrviTerminPoseteIstekao = dnevniBrojTerminaZaPosete == 1;

            var pacijentiZaPosete = zahteviZaPoseteDanas
                                    .GroupBy(x => x.PacijentNaLecenjuId)
                                    .Select(x => x.Key)
                                    .ToList();

            zahteviZaPoseteDanas.ForEach(x => x.IsObradjen = true);

            foreach (var pacijentId in pacijentiZaPosete)
            {
                //==== SINGLE PACIJENT ITERATION ====

                var zahteviZaPacijenta = zahteviZaPoseteDanas.Where(x => x.PacijentNaLecenjuId == pacijentId).ToList();

                if (zahteviZaPacijenta.Count > maxBrojPosetiocaPoPacijentu * dnevniBrojTerminaZaPosete)
                {
                    //If the number of requests exceeds maxBrojPosetiocaPoPacijentu * dnevniBrojTerminaZaPosete
                    zahteviZaPacijenta = zahteviZaPacijenta
                                         .OrderBy(x => x.DatumVremeKreiranja)
                                         .Take(maxBrojPosetiocaPoPacijentu * dnevniBrojTerminaZaPosete)
                                         .ToList();
                }

                var flagCounter = 0;
                var vrijeme     = IsPrviTerminPoseteIstekao ? drugiTerminPosetePocetak : prviTerminPosetePocetak; // Ako je prvi istekao, bice dostupan samo drugi termin za posetu
                foreach (var zahtev in zahteviZaPacijenta)
                {
                    if (!IsPrviTerminPoseteIstekao && flagCounter == maxBrojPosetiocaPoPacijentu)
                    {
                        vrijeme = drugiTerminPosetePocetak;
                    }

                    zahtev.ZakazanoDatumVreme = vrijeme;

                    //SMS notifications
                    _smsGateway.Send(zahtev.BrojTelefonaPosetioca, "Zahtev za posetu koji ste poslali je odobren. Odobreno vreme je: " +
                                     $"{zahtev.ZakazanoDatumVreme.Value.ToString("G", CultureInfo.CreateSpecificCulture("de-De"))}");
                    flagCounter++;
                }

                await _dbContext.SaveChangesAsync();
            }

            return(ServiceResult.OK());
        }
コード例 #29
0
        public override async Task <ServiceResult> Insert(PacijentUpsertDto dtoForCreation)
        {
            var zdravstvenaKnjizica = await _dbContext.ZdravstvenaKnjizica
                                      .Include(x => x.LicniPodaci)
                                      .FirstOrDefaultAsync(x => x.Id == dtoForCreation.BrojZdravstveneKnjizice);

            var validInput = await ValidateUpsertData(dtoForCreation, zdravstvenaKnjizica);

            if (!validInput.Succeeded)
            {
                return(ServiceResult.WithStatusCode(validInput.StatusCode, validInput.Message));
            }

            var korisnickiNalog = _mapper.Map <KorisnickiNalog>(dtoForCreation.KorisnickiNalog);

            if (dtoForCreation.KorisnickiNalog.ConfirmPassword != dtoForCreation.KorisnickiNalog.Password)
            {
                return(ServiceResult.BadRequest("Lozinke se ne podudaraju"));
            }

            var addedPersonId =
                await _faceRecognitionService.AddFaceForUser(dtoForCreation.ProfilePicture, dtoForCreation.KorisnickiNalog.Username);

            korisnickiNalog.PasswordSalt = _securityService.GenerateSalt();
            korisnickiNalog.PasswordHash = _securityService.GenerateHash(korisnickiNalog.PasswordSalt, dtoForCreation.KorisnickiNalog.Password);

            korisnickiNalog.DateCreated = DateTime.Now;
            korisnickiNalog.LastOnline  = DateTime.Now;
            korisnickiNalog.FaceId      = addedPersonId.ToString();

            await _dbContext.KorisnickiNalozi.AddAsync(korisnickiNalog);

            await _dbContext.SaveChangesAsync();

            //Adding user to Pacijent role
            var pacijentRole = await _dbContext.Roles.FirstOrDefaultAsync(x => x.Naziv == "Pacijent");

            await _dbContext.RolesKorisnickiNalozi.AddAsync(new RoleKorisnickiNalog
                                                            { KorisnickiNalogId = korisnickiNalog.Id, RoleId = pacijentRole.Id });

            await _dbContext.SaveChangesAsync();

            var pacijent = new Pacijent
            {
                KorisnickiNalogId     = korisnickiNalog.Id,
                ZdravstvenaKnjizicaId = zdravstvenaKnjizica.Id
            };

            await _dbContext.AddAsync(pacijent);

            await _dbContext.SaveChangesAsync();

            var zdravstvenaKnjizicaFromDb = await _dbContext.ZdravstvenaKnjizica
                                            .Include(x => x.LicniPodaci).FirstOrDefaultAsync(x => x.Id == pacijent.ZdravstvenaKnjizicaId);

            if (zdravstvenaKnjizicaFromDb != null)
            {
                zdravstvenaKnjizicaFromDb.LicniPodaci.ProfilePicture = dtoForCreation.ProfilePicture;
                _dbContext.Update(zdravstvenaKnjizicaFromDb.LicniPodaci);
                await _dbContext.SaveChangesAsync();
            }

            return(ServiceResult.OK(_mapper.Map <PacijentDtoLL>(pacijent)));
        }