public void AcceptRequest(Agent Agent, Client Client)
        {
            OfferRequest Request = unitOfWork.Repository <OfferRequest>().SingleOrDefault(o => o.ClientUsername == Client.Username);

            Request.State = RequestState.Draft;
            unitOfWork.SaveChanges();
        }
        public void RemoveRequest(Client Client)
        {
            OfferRequest Request = unitOfWork.Repository <OfferRequest>().SingleOrDefault(o => o.ClientUsername == Client.Username);

            Request.isDeleted = true;
            unitOfWork.SaveChanges();
        }
 public override int GetHashCode()
 {
     unchecked
     {
         return((Price.GetHashCode() * OfferRequest.GetHashCode()) ^ 1337);
     }
 }
Exemple #4
0
        public static string[] getOfferRequestToAnswer(string username, int requestID)
        {
            aUser requestsHolder = getUser(username);

            if (requestsHolder == null)
            {
                return(null);
            }

            OfferRequest request = requestsHolder.getRequestToAnswer(requestID);

            if (request == null)
            {
                return(null);
            }

            // convert it to string array
            string[] requestString = new string[7]; // the length is equal to the number of relevant fields in OfferRequest

            requestString[0] = "" + request.id;
            requestString[1] = request.requester.getUserName();
            requestString[2] = request.store.name;
            requestString[3] = request.product.info.ToString();
            requestString[4] = "" + request.product.amount;
            requestString[5] = "" + request.getPrice();
            requestString[6] = "" + request.status;

            return(requestString);
        }
        public async Task <IActionResult> CreateOffer(OfferRequest request)
        {
            if (request is null)
            {
                return(UnprocessableEntity(Constants.ErrorMessages.UnprocessableEntity));
            }

            if (!_context.Auctions.Any(a => a.Id == request.AuctionId))
            {
                return(BadRequest(Constants.ErrorMessages.AuctionDoesntExist));
            }

            if (_context.Auctions.Where(a => a.Id == request.AuctionId).Select(a => a.StartDate).FirstOrDefault().Date > DateTime.UtcNow)
            {
                return(BadRequest(Constants.ErrorMessages.ToSoon));
            }

            var auctionPrice = 0M;

            if (_context.Offers.Any(a => a.AuctionId == request.AuctionId))
            {
                auctionPrice = _context.Offers.Where(a => a.AuctionId == request.AuctionId)
                               .OrderByDescending(a => a.Price)
                               .Select(a => a.Price)
                               .FirstOrDefault();

                if (request.Price <= auctionPrice)
                {
                    return(BadRequest(Constants.ErrorMessages.InvalidPriceOffer));
                }
            }
            else
            {
                auctionPrice = _context.Auctions.Where(a => a.Id == request.AuctionId)
                               .Select(a => a.StartingPrice).FirstOrDefault();

                if (request.Price < auctionPrice)
                {
                    return(BadRequest(Constants.ErrorMessages.InvalidPriceOffer));
                }
            }

            var offer = request.MapToEntity();

            bool parsed = int.TryParse(User.Identity.Name, out int userId);

            if (!parsed)
            {
                throw new ApplicationException(Constants.ErrorMessages.UnreachableUserId);
            }

            offer.UserId = userId;

            var entity = _context.Offers.Add(offer);

            try { await _context.SaveChangesAsync().ConfigureAwait(false); }
            catch (Exception) { return(this.InternalServerError()); }

            return(Ok(entity.Entity));
        }
        public void TestGetOfferRequestsById()
        {
            string       expectedEmail = "*****@*****.**";
            var          controller    = new OfferRequestService(carpentryWebsiteContext);
            OfferRequest result        = controller.GetOfferRequestDetails(7);

            Assert.Equal(expectedEmail, result.EmailAddress);
        }
        public void TestDeleteOfferRequests()
        {
            var service = new OfferRequestService(carpentryWebsiteContext);

            service.DeleteOfferRequest(5);
            OfferRequest result = service.GetOfferRequestDetails(5);

            Assert.Null(result);
        }
Exemple #8
0
 public void AddOfferRequest(OfferRequest offerRequest)
 {
     using (var context = new ApplicationDbContext())
     {
         if (offerRequest != null)
         {
             context.OfferRequests.Add(offerRequest);
             context.SaveChanges();
         }
     }
 }
Exemple #9
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            OfferRequest offerRequest = null;

            offerRequest = await req.Content.ReadAsAsync <OfferRequest>();

            bool IsRedemptionError = false;

            // parse query parameter
            foreach (var Program in offerRequest.program)
            {
                IsRedemptionError = false;
                foreach (var item in Program.Item)
                {
                    if (item.history != null)
                    {
                        foreach (var history in item.history)
                        {
                            if ((DateTime.UtcNow - history.LastRedemptiondate).TotalDays < 30)
                            {
                                IsRedemptionError = true;
                                break;
                            }
                        }
                    }
                    if (IsRedemptionError)
                    {
                        break;
                    }
                }
                if (IsRedemptionError)
                {
                    foreach (var item in Program.Item)
                    {
                        item.details.statusCode    = "113";
                        item.details.statusMessage = ApplicationConstants.Code113;
                    }
                }
            }

            if (offerRequest.State == "NE")
            {
                foreach (var Program in offerRequest.program)
                {
                    foreach (var item in Program.Item)
                    {
                        item.details.statusCode    = "052";
                        item.details.statusMessage = ApplicationConstants.Code052;
                    }
                }
            }
            return(req.CreateResponse(HttpStatusCode.OK, offerRequest));
        }
        public bool BindRequestToAgent(Agent Agent, Client Client)
        {
            OfferRequest Request = unitOfWork.Repository <OfferRequest>().SingleOrDefault(o => o.ClientUsername == Client.Username);

            if (Request.Agent != null)
            {
                throw new Exception("The Request already has an Agent");
            }
            Request.AgentUsername = Agent.Username;
            unitOfWork.SaveChanges();
            return(true);
        }
        public void TestAddOfferRequest()
        {
            var          service   = new OfferRequestService(carpentryWebsiteContext);
            OfferRequest itemToAdd = new OfferRequest {
                OfferRequestId = 105, Name = "New name", EmailAddress = "New email", Message = "New message"
            };

            service.AddOfferRequest(itemToAdd, null, "false");
            OfferRequest result = service.GetOfferRequestDetails(105);

            Assert.Equal(itemToAdd, result);
        }
 public OfferRequest GetOfferRequestDetails(int id)
 {
     try
     {
         OfferRequest offerRequest = db.OfferRequest.Find(id);
         return(offerRequest);
     }
     catch
     {
         throw;
     }
 }
 public int UpdateOfferRequest(OfferRequest offerRequest)
 {
     try
     {
         db.Entry(offerRequest).State = EntityState.Modified;
         db.SaveChanges();
         return(1);
     }
     catch
     {
         throw;
     }
 }
Exemple #14
0
        public static Offer MapToEntity(this OfferRequest request)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            return(new Offer
            {
                AuctionId = request.AuctionId,
                Price = request.Price
            });
        }
 public int DeleteOfferRequest(int id)
 {
     try
     {
         OfferRequest offerRequest = db.OfferRequest.Find(id);
         db.OfferRequest.Remove(offerRequest);
         db.SaveChanges();
         return(1);
     }
     catch
     {
         throw;
     }
 }
        public override bool Equals(object obj)
        {
            if (obj is null)
            {
                return(false);
            }
            ReservationOffer other = obj as ReservationOffer;

            if (other is null)
            {
                return(false);
            }

            return(Price == other.Price &&
                   OfferRequest.Equals(other.OfferRequest));
        }
Exemple #17
0
        public async Task PostOffer(OfferRequest offerRequest)
        {
            var offerDto = new OfferDto
            {
                AirlineName  = _configuration.AirlineName,
                CreationTime = DateTime.Now,
                OfferId      = Guid.NewGuid().ToString(),
                Price        = offerRequest.Price,
                InboundDate  = offerRequest.ReturnDate,
                OutboundDate = offerRequest.DepartureDate,
                ProposalId   = offerRequest.ProposalId,
                OfferCode    = offerRequest.OfferCode
            };

            await _bmtCoreApiService.PostOffer(offerDto).ConfigureAwait(false);
        }
Exemple #18
0
 public string CreateRide(OfferRequest model, ApplicationUser user)
 {
     try
     {
         Driver driver = carpoolDb.Drivers.FirstOrDefault(c => c.ApplicationUserId.Equals(user.Id));
         if (driver == null)
         {
             return("Driver not registered");
         }
         var           rideId      = HelperService.GenerateId("RID");
         List <string> vaiPointIds = new List <string>();
         AddLocation(model.Source);
         AddLocation(model.Destination);
         vaiPointIds.Add(model.Source.Id);
         foreach (Location loc in model.ViaPoints)
         {
             AddLocation(loc);
             vaiPointIds.Add(loc.Id);
         }
         vaiPointIds.Add(model.Destination.Id);
         Ride ride = new Ride
                     (
             rideId,
             driver.Id,
             Convert.ToDateTime(model.Date),
             model.Time,
             model.Source.Id,
             model.Destination.Id,
             String.Join(",", vaiPointIds)
                     );
         carpoolDb.Rides.Add(ride);
         List <Seat> seats = new List <Seat>();
         for (int j = 0; j < Convert.ToInt32(model.Seats); j++)
         {
             Seat seat = new Seat(HelperService.GenerateId("SEA") + Convert.ToString(j), ride.Id);
             seats.Add(seat);
         }
         carpoolDb.Seats.AddRange(seats);
         carpoolDb.SaveChanges();
         return("Ok");
     }
     catch (Exception e)
     {
         return(e.Message);
     }
 }
Exemple #19
0
        public static int placeOffer(string username, string storeName, string productName, string category, string manufacturer, int amount, double price)
        {
            aUser       requester = getUser(username);
            Store       store     = Stores.searchStore(storeName);
            ProductInfo pInfo     = ProductInfo.getProductInfo(productName, category, manufacturer);

            if (requester == null | store == null | pInfo == null | price < 0)
            {
                return(-1);
            }

            Product      product = new Product(pInfo, amount, price);
            OfferRequest request = new OfferRequest(product, requester, store);

            requester.placeOffer(request);
            return(request.id);
        }
Exemple #20
0
        // POST: Account/RemoveRequest/id
        //[Authorize(Roles = "agent")]
        public ActionResult RemoveRequest(int id)
        {
            OfferRequest Request = unitOfWork.Repository <OfferRequest>()
                                   .Include("Client")
                                   .Include("Agent")
                                   .SingleOrDefault(o => o.Id == id);

            if (Request == null)
            {
                throw new Exception("La solicitud " + id.ToString() + " no existe !");
            }
            if (HttpContext.User.Identity.Name == Request.AgentUsername)
            {
                requestService.RemoveRequest(Request.Client);
            }
            return(RedirectToAction("Index"));
        }
        public void TestEditOfferRequests()
        {
            string       expectedName = "Different name";
            var          service      = new OfferRequestService(carpentryWebsiteContext);
            OfferRequest itemToAdd    = new OfferRequest {
                OfferRequestId = 17, Name = "New name", EmailAddress = "New email", Message = "New message"
            };

            service.AddOfferRequest(itemToAdd, null, "false");
            carpentryWebsiteContext.Entry(service.GetOfferRequestDetails(17)).State = EntityState.Detached;

            service.UpdateOfferRequest(new OfferRequest {
                OfferRequestId = 17, Name = "Different name", EmailAddress = "Different email", Message = "Different message"
            });
            OfferRequest result = service.GetOfferRequestDetails(17);

            Assert.Equal(expectedName, result.Name);
        }
 public bool MakeRequest(Client Client)
 {
     if (unitOfWork.Repository <OfferRequest>().SingleOrDefault(o => o.ClientUsername == Client.Username) == null)
     {
         OfferRequest newReq = new OfferRequest()
         {
             ClientUsername = Client.Username,
             AgentUsername  = "******",
             State          = RequestState.Requested,
             RequestedDate  = DateTime.Today
         };
         //TODO: Asignar un agente a la oferta
         unitOfWork.Repository <OfferRequest>().Add(newReq);
         unitOfWork.SaveChanges();
         return(true);
     }
     return(false);
 }
Exemple #23
0
        public void OfferRequestApproval(string requestId, IEnums.Decisions decision)
        {
            OfferRequest   offerRequest      = offerRequestRepository.GetById(requestId);
            BookingService NewBookingService = new BookingService();
            OfferService   OfferService      = new OfferService();

            if (decision == IEnums.Decisions.Accept)
            {
                offerRequest.Status = IEnums.RequestStatus.Accepted;
                NewBookingService.UpdateBookingStatus(offerRequest.RiderId, offerRequest.RideeId, IEnums.BookingStatus.Confirmed);
                OfferService.UpdateAvailability(offerRequest.RiderId, offerRequest.NumberOfPassengers);
            }
            else if (decision == IEnums.Decisions.Reject)
            {
                offerRequest.Status = IEnums.RequestStatus.Rejected;
                NewBookingService.UpdateBookingStatus(offerRequest.RiderId, offerRequest.RideeId, IEnums.BookingStatus.Cancelled);
            }
        }
        public IActionResult CreateRide([FromBody] OfferRequest model)
        {
            if (model == null)
            {
                return(BadRequest("invalid object"));
            }
            string          email  = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            ApplicationUser user   = context.ApplicationUsers.FirstOrDefault(c => c.Email.Equals(email));
            string          result = IDriverService.CreateRide(model, user);

            if (result == "Ok")
            {
                return(Ok(new {
                    status = 200,
                    message = "Ride Created Successfully."
                }));
            }
            return(BadRequest(new
            {
                error = result
            }));
        }
Exemple #25
0
        /// <summary>
        /// Método de atualização de ofertas
        /// </summary>
        /// <param name="Offers">offerUpdateRequest</param>
        /// <returns>OfferResponse</returns>
        public async Task <OfferResponse> UpdateOffersUsingPOSTAsync(OfferRequest Offers)
        {
            // verify the required parameter 'Offers' is set
            if (Offers == null)
            {
                throw new ApiException(400, "Missing required parameter 'Offers' when calling UpdateOffersUsingPOST");
            }


            var path = "/offers";

            path = path.Replace("{format}", "json");


            var    queryParams  = new Dictionary <String, String>();
            var    headerParams = new Dictionary <String, String>();
            var    formParams   = new Dictionary <String, String>();
            var    fileParams   = new Dictionary <String, String>();
            String postBody     = null;



            postBody = apiClient.Serialize(Offers); // http body (model) parameter


            // authentication setting, if any
            String[] authSettings = new String[] { "client_id", "access_token" };

            // make the HTTP request
            IRestResponse response = (IRestResponse)await apiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);

            if (((int)response.StatusCode) >= 400)
            {
                throw new ApiException((int)response.StatusCode, "Error calling UpdateOffersUsingPOST: " + response.Content, response.Content);
            }
            return((OfferResponse)apiClient.Deserialize(response.Content, typeof(OfferResponse)));
        }
Exemple #26
0
        public async Task <ActionResult> PostOffer(OfferRequest request)
        {
            await _offersService.PostOffer(request);

            return(RedirectToAction("Index", new { ProposalId = request.ProposalId }));
        }
Exemple #27
0
        public List <OfferViewModel> GetOffers(String LoadnAmount, string grossIncome, Applicant applicant)
        {
            string endPoint = @"https://stage.mktplacegateway.com/gateway/v1/loans/publish";

            var    httpWebRequest = (HttpWebRequest)WebRequest.Create(endPoint);
            string authInfo       = "cWo2ckxqSlFScHVrNzZwMTp5RWNHNlNXRVZ1bDcza1BaZzA3bzNhb0tTVFk2ZEc5OT0=";

            httpWebRequest.Headers["Authorization"] = "Basic " + authInfo;
            httpWebRequest.Headers["PartnerKey"]    = "testMerchantPartner123";
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = "POST";

            try
            {
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    OfferRequest offers = new OfferRequest();
                    offers.loanCategory = "CONSUMER_POS";
                    offers.loanType     = "POINT_OF_SALE";
                    offers.isPosLoan    = true;
                    offers.loanAmount   = LoadnAmount;
                    Consumerloan consumerLoan = new Consumerloan();
                    consumerLoan.grossIncome = grossIncome;
                    offers.consumerLoan      = consumerLoan;

                    applicant.firstName = "MIMIC";
                    applicant.lastName  = "APPROVE";

                    offers.applicant = applicant;
                    String json = new JavaScriptSerializer().Serialize(offers);

                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
                var file = @"F:/ChargeAfter/APICode/ChargeAfter-API_Refund/ChargeAfter/ChargeAfter/LogFile/APIRequestLog.txt";
                using (StreamWriter writer = new FileInfo(file).AppendText())
                {
                    writer.WriteLine("------ API Call Request------");
                    writer.WriteLine("-----------------------------");
                    OfferRequest offers = new OfferRequest();
                    offers.loanCategory = "CONSUMER_POS";
                    offers.loanType     = "POINT_OF_SALE";
                    offers.isPosLoan    = true;
                    offers.loanAmount   = LoadnAmount;
                    Consumerloan consumerLoan = new Consumerloan();
                    consumerLoan.grossIncome = grossIncome;
                    offers.consumerLoan      = consumerLoan;
                    applicant.firstName      = "MIMIC";
                    applicant.lastName       = "APPROVE";

                    offers.applicant = applicant;
                    String data = new JavaScriptSerializer().Serialize(offers);
                    writer.WriteLine(data);
                    writer.WriteLine("-----------------------------");
                    writer.WriteLine(Environment.NewLine);
                }

                String jsona        = "";
                var    httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    jsona    = streamReader.ReadToEnd();
                    loaninfo = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize <LoanInfo>(jsona);
                }
            }
            catch (Exception e)
            {
            }



            string html = string.Empty;

            //string url = @"https://stage.mktplacegateway.com/gateway/v1/loans/" + loaninfo.loanId.ToString() + "/offer";
            string url = "https://stage.mktplacegateway.com/gateway/v1/loans/4430bb2e-2326-4f57-a363-3542a741ff85/offer";
            //string url = "https://stage.mktplacegateway.com/gateway/v1/loans/0b9595cc-ff55-4545-9212-89a6f2f72ce1/offer";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.AutomaticDecompression   = DecompressionMethods.GZip;
            request.Headers["Authorization"] = "Basic " + authInfo;
            request.Headers["PartnerKey"]    = "testMerchantPartner123";
            request.ContentType = "application/json";
            request.Method      = "GET";

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        html = reader.ReadToEnd();
                    }
            var path = "F:/ChargeAfter/APICode/ChargeAfter-API_Refund/ChargeAfter/ChargeAfter/LogFile/APIRequestLog.txt";

            using (StreamWriter writer = new FileInfo(path).AppendText())
            {
                writer.WriteLine("------ API Call Response------");
                writer.WriteLine("-----------------------------");

                String data = new JavaScriptSerializer().Serialize(html);
                writer.WriteLine(data);
                writer.WriteLine("-----------------------------");
                writer.WriteLine(Environment.NewLine);
                writer.WriteLine(Environment.NewLine);
                writer.WriteLine(Environment.NewLine);
                writer.WriteLine(Environment.NewLine);
            }
            Rootobject            Rootobject    = new Rootobject();
            Offer                 offer         = new Offer();
            List <OfferViewModel> viewmodellist = new List <OfferViewModel>();

            try
            {
                Rootobject = new JavaScriptSerializer().Deserialize <Rootobject>(html);
            }
            catch (Exception ex)
            {
                OfferViewModel viewmodel = new OfferViewModel();
                viewmodel.Lender   = "No Lender Avaialable";
                viewmodel.Amount   = "Sorry Your Loan Ammount is not Accepted";
                viewmodel.Duration = " ";
                viewmodel.Intrest  = " ";
                ////viewmodel.loanId = "f8c5774a-d532-49eb-8cac-c5cdb5a6b52c";
                viewmodel.loanId  = "0";
                viewmodel.offerId = "0";
                //viewmodel.monthlyPayment = "0";
                viewmodellist.Add(viewmodel);

                //viewmodel.loanAmount = 0;
                //viewmodel.annualFee = 0;
                //viewmodel.eligibility = false;
                //viewmodel.isPreQualifyOffer = false;
                ////viewmodel.minApr = ;
                ////viewmodel.offerExpirationDate = ;
                ////viewmodel.pendingOffers = ;
                //viewmodel.status = "No Offer";
                //viewmodel.term = 0;
                //viewmodel.dateCreated = " ";
                ////viewmodel.declineReasons = ;

                //viewmodel.apr = 0;
                ////viewmodel.monthlyPayment = item.monthlyPayment;
                //viewmodel.term = 0;


                return(viewmodellist);
            }



            if (Rootobject.offers.Count() == 0)
            {
                OfferViewModel viewmodels = new OfferViewModel();
                viewmodels.Lender   = "No Lender Avaialable";
                viewmodels.Amount   = "Sorry Your Loan Ammount is not Accepted";
                viewmodels.Duration = " ";
                viewmodels.Intrest  = " ";
                ////viewmodel.loanId = "f8c5774a-d532-49eb-8cac-c5cdb5a6b52c";
                viewmodels.loanId  = "0";
                viewmodels.offerId = "0";
                //viewmodel.monthlyPayment = "0";
                viewmodellist.Add(viewmodels);

                return(viewmodellist);
            }
            foreach (var item in Rootobject.offers)
            {
                OfferViewModel viewmodel = new OfferViewModel();
                viewmodel.Lender   = "Fortiva";
                viewmodel.Amount   = Rootobject.loanAmount.ToString();
                viewmodel.Duration = item.term.ToString();
                viewmodel.Intrest  = item.interestRate.ToString();
                //viewmodel.loanId = "f8c5774a-d532-49eb-8cac-c5cdb5a6b52c";
                viewmodel.loanId  = loaninfo.loanId;
                viewmodel.offerId = item.offerId.ToString();



                //new Fields
                viewmodel.loanAmount          = item.loanAmount;
                viewmodel.annualFee           = item.annualFee;
                viewmodel.eligibility         = item.eligibility;
                viewmodel.isPreQualifyOffer   = item.isPreQualifyOffer;
                viewmodel.minApr              = item.minApr;
                viewmodel.offerExpirationDate = item.offerExpirationDate;
                viewmodel.pendingOffers       = item.pendingOffers;
                viewmodel.status              = item.status;
                viewmodel.term           = item.term;
                viewmodel.dateCreated    = item.dateCreated;
                viewmodel.declineReasons = item.declineReasons;

                viewmodel.apr            = item.apr;
                viewmodel.monthlyPayment = item.monthlyPayment;
                viewmodel.term           = item.term;

                //extra
                //    viewmodel.extra.accountId = item.extra.accountId.ToString();
                //viewmodel.extra.applicationUID = item.extra.applicationUID.ToString();

                //viewmodel.extra.latePaymentFee = item.extra.latePaymentFee.ToString();
                //viewmodel.extra.offerId = item.extra.offerId;
                //viewmodel.extra.penaltyAPR = item.extra.penaltyAPR.ToString();
                //viewmodel.extra.manualUnderwriting = item.extra.manualUnderwriting.ToString();
                //viewmodel.extra.transactionFee = item.extra.transactionFee.ToString();


                //viewmodel.legalDisclosure = item.legalDisclosure;
                //viewmodel.maxMonthlyPayment = item.maxMonthlyPayment;

                viewmodel.legalDisclosure   = item.legalDisclosure;
                viewmodel.maxMonthlyPayment = item.maxMonthlyPayment;



                viewmodellist.Add(viewmodel);
            }


            return(viewmodellist);
        }
Exemple #28
0
        public void SendRideRequest(Location fromLocation, Location toLocation, int numberOfPassengers, string riderId, string rideeId)
        {
            OfferRequest NewOfferRequest = new OfferRequest(fromLocation, toLocation, numberOfPassengers, riderId, rideeId);

            offerRequestRepository.Add(NewOfferRequest);
        }
        public int AddOfferRequest(OfferRequest offerRequest, IFormFile image, string imageAdded)
        {
            try
            {
                if (imageAdded.Equals("false"))
                {
                    db.OfferRequest.Add(offerRequest);
                    db.SaveChanges();
                    return(1);
                }
                var dir = _env.ContentRootPath;

                string pathToFabricPictures = "/Images/offer_pictures";

                string fullPath = dir + pathToFabricPictures;

                if (!Directory.Exists(fullPath))
                {
                    Directory.CreateDirectory(fullPath);
                }

                int fileSuffix = 1;

                string fullFileName = "offer_picture_" + fileSuffix + ".png";

                bool exists = File.Exists(Path.Combine(fullPath, fullFileName));

                while (exists)
                {
                    fileSuffix++;
                    fullFileName = "offer_picture_" + fileSuffix + ".png";
                    exists       = File.Exists(Path.Combine(fullPath, fullFileName));
                }

                using (var fileStream = new FileStream(Path.Combine(fullPath, fullFileName), FileMode.Create, FileAccess.Write))
                {
                    image.CopyTo(fileStream);

                    OfferRequest offerRequestToCreate = new OfferRequest();
                    Picture      pictureExists        = db.Picture
                                                        .Where(p => p.PictureName == fullFileName)
                                                        .FirstOrDefault();

                    if (pictureExists == null)
                    {
                        Picture picture = new Picture(0, fullFileName);
                        db.Picture.Add(picture);
                        offerRequest.PictureId = picture.PictureId;
                        offerRequest.Picture   = picture;
                    }
                    else
                    {
                        offerRequest.PictureId = pictureExists.PictureId;
                        offerRequest.Picture   = pictureExists;
                    }

                    db.OfferRequest.Add(offerRequest);
                    db.SaveChanges();
                    return(1);
                }
            }
            catch
            {
                throw;
            }
        }
 public async Task SubmitRequest(OfferRequest request)
 {
     Guard.Against.Null(request, nameof(request));
     await _heroApi.SubmitRequest(request);
 }