public async Task <ActionResult <OfferDTO> > PostOffer(OfferDTO offerDTO)
        {
            Offer offer = DTOToOffer(offerDTO);
            User  user  = await userManager.FindByNameAsync(User.Identity.Name);

            IList <string> roles = await userManager.GetRolesAsync(user);

            if (!roles.Contains(UserRoles.Admin))
            {
                var query = from application in _context.Applications
                            join jobPost in _context.JobPosts on application.JobId equals jobPost.JobPostId
                            join recruiter in _context.Recruiters on user.Id equals recruiter.UserId
                            where jobPost.CompanyId == recruiter.CompanyId && offer.ApplicationId == application.ApplicationId
                            select application;
                if (!await query.AnyAsync())
                {
                    return(Unauthorized("Cannot make an offer for that application"));
                }
            }

            _context.Offers.Add(offer);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("PostOffer", new { ApplicationId = offer.ApplicationId, OfferId = offer.OfferId }, offerDTO));
        }
        public async Task SendRequest(CallbackQueryEventArgs callback)
        {
            long chatid = callback.CallbackQuery.Message.Chat.Id;

            ShowOrdersDTO order = await provider.showOrderService.CurrentProduct(chatid);

            List <int> idProducts = await provider.showOrderService.GetIdTasksForUser(chatid);

            if (idProducts.Contains(order.CurrentProductId))
            {
                await client.SendTextMessageAsync(chatid, "It's your order");

                return;
            }

            BuisnessTaskDTO task = await provider.buisnessTaskService.FindTaskByTaskId(order.CurrentProductId);


            OfferDTO offer = new OfferDTO
            {
                ChatId = chatid,
                TaskId = task.Id
            };

            await provider.offerService.Create(chatid, offer);

            await client.SendTextMessageAsync(chatid, "Created");
        }
Exemplo n.º 3
0
        public IHttpActionResult PostOffer([FromBody] OfferDTO offerDTO)
        {
            offerDTO.DateCreated = DateTime.UtcNow;
            Offer offer = Mapper.Map <OfferDTO, Offer>(offerDTO);

            offer.BranchID = this.getBranchID();

            //if (offerDTO.File != null)
            //{
            //    if (!Utilities.IsImageExtension(Utilities.GetFileExtension(offerDTO.File.FileName)))
            //    {
            //        return BadRequest("Invalid Image");
            //    }
            //    offer.ImageFileName = offerDTO.File.FileName;

            //    using (var binaryReader = new BinaryReader(offerDTO.File.InputStream))
            //    {
            //        offer.Image = binaryReader.ReadBytes(offerDTO.File.ContentLength);
            //    }
            //}

            offerService.AddOffer(offer);
            offerService.SaveOffer();

            offerDTO.OfferID = offer.OfferID;
            return(CreatedAtRoute("DefaultApi", new { id = offer.OfferID }, offerDTO));
        }
Exemplo n.º 4
0
        public void CreateOffer(OfferDTO offerDTO)
        {
            if (offerDTO == null)
            {
                throw new ArgumentNullException(nameof(offerDTO));
            }

            if (offerDTO.Id != 0 && Database.Offers.Get(offerDTO.Id) != null)
            {
                throw new ArgumentOutOfRangeException("Found duplicate id offer");
            }

            if (Database.Resumes.Get(offerDTO.ResumeId) == null)
            {
                throw new ArgumentOutOfRangeException("Invalid argument ResumeId");
            }

            if (Database.Careers.Get(offerDTO.CareerId) == null)
            {
                throw new ArgumentOutOfRangeException("Invalid argument CareerId");
            }

            Database.Offers.Create(Mapper.Map <OfferDTO, Offer>(offerDTO));
            Database.Save();
        }
Exemplo n.º 5
0
        public async Task UpdateOfferAsync(OfferDTO offerDto)
        {
            var offer = await _unitOfWork.OfferRepository
                        .Query
                        .Include(o => o.Company)
                        .Include(o => o.Company.Account)
                        .Include(o => o.Vendor)
                        .Include(o => o.Vendor.Person)
                        .SingleOrDefaultAsync(o => o.Id == offerDto.Id);

            if (offer == null)
            {
                throw new Exception();
            }

            if (!string.IsNullOrEmpty(offerDto.DeclinedMessage))
            {
                offer.DeclinedMessage = offerDto.DeclinedMessage;
            }

            offer.Status = offerDto.Status;
            _unitOfWork.OfferRepository.Update(offer);

            await _unitOfWork.SaveAsync();

            if (offer.Status == OfferStatus.Accepted)
            {
                await AcceptVendorAsync(offer);
            }

            var status = offer.Status == OfferStatus.Accepted ? "accepted" : "declined";

            /*Send message*/

            string msg           = EmailTemplate.OfferStatusChanged(offer.Vendor.Person.Name, status, offer.Company.Id, offer.Vendor.Id);
            string receiverEmail = offer.Company.Account.Email;

            _mailService.Send(new EmailMessage
            {
                ReceiverEmail = receiverEmail,
                Subject       = "Offer status changed",
                Body          = msg,
                IsHtml        = true
            });

            /*Send notification*/

            var notification = new NotificationDTO()
            {
                Title        = $"Offer status changed",
                Description  = $"{offer.Vendor.Person.Name} {status} your offer. Check your vendors page to find out details.",
                SourceItemId = offer.Id,
                Time         = DateTime.Now,
                Type         = NotificationType.OfferNotification
            };

            var receiverId = offer.Company.Account.Id;
            await _notifyService.CreateAsync(receiverId, notification);
        }
 private static Offer DTOToOffer(OfferDTO oDTO) =>
 new Offer
 {
     OfferId           = oDTO.OfferId,
     ApplicationId     = oDTO.ApplicationId,
     Application       = null,
     AcceptanceEndDate = oDTO.AcceptanceEndDate,
     Text = oDTO.Text
 };
Exemplo n.º 7
0
        public List <OfferDTO> GetOffers(OfferCriteria offerCriteria)
        {
            OfferQuery offerQuery = new OfferQuery(language);

            System.Data.DataTable OfferDT = conn_db.ReadTable(offerQuery.GetOffersWithCondition(offerCriteria.filters, offerCriteria.sort));

            OfferDTO        offersDTO;
            List <OfferDTO> Offers = new List <OfferDTO>();

            if (OfferDT.Rows.Count == 0)
            {
                throw new EmptyViewException(language, Messages.GetMessage(language, TypeM.OFFER, offerM.OFFER_NOT_FOUND));
            }

            foreach (System.Data.DataRow dataRow   in OfferDT.Rows)
            {
                offersDTO               = new OfferDTO();
                offersDTO.OFFER_ID      = dataRow["OFFER_ID"] is DBNull ? 0 : Convert.ToInt32(dataRow["OFFER_ID"]);
                offersDTO.ORDER_ID      = dataRow["ORDER_ID"] is DBNull ? 0 : Convert.ToInt32(dataRow["ORDER_ID"]);
                offersDTO.PRICE         = dataRow["PRICE"] is DBNull ? 0 : Convert.ToDouble(dataRow["PRICE"]);
                offersDTO.SUPPLIER_Name = dataRow["SUPPLIER_Name"] is DBNull ? "" : dataRow["SUPPLIER_Name"].ToString();
                offersDTO.timeValue     = dataRow["timeValue"] is DBNull ? 0 : Convert.ToInt32(dataRow["timeValue"]);
                offersDTO.timeFlag      = dataRow["timeFlag"] is DBNull ? 0 : Convert.ToInt32(dataRow["timeFlag"]);
                offersDTO.supplierImage = dataRow["supplierImage"] is DBNull ? "" : dataRow["supplierImage"].ToString();
                offersDTO.PHONENUMBER   = dataRow["PHONENUMBER"] is DBNull ? "" : dataRow["PHONENUMBER"].ToString();
                offersDTO.lat           = dataRow["LOCATIONX"] is DBNull ? 0 : Convert.ToDouble(dataRow["LOCATIONX"]);
                offersDTO.lng           = dataRow["LOCATIONY"] is DBNull ? 0 : Convert.ToDouble(dataRow["LOCATIONY"]);
                offersDTO.Rating        = dataRow["RATING"] is DBNull ? 0 : Convert.ToDouble(dataRow["RATING"]);
                offersDTO.offerStatus   = dataRow["offer_status"] is DBNull ? 0 : Convert.ToInt32(dataRow["offer_status"]);

                offersDTO.RateType   = new Enums().checkRateTypeWords(offersDTO.Rating, language);
                offersDTO.RateTypeId = (int)new Enums().checkRateType(offersDTO.Rating);

                if (offerCriteria.lat == 0 || offerCriteria.lng == 0 || offersDTO.lat == 0 || offersDTO.lng == 0)
                {
                    offersDTO.DISTANCE = 0;
                    offersDTO.time     = "0";
                }

                else
                {
                    double distanceMiles = Math.Sqrt(
                        Math.Pow((offerCriteria.lat - offersDTO.lat) * 69, 2) +
                        Math.Pow((offerCriteria.lng - offersDTO.lng) * 69.172, 2));
                    offersDTO.DISTANCE = Math.Round(distanceMiles * 1.60934, 2);
                    offersDTO.time     = new ServicesRepository(language).getTime(offerCriteria.lat + "," + offerCriteria.lng, offersDTO.lat + "," + offersDTO.lng);
                }



                Offers.Add(offersDTO);
            }



            return(Offers);
        }
Exemplo n.º 8
0
        public async Task <ActionResult> Create(FormCollection collection)
        {
            try
            {
                OfferDTO newOffer = new OfferDTO();
                string   name = "", details = "";

                foreach (string key in collection.AllKeys)
                {
                    switch (key)
                    {
                    case "Name":
                        name          = collection[key];
                        newOffer.Name = collection[key];
                        break;

                    case "AdditionalInfo":
                        newOffer.AdditionalInfo = collection[key];
                        break;

                    case "Details":
                        details = collection[key];
                        break;

                    case "Price":
                        if (Double.TryParse(collection[key], out double value))
                        {
                            newOffer.Price = (long)Math.Truncate(value);
                        }

                        break;

                    case "Category":
                        if (Enum.TryParse(collection[key], out Category newSex))
                        {
                            newOffer.Category = newSex;
                        }
                        break;
                    }
                }

                newOffer.Description = name + ": " + details;
                var user = await UserFacade.GetUserAccordingToUsernameAsync(User.Identity.Name);

                newOffer.CreatorId   = user.Id;
                newOffer.CreatorRole = (UserRole)Enum.Parse(typeof(UserRole), user.UserRole);

                int newId = await OfferFacade.CreateOfferAsync(newOffer);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View("~/Views/Home/GeneralExceptionView.cshtml"));
            }
        }
Exemplo n.º 9
0
        public async Task <int> CreateOfferAsync(OfferDTO offer)
        {
            using (var uow = UnitOfWorkProvider.Create())
            {
                var offerId = offerService.Create(offer);
                await uow.Commit();

                return(offerId);
            }
        }
Exemplo n.º 10
0
 public static Offer FromDTO(OfferDTO offer)
 => new Offer
 {
     Id          = offer.Id,
     TradeId     = offer.TradeId,
     Title       = offer.Title,
     Description = offer.Description,
     ImageUrl    = offer.ImageUrl,
     Target      = offer.Target
 };
Exemplo n.º 11
0
        public void EditOffer_NullElement_ShouldThrowException()
        {
            //arrange
            var Offer = new OfferDTO {
                Id = It.IsAny <int>(), ResumeId = It.IsAny <int>(), VacancyId = It.IsAny <int>(), Checked = It.IsAny <bool>()
            };

            //act & assert
            NUnit.Framework.Assert.Throws <ArgumentOutOfRangeException>(() => offerService.EditOffer(Offer));
        }
 public IActionResult ThisWillNeverBeOverridden([FromBody] OfferDTO offerDTO)
 {
     try
     {
         return(Ok("Something crazy!"));
     }
     catch (Exception ex)
     {
         return(StatusCode(500, ex));
     }
 }
Exemplo n.º 13
0
 public async Task <HttpResponseMessage> UpdateOfferAsync(OfferDTO offer)
 {
     try
     {
         await _offerService.UpdateOfferAsync(offer);
     }
     catch
     {
         return(Request.CreateResponse(HttpStatusCode.BadRequest));
     }
     return(Request.CreateResponse(HttpStatusCode.OK));
 }
Exemplo n.º 14
0
        public void CreateOffer_TryToCreateOffer_ShouldRepositoryCreateOnce()
        {
            var Offer = new OfferDTO {
                Id = It.IsAny <int>()
            };

            // act
            offerService.CreateOffer(Offer);

            //assert
            offerRepository.Verify(x => x.Create(It.IsAny <Offer>()));
        }
Exemplo n.º 15
0
        public OfferDTO Insert(OfferDTO createDto)
        {
            if (createDto == null)
            {
                throw new ArgumentNullException();
            }
            var offer    = Mapper.Map <Offer>(createDto);
            var inserted = TheUnitOfWork.OfferRepo.Insert(offer);

            TheUnitOfWork.SaveChanges();
            return(Mapper.Map <OfferDTO>(inserted));
        }
Exemplo n.º 16
0
        public async Task Create(long chatid, OfferDTO offer)
        {
            if (offer == null)
            {
                throw new SystemException("offer cannot be null");
            }
            int count = await offerRepository.Get().Where(i => i.TaskId == offer.TaskId && i.ChatId == chatid).CountAsync();

            if (count == 0)
            {
                await offerRepository.Create(offer);
            }
        }
 public ActionResult Show(int id)
 {
     using (var repos = DataRepos.Instance)
     {
         OfferDTO offer = repos.Offers.GetById(id);
         if (offer == null)
         {
             return(NewErrorView());
         }
         ViewBag.LocationName = repos.Locations.GetById(offer.LocationId).Name;
         return(View(offer));
     }
 }
Exemplo n.º 18
0
        public bool Update(OfferDTO offerDto)
        {
            if (offerDto == null)
            {
                throw new ArgumentNullException();
            }
            var result = false;
            var offer  = Mapper.Map <Offer>(offerDto);

            TheUnitOfWork.OfferRepo.Update(offer);
            result = TheUnitOfWork.SaveChanges() > new int();
            return(result);
        }
        public async Task <IActionResult> PatchOffer(long appId, long offerId, OfferDTO offerDTO)
        {
            Offer offer = DTOToOffer(offerDTO);

            if (offerId != offerDTO.OfferId || appId != offerDTO.ApplicationId)
            {
                return(BadRequest());
            }

            User user = await userManager.FindByNameAsync(User.Identity.Name);

            IList <string> roles = await userManager.GetRolesAsync(user);

            if (!roles.Contains(UserRoles.Admin))
            {
                var query = from queryOffer in _context.Offers
                            join application in _context.Applications on queryOffer.ApplicationId equals application.ApplicationId
                            join jobPost in _context.JobPosts on application.JobId equals jobPost.JobPostId
                            join recruiter in _context.Recruiters on user.Id equals recruiter.UserId
                            where jobPost.CompanyId == recruiter.CompanyId &&
                            queryOffer.ApplicationId == offer.ApplicationId &&
                            queryOffer.OfferId == offer.OfferId
                            select queryOffer;
                if (!await query.AnyAsync())
                {
                    return(Unauthorized("Cannot make an offer for that application"));
                }
            }

            _context.Entry(offer).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!OfferExists(appId, offerId))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(AcceptedAtAction("PatchOffer", new { ApplicationId = offer.ApplicationId, OfferId = offer.OfferId }, offerDTO));
        }
Exemplo n.º 20
0
        public async Task <List <OfferDTO> > FindAll()
        {
            IEnumerable <Offer> offers = await _context.Offers.Find(_ => true).ToListAsync();

            List <OfferDTO> result = new List <OfferDTO>();

            foreach (Offer offer in offers)
            {
                OfferDTO dto = OfferDTO.FromOffer(offer);

                result.Add(dto);
            }

            return(result);
        }
Exemplo n.º 21
0
        public async Task <List <OfferDTO> > FindOffersByTrade(int tradeId)
        {
            IEnumerable <Offer> offers = await _context.Offers.Find(Builders <Offer> .Filter.Eq(t => t.TradeId, tradeId)).ToListAsync();

            List <OfferDTO> result = new List <OfferDTO>();

            foreach (Offer offer in offers)
            {
                OfferDTO dto = OfferDTO.FromOffer(offer);

                result.Add(dto);
            }

            return(result);
        }
Exemplo n.º 22
0
        public async Task <OfferDTO> Insert(OfferDTO dto)
        {
            Counter counter = await _counterDAO.GetCountersAsync();

            int id = counter.Offers++;
            await _counterDAO.UpdateCountersAsync(counter);

            Offer offer = Offer.FromDTO(dto);

            offer.Id = id;

            await _context.Offers.InsertOneAsync(offer);

            return(OfferDTO.FromOffer(offer));
        }
Exemplo n.º 23
0
        public void RemoveOffer(OfferDTO offerDTO)
        {
            if (offerDTO == null)
            {
                throw new ArgumentNullException(nameof(offerDTO));
            }

            if (Database.Offers.Get(offerDTO.Id) == null)
            {
                throw new ArgumentOutOfRangeException("Not found offer");
            }

            Database.Offers.Delete(offerDTO.Id);
            Database.Save();
        }
Exemplo n.º 24
0
        public async Task <bool> AppyForOfferAsync(OfferDTO offer)
        {
            using (var uow = UnitOfWorkProvider.Create())
            {
                if ((await offerService.GetAsync(offer.Id, false)) == null)
                {
                    return(false);
                }
                await offerService.Update(offer, (int)offer.ApplierId);

                await uow.Commit();

                return(true);
            }
        }
Exemplo n.º 25
0
        public void MakeOffer(OfferDTO offerDto)
        {
            Offer offers = Database.Offers.Get(offerDto.Id);


            Offer offer = new Offer
            {
                Id              = offerDto.Id,
                Name            = offerDto.Name,
                CurrentCategory = offerDto.CurrentCategory
            };

            Database.Offers.Create(offer);
            Database.Save();
        }
Exemplo n.º 26
0
        public void RemoveOffer_Delete()
        {
            var Offer = new OfferDTO {
                Id = It.IsAny <int>(), Checked = It.IsAny <bool>()
            };

            offerRepository.Setup(x => x.Get(It.IsAny <int>())).Returns(new Offer {
                Id = It.IsAny <int>(), Checked = It.IsAny <bool>()
            });

            //act
            offerService.RemoveOffer(Offer);

            //assert
            offerRepository.Verify(x => x.Delete(It.IsAny <int>()));
        }
Exemplo n.º 27
0
        public IHttpActionResult DeleteOffer(int id)
        {
            Offer offer = offerService.GetOffer(id);

            if (offer == null)
            {
                return(NotFound());
            }

            offerService.DeleteOffer(offer);
            offerService.SaveOffer();

            OfferDTO offerDTO = Mapper.Map <Offer, OfferDTO>(offer);

            return(Ok(offerDTO));
        }
Exemplo n.º 28
0
        public async Task SendRequest(CallbackQueryEventArgs callback)
        {
            long chatid = callback.CallbackQuery.Message.Chat.Id;

            ShowOrdersDTO order = await provider.showOrderService.CurrentProduct(chatid);

            List <int> idProducts = await provider.showOrderService.GetIdTasksForUser(chatid);

            if (idProducts.Contains(order.CurrentProductId))
            {
                await client.SendTextMessageAsync(chatid, "Нельзя брать заказ у самого себя");

                return;
            }

            BuisnessTaskDTO task = await provider.buisnessTaskService.FindTaskByTaskId(order.CurrentProductId);

            if (task.ChatIdPerformer.HasValue)
            {
                await client.SendTextMessageAsync(chatid, "К сожалению,этот заказ уже выполняется другим пилотом");

                return;
            }

            OfferDTO offer = new OfferDTO
            {
                ChatId = chatid,
                TaskId = task.Id
            };

            UserDTO user = await provider.userService.FindById(chatid);



            await provider.offerService.Create(chatid, offer);

            string message = $"Пилот {user.FIO} хочет выполнить ваш заказ. " +
                             $"Данные по заказу:\n " +
                             $"Id заказа:{task.Id} \n " +
                             $"Описание заказа:{task.Description} \n " +
                             $"Сумма заказа:{task.Sum} \n " +
                             $"Подробнее можете посмотреть в разделе просмотра своих заявок";

            await client.SendTextMessageAsync(task.ChatId, message);

            await client.SendTextMessageAsync(chatid, "Заявка успеешно создана");
        }
Exemplo n.º 29
0
        public async Task Test_AddOffer_ShouldAddOffer()
        {
            var offer = new OfferDTO
            {
                TutorId = "100",
                Title   = "NewlyAdded"
            };

            var context = await GetContext();

            var offerRepo    = new DbRepository <Offer>(context);
            var offerService = new OfferService(offerRepo);
            int result       = await offerService.AddOffer(offer);

            Assert.Equal(5, context.Offers.CountAsync().Result);
            Assert.Contains("NewlyAdded", context.Offers.Select(p => p.Title).ToArray());
        }
Exemplo n.º 30
0
        public void EditOffer_NullElement_ShouldThrowException()
        {
            //arrange
            var Offer = new OfferDTO {
                Id = It.IsAny <int>(), ResumeId = It.IsAny <int>(), CareerId = It.IsAny <int>(), Viewed = It.IsAny <bool>()
            };

            uow.Setup(x => x.Resumes.Get(It.IsAny <int>())).Returns(new Resume()
            {
            });
            uow.Setup(x => x.Careers.Get(It.IsAny <int>())).Returns(new Career()
            {
            });

            //act & assert
            NUnit.Framework.Assert.Throws <ArgumentOutOfRangeException>(() => offerService.EditOffer(Offer));
        }