Example #1
0
        /// <summary>
        /// Add or Edit an existing branch
        /// </summary>
        /// <param name="branchId"></param>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <Response> AddOrEditBranchAsync(int branchId, CreateBranchRequest request, CancellationToken cancellationToken = default)
        {
            var responseModel = new Response();

            if (await BranchExists(request.Address.CountryId, request.Address.CityId, request.Name))
            {
                responseModel.AddError(ExceptionCreator.CreateBadRequestError("branch", $"branch name: {request.Name} already exists"));
                return(responseModel);
            }

            if (branchId != 0)
            {
                var branch = await _branchRepo.FindByIdAsync(branchId);

                if (branch != null)
                {
                    branch.Name           = request.Name;
                    branch.Code           = request.Code;
                    branch.Address        = request.Address;
                    branch.LastModifiedBy = _httpContextAccessor.HttpContext.User.Identity.Name;
                    branch.LastModifiedOn = DateTime.UtcNow;

                    await _branchRepo.UpdateAsync(_dbContext, branch);
                }
                else
                {
                    responseModel.AddError(ExceptionCreator.CreateNotFoundError(nameof(branch), $"branch of Id: {branchId} not found"));
                    return(responseModel);
                }
            }
            else
            {
                var newAddress = CreateAddress(request);
                var newBranch  = CreateBranch(request);

                var dbContextTransaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken);

                using (dbContextTransaction)
                {
                    try
                    {
                        await _addressRepo.AddAsync(newAddress, _dbContext);

                        newBranch.AddressId = newAddress.Id;

                        await _branchRepo.AddAsync(_dbContext, newBranch);

                        await dbContextTransaction.CommitAsync(cancellationToken);
                    }
                    catch (Exception ex)
                    {
                        await dbContextTransaction.RollbackAsync(cancellationToken);

                        responseModel.AddError(ExceptionCreator.CreateInternalServerError(ex.ToString()));
                    }
                }
            }

            return(responseModel);
        }
Example #2
0
        public async Task <int> SaveAddressAsync(AddressModel model)
        {
            AddressEntity addressEntity = await _addressRep.FirstOrDefaultAsync(m => m.Id == model.Id);

            using (Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction trs = await _uow.BeginTransactionAsync())
            {
                if (addressEntity == null)
                {
                    //yeni kayit
                    addressEntity = Mapper.Map <AddressModel, AddressEntity>(model);

                    await _addressRep.AddAsync(addressEntity);

                    await _uow.SaveChangesAsync();
                }
                else
                {
                    //güncelleme
                    Mapper.Map(model, addressEntity);

                    await _addressRep.UpdateAsync(addressEntity);

                    await _uow.SaveChangesAsync();
                }

                trs.Commit();
            }

            return(addressEntity.Id);
        }
        //
        // Summary:
        //     /// Method responsible for create registry. ///
        //
        // Parameters:
        //   command:
        //     The command param.
        //
        public async Task <Address> AddAsync(AddressCommand command)
        {
            _validationResult = await _addressValidator.ValidateAsync(command);

            if (_validationResult.IsValid is false)
            {
                return(null);
            }

            if (command.PrimaryAddress is true)
            {
                Address currentPrimaryAddress = await _addressRepository.FindCurrentPrimaryAddressByPersonId(command.PersonId);

                if (currentPrimaryAddress != null)
                {
                    currentPrimaryAddress.UpdatePrimaryAddress(false);

                    await _addressRepository.UpdateAsync(currentPrimaryAddress);
                }
            }

            Person person = await _personRepository.FindAsync(command.PersonId);

            Address address = new Address(command.PostalCode, command.State, command.City, command.District, command.Street, command.StreetNumber, command.Complement, command.PrimaryAddress, person);

            await _addressRepository.AddAsync(address);

            await _entityAuditService.AddAsync("INS", nameof(Address), address);

            return(address);
        }
        public async Task <AddressDetailsDto> Handle(CreateAddressCommand request, CancellationToken cancellationToken)
        {
            var address = _mapper.Map <Address>(request);

            await _addressRepository.AddAsync(address);

            return(_mapper.Map <AddressDetailsDto>(address));
        }
        public async Task <AddressDto> AddAsync(int userId, AddressDto dto)
        {
            var model    = AddressMapper.Map(dto);
            var newModel = await _addressRepository.AddAsync(userId, model);

            var result = AddressDtoMapper.Map(newModel);

            return(result);
        }
Example #6
0
        /// <summary>
        /// Add or Edit an existing address
        /// </summary>
        /// <param name="cityId"></param>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <Response> AddOrEditAddressAsync(int addressId, CreateAddressRequest request, CancellationToken cancellationToken = default)
        {
            var responseModel = new Response();


            if (addressId != 0)
            {
                var address = await _addressRepository.FindByIdAsync(addressId);

                if (address != null)
                {
                    address.Name           = request.Name;
                    address.CountryId      = request.CountryId;
                    address.CityId         = request.CityId;
                    address.DistrictId     = request.DistrictId;
                    address.Street         = request.Street;
                    address.PostalCode     = request.PostalCode;
                    address.LastModifiedBy = _httpContextAccessor.HttpContext.User.Identity.Name;
                    address.LastModifiedOn = DateTime.UtcNow;

                    await _addressRepository.UpdateAsync(address);
                }
                else
                {
                    responseModel.AddError(ExceptionCreator.CreateNotFoundError(nameof(address), $"address id: {addressId} not found"));

                    return(responseModel);
                }
            }
            else
            {
                if (await AddressExistsAsync(request.CountryId, request.CityId, request.DistrictId, request.Street, request.Name))
                {
                    responseModel.AddError(ExceptionCreator.CreateBadRequestError("address", "naddress name does already exist"));

                    return(responseModel);
                }

                try
                {
                    await _addressRepository.AddAsync(CreateAddress(request));
                }
                catch (Exception ex)
                {
                    responseModel.AddError(ExceptionCreator.CreateInternalServerError(ex.ToString()));
                }
            }

            return(responseModel);
        }
Example #7
0
        public async Task <SaveAddressResponse> SaveAsync(Address address)
        {
            try
            {
                await _addressRepository.AddAsync(address);

                await _unitOfWork.CompleteAsync();

                return(new SaveAddressResponse(address));
            }
            catch (Exception ex)
            {
                // Do some logging stuff
                return(new SaveAddressResponse($"An error occurred when saving the address: {ex.Message}"));
            }
        }
        public async Task CreateCoachLesson(CoachLessonCreateDTO coachLessonDTO, int currentUserID)
        {
            Address address = _mapper.Map <Address>(coachLessonDTO.Address);

            address.CoachId = currentUserID;
            Address dbAddress = _addressRepository.Query()
                                .Where(add => add.CoachId == currentUserID)
                                .Where(add => add.Latitude == address.Latitude && add.Longitude == address.Longitude && add.City == address.City && add.Street == address.Street).FirstOrDefault();

            address = dbAddress == null
                ? await _addressRepository.AddAsync(address)
                : address = dbAddress;

            List <CoachLesson> coachLessonList = new List <CoachLesson>();

            DateTime          currentDate = coachLessonDTO.DateStart.Value;
            ICollection <int> levels      = coachLessonDTO.LessonLevels;

            while (currentDate.AddMinutes(coachLessonDTO.Time).Subtract(coachLessonDTO.DateEnd.Value).TotalMinutes <= 0)
            {
                CoachLesson coachLesson = _mapper.Map <CoachLesson>(coachLessonDTO);
                coachLesson.DateStart      = currentDate;
                currentDate                = currentDate.AddMinutes(coachLessonDTO.Time);
                coachLesson.DateEnd        = currentDate;
                coachLesson.AddressId      = address.Id;
                coachLesson.LessonStatusId = (int)LessonStatuses.WaitingForStudents;

                coachLessonList.Add(coachLesson);
            }

            foreach (var item in coachLessonList)
            {
                ICollection <CoachLessonLevel> mappedLevels = new List <CoachLessonLevel>();
                foreach (var level in levels)
                {
                    CoachLessonLevel a = new CoachLessonLevel {
                        CoachLessonId = item.Id, LessonLevelId = level
                    };
                    mappedLevels.Add(a);
                }
                item.LessonLevels = mappedLevels;
                item.CoachId      = currentUserID;
                await _coachLessonRepository.AddAsync(item);
            }
        }
Example #9
0
        public async Task <IActionResult> Create([FromQuery] int clientId, Address address)
        {
            if (!_authentication.IsAuthenticated(User))
            {
                return(RedirectToAction("SignIn", "Authentication"));
            }

            if (!ModelState.IsValid)
            {
                return(PartialView("_AddressModal", address));
            }

            address.ClientId = clientId;
            address.Postcode = address.Postcode.ToUpper();

            Address newAddress = await _repository.AddAsync(address);

            return(PartialView("_AddressModal", newAddress));
        }
Example #10
0
        /// <summary>
        /// Update address Async
        /// </summary>
        /// <exception cref="NotFoundException">No matching address could be found.</exception>
        /// <exception>Tenant with same name already exist.</exception>
        /// <typeparam name="TRequest">Payload type (must be map-able to Address)</typeparam>
        /// <typeparam name="TResponse">Desired return type.</typeparam>
        /// <returns></returns>
        public async Task <TResponse> CreateOrUpdateAsync <TRequest, TResponse>(TRequest addressPayload)
        {
            // Map payload to entity.
            var newAddressEntity = _mapper.Map <Address>(addressPayload);

            if (newAddressEntity.Id == Guid.Empty)
            {
                newAddressEntity.Id = Guid.NewGuid();
            }
            ValidateEntity(newAddressEntity);

            var oldAddressEntity = await _addressRepository.GetByIdAsync(newAddressEntity.Id);

            if (oldAddressEntity.IsNull())
            {
                await _addressRepository.AddAsync(newAddressEntity);
            }

            await _addressRepository.UpdateEntryAsync(newAddressEntity);

            await _addressRepository.SaveChangesAsync();

            return(_mapper.Map <TResponse>(newAddressEntity));
        }
        public override async Task <int> HandleCommand(InsertCompanyCommand request, CancellationToken cancellationToken)
        {
            var id = 0;

            using (var conn = DALHelper.GetConnection())
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        request.Model.Address.CreatedDate  = DateTime.Now;
                        request.Model.Address.CreatedBy    = request.LoginSession?.Id ?? 0;
                        request.Model.Address.ModifiedDate = DateTime.Now;
                        request.Model.Address.ModifiedBy   = request.LoginSession?.Id ?? 0;
                        var addressId = await addressRepository.AddAsync(request.Model.Address);


                        request.Model.Contact.CreatedDate  = DateTime.Now;
                        request.Model.Contact.CreatedBy    = request.LoginSession?.Id ?? 0;
                        request.Model.Contact.ModifiedDate = DateTime.Now;
                        request.Model.Contact.ModifiedBy   = request.LoginSession?.Id ?? 0;
                        var contactId = await contactRepository.AddAsync(request.Model.Contact);

                        request.Model.AddressId    = addressId;
                        request.Model.ContactId    = contactId;
                        request.Model.CreatedDate  = DateTime.Now;
                        request.Model.CreatedBy    = request.LoginSession?.Id ?? 0;
                        request.Model.ModifiedDate = DateTime.Now;
                        request.Model.ModifiedBy   = request.LoginSession?.Id ?? 0;
                        id = await companyRepository.AddAsync(request.Model);

                        Company company = await companyQueries.GetByIdAsync(id);

                        var filePath = await storageFile.getCompanyFilePathAsync(company);

                        if ((request.Model.ImageData?.Length ?? 0) > Constant.MaxImageLength)
                        {
                            throw new BusinessException("Image.OutOfLength");
                        }

                        if (request.Model.IsChangedImage && (request.Model.ImageData?.Length ?? 0) > 0)
                        {
                            string type = CommonHelper.GetImageType(System.Text.Encoding.ASCII.GetBytes(request.Model.ImageData));
                            if (!CommonHelper.IsImageType(type))
                            {
                                throw new BusinessException("Image.WrongType");
                            }
                            string base64Data = request.Model.ImageData.Substring(request.Model.ImageData.IndexOf(",") + 1);
                            string fileName   = Guid.NewGuid().ToString().Replace("-", "");
                            company.LogoPath = await storageFile.SaveCompanyLogo(filePath, type, base64Data);

                            await companyRepository.UpdateAsync(company);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        if (id > 0)
                        {
                            trans.Commit();
                        }
                        else
                        {
                            try { trans.Rollback(); } catch { }
                        }
                    }
                }
            }

            return(id);
        }
Example #12
0
        /// <summary>
        /// Add or Edit an existing customer
        /// </summary>
        /// <param name="customerId"></param>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <Response> AddOrEditCustomerAsync(int customerId, CreateCustomerRequest request, CancellationToken cancellationToken)
        {
            var responseModel = new Response();

            if (await CustomerExistsAsync(request))
            {
                responseModel.AddError(ExceptionCreator.CreateBadRequestError("customer", "customer name does already exist"));
                return(responseModel);
            }

            if (customerId != 0)
            {
                var customer = await _dbContext.Customers.FirstOrDefaultAsync(c => c.Id == customerId && c.Disabled == false);

                try
                {
                    if (customer != null)
                    {
                        customer.IdentificationNo   = request.IdentificationNo;
                        customer.IdentificationType = request.IdentificationType;
                        customer.FirstName          = request.FirstName;
                        customer.MiddleName         = request.MiddleName;
                        customer.LastName           = request.LastName;
                        customer.Gender             = request.Gender;
                        customer.Nationality        = request.Nationality;
                        customer.Address            = request.Address;
                        customer.BirthDate          = request.BirthDate;
                        customer.LastModifiedOn     = DateTime.UtcNow;
                        customer.LastModifiedBy     = _httpContextAccessor.HttpContext.User.Identity.Name;

                        await _customerRepo.UpdateAsync(customer);
                    }
                    else
                    {
                        responseModel.AddError(ExceptionCreator.CreateNotFoundError(nameof(customer), $"customer of id: {customerId} not found"));
                        return(responseModel);
                    }
                }
                catch (Exception ex)
                {
                    responseModel.AddError(ExceptionCreator.CreateInternalServerError(ex.ToString()));
                }
            }
            else
            {
                var newCustomer = CreateCustomer(request);

                var dbContextTransaction = await _dbContext.Database.BeginTransactionAsync();

                using (dbContextTransaction)
                {
                    try
                    {
                        var newAddress = await _addressRepo.AddAsync(CreateAddress(request), _dbContext);

                        newCustomer.AddressId = newAddress.Id;
                        await _customerRepo.AddAsync(_dbContext, newCustomer);

                        await dbContextTransaction.CommitAsync();
                    }
                    catch (Exception ex)
                    {
                        await dbContextTransaction.RollbackAsync();

                        responseModel.AddError(ExceptionCreator.CreateInternalServerError(ex.ToString()));
                    }
                }
            }

            return(responseModel);
        }