Esempio n. 1
0
        private void btnRemoveOffer_Click(object sender, EventArgs e)
        {
            try
            {
                if (FormHelper.IsGoodToGoOffer(labelDeviceId) == false)
                {
                    return;
                }

                ColumnView view         = gridControlOffers.MainView as ColumnView;
                int[]      selectedRows = gridViewOffers.GetSelectedRows();
                string     offerId;
                if (selectedRows.Length > 0)
                {
                    offerId = view.GetRowCellDisplayText(selectedRows[0], view.Columns["OfferId"]);
                    //Delete Offer
                    OfferController.RemoveOffer(int.Parse(offerId));
                    FormHelper.LoadOffer(gridControlOffers, gridViewOffers);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Exception Error", MessageBoxButtons.OK, MessageBoxIcon.Question);
            }
        }
Esempio n. 2
0
        protected void btnExport_Click(object sender, EventArgs e)
        {
            System.Data.DataTable dt = new System.Data.DataTable();

            dt.Columns.Add(new System.Data.DataColumn(BidString.GetText(@"SupplierName"), typeof(string)));
            dt.Columns.Add(new System.Data.DataColumn(BidString.GetText(@"Price"), typeof(string)));
            dt.Columns.Add(new System.Data.DataColumn(BidString.GetText(@"Gift"), typeof(string)));
            dt.Columns.Add(new System.Data.DataColumn(BidString.GetText(@"IsOrder"), typeof(string)));


            List <OfferUI> coll = OfferController.GetAllOfferByBidIdWithIsOrder(BidId);

            foreach (OfferUI offer in coll)
            {
                int i = 0;
                System.Data.DataRow row = dt.NewRow();
                row[i++] = offer.SupplierName;
                row[i++] = offer.TotalPrice;
                row[i++] = offer.Gift;
                row[i++] = GlobalStrings.GetYesNo(offer.IsOrder);
                dt.Rows.Add(row);
            }
            SpreadsheetWriter ex = SpreadsheetWriter.FromDataTable(dt, false, true);

            Response.Clear();
            Response.AddHeader(@"content-disposition", @"attachment;filename=OffersExport_" + DateTime.UtcNow.ToString(@"yyyy_MM_dd_HH_mm_ss") + "." + ex.FileExtension);
            Response.Charset         = @"UTF-8";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = ex.FileContentType;
            Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
            Response.Write(ex.ToString());
            Response.End();
        }
        public void GetAllOfferes()
        {
            var mock = new Mock <IRepository <Offer> >();

            mock.Setup(repo => repo.GetAll()).Returns(GetAllTest());
            var factoryMock = new Mock <IRepositoryFactory>();

            factoryMock.Setup(f => f.GetRepository <Offer>()).Returns(mock.Object);
            _offerController = new OfferController(factoryMock.Object);

            var json  = _offerController.GetAll();
            var offer = json.Value as List <Offer>;

            Assert.NotNull(json);
            Assert.NotNull(offer);
            Assert.AreEqual(offer.Count, 2);

            //var mock1 = new Mock<IRepository<Offer>>();
            //mock1.Setup(repo => repo.GetAll().FirstOrDefault()).Returns(GetFirstOrDefaultTest(1));
            //var factoryMock1 = new Mock<IRepositoryFactory>();
            //factoryMock1.Setup(f => f.GetRepository<Offer>()).Returns(mock1.Object);
            //_offerController = new OfferController(factoryMock1.Object);

            //json = _offerController.GetAll();
            //offer = json.Value as List<Offer>;
            //Assert.AreEqual();
        }
        public void findByIdTest()
        {
            Mock <IAuctionRepository> moc = new Mock <IAuctionRepository>();

            moc.Setup(m => m.Auctions).Returns(new Auction[]
            {
                new Auction {
                    Id = 3, Description = "Good staff"
                }
            });

            Mock <IOfferRepository> mock = new Mock <IOfferRepository>();

            mock.Setup(m => m.Offers).Returns(new Offer[]
            {
                new Offer {
                    Id = 2, Price = 120, Accepted = true
                }
            });
            var controller = new OfferController(mock.Object, moc.Object);

            Offer o = controller.findById(1);

            Assert.IsNull(o);
        }
Esempio n. 5
0
        private void btnCreateNewConfigOffer_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(textBoxOfferId.Text))
            {
                MessageBox.Show("Điền OfferId Trên Site Offer18");
                return;
            }
            OfferModel offer        = this.GenerateNewConfigOffer();
            bool       isAbleCreate = ValidateOffer(offer);

            if (!isAbleCreate)
            {
                MessageBox.Show("Tạo Offer Cần Điền Đầy Đủ Thông Tin Hoặc Chọn Thiết Bị Đã Cài Tweak");
                return;
            }
            if (btnCreateNewConfigOffer.Text == "Add New Offer")
            {
                //Check new constraint

                OfferController.SaveOffer(offer);
                MessageBox.Show($"Add Offer {offer.AppName} Có Tracking {offer.TrackingLink} Thành Công. Chúc Nhiều Lead", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                OfferController.UpdateOffer(offer, int.Parse(textBoxOfferId.Text));
                MessageBox.Show($"Update Offer {offer.AppName} Có Tracking {offer.TrackingLink} Thành Công. Chúc Nhiều Lead", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Esempio n. 6
0
 public static void LoadOffer(GridControl control, GridView view)
 {
     control.DataSource = OfferController.GetAllOffers();
     view.Columns["DeviceId"].Visible       = false;
     view.Columns["IsRandomCTIT"].Visible   = false;
     view.Columns["FromRandomCTIT"].Visible = false;
     view.Columns["ToRandomCTIT"].Visible   = false;
     view.Columns["InAppCTIT"].Visible      = false;
     view.BestFitColumns();
 }
Esempio n. 7
0
        protected void LoadItems()
        {
            phHasItems.Visible   = true;
            phHasNoItems.Visible = false;
            if (dgOffers.PageSize * dgOffers.CurrentPageIndex > dgOffers.VirtualItemCount)
            {
                dgOffers.CurrentPageIndex         = 0;
                hfCurrentPageIndex_dgOffers.Value = dgOffers.CurrentPageIndex.ToString();
            }
            List <OfferUI> coll = OfferController.GetAllOfferByBidIdWithIsOrder(BidId);

            BindList(coll);
        }
Esempio n. 8
0
 public OfferConfig(string DeviceId, int OfferId = -1)
 {
     InitializeComponent();
     checkedComboBoxSelectScript.Properties.Items.Add("Test");
     comboBoxEditAppName.Properties.Items.Add("test");
     labelDeviceId.Text = DeviceId;
     if (OfferId >= 1)
     {
         OfferModel offer = OfferController.FindOffer(OfferId);
         LoadOfferToOfferConfigDialog(offer);
         btnCreateNewConfigOffer.Text = $"Update Offer";
         textBoxOfferId.Text          = OfferId.ToString();
         textBoxOfferId.Enabled       = false;
     }
 }
        public void Create2()
        {
            Offer offer = new Offer()
            {
                Id = 1
            };
            var mock = new Mock <IRepository <Offer> >();

            mock.Setup(repo => repo.Create(offer));
            var factoryMock = new Mock <IRepositoryFactory>();

            factoryMock.Setup(f => f.GetRepository <Offer>()).Returns(mock.Object);
            _offerController = new OfferController(factoryMock.Object);
            //Assert.AreEqual(offer, factoryMock);
        }
Esempio n. 10
0
        public void GetOffersFilter()
        {
            int      id            = 0;
            DateTime dateOfPosting = DateTime.Now;
            string   from          = "Ukraine";
            string   to            = "Poland";
            DateTime dateOfLoading = DateTime.Now;
            Vehicle  vehicle       = new Vehicle()
            {
                VehicleId = 1,
                Type      = VehicleType.Box,
                Weight    = 25
            };
            Carrier carrier = new Carrier()
            {
                CarrierId   = 1,
                Name        = "John",
                Email       = "*****@*****.**",
                PhoneNumber = "+123456789",
                VehicleId   = 1,
                Vehicle     = vehicle
            };
            Offer offer = new Offer()
            {
                OfferId       = id,
                DateOfLoading = dateOfLoading,
                DateOfPosting = dateOfPosting,
                From          = from,
                To            = to,
                CarrierId     = 1,
                Carrier       = carrier
            };

            Filter filter = new Filter(

                minDateOfPosting: dateOfPosting,
                from: from,
                type: vehicle.Type,
                maxWeight: vehicle.Weight
                );

            OfferController offerController = new OfferController();

            offerController.AddOffer(offer);
            var res = offerController.GetOffers(filter);

            Assert.IsTrue(res.Count == 1);
        }
        public void GetOffer()
        {
            var mock = new Mock <IRepository <Offer> >();

            mock.Setup(repo => repo.GetById(It.IsAny <int>())).Returns(GetByIdTest(1));
            var factoryMock = new Mock <IRepositoryFactory>();

            factoryMock.Setup(f => f.GetRepository <Offer>()).Returns(mock.Object);
            _offerController = new OfferController(factoryMock.Object);

            var json  = _offerController.Get(1);
            var offer = json.Value as Offer;

            Assert.NotNull(json);
            Assert.NotNull(offer);
            Assert.AreEqual(offer.Id, 1);
        }
Esempio n. 12
0
        private void btnRemoveAll_Click(object sender, EventArgs e)
        {
            try
            {
                if (FormHelper.IsGoodToGoOffer(labelDeviceId) == false)
                {
                    return;
                }
                if (MessageBox.Show("Are you sure to erase all offer data", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    OfferController.RemoveAllOffer();
                }

                FormHelper.LoadOffer(gridControlOffers, gridViewOffers);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Exception Error", MessageBoxButtons.OK, MessageBoxIcon.Question);
            }
        }
        public void Create()
        {
            var   memoryStore = new List <Offer>();
            Offer offerStub   = new Offer {
                Id = 1
            };
            var mock = new Mock <IRepository <Offer> >();

            mock.Setup(repo => repo.GetAll()).Returns(memoryStore.AsQueryable());
            mock.Setup(repo => repo.Create(It.IsAny <Offer>())).Returns((Offer offer) => {
                offer.Id = 1;
                memoryStore.Add(offer);
                return(offer);
            });
            var factoryMock = new Mock <IRepositoryFactory>();

            factoryMock.Setup(f => f.GetRepository <Offer>()).Returns(mock.Object);
            _offerController = new OfferController(factoryMock.Object);
            var emptyJson = _offerController.GetAll();

            Assert.IsNotNull(emptyJson);
            var emptyStore = emptyJson.Value as List <Offer>;

            Assert.IsNotNull(emptyStore);
            Assert.AreEqual(emptyStore.Count, 0);
            var json = _offerController.Create(offerStub);

            Assert.IsNotNull(json);
            var result = json.Value as Offer;

            Assert.NotNull(result);
            Assert.AreEqual(result.Id, 1);
            Assert.AreEqual(result.Company, offerStub.Company);
            var notEmptyJson = _offerController.GetAll();

            Assert.IsNotNull(notEmptyJson);
            var notEmptyStore = notEmptyJson.Value as List <Offer>;

            Assert.IsNotNull(notEmptyStore);
            Assert.AreEqual(notEmptyStore.Count, 1);
        }
Esempio n. 14
0
        /// <summary>
        /// Button Click.
        /// </summary>
        /// <param name="sender">Just Object.</param>
        /// <param name="e">MouseButtonEventArgs e.</param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Filter f = new Filter(
                    from: this.fromCountry.Text != string.Empty ? this.fromCountry.Text : null,
                    to: this.toCountry.Text != string.Empty ? this.toCountry.Text : null,
                    minDateOfLoading: this.dateFrom.SelectedDate,
                    maxDateOfLoading: this.dateTo.SelectedDate,
                    type: (VehicleType?)(this.expander1.SelectedIndex - 1),
                    minWeight: double.TryParse(this.weightFrom.Text, out double res1) ? res1 as double? : null,
                    maxWeight: double.TryParse(this.weightTo.Text, out double res2) ? res2 as double? : null);

                using (UnitOfWork unitOfWork = new UnitOfWork())
                {
                    OfferController offerController = new OfferController(new List <Offer>(unitOfWork.Offers.GetAll()));
                    this.dataList.ItemsSource = offerController.GetOffers(f);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Unexpected error occured");
            }
        }
        public override void Post(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);
            JObject inputData = null;

            try
            {
                using (StreamReader reader = new StreamReader(Request.InputStream))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(reader))
                    {
                        inputData = JObject.Load(jsonReader);
                    }
                }
            }
            catch
            {
                RespondBadRequest(Response);
            }

            try
            {
                Int64 AppUserId;
                if (IsAuthorizedRequest(Request, Response, true, out AppUserId))
                {
                    JToken  jt;
                    string  specialInstruction = null, masterCardNumber = null;
                    JArray  products         = null;
                    Int64   supplierId       = 0;
                    int     numberOfPayments = 1;
                    decimal totalPrice       = 0;
                    var     lstProduct       = new Dictionary <Int64, int>();

                    if (inputData.TryGetValue(@"products", out jt))
                    {
                        products = jt.Value <JArray>();
                    }
                    if (inputData.TryGetValue(@"supplier_id", out jt))
                    {
                        supplierId = jt.Value <Int64>();
                    }
                    if (inputData.TryGetValue(@"total_price", out jt) && jt != null)
                    {
                        totalPrice = jt.Value <decimal>();
                    }
                    if (inputData.TryGetValue(@"special_instructions", out jt) && jt != null)
                    {
                        specialInstruction = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"mastercardCode", out jt) && jt != null)
                    {
                        masterCardNumber = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"num_of_payments", out jt) && jt != null)
                    {
                        numberOfPayments = jt.Value <int>();
                    }

                    bool isNumberOfPaymentsValid = numberOfPayments == 3 && totalPrice > 239 ||
                                                   numberOfPayments == 2 && totalPrice >= 150 ||
                                                   (totalPrice / 100 / numberOfPayments > 1 && numberOfPayments <= 12);
                    if (!isNumberOfPaymentsValid)
                    {
                        RespondError(Response, HttpStatusCode.OK, @"num-of-payments-not-valid");
                    }

                    foreach (JObject obj in products.Children <JObject>())
                    {
                        Int64 product_id = 0;
                        int   amount     = 1;
                        if (obj.TryGetValue(@"product_id", out jt))
                        {
                            product_id = jt.Value <Int64>();
                        }
                        if (obj.TryGetValue(@"amount", out jt))
                        {
                            amount = jt.Value <int>();
                        }
                        lstProduct.Add(product_id, amount);
                    }
                    string token        = Request.Headers["Authorization"].Substring(6);
                    bool   isPriceValid = false;

                    if (supplierId > 0 && totalPrice > 0)
                    {
                        isPriceValid = OfferController.IsOfferStillValid(lstProduct, supplierId, totalPrice);
                    }
                    if (!isPriceValid)
                    {
                        RespondError(Response, HttpStatusCode.ExpectationFailed, @"price-not-valid");
                    }

                    Response.ContentType = @"application/json";
                    using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                    {
                        using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                        {
                            string gifts;
                            Random rand     = new Random();
                            long   uniqueID = DateTime.Now.Ticks + rand.Next(0, 1000);
                            string tansactionId;
                            string url = CreditGuardManager.GetCgUrl(AppUserId, totalPrice, uniqueID, numberOfPayments, masterCardNumber, specialInstruction, out tansactionId);

                            var bidId    = BidController.CreateBidProduct(AppUserId, supplierId, lstProduct, false, out gifts);
                            var preOrder = new Snoopi.core.DAL.PreOrder
                            {
                                BidId         = bidId,
                                TotalPrice    = totalPrice,
                                UniqueId      = uniqueID,
                                TransactionId = tansactionId,
                                SupplierId    = supplierId,
                                Created       = DateTime.Now,
                                Gifts         = gifts
                            };
                            preOrder.Save();

                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName(@"url");
                            jsonWriter.WriteValue(url);
                            jsonWriter.WriteEndObject();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Helpers.LogProcessing("ProcessingUrlHandler - ex -", "\n exception: " + e.ToString(), true);
            }
        }
Esempio n. 16
0
 private void Awake()
 {
     instance = this;
 }
Esempio n. 17
0
        public override void Post(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);
            JObject inputData = null;

            try
            {
                using (StreamReader reader = new StreamReader(Request.InputStream))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(reader))
                    {
                        inputData = JObject.Load(jsonReader);
                    }
                }
            }
            catch
            {
                RespondBadRequest(Response);
            }

            Int64 AppUserId;

            if (IsAuthorizedRequest(Request, Response, true, out AppUserId))
            {
                Response.ContentType = @"application/json";

                try
                {
                    JToken  jt;
                    JArray  products   = null;
                    Int64   supplierId = 0;
                    decimal totalPrice = 0;
                    var     lstProduct = new Dictionary <Int64, int>();

                    if (inputData.TryGetValue(@"products", out jt))
                    {
                        products = jt.Value <JArray>();
                    }
                    if (inputData.TryGetValue(@"supplier_id", out jt))
                    {
                        supplierId = jt.Value <Int64>();
                    }
                    if (inputData.TryGetValue(@"total_price", out jt) && jt != null)
                    {
                        totalPrice = jt.Value <decimal>();
                    }
                    foreach (JObject obj in products.Children <JObject>())
                    {
                        Int64 product_id = 0;
                        int   amount     = 1;
                        if (obj.TryGetValue(@"product_id", out jt))
                        {
                            product_id = jt.Value <Int64>();
                        }
                        if (obj.TryGetValue(@"amount", out jt))
                        {
                            amount = jt.Value <int>();
                        }
                        lstProduct.Add(product_id, amount);
                    }

                    bool isPriceValid = false;
                    if (supplierId > 0 && totalPrice > 0)
                    {
                        isPriceValid = OfferController.IsOfferStillValid(lstProduct, supplierId, totalPrice);
                    }
                    if (!isPriceValid)
                    {
                        RespondError(Response, HttpStatusCode.ExpectationFailed, @"price-not-valid");
                    }

                    using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                    {
                        using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                        {
                            //var o = new Order();
                            //o.TotalPrice = totalPrice;
                            //o.AppUserId = AppUserId;
                            //o.UserPaySupplierStatus = UserPaymentStatus.NotPayed;
                            //o.Save();
                            jsonWriter.WriteStartObject();
                            //jsonWriter.WritePropertyName(@"order_id");
                            //jsonWriter.WriteValue(o.OrderId);
                            jsonWriter.WritePropertyName(@"total_price");
                            jsonWriter.WriteValue(totalPrice);
                            jsonWriter.WriteEndObject();
                        }
                    }
                }
                catch (InvalidDataException e)
                {
                    RespondError(Response, HttpStatusCode.InternalServerError, e.Message);
                }

                catch (Exception ex)
                {
                    RespondError(Response, HttpStatusCode.InternalServerError, @"db-error");
                }
            }
        }
        public override void Post(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);
            JObject inputData = null;

            try
            {
                using (StreamReader reader = new StreamReader(Request.InputStream))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(reader))
                    {
                        inputData = JObject.Load(jsonReader);
                    }
                }
            }
            catch
            {
                RespondBadRequest(Response);
            }

            try
            {
                Int64 AppUserId;
                if (IsAuthorizedRequest(Request, Response, true, out AppUserId))
                {
                    JToken  jt;
                    string  specialInstruction = null, masterCardNumber = null, cardToken = null, cardExp = null;
                    JArray  products         = null;
                    Int64   supplierId       = 0;
                    int     numberOfPayments = 1;
                    decimal totalPrice       = 0;
                    var     lstProduct       = new Dictionary <Int64, int>();

                    if (inputData.TryGetValue(@"products", out jt))
                    {
                        products = jt.Value <JArray>();
                    }
                    if (inputData.TryGetValue(@"supplier_id", out jt))
                    {
                        supplierId = jt.Value <Int64>();
                    }
                    if (inputData.TryGetValue(@"total_price", out jt) && jt != null)
                    {
                        totalPrice = jt.Value <decimal>();
                    }
                    if (inputData.TryGetValue(@"special_instructions", out jt) && jt != null)
                    {
                        specialInstruction = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"mastercardCode", out jt) && jt != null)
                    {
                        masterCardNumber = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"num_of_payments", out jt) && jt != null)
                    {
                        numberOfPayments = jt.Value <int>();
                    }
                    if (inputData.TryGetValue(@"card_token", out jt) && jt != null)
                    {
                        cardToken = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"card_exp", out jt) && jt != null)
                    {
                        cardExp = jt.Value <string>();
                    }

                    bool isNumberOfPaymentsValid = numberOfPayments == 3 && totalPrice > 239 ||
                                                   numberOfPayments == 2 && totalPrice >= 150 ||
                                                   totalPrice / 100 / numberOfPayments > 1;
                    if (!isNumberOfPaymentsValid)
                    {
                        RespondError(Response, HttpStatusCode.OK, @"num-of-payments-not-valid");
                    }

                    foreach (JObject obj in products.Children <JObject>())
                    {
                        Int64 product_id = 0;
                        int   amount     = 1;
                        if (obj.TryGetValue(@"product_id", out jt))
                        {
                            product_id = jt.Value <Int64>();
                        }
                        if (obj.TryGetValue(@"amount", out jt))
                        {
                            amount = jt.Value <int>();
                        }
                        lstProduct.Add(product_id, amount);
                    }
                    string token        = Request.Headers["Authorization"].Substring(6);
                    bool   isPriceValid = false;

                    if (supplierId > 0 && totalPrice > 0)
                    {
                        isPriceValid = OfferController.IsOfferStillValid(lstProduct, supplierId, totalPrice);
                    }
                    if (!isPriceValid)
                    {
                        RespondError(Response, HttpStatusCode.ExpectationFailed, @"price-not-valid");
                    }

                    string gifts;
                    Random rand     = new Random();
                    long   uniqueID = DateTime.Now.Ticks + rand.Next(0, 1000);
                    string tansactionId;
                    var    results = CreditGuardManager.ProcessSavedCard(AppUserId, totalPrice, numberOfPayments, masterCardNumber, specialInstruction, cardToken, cardExp, out tansactionId);
                    if (results.ResultCode != "000")
                    {
                        RespondError(Response, HttpStatusCode.ExpectationFailed, @"failed");
                    }


                    results.SpecialInstructions = specialInstruction;
                    results.NumOfPayments       = numberOfPayments;
                    var bidId          = BidController.CreateBidProduct(AppUserId, supplierId, lstProduct, true, out gifts);
                    var order          = OrderController.GenerateNewOrder(results, AppUserId, bidId, gifts, supplierId, totalPrice, core.DAL.Source.WebSite);
                    var productsParams = ProductController.GetProductsWithIds(lstProduct.Select(x => x.Key));
                    using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                    {
                        using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                        {
                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName(@"isSuccess");
                            jsonWriter.WriteValue(results != null);
                            jsonWriter.WritePropertyName(@"total_price");
                            jsonWriter.WriteValue(totalPrice);
                            jsonWriter.WritePropertyName(@"bid_id");
                            jsonWriter.WriteValue(bidId);


                            jsonWriter.WritePropertyName(@"products");
                            jsonWriter.WriteStartArray();
                            foreach (var product in productsParams)
                            {
                                jsonWriter.WriteStartObject();

                                jsonWriter.WritePropertyName(@"product_id");
                                jsonWriter.WriteValue(product.ProductId);
                                jsonWriter.WritePropertyName(@"product_name");
                                jsonWriter.WriteValue(product.ProductName);
                                jsonWriter.WritePropertyName(@"product_category");
                                jsonWriter.WriteValue(product.CategoryName);
                                jsonWriter.WritePropertyName(@"product_sub_category");
                                jsonWriter.WriteValue(product.SubCategoryName);
                                jsonWriter.WritePropertyName(@"product_animal_name");
                                jsonWriter.WriteValue(product.AnimalName);
                                jsonWriter.WritePropertyName(@"product_quentity");
                                jsonWriter.WriteValue(lstProduct[product.ProductId]);
                                jsonWriter.WriteEndObject();
                            }

                            jsonWriter.WriteEndArray();

                            jsonWriter.WriteEndObject();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Helpers.LogProcessing("SavedCardProcessingHandler - ex -", "\n exception: " + ex.ToString(), true);
            }
        }
        public override void Post(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);

            JObject inputData = null;

            try
            {
                using (StreamReader reader = new StreamReader(Request.InputStream))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(reader))
                    {
                        inputData = JObject.Load(jsonReader);
                    }
                }
            }
            catch
            {
                RespondBadRequest(Response);
            }

            Response.ContentType = @"application/json";

            JToken jt;
            JArray products       = null;
            var    productsOffers = new List <BidProductUI>();
            Dictionary <Int64, int> lstProduct = new Dictionary <Int64, int>();

            Int64 AppUserId;

            IsAuthorizedRequest(Request, Response, false, out AppUserId);

            Int64 TempAppUserId = 0;

            if (inputData.TryGetValue(@"temp_app_user_id", out jt))
            {
                TempAppUserId = jt.Value <Int64>();
            }
            if (AppUserId == 0 && TempAppUserId == 0)
            {
                RespondError(Response, HttpStatusCode.Forbidden, @"authorization-error");
                return;
            }
            var user     = AppUser.FetchByID(AppUserId);
            var tempUser = TempAppUser.FetchByID(TempAppUserId);

            if (user == null && tempUser == null)
            {
                RespondError(Response, HttpStatusCode.Forbidden, @"authorization-error");
                return;
            }

            long cityId = 0;

            if (user != null)
            {
                bool _locked = user.IsLocked;
                if (_locked)
                {
                    RespondError(Response, HttpStatusCode.BadRequest, @"appuser-locked");
                    return;
                }
                cityId = user.CityId;
            }
            else if (tempUser != null)
            {
                cityId = tempUser.CityId;
            }

            if (inputData.TryGetValue(@"products", out jt))
            {
                products = jt.Value <JArray>();
            }
            foreach (JObject obj in products.Children <JObject>())
            {
                Int64 product_id = 0;
                int   amount     = 1;
                if (obj.TryGetValue(@"product_id", out jt))
                {
                    product_id = jt.Value <Int64>();
                }
                if (obj.TryGetValue(@"amount", out jt))
                {
                    amount = jt.Value <int>();
                }
                lstProduct.Add(product_id, amount);
            }

            var lstOfferUI = OfferController.GetAllOfferByProductIds(lstProduct, cityId);

            Response.ContentType = @"application/json";
            using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
            {
                using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                {
                    if (IsAuthorizedRequest(Request, Response, false, out AppUserId))
                    {
                        jsonWriter.WriteStartObject();
                        jsonWriter.WritePropertyName(@"products");
                        jsonWriter.WriteStartArray();
                        foreach (BidProductUI item in productsOffers) /* TODO: should be deleted*/
                        {
                            jsonWriter.WriteStartObject();

                            jsonWriter.WritePropertyName(@"order_amount");
                            jsonWriter.WriteValue(item.Amount);
                            jsonWriter.WritePropertyName(@"product_name");
                            jsonWriter.WriteValue(item.ProductName);
                            jsonWriter.WritePropertyName(@"product_image");
                            jsonWriter.WriteValue(item.ProductImage);

                            jsonWriter.WriteEndObject();
                        }

                        jsonWriter.WriteEndArray();

                        jsonWriter.WritePropertyName(@"offers");
                        jsonWriter.WriteStartArray();

                        foreach (OfferUI item in lstOfferUI)
                        {
                            jsonWriter.WriteStartObject();

                            jsonWriter.WritePropertyName(@"offer_id");
                            jsonWriter.WriteValue(item.OfferId);
                            jsonWriter.WritePropertyName(@"supplier_id");
                            jsonWriter.WriteValue(item.SupplierId);
                            jsonWriter.WritePropertyName(@"mastercard_code");
                            if (item.MastercardCode == "")
                            {
                                jsonWriter.WriteValue((-1).ToString());
                            }
                            else
                            {
                                jsonWriter.WriteValue(item.MastercardCode);
                            }
                            jsonWriter.WritePropertyName(@"avg_rate");
                            jsonWriter.WriteValue(item.AvgRate);
                            jsonWriter.WritePropertyName(@"supplier_name");
                            jsonWriter.WriteValue(item.SupplierName);
                            jsonWriter.WritePropertyName(@"total_price");
                            jsonWriter.WriteValue(item.TotalPrice);
                            jsonWriter.WritePropertyName(@"gift");
                            jsonWriter.WriteValue(item.Gift);

                            jsonWriter.WriteEndObject();
                        }

                        jsonWriter.WriteEndArray();

                        jsonWriter.WriteEndObject();
                    }
                }
            }
        }
Esempio n. 20
0
        public override void Get(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);

            try
            {
                //Int64 bid_id = (Request.QueryString["bid_id"] != null ? Int64.Parse(Request.QueryString["bid_id"].ToString()) : 0 );

                Response.ContentType = @"application/json";
                using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                {
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                    {
                        Int64 bid_id = 0;
                        Int64 AppUserId;
                        Int64 TempAppUserId = 0;
                        if (IsAuthorizedRequest(Request, Response, false, out AppUserId))
                        {
                            //the last bid of the app user that ended
                            Bid b = Bid.FetchByAppUserId(AppUserId);
                            if (b != null)
                            {
                                //if the bid isn't closed (there arn't any orders for this bid)
                                Order o = Order.FetchByBidId(b.BidId);
                                //if (o == null)
                                if (o == null || o.UserPaySupplierStatus == UserPaymentStatus.NotPayed)
                                {
                                    bid_id = b.BidId;
                                }
                            }
                        }
                        else
                        {
                            TempAppUserId = Request["temp_app_user_id"] != null?Convert.ToInt64(Request["temp_app_user_id"]) : 0;

                            if (TempAppUserId != 0)
                            {
                                //the last bid of the temp app user that ended
                                Bid b = Bid.FetchByTempAppUserId(TempAppUserId);
                                if (b != null)
                                {
                                    //if the bid isn't closed (there arn't any orders for this bid)
                                    Order o = Order.FetchByBidId(b.BidId);
                                    //if (o == null)
                                    if (o == null || o.UserPaySupplierStatus == UserPaymentStatus.NotPayed)
                                    {
                                        bid_id = b.BidId;
                                    }
                                }
                            }
                        }

                        Bid bid = Bid.FetchByID(bid_id);
                        if (bid_id == 0 || bid == null)
                        {
                            jsonWriter.WriteStartObject();
                            jsonWriter.WriteEndObject();
                        }
                        else
                        {
                            DateTime DateExpiryOffers = bid.EndDate.AddHours(Convert.ToDouble(Settings.GetSetting(Settings.Keys.EXPIRY_OFFER_TIME_HOURS)));

                            List <OfferUI> lstOfferUI = (bid_id != 0 && bid != null && DateTime.UtcNow < DateExpiryOffers ? OfferController.GetAllOfferByBidId(bid_id) : new List <OfferUI>());
                            jsonWriter.WriteStartObject();

                            jsonWriter.WritePropertyName(@"bid_id");
                            jsonWriter.WriteValue(bid_id);

                            jsonWriter.WritePropertyName(@"products");
                            jsonWriter.WriteStartArray();
                            List <BidProductUI> products = BidController.GetProductsByBid(bid_id);
                            foreach (BidProductUI item in products)
                            {
                                jsonWriter.WriteStartObject();

                                jsonWriter.WritePropertyName(@"product_id");
                                jsonWriter.WriteValue(item.ProductId);
                                jsonWriter.WritePropertyName(@"order_amount");
                                jsonWriter.WriteValue(item.Amount);
                                jsonWriter.WritePropertyName(@"product_name");
                                jsonWriter.WriteValue(item.ProductName);
                                jsonWriter.WritePropertyName(@"product_image");
                                jsonWriter.WriteValue(item.ProductImage);

                                jsonWriter.WriteEndObject();
                            }

                            jsonWriter.WriteEndArray();

                            jsonWriter.WritePropertyName(@"offers");
                            jsonWriter.WriteStartArray();

                            foreach (OfferUI item in lstOfferUI)
                            {
                                jsonWriter.WriteStartObject();

                                jsonWriter.WritePropertyName(@"offer_id");
                                jsonWriter.WriteValue(item.OfferId);
                                jsonWriter.WritePropertyName(@"supplier_id");
                                jsonWriter.WriteValue(item.SupplierId);
                                jsonWriter.WritePropertyName(@"mastercard_code");
                                if (item.MastercardCode == "")
                                {
                                    jsonWriter.WriteValue((-1).ToString());
                                }
                                else
                                {
                                    jsonWriter.WriteValue(item.MastercardCode);
                                }
                                jsonWriter.WritePropertyName(@"avg_rate");
                                jsonWriter.WriteValue(item.AvgRate);
                                jsonWriter.WritePropertyName(@"supplier_name");
                                jsonWriter.WriteValue(item.SupplierName);
                                jsonWriter.WritePropertyName(@"total_price");
                                jsonWriter.WriteValue(item.TotalPrice);
                                jsonWriter.WritePropertyName(@"gift");
                                jsonWriter.WriteValue(item.Gift);

                                jsonWriter.WriteEndObject();
                            }

                            jsonWriter.WriteEndArray();

                            jsonWriter.WriteEndObject();
                        }
                    }
                }
            }
            catch (Exception) { }
        }
 public void Init()
 {
     _context    = new AccommodationMockContext();
     _controller = new OfferController(new TestContextProvider(_context));
 }
        public override void Post(HttpRequest Request, HttpResponse Response, params string[] PathParams)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetMaxAge(TimeSpan.Zero);
            JObject inputData = null;

            try
            {
                using (StreamReader reader = new StreamReader(Request.InputStream))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(reader))
                    {
                        inputData = JObject.Load(jsonReader);
                    }
                }
            }
            catch
            {
                RespondBadRequest(Response);
            }

            Int64 AppUserId;

            if (IsAuthorizedRequest(Request, Response, true, out AppUserId))
            {
                Response.ContentType = @"application/json";

                try
                {
                    JToken jt;
                    string card_tk = null, expire_date = null, authNumber = null, last4_digits = null, id_number = null, special_instructions = null;
                    //Int64 order_id = 0;
                    JArray  products      = null;
                    Int64   supplierId    = 0;
                    int     numOfPayments = 1;
                    decimal totalPrice    = 0;
                    var     lstProduct    = new Dictionary <Int64, int>();

                    if (inputData.TryGetValue(@"card_tk", out jt))
                    {
                        card_tk = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"expire_date", out jt))
                    {
                        expire_date = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"last4_digits", out jt))
                    {
                        last4_digits = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"id_number", out jt))
                    {
                        id_number = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"products", out jt))
                    {
                        products = jt.Value <JArray>();
                    }
                    if (inputData.TryGetValue(@"supplier_id", out jt))
                    {
                        supplierId = jt.Value <Int64>();
                    }
                    if (inputData.TryGetValue(@"total_price", out jt) && jt != null)
                    {
                        totalPrice = jt.Value <decimal>();
                    }
                    if (inputData.TryGetValue(@"auth_num", out jt) && jt != null)
                    {
                        authNumber = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"special_instructions", out jt) && jt != null)
                    {
                        special_instructions = jt.Value <string>();
                    }
                    if (inputData.TryGetValue(@"num_of_payments", out jt) && jt != null)
                    {
                        numOfPayments = jt.Value <int>();
                    }
                    foreach (JObject obj in products.Children <JObject>())
                    {
                        Int64 product_id = 0;
                        int   amount     = 1;
                        if (obj.TryGetValue(@"product_id", out jt))
                        {
                            product_id = jt.Value <Int64>();
                        }
                        if (obj.TryGetValue(@"amount", out jt))
                        {
                            amount = jt.Value <int>();
                        }
                        lstProduct.Add(product_id, amount);
                    }

                    bool isPriceValid = false;
                    if (supplierId > 0 && totalPrice > 0)
                    {
                        isPriceValid = OfferController.IsOfferStillValid(lstProduct, supplierId, totalPrice);
                    }
                    if (!isPriceValid)
                    {
                        RespondError(Response, HttpStatusCode.ExpectationFailed, @"price-not-valid");
                    }

                    var results = new ProcessingResults {
                        AuthNumber          = authNumber,
                        CardExpiration      = expire_date,
                        CardToken           = card_tk,
                        NumOfPayments       = numOfPayments,
                        SpecialInstructions = special_instructions,
                        Last4Digits         = last4_digits
                    };
                    using (StreamWriter streamWriter = new StreamWriter(Response.OutputStream))
                    {
                        using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                        {
                            string gifts;
                            var    bidId         = BidController.CreateBidProduct(AppUserId, supplierId, lstProduct, true, out gifts);
                            var    order         = OrderController.GenerateNewOrder(results, AppUserId, bidId, gifts, supplierId, totalPrice, Source.Application);
                            var    offerProducts = ProductController.GetProductsByBid(order.BidId);
                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName(@"products");
                            jsonWriter.WriteStartArray();
                            foreach (var product in offerProducts)
                            {
                                jsonWriter.WriteStartObject();
                                jsonWriter.WritePropertyName(@"product_id");
                                jsonWriter.WriteValue(product.ProductId);
                                jsonWriter.WritePropertyName(@"product_name");
                                jsonWriter.WriteValue(product.ProductName);
                                jsonWriter.WritePropertyName(@"product_category");
                                jsonWriter.WriteValue(product.CategoryName);
                                jsonWriter.WritePropertyName(@"product_sub_category");
                                jsonWriter.WriteValue(product.SubCategoryName);
                                jsonWriter.WritePropertyName(@"product_animal_name");
                                jsonWriter.WriteValue(product.AnimalName);
                                jsonWriter.WriteEndObject();
                            }
                            jsonWriter.WriteEndArray();
                            jsonWriter.WritePropertyName(@"total_price");
                            jsonWriter.WriteValue(order.TotalPrice);
                            jsonWriter.WritePropertyName(@"order_id");
                            jsonWriter.WriteValue(order.OrderId);
                            jsonWriter.WritePropertyName(@"bid_id");
                            jsonWriter.WriteValue(order.BidId);
                            jsonWriter.WriteEndObject();
                        }
                    }
                }

                catch (Exception ex)
                {
                    Helpers.LogProcessing("ProductOrderHandler - ex -", "\n exception: " + ex.ToString(), true);
                    RespondError(Response, HttpStatusCode.InternalServerError, @"db-error");
                }
            }
        }