public void PaymentFail(String orderStatus = "010") { NBrightBuyUtils.ProcessEventProvider(EventActions.BeforePaymentFail, PurchaseInfo); if (!PurchaseInfo.GetXmlPropertyBool("genxml/stopprocess")) { // only move back to cart, if we've not processed payment already. if (IsNotPaid()) { ReleaseModelTransQty(); OrderStatus = orderStatus; PurchaseTypeCode = "CART"; SavePurchaseData(); } } NBrightBuyUtils.ProcessEventProvider(EventActions.AfterPaymentFail, PurchaseInfo); }
public void MakePurchase(PurchaseInfo curProduct, OnPayFinish delPayFinish) { if (null == curProduct) { FinishPay(false, PurchaseTip.TIP_NOTSUPPORT); return; } else if (CheckOrder() != null) { FinishPay(false, "有未处理的订单,请返回刷新商店列表验证订单"); return; } Debug.Log("try purchase id:" + curProduct.productId + "goodid: " + curProduct.goodsId.ToString()); m_curOrder.productID = curProduct.productId; m_curOrder.goodId = curProduct.goodsId; m_curOrder.price = curProduct.goodsPrice.ToString(); m_curOrder.productName = curProduct.goodsName; m_curOrder.userID = Obj_MyselfPlayer.GetMe().uid; m_curOrder.zoneID = 0; PayVarifyResult = -10; m_delFinishPay = delPayFinish; if (DeviceHelper.IAPStyle() == (int)IAPStyle.PAY_APPSTORE) { MakeAppStorePurchase(); } else if (DeviceHelper.IAPStyle() == (int)IAPStyle.PAY_IAPPPAY) { m_curOrder.strOder = OrderManager.Instance().GenerateOrderString(m_curOrder.goodId); OrderManager.Instance().AddOrder(m_curOrder); BoxManager.removeMessage(); MakeIAppPurchase(); } else if (DeviceHelper.IAPStyle() == (int)IAPStyle.PAY_PP) { m_curOrder.strOder = OrderManager.Instance().GenerateOrderString(m_curOrder.goodId); OrderManager.Instance().AddOrder(m_curOrder); MakePPPurchase(); } else { FinishPay(false, PurchaseTip.TIP_NOTSUPPORT); } }
public void Purchase() { money = currencyManager.money; if (price <= money) { isBought[characterInfoArrayNumber] = true; purchaseButton.gameObject.SetActive(false); selectButton.gameObject.SetActive(true); money = money - price; currencyManager.money = money; //saving the purchase BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/Purchases.dat", FileMode.OpenOrCreate); PurchaseInfo myInfo = new PurchaseInfo(); myInfo.purchase = isBought; bf.Serialize(file, myInfo); file.Close(); } }
public override void PurchaseProductFromStore(string product) { isPurchaseInProgress = true; CommerceLog("Mock PurchaseProduct: Purchasing sku " + product); CommerceError commerceError = null; PurchaseInfo purchaseInfo = null; SkuInfo skuInfo = null; switch (testMode) { case 0: commerceError = new CommerceError(100, "Mock Object general failure"); sendPurchaseResponse(commerceError); break; case 1: purchaseInfo = new PurchaseInfo("1001", product, 1413836611000L, "product1_token", "Purchased"); skuInfo = new SkuInfo("Product 1", "$1.99", "Non-Consumable", "Product 1 Desc", product, "USD", "$", i_purchasable: true); sendPurchaseResponse(purchaseInfo, skuInfo); break; case 2: commerceError = new CommerceError(300, "Mock Object general failure"); sendPurchaseResponse(commerceError); break; case 3: commerceError = new CommerceError(305, "Apple Ask To Buy"); sendPurchaseResponse(commerceError); break; case 4: purchaseInfo = new PurchaseInfo("1001", product, 1413836611000L, "product1_token", "Purchased"); skuInfo = new SkuInfo("Product 1", "$1.99", "Non-Consumable", "Product 1 Desc", product, "USD", "$", i_purchasable: true); sendUnexpectedPurchaseResponse(purchaseInfo, skuInfo); break; default: CommerceLog("Mock Object: PurchaseProduct does not cover this case"); break; } isPurchaseInProgress = false; }
/// <summary> /// Implements call to Twofish method purchase/paypal/checkout/recurring to start the Paypal recurring payment purchase checkout process /// Recurring purchase of a foreign exchange /// </summary> /// <param name="userId">userId, IPAddress</param> /// <param name="purchaseInfo">OfferId, ExternalTxnId, BillingDescription, StartDate, NumPayments, PayFrequency</param> /// <param name="recurringInfo">BillingDescription, StartDate, NumPayments, PayFrequency</param> /// <param name="commmonKeyValue">Twofish REST service common values</param> /// <param name="baseAddress">Twofish REST service base address</param> /// <returns>XML document containing Paypal url used to continue the recurring payment purchase process</returns> public XmlDocument PayPalRecurringCheckout(UserId userId, PurchaseInfo purchaseInfo, PurchaseRecurringInfo recurringInfo, CommmonKeyValues commmonKeyValue, BaseAddress baseAddress) { ServiceHandler rest = new ServiceHandler(baseAddress.BaseAddressValue); Dictionary <string, string> keyValues = commmonKeyValue.GetCommmonInfo(false); keyValues.Add("userId", userId.ToString()); keyValues.Add("offerId", purchaseInfo.OfferId); keyValues.Add("externalTxnId", purchaseInfo.ExternalTxnId); keyValues.Add("ipAddress", userId.IPAddress); keyValues.Add("billingDescription", recurringInfo.BillingDescription); keyValues.Add("startDateString", recurringInfo.StartDate); keyValues.Add("numPayments", recurringInfo.NumPayments); keyValues.Add("payFrequency", recurringInfo.PayFrequency); DebugLog("PayPalRecurringCheckout", keyValues); return(rest.PostXMLRequest("purchase/paypal/checkout/recurring", keyValues)); }
/// <summary> /// Implements call to Twofish method purchase/oneClick to complete a one click credit card purchase /// User SecureKey is required /// Purchase of a foreign exchange offer /// </summary> /// <param name="userId">userId, IPAddress, SecureKey</param> /// <param name="purchaseInfo">OfferId, ExternalTxnId</param> /// <param name="creditCardInfo">SecurityCode</param> /// <param name="commmonKeyValue">Twofish REST service common values</param> /// <param name="baseAddress">Twofish REST service base address</param> /// <returns>XML document containing one click credit card purchase results</returns> public XmlDocument PurchaseCreditCardOneClick(UserId userId, PurchaseInfo purchaseInfo, CreditCardInfo creditCardInfo, CommmonKeyValues commmonKeyValue, BaseAddress baseAddress) { ServiceHandler rest = new ServiceHandler(baseAddress.BaseAddressValue); Dictionary <string, string> keyValues = commmonKeyValue.GetCommmonInfo(false); keyValues.Add("userId", userId.ToString()); keyValues.Add("ipAddress", userId.IPAddress); keyValues.Add("secureKey", userId.SecureKey); keyValues.Add("offerId", purchaseInfo.OfferId); keyValues.Add("externalTxnId", purchaseInfo.ExternalTxnId); keyValues.Add("cc.securityCode", creditCardInfo.SecurityCode); //Do not log the credit card number in plain text string[] itemsToEncrypt = new string[] { "cc.securityCode" }; DebugLogEncryptList("PurchaseCreditCard", keyValues, itemsToEncrypt); return(rest.PostXMLRequest("purchase/oneClick", keyValues)); }
public void AddMapInfo(MapInfo model) { string strXml = "<mapinfo>"; strXml += "<genxml>"; strXml += "<textbox>"; strXml += $"<merchantid>{model.MerchantID}</merchantid>"; strXml += $"<merchanttradeno>{model.MerchantTradeNo}</merchanttradeno>"; strXml += $"<logisticssubtype>{model.LogisticsSubType}</logisticssubtype>"; strXml += $"<cvsstoreid>{model.CVSStoreID}</cvsstoreid>"; strXml += $"<cvsstoreName>{model.CVSStoreName}</cvsstoreName>"; strXml += $"<cvsaddress>{model.CVSAddress}</cvsaddress>"; strXml += $"<cvstelephone>{model.CVSTelephone}</cvstelephone>"; strXml += $"<extradata>{model.ExtraData}</extradata>"; strXml += "</textbox>"; strXml += "</genxml>"; strXml += "</mapinfo>"; PurchaseInfo.RemoveXmlNode("genxml/mapinfo"); PurchaseInfo.AddXmlNode(strXml, "mapinfo", "genxml"); }
/// <summary> /// 金増加アイテムのレシート検証 /// </summary> /// <param name="Info">購入情報</param> public static IEnumerator VerifyAddGoldPurchase(PurchaseInfo Info, Action <AddMoneyResult> Callback) { string URL = BaseURL + "purchase/add_gold"; using (var Req = MakePostRequest <PurchaseInfo>(URL, Info)) { yield return(Req.SendWebRequest()); if (Req.responseCode != 200) { AddMoneyResult FailResult = new AddMoneyResult(); FailResult.success = false; Callback?.Invoke(FailResult); yield break; } AddMoneyResult Result = JsonUtility.FromJson <AddMoneyResult>(Req.downloadHandler.text); Callback?.Invoke(Result); } }
public Result <PurchaseInfoDto> Handle(GetPurchaseInfoQuery query) { List <string> errors = new List <string>(); var vatRateResult = VatRate.Create(query.VatRate); if (vatRateResult.IsFailure) { errors.AddRange(vatRateResult.Errors); } var amountResult = MoneyAmount.Create(query.Amount); if (amountResult.IsFailure) { errors.AddRange(amountResult.Errors); return(Result <PurchaseInfoDto> .ResultFail(errors)); } if (errors.Any()) { return(Result <PurchaseInfoDto> .ResultFail(errors)); } if (query.AmountType == AmountType.Gross) { return(MapPurchaseInfoToDto(PurchaseInfo.CreateWithGrossAmount(vatRateResult.Value, amountResult.Value))); } else if (query.AmountType == AmountType.Net) { return(MapPurchaseInfoToDto(PurchaseInfo.CreateWithNetAmount(vatRateResult.Value, amountResult.Value))); } else if (query.AmountType == AmountType.Vat) { return(MapPurchaseInfoToDto(PurchaseInfo.CreateWithVatAmount(vatRateResult.Value, amountResult.Value))); } else { throw new ArgumentException(nameof(AmountType)); } }
public void OnPurchase(PurchaseInfo purchaseInfo) { string message = string.Format( "[Game] Purchase Succeeded, productId: {0}, cpOrderId: {1}, developerPayload: {2}, storeJson: {3}", purchaseInfo.ProductId, purchaseInfo.GameOrderId, purchaseInfo.DeveloperPayload, purchaseInfo.StorePurchaseJsonString); Debug.Log(message); Show(message); /* * If the product is consumable, consume it and deliver the product in OnPurchaseConsume(). * Otherwise, deliver the product here. */ if (m_ConsumeOnPurchase) { Debug.Log("Consuming"); StoreService.ConsumePurchase(purchaseInfo, this); } }
public async Task <bool> PurchaseShoppingCart(PurchaseInfo purchaseInfo) { Result <bool> result = await marketShoppingCartService.PurchaseShoppingCart ( SystemContext.TokenUsername, purchaseInfo.CreditCard.CardNumber, purchaseInfo.CreditCard.Month, purchaseInfo.CreditCard.Year, purchaseInfo.CreditCard.HolderName, purchaseInfo.CreditCard.Cvv, purchaseInfo.CreditCard.HolderId, purchaseInfo.PhoneNumber, purchaseInfo.Address.State, purchaseInfo.Address.City, purchaseInfo.Address.Street, purchaseInfo.Address.ApartmentNum, purchaseInfo.Address.ZipCode ); return(!result.IsErr && result.Ret); }
/// <summary> /// Purchase Game Items /// Currency Name can be used instead of the AccountId. /// Uses the AccountId (optional) specified and if not specified finds the account from the CurrencyName. /// </summary> /// <param name="userId">userId, IPAddress</param> /// <param name="purchaseInfo">OfferIds, ExternalTxnId (optional), AccountId (optional)</param> /// <param name="currencyInfo">CurrencyName</param> /// <returns>XML document with the purchase results</returns> public XmlDocument PurchaseItems(UserId userId, PurchaseInfo purchaseInfo, CurrencyInfo currencyInfo) { XmlDocument response = null; try { PaymentCommand cmd = new PaymentCommand(); cmd.Noun = "Store"; cmd.Verb = "PurchaseItems"; cmd.Parameters.Add("userId", userId.ToString()); if (currencyInfo == null || currencyInfo.CurrencyName.Length == 0) { cmd.Parameters.Add("accountId", purchaseInfo.AccountId); } else { cmd.Parameters.Add("accountId", GetAccountIdFromUserIdAndCurrencyName(userId.ToString(), currencyInfo.CurrencyName)); } cmd.Parameters.Add("offerIds", purchaseInfo.OfferIds); cmd.Parameters.Add("externalTxnId", purchaseInfo.ExternalTxnId); cmd.Parameters.Add("ipAddress", userId.IPAddress); response = CallTwoFishService(cmd, MethodBase.GetCurrentMethod()); response = UpdateResponseForErrors(response, cmd.Parameters); AddUserAccountBalances(userId, response, "/Response/errors"); } catch (Exception ex) { response = CreateErrorDoc(ex.Message); logError("PurchaseItems", ex); } return(response); }
//constructor public ManagePurchaseOrder() { //loading purchase list on left panel PurchaseManager purchaseManager = new PurchaseManager(); for (Iterator i = purchaseManager.getAllPurchaseOrders().iterator(); i.hasNext();) { PurchaseInfo purchaseInfo = (PurchaseInfo)i.next(); PurchaseInfoNJ purchaseInfoNJ = new PurchaseInfoNJ(); //We will display order no in grid view on left panel purchaseInfoNJ.OrderNo = purchaseInfo.getOrderNo(); //right now after clicking on item on left panel purchase info is again retrived from the database //so we can ignore rest of the part right now if required. purchaseInfoNJ.StatusId = purchaseInfo.getStatusId(); purchaseInfoNJ.Remarks = purchaseInfo.getRemarks(); for (Iterator j = purchaseInfo.getProductList().iterator(); j.hasNext();) { ProductInfo productInfo = (ProductInfo)j.next(); ProductInfoNJ productInfoNJ = new ProductInfoNJ(); productInfoNJ.Id = productInfo.getId(); productInfoNJ.Name = productInfo.getName(); productInfoNJ.Code = productInfo.getCode(); productInfoNJ.UnitPrice = productInfo.getUnitPrice(); productInfoNJ.Quantity = productInfo.getQuantity(); purchaseInfoNJ.ProductList.Add(productInfoNJ); } SupplierInfo supplierInfo = new SupplierInfo(); SupplierInfoNJ supplierInfoNJ = new SupplierInfoNJ(); supplierInfoNJ.ProfileInfoNJ.Id = purchaseInfo.getSupplierInfo().getProfileInfo().getId(); supplierInfoNJ.ProfileInfoNJ.FirstName = purchaseInfo.getSupplierInfo().getProfileInfo().getFirstName(); supplierInfoNJ.ProfileInfoNJ.LastName = purchaseInfo.getSupplierInfo().getProfileInfo().getLastName(); purchaseInfoNJ.SupplierInfoNJ = supplierInfoNJ; PurchaseOrderList.Add(purchaseInfoNJ); } //Setting a default random Order No for Purchase Info PurchaseInfoNJ.OrderNo = Guid.NewGuid().ToString().ToUpper();; }
public void CopyToCart(Boolean debugMode = false, String storageType = "Cookie", string nameAppendix = "") { PurchaseTypeCode = "CART"; EditMode = "R"; // reset order fields ShippedDate = ""; OrderStatus = "010"; TrackingCode = ""; InvoiceFileExt = ""; InvoiceFileName = ""; InvoiceFilePath = ""; PurchaseInfo.SetXmlProperty("genxml/audit", ""); var cartId = base.SavePurchaseData(true); var cartData = new CartData(PortalId, "", cartId.ToString("")); //create the client record (cookie) cartData.Save(); if (StoreSettings.Current.DebugModeFileOut) { OutputDebugFile("debug_copytocart.xml"); } }
public async Task <IActionResult> AddPurchasedBook(int bookid) { if (ModelState.IsValid) { try { var username = _httpcontext.HttpContext.User.FindFirst(ClaimTypes.Name).Value; var usermodel = _userService.GetUsersInfo().Result.FirstOrDefault(x => x.UserName == username); var bookmodel = _bookService.GetBooksInfo().Result.FirstOrDefault(x => x.BookId == bookid); var model = new PurchaseInfo() { FirstName = usermodel.FirstName, LastName = usermodel.LastName, UserName = usermodel.UserName, BookName = bookmodel.Name, Category = bookmodel.Category, Price = bookmodel.Price, PurchaseDate = DateTime.Now }; var modeladd = await _bookPurchaseService.PurchaseBook(model); if (modeladd > 0) { return(Ok(new { message = "Book Purchasing Successfully Done" })); } else { return(BadRequest(new { message = "Book Purchasing failed" })); } } catch (Exception ex) { return(BadRequest()); } } return(BadRequest()); }
private void SavePurchaseUpdatesToDB() { if (PurchaseInfoIsVisible && PurchaseInfo != null) { UpdatePurchaseInfoCurrencies(); if (Quantity > PurchasedItem.Quantity) { // too much!! can't buy this many. :( _failureSoundPlayer.Play(); QuantityErrorMessage = "Quantity to purchase is higher than the number of available items"; } else { QuantityErrorMessage = ""; PurchaseInfo.QuantitySold = Quantity; var paidAsDecimal = 0m; if (!decimal.TryParse(PaidAmount, out paidAsDecimal)) { paidAsDecimal = 0; } PurchaseInfo.Paid = paidAsDecimal; if (_amountInventoryChanged != Quantity) { if (_amountInventoryChanged < Quantity) // e.g. 1 -> 3 (= diff of 2; needs to be adjusted by -2) { PurchasedItem.AdjustQuantityByAmount(_amountInventoryChanged - Quantity); } else // e.g. 3 -> 1 (= diff of 2; needs to be adjusted by 2) { PurchasedItem.AdjustQuantityByAmount(Quantity - _amountInventoryChanged); } _amountInventoryChanged = Quantity; } PurchaseInfo.SaveUpdates(); } } }
/* * This method will display selected purchase info * @author nazmul hasan on 26th january 2016 */ public void OnSelectPurchaseOrderEvent(PurchaseInfoNJ purchaseInfoNJ) { PurchaseManager purchaseManager = new PurchaseManager(); ResultEvent resultEvent = purchaseManager.getPurchaseOrderInfo(purchaseInfoNJ.OrderNo); if (resultEvent.getResponseCode() == Responses.RESPONSE_CODE_SUCCESS) { PurchaseInfo purchaseInfo = (PurchaseInfo)resultEvent.getResult(); PurchaseInfoNJ tempPurchaseInfoNJ = new PurchaseInfoNJ(); tempPurchaseInfoNJ.OrderNo = purchaseInfo.getOrderNo(); tempPurchaseInfoNJ.StatusId = purchaseInfo.getStatusId(); tempPurchaseInfoNJ.Remarks = purchaseInfo.getRemarks(); for (Iterator j = purchaseInfo.getProductList().iterator(); j.hasNext();) { ProductInfo productInfo = (ProductInfo)j.next(); ProductInfoNJ productInfoNJ = new ProductInfoNJ(); productInfoNJ.Id = productInfo.getId(); productInfoNJ.Name = productInfo.getName(); productInfoNJ.Code = productInfo.getCode(); productInfoNJ.UnitPrice = productInfo.getUnitPrice(); productInfoNJ.Quantity = productInfo.getQuantity(); tempPurchaseInfoNJ.ProductList.Add(productInfoNJ); } SupplierInfo supplierInfo = new SupplierInfo(); SupplierInfoNJ supplierInfoNJ = new SupplierInfoNJ(); supplierInfoNJ.ProfileInfoNJ.Id = purchaseInfo.getSupplierInfo().getProfileInfo().getId(); supplierInfoNJ.ProfileInfoNJ.FirstName = purchaseInfo.getSupplierInfo().getProfileInfo().getFirstName(); supplierInfoNJ.ProfileInfoNJ.LastName = purchaseInfo.getSupplierInfo().getProfileInfo().getLastName(); tempPurchaseInfoNJ.SupplierInfoNJ = supplierInfoNJ; PurchaseInfoNJ = tempPurchaseInfoNJ; } else { MessageBox.Show(resultEvent.getMessage()); } }
public void VerifyUnexpectedPurchase(PurchaseInfo purchase) { verifyPurchaseWithService(purchase); }
private void verifyPurchaseWithService(PurchaseInfo purchase) { PurchaseRequest purchaseRequest = new PurchaseRequest(purchase.token, purchase.sku, purchase.signature, purchase.originalJson, commerceProcessor.GetStoreType(), biUserId); Service.Get <INetworkServicesManager>().IAPService.Purchase(purchaseRequest); }
protected abstract void FillBillingInfo(PurchaseInfo purchaseInfo);
public void PurchaseItem(string rocketName, string couponName, int quantity, string expectedPrice, PurchaseInfo purchaseInfo) { AddItemToShoppingCart(rocketName); ApplyCoupon(couponName); AssertCouponAppliedSuccessfully(); IncreaseProductQuantity(quantity); AssertTotalPrice(expectedPrice); ProceedToCheckout(); FillBillingInfo(purchaseInfo); AssertOrderReceived(); }
public void AddPurchase(PurchaseInfo purchase, long timestamp) { lock (this) _purchases[purchase.PurchaseItemId] = new RevokeablePurchaseInfo(purchase, timestamp); }
public void OnPurchaseConsumeFailed(string message, PurchaseInfo purchaseInfo) { throw new System.NotImplementedException(); }
public void OnPurchaseConsume(PurchaseInfo purchaseInfo) { throw new System.NotImplementedException(); }
private NBrightInfo ValidateCartItem(int portalId, int userId, NBrightInfo cartItemInfo, Boolean removeZeroQtyItems = false) { #region "get cart values" cartItemInfo = NBrightBuyUtils.ProcessEventProvider(EventActions.ValidateCartItemBefore, cartItemInfo); var modelid = cartItemInfo.GetXmlProperty("genxml/modelid"); var prdid = cartItemInfo.GetXmlPropertyInt("genxml/productid"); var qty = cartItemInfo.GetXmlPropertyDouble("genxml/qty"); var lang = cartItemInfo.GetXmlProperty("genxml/lang"); if (removeZeroQtyItems && qty == 0) { return(null); // Remove zero qty item } if (lang == "") { lang = Utils.GetCurrentCulture(); } var prd = ProductUtils.GetProductData(prdid, lang); if (!prd.Exists || prd.Disabled) { return(null); //Invalid product remove from cart } // update product xml data on cart (product may have change via plugin so always replace) cartItemInfo.RemoveXmlNode("genxml/productxml"); // add entitytype for validation methods prd.Info.SetXmlProperty("genxml/entitytypecode", prd.Info.TypeCode); cartItemInfo.AddSingleNode("productxml", prd.Info.XMLData, "genxml"); var prdModel = prd.GetModel(modelid); if (prdModel == null) { return(null); // Invalid Model remove from cart } // check if dealer (for tax calc) if (NBrightBuyUtils.IsDealer()) { cartItemInfo.SetXmlProperty("genxml/isdealer", "True"); } else { cartItemInfo.SetXmlProperty("genxml/isdealer", "False"); } // check for price change var unitcost = prdModel.GetXmlPropertyDouble("genxml/textbox/txtunitcost"); var dealercost = prdModel.GetXmlPropertyDouble("genxml/textbox/txtdealercost"); var saleprice = prdModel.GetXmlPropertyDouble("genxml/textbox/txtsaleprice"); var dealersalecost = prdModel.GetXmlPropertyDouble("genxml/textbox/txtdealersale"); // always make sale price best price if (unitcost > 0 && (unitcost < saleprice || saleprice <= 0)) { saleprice = unitcost; } // if we have a promoprice use it as saleprice (This is passed in via events provider like "Multi-Buy promotions") if (cartItemInfo.GetXmlPropertyDouble("genxml/promoprice") > 0 && cartItemInfo.GetXmlPropertyDouble("genxml/promoprice") < saleprice) { saleprice = cartItemInfo.GetXmlPropertyDouble("genxml/promoprice"); } // always assign the dealercost the best price. if (dealersalecost > 0 && dealersalecost < dealercost) { dealercost = dealersalecost; } if (saleprice > 0 && (saleprice < dealercost || dealercost <= 0)) { dealercost = saleprice; } if (unitcost > 0 && (unitcost < dealercost || dealercost <= 0)) { dealercost = unitcost; } // calc sell price // sellcost = the calculated cost of the item. var sellcost = unitcost; if (saleprice > 0 && saleprice < sellcost) { sellcost = saleprice; } if (NBrightBuyUtils.IsDealer()) { if (dealercost > 0 && dealercost < sellcost) { sellcost = dealercost; } } // -------------------------------------------- #endregion if (prdModel != null) { #region "Stock Control" var stockon = prdModel.GetXmlPropertyBool("genxml/checkbox/chkstockon"); var stocklevel = prdModel.GetXmlPropertyDouble("genxml/textbox/txtqtyremaining"); var minStock = prdModel.GetXmlPropertyDouble("genxml/textbox/txtqtyminstock"); if (minStock == 0) { minStock = StoreSettings.Current.GetInt("minimumstocklevel"); } var maxStock = prdModel.GetXmlPropertyDouble("genxml/textbox/txtqtystockset"); var weight = prdModel.GetXmlPropertyDouble("genxml/textbox/weight"); if (stockon) { stocklevel = stocklevel - minStock; stocklevel = stocklevel - prd.GetModelTransQty(modelid, _cartId); if (stocklevel < qty) { qty = stocklevel; if (qty <= 0) { qty = 0; cartItemInfo.SetXmlProperty("genxml/validatecode", "OUTOFSTOCK"); } else { cartItemInfo.SetXmlProperty("genxml/validatecode", "STOCKADJ"); } base.SetValidated(false); cartItemInfo.SetXmlPropertyDouble("genxml/qty", qty.ToString("")); } } #endregion #region "Addtional options costs" Double additionalCosts = 0; var optNods = cartItemInfo.XMLDoc.SelectNodes("genxml/options/*"); if (optNods != null) { var lp = 1; foreach (XmlNode nod in optNods) { var optid = nod.SelectSingleNode("optid"); if (optid != null) { var optvalueid = nod.SelectSingleNode("optvalueid"); if (optvalueid != null && optvalueid.InnerText != "False") { XmlNode optvalcostnod; if (optvalueid.InnerText == "True") { optvalcostnod = cartItemInfo.XMLDoc.SelectSingleNode("genxml/productxml/genxml/optionvalues[@optionid='" + optid.InnerText + "']/genxml/textbox/txtaddedcost"); } else { optvalcostnod = cartItemInfo.XMLDoc.SelectSingleNode("genxml/productxml/genxml/optionvalues/genxml[./hidden/optionvalueid='" + optvalueid.InnerText + "']/textbox/txtaddedcost"); } if (optvalcostnod != null) { var optvalcost = optvalcostnod.InnerText; if (Utils.IsNumeric(optvalcost)) { cartItemInfo.SetXmlPropertyDouble("genxml/options/option[" + lp + "]/optvalcost", optvalcost); var optvaltotal = Convert.ToDouble(optvalcost, CultureInfo.GetCultureInfo("en-US")) * qty; cartItemInfo.SetXmlPropertyDouble("genxml/options/option[" + lp + "]/optvaltotal", optvaltotal); additionalCosts += optvaltotal; } } else { cartItemInfo.SetXmlPropertyDouble("genxml/options/option[" + lp + "]/optvalcost", "0"); cartItemInfo.SetXmlPropertyDouble("genxml/options/option[" + lp + "]/optvaltotal", "0"); } } } lp += 1; } } if (qty > 0) // can't devide by zero { unitcost += (additionalCosts / qty); if (dealercost > 0) { dealercost += (additionalCosts / qty); // zero turns off } if (saleprice > 0) { saleprice += (additionalCosts / qty); // zero turns off } sellcost += (additionalCosts / qty); } #endregion var totalcost = qty * unitcost; var totalsellcost = qty * sellcost; var totalweight = weight * qty; cartItemInfo.SetXmlPropertyDouble("genxml/unitcost", unitcost); cartItemInfo.SetXmlPropertyDouble("genxml/dealercost", dealercost); cartItemInfo.SetXmlPropertyDouble("genxml/saleprice", saleprice); cartItemInfo.SetXmlPropertyDouble("genxml/totalweight", totalweight.ToString("")); cartItemInfo.SetXmlPropertyDouble("genxml/totalcost", totalcost); cartItemInfo.SetXmlPropertyDouble("genxml/totaldealerbonus", (totalcost - (qty * dealercost))); Double salediscount = 0; Double discountcodeamt = 0; Double totaldiscount = 0; //add update genxml/discountcodeamt var discountcode = PurchaseInfo.GetXmlProperty("genxml/extrainfo/genxml/textbox/promocode"); if (discountcode != "") { cartItemInfo = DiscountCodeInterface.UpdateItemPercentDiscountCode(PortalId, UserId, cartItemInfo, discountcode); discountcodeamt = cartItemInfo.GetXmlPropertyDouble("genxml/discountcodeamt"); if (discountcodeamt > 0) { PurchaseInfo.SetXmlProperty("genxml/discountprocessed", "False"); } } if (NBrightBuyUtils.IsDealer()) { salediscount = (unitcost - dealercost); } else { salediscount = (unitcost - saleprice); } totaldiscount = (salediscount * qty) + discountcodeamt; // add on any promo code amount if (totaldiscount < 0) { totaldiscount = 0; } // if we have a promodiscount use it if (cartItemInfo.GetXmlPropertyDouble("genxml/promodiscount") > 0) { totaldiscount = cartItemInfo.GetXmlPropertyDouble("genxml/promodiscount"); totalcost = totalcost - totaldiscount; if (totalcost < 0) { totalcost = 0; } cartItemInfo.SetXmlPropertyDouble("genxml/appliedtotalcost", totalcost); } cartItemInfo.SetXmlPropertyDouble("genxml/totaldiscount", totaldiscount); // if product is on sale then we need to display the sale price in the cart, and any discount codes don;t show at this cart item level, only on the order total. cartItemInfo.SetXmlPropertyDouble("genxml/appliedtotalcost", totalsellcost); cartItemInfo.SetXmlPropertyDouble("genxml/appliedcost", sellcost); // calc tax for item var taxproviderkey = PurchaseInfo.GetXmlProperty("genxml/hidden/taxproviderkey"); var taxprov = TaxInterface.Instance(taxproviderkey); if (taxprov != null) { var nbi = (NBrightInfo)cartItemInfo.Clone(); cartItemInfo.SetXmlPropertyDouble("genxml/taxcost", taxprov.CalculateItemTax(nbi)); } } cartItemInfo = NBrightBuyUtils.ProcessEventProvider(EventActions.ValidateCartItemAfter, cartItemInfo); return(cartItemInfo); }
public void ValidateCart(Boolean removeZeroQtyItems = false) { PurchaseInfo = NBrightBuyUtils.ProcessEventProvider(EventActions.ValidateCartBefore, PurchaseInfo); var itemList = GetCartItemList(); Double subtotalcost = 0; Double totaldealerbonus = 0; Double totaldiscount = 0; Double totalsalediscount = 0; Double totalqty = 0; Double totalweight = 0; Double totalunitcost = 0; // Calculate Promotions // Calculate first, so if we add items the price is calculated if (PromoInterface.Instance() != null) { var promol = PromoInterface.ProviderList; foreach (var p in promol) { PurchaseInfo = PromoInterface.Instance(p.Key).CalculatePromotion(PortalId, PurchaseInfo); itemList = GetCartItemList(); // get any new items } } var strXml = "<items>"; foreach (var info in itemList) { // check product still exists and remove if deleted, altered or disabled. var cartItem = ValidateCartItem(PortalId, UserId, info, removeZeroQtyItems); if (cartItem != null) { strXml += cartItem.XMLData; totalunitcost += info.GetXmlPropertyDouble("genxml/unitcost"); subtotalcost += info.GetXmlPropertyDouble("genxml/totalcost"); totaldealerbonus += info.GetXmlPropertyDouble("genxml/totaldealerbonus"); totaldiscount += info.GetXmlPropertyDouble("genxml/totaldiscount"); totalsalediscount += info.GetXmlPropertyDouble("genxml/salediscount"); totalqty += info.GetXmlPropertyDouble("genxml/qty"); totalweight += info.GetXmlPropertyDouble("genxml/totalweight"); } } strXml += "</items>"; PurchaseInfo.RemoveXmlNode("genxml/items"); PurchaseInfo.AddXmlNode(strXml, "items", "genxml"); PopulateItemList(); // put changed items and prices back into base class for saving to DB // calculate totals var promototaldiscount = (totaldiscount - totalsalediscount); PurchaseInfo.SetXmlPropertyDouble("genxml/totalqty", totalqty); PurchaseInfo.SetXmlPropertyDouble("genxml/totalweight", totalweight); PurchaseInfo.SetXmlPropertyDouble("genxml/totalunitcost", totalunitcost); PurchaseInfo.SetXmlPropertyDouble("genxml/subtotalcost", subtotalcost); PurchaseInfo.SetXmlPropertyDouble("genxml/subtotal", subtotalcost); PurchaseInfo.SetXmlPropertyDouble("genxml/appliedsubtotal", (subtotalcost + totalsalediscount)); // calc any voucher amounts var discountcode = PurchaseInfo.GetXmlProperty("genxml/extrainfo/genxml/textbox/promocode"); Double voucherDiscount = 0; if (DiscountCodeInterface.Instance() != null) { PurchaseInfo = DiscountCodeInterface.Instance().CalculateVoucherAmount(PortalId, UserId, PurchaseInfo, discountcode); voucherDiscount = PurchaseInfo.GetXmlPropertyDouble("genxml/voucherdiscount"); } promototaldiscount += voucherDiscount; totaldiscount += voucherDiscount; PurchaseInfo.SetXmlPropertyDouble("genxml/applieddiscount", totaldiscount); PurchaseInfo.SetXmlPropertyDouble("genxml/totaldealerbonus", totaldealerbonus); PurchaseInfo.SetXmlPropertyDouble("genxml/totaldiscount", totaldiscount); PurchaseInfo.SetXmlPropertyDouble("genxml/totalsalediscount", totalsalediscount); //add shipping Double shippingcost = 0; Double shippingdealercost = 0; var shippingkey = PurchaseInfo.GetXmlProperty("genxml/extrainfo/genxml/radiobuttonlist/shippingprovider"); var currentcartstage = PurchaseInfo.GetXmlProperty("genxml/currentcartstage"); if (currentcartstage == "cartaddress" || currentcartstage == "cartsummary") // can only calc shipping on this stage. { ShippingInterface shipprov = null; shipprov = ShippingInterface.Instance(shippingkey); if (shipprov != null) { PurchaseInfo = shipprov.CalculateShipping(PurchaseInfo); shippingcost = PurchaseInfo.GetXmlPropertyDouble("genxml/shippingcost"); shippingdealercost = PurchaseInfo.GetXmlPropertyDouble("genxml/shippingdealercost"); } PurchaseInfo.SetXmlPropertyDouble("genxml/appliedshipping", AppliedCost(shippingcost, shippingdealercost)); } else { // clear the provider if not cartshipping stage PurchaseInfo.SetXmlProperty("genxml/extrainfo/genxml/radiobuttonlist/shippingprovider", ""); } //add tax Double appliedtax = 0; var taxproviderkey = PurchaseInfo.GetXmlProperty("genxml/extrainfo/genxml/hidden/taxproviderkey"); var taxprov = TaxInterface.Instance(taxproviderkey); if (taxprov != null) { PurchaseInfo = taxprov.Calculate(PurchaseInfo); appliedtax = PurchaseInfo.GetXmlPropertyDouble("genxml/appliedtax"); } //cart full total var total = (subtotalcost + shippingcost + appliedtax) - promototaldiscount; if (total < 0) { total = 0; } PurchaseInfo.SetXmlPropertyDouble("genxml/total", total); PurchaseInfo.SetXmlPropertyDouble("genxml/appliedtotal", total); if (PurchaseInfo.GetXmlProperty("genxml/clientmode") == "True") { // user not editor, so stop edit mode. if (!UserController.Instance.GetCurrentUserInfo().IsInRole("Administrators") && !UserController.Instance.GetCurrentUserInfo().IsInRole(StoreSettings.ManagerRole) && !UserController.Instance.GetCurrentUserInfo().IsInRole(StoreSettings.EditorRole)) { PurchaseInfo.SetXmlProperty("genxml/clientmode", "False"); } } PurchaseInfo = NBrightBuyUtils.ProcessEventProvider(EventActions.ValidateCartAfter, PurchaseInfo); SavePurchaseData(); }
/// <summary> /// Called when Button SendToViewModel is clicked /// </summary> private void OnAdd() { //productInfo.setId(productInfo.getId()); //productInfo.setUnitPrice(productInfo.getUnitPrice()); //productInfo.setQuantity(productInfo.getQuantity()); //productInfo.setDiscount(productInfo.getDiscount()); java.util.List productList = new java.util.ArrayList(); for(int i = 0; i < ProductItemList.Count; i ++){ ProductInfo productInfo = new ProductInfo(); ProductInfoNJ productInfoNJ = ProductItemList.ElementAt(i); productInfo.setId(productInfoNJ.ProductId); productInfo.setUnitPrice(productInfoNJ.Price); productInfo.setQuantity(productInfoNJ.Quantity); productInfo.setDiscount(productInfoNJ.Discount); productList.add(productInfo); } PurchaseInfo purchaseInfo = new PurchaseInfo(); purchaseInfo.setProductList(productList); purchaseInfo.setSupplierUserId(SupplierUserId); purchaseInfo.setOrderNo(purchaseInfo.getOrderNo()); purchaseInfo.setStatusId(purchaseInfo.getStatusId()); purchaseInfo.setRemarks(purchaseInfo.getRemarks()); purchaseInfo.setOrderDate(purchaseInfo.getOrderDate()); purchaseInfo.setRequestShippedDate(purchaseInfo.getRequestShippedDate()); PurchaseManager purchaseManager = new PurchaseManager(); purchaseManager.addPurchaseOrder(purchaseInfo); MessageBox.Show("Save Successfully"); }
public ActionResult CreatePurchase(PurchaseInfo purchaseInfo) { try { string action = "Index"; var payer = new Payer { payment_method = "credit_card", funding_instruments = new List <FundingInstrument>(), payer_info = new PayerInfo { email = "*****@*****.**" } }; var creditCard = new CreditCard(); if (!string.IsNullOrEmpty(purchaseInfo.CreditCardId)) { payer.funding_instruments.Add(new FundingInstrument() { credit_card_token = new CreditCardToken() { credit_card_id = purchaseInfo.CreditCardId } }); } else { creditCard = new CreditCard() { billing_address = new Address() { city = "Orlando", country_code = "US", line1 = "123 Test Way", postal_code = "32803", state = "FL" }, cvv2 = purchaseInfo.CVV2, expire_month = purchaseInfo.ExpMonth, expire_year = purchaseInfo.ExpYear, first_name = purchaseInfo.FirstName, last_name = purchaseInfo.LastName, number = purchaseInfo.CreditCardNumber, type = Common.GetCardType(purchaseInfo.CreditCardNumber) }; payer.funding_instruments.Add(new FundingInstrument() { credit_card = creditCard }); } if (!purchaseInfo.IsRecurring) { var transaction = new Transaction { amount = new Amount { currency = "USD", total = purchaseInfo.Amount.ToString() }, description = "Featured Profile on ProductionHUB", invoice_number = Common.GetRandomInvoiceNumber() }; var payment = new Payment() { intent = "sale", payer = payer, transactions = new List <Transaction>() { transaction } }; var createdPayment = payment.Create(apiContext); TempData["info"] = createdPayment.id; if (createdPayment.state == "approved") { action = "Completed"; } else { action = "Rejected"; } } else { var agreement = new Agreement() { name = "Basic profile", description = "Monthly basic profile in perpetuity", payer = payer, plan = new Plan { id = purchaseInfo.BillingPlanId }, start_date = DateTime.UtcNow.AddDays(1).ToString("u").Replace(" ", "T"), }; var createdAgreement = agreement.Create(apiContext); TempData["info"] = createdAgreement.create_time; TempData["success"] = "Recurring agreement created"; } if (purchaseInfo.SavePaymentInfo) { creditCard.external_customer_id = customerId; creditCard.Create(apiContext); } return(RedirectToAction(action)); } catch (Exception exc) { TempData["error"] = exc.Message; } ViewBag.Cards = CreditCard.List(apiContext, externalCustomerId: customerId); ViewBag.Plans = plans; AddPaymentDropdowns(); return(View()); }
public bool Insert(PurchaseInfo purchaseInfo) { return(_purchaseRepository.Insert(purchaseInfo)); }
public static void OnGoodBought( PurchaseInfo info ) { if(goodBoughtEvent!=null) goodBoughtEvent(info); }
public void PurchaseItem(string rocketName, string couponName, int quantity, string expectedPrice, PurchaseInfo purchaseInfo) { _mainPage.Open(); _mainPage.AddRocketToShoppingCart(rocketName); _cartPage.ApplyCoupon(couponName); _cartPage.Assertions.AssertCouponAppliedSuccessfully(); _cartPage.IncreaseProductQuantity(quantity); _cartPage.Assertions.AssertTotalPrice(expectedPrice); _cartPage.ClickProceedToCheckout(); _checkoutPage.FillBillingInfo(purchaseInfo); _checkoutPage.Assertions.AssertOrderReceived(); }
public UnexpectedPurchase(PurchaseInfo pi, SkuInfo si) { PI = pi; SI = si; }