protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // set default start/end date range
                // use query parameters if found, otherwise default to start beginning of current month ending current day
                DateTime localNow = LocaleHelper.LocalNow;
                StartDate.SelectedDate = AlwaysConvert.ToDateTime(Request.QueryString["SDate"], new DateTime(localNow.Year, localNow.Month, 1));
                EndDate.SelectedDate   = AlwaysConvert.ToDateTime(Request.QueryString["EDate"], new DateTime(localNow.Year, localNow.Month, DateTime.DaysInMonth(localNow.Year, localNow.Month)));

                // set up country list
                list_Country.DataSource     = CountryDataSource.LoadAll();
                list_Country.DataTextField  = "Name";
                list_Country.DataValueField = "CountryCode";
                list_Country.DataBind();

                // set country to default to primary warehouse country
                string defCountry = Request.QueryString["CountryCode"];
                if (string.IsNullOrEmpty(defCountry))
                {
                    defCountry = AbleContext.Current.Store.DefaultWarehouse.CountryCode;
                }
                ListItem findItem = list_Country.Items.FindByValue(defCountry);
                if (findItem != null)
                {
                    list_Country.SelectedIndex = list_Country.Items.IndexOf(findItem);
                }

                // fire immediate report
                ProcessButton_Click(null, null);
            }
        }
示例#2
0
        protected void BindReport()
        {
            DateTime reportDate = AlwaysConvert.ToDateTime(ViewState["ReportDate"], DateTime.MinValue);

            ReportCaption.Visible = true;
            ReportCaption.Text    = string.Format(ReportCaption.Text, ReportDate.SelectedDate);
        }
示例#3
0
 protected void ShipButton_Click(object sender, EventArgs e)
 {
     foreach (GridViewRow row in ShipmentGrid.Rows)
     {
         DateTime shipDate   = LocaleHelper.LocalNow;
         int      shipmentId = (int)ShipmentGrid.DataKeys[row.DataItemIndex].Value;
         int      index      = _Shipments.IndexOf(shipmentId);
         if (index > -1)
         {
             OrderShipment shipment = _Shipments[index];
             TextBox       tb       = row.FindControl("ShipDate") as TextBox;
             if (tb != null)
             {
                 shipDate = AlwaysConvert.ToDateTime(tb.Text, LocaleHelper.LocalNow);
             }
             DropDownList ddl = row.FindControl("ShipGateway") as DropDownList;
             tb = row.FindControl("TrackingNumber") as TextBox;
             if ((ddl != null) && (tb != null))
             {
                 TrackingNumber tn = new TrackingNumber();
                 tn.OrderShipmentId    = shipmentId;
                 tn.ShipGatewayId      = AlwaysConvert.ToInt(ddl.SelectedValue);
                 tn.TrackingNumberData = tb.Text;
                 shipment.TrackingNumbers.Add(tn);
                 shipment.TrackingNumbers.Save();
             }
             shipment.Ship(shipDate);
         }
     }
     UpdatePanel.Visible  = false;
     ConfirmPanel.Visible = true;
 }
示例#4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // VALIDATE THE SPECIFIED TAX NAME
            string taxName  = Request.QueryString["T"];
            string locCode  = Request.QueryString["L"];
            string country  = Request.QueryString["C"];
            string province = Request.QueryString["P"];
            int    zoneId   = AlwaysConvert.ToInt(Request.QueryString["Z"]);

            if (!TaxReportDataSource.IsTaxNameValid(taxName))
            {
                Response.Redirect("Taxes.aspx");
            }
            HiddenTaxName.Value = taxName;
            HiddenLocCode.Value = locCode;

            if (!Page.IsPostBack)
            {
                // SET THE DEFAULT DATE FILTER
                DateTime localNow = LocaleHelper.LocalNow;
                StartDate.SelectedDate = AlwaysConvert.ToDateTime(Request.QueryString["StartDate"], new DateTime(localNow.Year, 1, 1));
                EndDate.SelectedDate   = AlwaysConvert.ToDateTime(Request.QueryString["EndDate"], localNow);
                BindReport();
            }
        }
示例#5
0
        protected void BasketsDs_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            DateTime reportDate = AlwaysConvert.ToDateTime(ViewState["ReportDate"], DateTime.MinValue);

            e.InputParameters["year"]  = reportDate.Year.ToString();
            e.InputParameters["month"] = reportDate.Month.ToString();
            e.InputParameters["day"]   = reportDate.Day.ToString();
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
         DateTime localNow  = LocaleHelper.LocalNow;
         DateTime startDate = AlwaysConvert.ToDateTime(Request.QueryString["StartDate"], new DateTime(localNow.Year, localNow.Month, 1));
         DateTime endDate   = AlwaysConvert.ToDateTime(Request.QueryString["EndDate"], localNow);
         StartDate.SelectedDate = startDate;
         EndDate.SelectedDate   = endDate;
         BindReport();
     }
 }
        protected void SubscriptionGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int          subscriptionId = (int)SubscriptionGrid.DataKeys[e.RowIndex].Value;
            Subscription subscription   = SubscriptionDataSource.Load(subscriptionId);

            if (subscription != null)
            {
                subscription.ExpirationDate = AlwaysConvert.ToDateTime(e.NewValues["ExpirationDate"], DateTime.MinValue);
                subscription.Save();
            }
            SubscriptionGrid.EditIndex = -1;
            e.Cancel = true;
        }
示例#8
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
         DateTime tempDate = AlwaysConvert.ToDateTime(Request.QueryString["Date"], System.DateTime.MinValue);
         if (tempDate == System.DateTime.MinValue)
         {
             tempDate = LocaleHelper.LocalNow;
         }
         ViewState["ReportDate"] = tempDate;
         ReportDate.SelectedDate = tempDate;
         BindReport();
     }
 }
        protected void ExportButton_Click(Object sender, EventArgs e)
        {
            GenericExportManager <ReferrerSalesSummary> exportManager = GenericExportManager <ReferrerSalesSummary> .Instance;
            GenericExportOptions <ReferrerSalesSummary> options       = new GenericExportOptions <ReferrerSalesSummary>();

            options.CsvFields = new string[] { "Referrer", "OrderCount", "ProductSubtotal", "SalesTotal" };

            DateTime fromDate = AlwaysConvert.ToDateTime(HiddenStartDate.Value);
            DateTime toDate   = AlwaysConvert.ToDateTime(HiddenEndDate.Value);
            IList <ReferrerSalesSummary> reportData = ReportDataSource.GetSalesByReferrer(fromDate, toDate, "OrderCount DESC");

            options.ExportData = reportData;
            options.FileTag    = string.Format("SALES_BY_REFERRER(from_{0}_to_{1})", fromDate.ToShortDateString(), toDate.ToShortDateString());
            exportManager.BeginExport(options);
        }
示例#10
0
        protected void ExportButton_Click(Object sender, EventArgs e)
        {
            GenericExportManager <AffiliateSalesSummary> exportManager = GenericExportManager <AffiliateSalesSummary> .Instance;
            GenericExportOptions <AffiliateSalesSummary> options       = new GenericExportOptions <AffiliateSalesSummary>();

            options.CsvFields = new string[] { "AffiliateName", "ReferralCount", "FormattedConversionRate", "OrderCount", "ProductSubtotal", "OrderTotal", "FormattedCommission" };

            DateTime fromDate = AlwaysConvert.ToDateTime(HiddenStartDate.Value);
            DateTime toDate   = AlwaysConvert.ToDateTime(HiddenEndDate.Value);
            IList <AffiliateSalesSummary> reportData = ReportDataSource.GetSalesByAffiliate(fromDate, toDate, 0);

            options.ExportData = reportData;
            options.FileTag    = string.Format("SALES_BY_AFFILIATE(from_{0}_to_{1})", fromDate.ToShortDateString(), toDate.ToShortDateString());
            exportManager.BeginExport(options);
        }
示例#11
0
        protected IList <RssNewsItem> GetNewsItems()
        {
            List <RssNewsItem> newsItems;
            CacheWrapper       cacheWrapper = Cache["AbleRssNews"] as CacheWrapper;

            if (cacheWrapper == null)
            {
                XmlDocument AbleRssXml = new XmlDocument();
                try
                {
                    AbleRssXml.Load("http://www.ablecommerce.com/rss/acgold.xml");
                }
                catch
                {
                    AbleRssXml.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><rss></rss>");
                }
                newsItems = new List <RssNewsItem>();
                XmlNodeList nodes      = AbleRssXml.SelectNodes("rss/channel/item");
                int         itemsCount = 0;
                foreach (XmlNode node in nodes)
                {
                    XmlElement  ele      = (XmlElement)node;
                    RssNewsItem newsItem = new RssNewsItem();
                    newsItem.PubDate     = AlwaysConvert.ToDateTime(XmlUtility.GetElementValue(ele, "pubDate"), DateTime.UtcNow);
                    newsItem.Link        = XmlUtility.GetElementValue(ele, "link");
                    newsItem.Title       = XmlUtility.GetElementValue(ele, "title");
                    newsItem.Description = XmlUtility.GetElementValue(ele, "description");
                    newsItems.Add(newsItem);

                    if (++itemsCount > 2)
                    {
                        break;
                    }
                }
                cacheWrapper = new CacheWrapper(newsItems);
                Cache.Remove("AbleRssNews");
                Cache.Add("AbleRssNews", cacheWrapper, null, DateTime.UtcNow.AddDays(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
            }
            else
            {
                newsItems = cacheWrapper.CacheValue as List <RssNewsItem>;
            }
            return(newsItems);
        }
示例#12
0
        private void UpdateInventory(bool sendEmails)
        {
            foreach (GridViewRow row in InventoryGrid.Rows)
            {
                int dataItemIndex = row.DataItemIndex;
                dataItemIndex = (dataItemIndex - (InventoryGrid.PageSize * InventoryGrid.PageIndex));
                int     productId        = (int)InventoryGrid.DataKeys[dataItemIndex].Values[0];
                int     productVariantId = AlwaysConvert.ToInt(InventoryGrid.DataKeys[dataItemIndex].Values[1].ToString());
                int     inStock          = GetControlValue(row, "InStock");
                int     lowStock         = GetControlValue(row, "LowStock");
                TextBox availDate        = (TextBox)row.FindControl("AvailabilityDate");
                Product product          = ProductDataSource.Load(productId);

                if (productVariantId.Equals(0))
                {
                    product.InStock             = inStock;
                    product.InStockWarningLevel = lowStock;
                    product.AvailabilityDate    = LocaleHelper.ToLocalTime(AlwaysConvert.ToDateTime(availDate.Text, DateTime.MinValue));
                    product.Save();

                    if (sendEmails && product.InStock > 0)
                    {
                        RestockNotify(sendEmails, product, null);
                    }
                }
                else
                {
                    ProductVariant variant = ProductVariantDataSource.Load(productVariantId);
                    variant.InStock             = inStock;
                    variant.InStockWarningLevel = lowStock;
                    variant.AvailabilityDate    = LocaleHelper.ToLocalTime(AlwaysConvert.ToDateTime(availDate.Text, DateTime.MinValue));
                    variant.Save();

                    if (sendEmails && variant.InStock > 0)
                    {
                        RestockNotify(sendEmails, product, variant);
                    }
                }
            }
            SavedMessage.Text    = string.Format(SavedMessage.Text, DateTime.Now);
            SavedMessage.Visible = true;
            InventoryGrid.DataBind();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string tempDateFilter = Request.QueryString["DateFilter"];
                if (string.IsNullOrEmpty(tempDateFilter))
                {
                    tempDateFilter = "THISMONTH";
                }
                UpdateDateFilter(tempDateFilter);

                DateTime startDate = AlwaysConvert.ToDateTime(Request.QueryString["StartDate"], DateTime.MinValue);
                DateTime endDate   = AlwaysConvert.ToDateTime(Request.QueryString["EndDate"], DateTime.MaxValue);
                if (startDate != DateTime.MinValue)
                {
                    StartDate.SelectedDate = startDate;
                }
                if (endDate != DateTime.MaxValue)
                {
                    EndDate.SelectedDate = endDate;
                }

                //BIND THE COUPON LIST
                CouponList.DataSource = OrderDataSource.GetCouponCodes();
                CouponList.DataBind();
                //INITIALIZE COUPON LIST
                string   couponCode = Request.QueryString["CouponCode"];
                ListItem listItem   = CouponList.Items.FindByValue(couponCode);
                if (listItem != null)
                {
                    CouponList.SelectedIndex = CouponList.Items.IndexOf(listItem);
                }
                //GENERATE REPORT ON FIRST VISIT
                ReportButton_Click(sender, e);
            }
        }
示例#14
0
        protected void VariantGrid_ItemCreated(object sender, RepeaterItemEventArgs e)
        {
            // GET THE ICON PATH
            if (string.IsNullOrEmpty(_IconPath))
            {
                _IconPath = AbleCommerce.Code.PageHelper.GetAdminThemeIconPath(this.Page);
            }
            if (e.Item.ItemType == ListItemType.Header)
            {
                PlaceHolder phVariantHeader = e.Item.FindControl("phVariantHeader") as PlaceHolder;

                if (phVariantHeader != null)
                {
                    StringBuilder headerBuilder = new StringBuilder();
                    if (names.Contains("SKU"))
                    {
                        headerBuilder.Append("<th>SKU</th>");
                    }
                    if (names.Contains("GTIN"))
                    {
                        headerBuilder.Append("<th>GTIN</th>");
                    }
                    if (names.Contains("Price"))
                    {
                        headerBuilder.Append("<th>Price</th>");
                    }
                    if (names.Contains("Retail"))
                    {
                        headerBuilder.Append("<th>Retail</th>");
                    }
                    if (names.Contains("Model"))
                    {
                        headerBuilder.Append("<th>Model #</th>");
                    }
                    if (names.Contains("Dimensions"))
                    {
                        headerBuilder.Append("<th>Dimensions</th>");
                    }
                    if (names.Contains("HandlingCharges"))
                    {
                        headerBuilder.Append("<th>Special Handling Charges</th>");
                    }
                    if (names.Contains("Weight"))
                    {
                        headerBuilder.Append("<th>Weight</th>");
                    }
                    if (names.Contains("COGS"))
                    {
                        headerBuilder.Append("<th>COGS</th>");
                    }
                    if (names.Contains("Available"))
                    {
                        headerBuilder.Append("<th>Available</th>");
                    }
                    if (_ShowInventory)
                    {
                        if (names.Contains("InStock"))
                        {
                            headerBuilder.Append("<th>In Stock</th>");
                        }
                        if (names.Contains("Availability"))
                        {
                            headerBuilder.Append("<th>Availability Date</th>");
                        }
                        if (names.Contains("LowStock"))
                        {
                            headerBuilder.Append("<th>Low Stock</th>");
                        }
                    }
                    if (names.Contains("Image"))
                    {
                        headerBuilder.Append("<th>Image</th>");
                    }
                    if (names.Contains("Thumbnail"))
                    {
                        headerBuilder.Append("<th>Thumbnail</th>");
                    }
                    if (names.Contains("Icon"))
                    {
                        headerBuilder.Append("<th>Icon</th>");
                    }
                    phVariantHeader.Controls.Add(new LiteralControl(headerBuilder.ToString()));
                }
            }
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                PlaceHolder phVariantRow = e.Item.FindControl("phVariantRow") as PlaceHolder;
                if (phVariantRow != null)
                {
                    ProductVariant variant            = (ProductVariant)e.Item.DataItem;
                    int            variantIndex       = _VariantManager.IndexOf(variant);
                    StringBuilder  rowBuilder         = new StringBuilder();
                    string         skuKey             = "V_" + variantIndex.ToString() + "S";
                    string         gtinKey            = "V_" + variantIndex.ToString() + "G";
                    string         priceKey           = "V_" + variantIndex.ToString() + "P";
                    string         retailKey          = "V_" + variantIndex.ToString() + "RT";
                    string         modelKey           = "V_" + variantIndex.ToString() + "M";
                    string         lengthKey          = "V_" + variantIndex.ToString() + "L";
                    string         widthKey           = "V_" + variantIndex.ToString() + "WI";
                    string         heightKey          = "V_" + variantIndex.ToString() + "H";
                    string         handlingChargesKey = "V_" + variantIndex.ToString() + "SH";
                    string         priceModKey        = "V_" + variantIndex.ToString() + "PM";
                    string         weightKey          = "V_" + variantIndex.ToString() + "W";
                    string         weightModKey       = "V_" + variantIndex.ToString() + "WM";
                    string         cogsKey            = "V_" + variantIndex.ToString() + "C";
                    string         availKey           = "V_" + variantIndex.ToString() + "A";
                    string         instockKey         = "V_" + variantIndex.ToString() + "I";
                    string         availDateKey       = "V_" + variantIndex.ToString() + "AD";
                    string         restockKey         = "V_" + variantIndex.ToString() + "R";
                    string         imageKey           = "V_" + variantIndex.ToString() + "IMG";
                    string         thumbKey           = "V_" + variantIndex.ToString() + "THU";
                    string         iconKey            = "V_" + variantIndex.ToString() + "ICO";

                    //CHECK IF THIS VARIANT IS IN FORM POST
                    if (_FormValues.Any(v => v.Key.StartsWith("V_" + variantIndex.ToString())))
                    {
                        //UPDATE THE VALUES BASED ON THE FORM POST
                        if (_FormValues.ContainsKey(skuKey))
                        {
                            variant.Sku = SafeTryGetValue(_FormValues, skuKey);
                        }
                        if (_FormValues.ContainsKey(gtinKey))
                        {
                            variant.GTIN = SafeTryGetValue(_FormValues, gtinKey);
                        }
                        if (_FormValues.ContainsKey(priceKey))
                        {
                            variant.Price = AlwaysConvert.ToDecimal(SafeTryGetValue(_FormValues, priceKey));
                        }
                        if (_FormValues.ContainsKey(retailKey))
                        {
                            variant.MSRP = AlwaysConvert.ToDecimal(SafeTryGetValue(_FormValues, retailKey));
                        }
                        if (_FormValues.ContainsKey(priceModKey))
                        {
                            variant.PriceModeId = AlwaysConvert.ToByte(SafeTryGetValue(_FormValues, priceModKey));
                        }
                        if (_FormValues.ContainsKey(modelKey))
                        {
                            variant.ModelNumber = SafeTryGetValue(_FormValues, modelKey);
                        }
                        if (_FormValues.ContainsKey(lengthKey))
                        {
                            variant.Length = AlwaysConvert.ToDecimal(SafeTryGetValue(_FormValues, lengthKey));
                        }
                        if (_FormValues.ContainsKey(widthKey))
                        {
                            variant.Width = AlwaysConvert.ToDecimal(SafeTryGetValue(_FormValues, widthKey));
                        }
                        if (_FormValues.ContainsKey(heightKey))
                        {
                            variant.Height = AlwaysConvert.ToDecimal(SafeTryGetValue(_FormValues, heightKey));
                        }
                        if (_FormValues.ContainsKey(handlingChargesKey))
                        {
                            variant.HandlingCharges = AlwaysConvert.ToDecimal(SafeTryGetValue(_FormValues, handlingChargesKey));
                        }
                        if (_FormValues.ContainsKey(weightKey))
                        {
                            variant.Weight = AlwaysConvert.ToDecimal(SafeTryGetValue(_FormValues, weightKey));
                        }
                        if (_FormValues.ContainsKey(weightModKey))
                        {
                            variant.WeightModeId = AlwaysConvert.ToByte(SafeTryGetValue(_FormValues, weightModKey));
                        }
                        if (_FormValues.ContainsKey(cogsKey))
                        {
                            variant.CostOfGoods = AlwaysConvert.ToDecimal(SafeTryGetValue(_FormValues, cogsKey));
                        }
                        if (_FormValues.ContainsKey(availKey))
                        {
                            variant.Available = (SafeTryGetValue(_FormValues, availKey) == "1,0");
                        }
                        if (_FormValues.ContainsKey(imageKey))
                        {
                            variant.ImageUrl = SafeTryGetValue(_FormValues, imageKey);
                        }
                        if (_FormValues.ContainsKey(thumbKey))
                        {
                            variant.ThumbnailUrl = SafeTryGetValue(_FormValues, thumbKey);
                        }
                        if (_FormValues.ContainsKey(iconKey))
                        {
                            variant.IconUrl = SafeTryGetValue(_FormValues, iconKey);
                        }

                        if (_ShowInventory)
                        {
                            if (_FormValues.ContainsKey(instockKey))
                            {
                                variant.InStock = AlwaysConvert.ToInt(SafeTryGetValue(_FormValues, instockKey));
                            }
                            if (_FormValues.ContainsKey(availDateKey))
                            {
                                variant.AvailabilityDate = AlwaysConvert.ToDateTime(SafeTryGetValue(_FormValues, availDateKey), DateTime.MinValue);
                            }
                            if (_FormValues.ContainsKey(restockKey))
                            {
                                variant.InStockWarningLevel = AlwaysConvert.ToInt(SafeTryGetValue(_FormValues, restockKey));
                            }
                        }
                    }

                    //DRAW THE DATA ROW
                    string rowClass         = (e.Item.ItemType == ListItemType.Item) ? "oddRow" : "evenRow";
                    string autoExpand       = selectedCount > 9 ? "noExpand" : "expandColumns";
                    string smallExpands     = selectedCount > 9 ? "nosmallExpand" : "expandSmallColumns";
                    string overrideSelected = string.Empty;

                    rowBuilder.Append("<tr class=\"" + rowClass + "\">\r\n");
                    rowBuilder.Append("<td>" + (variantIndex + 1) + "</td>\r\n");
                    rowBuilder.Append("<td>" + variant.VariantName + "</td>\r\n");
                    if (names.Contains("SKU"))
                    {
                        rowBuilder.Append("<td align=\"center\"><input name=\"" + skuKey + "\" type=\"text\" value=\"" + variant.Sku + "\" class= \"" + autoExpand + "\" /></td>\r\n");
                    }
                    if (names.Contains("GTIN"))
                    {
                        rowBuilder.Append("<td align=\"center\"><input name=\"" + gtinKey + "\" type=\"text\" value=\"" + variant.GTIN + "\" class= \"" + autoExpand + "\" /></td>\r\n");
                    }
                    if (names.Contains("Price"))
                    {
                        rowBuilder.Append("<td align=\"center\"><input name=\"" + priceKey + "\" type=\"text\" value=\"" + variant.Price.LSCurrencyFormat("F2") + "\" class= \"" + smallExpands + "\" />");
                        overrideSelected = (variant.PriceMode == ModifierMode.Modify) ? string.Empty : " selected";
                        rowBuilder.Append("<select name=\"" + priceModKey + "\"><option value=\"0\">Modify</option><option value=\"1\"" + overrideSelected + ">Override</option></select></td>\r\n");
                    }
                    if (names.Contains("Retail"))
                    {
                        rowBuilder.Append("<td align=\"center\"><input name=\"" + retailKey + "\" type=\"text\" value=\"" + variant.MSRP.LSCurrencyFormat("F2") + "\" class= \"" + smallExpands + "\" />");
                    }
                    if (names.Contains("Model"))
                    {
                        rowBuilder.Append("<td align=\"center\"><input name=\"" + modelKey + "\" type=\"text\" value=\"" + variant.ModelNumber + "\" class= \"" + autoExpand + "\" />");
                    }
                    if (names.Contains("Dimensions"))
                    {
                        rowBuilder.Append("<td align=\"center\">L <input name=\"" + lengthKey + "\" type=\"text\" value=\"" + variant.Length.LSCurrencyFormat("F2") + "\" style=\"width:46px;\" />");
                        rowBuilder.Append("W <input name=\"" + widthKey + "\" type=\"text\" value=\"" + variant.Width.LSCurrencyFormat("F2") + "\" style=\"width:46px;\" />");
                        rowBuilder.Append("H <input name=\"" + heightKey + "\" type=\"text\" value=\"" + variant.Height.LSCurrencyFormat("F2") + "\" style=\"width:46px;\" />");
                    }
                    if (names.Contains("HandlingCharges"))
                    {
                        rowBuilder.Append("<td align=\"center\"><input name=\"" + handlingChargesKey + "\" type=\"text\" value=\"" + variant.HandlingCharges.LSCurrencyFormat("F2") + "\" class= \"" + smallExpands + "\" />");
                    }
                    if (names.Contains("Weight"))
                    {
                        rowBuilder.Append("<td align=\"center\"><input name=\"" + weightKey + "\" type=\"text\" value=\"" + variant.Weight.LSCurrencyFormat("F2") + "\" class= \"" + smallExpands + "\" />");
                        overrideSelected = (variant.WeightMode == ModifierMode.Modify) ? string.Empty : " selected";
                        rowBuilder.Append("<select name=\"" + weightModKey + "\"><option value=\"0\">Modify</option><option value=\"1\"" + overrideSelected + ">Override</option></select></td>\r\n");
                    }
                    if (names.Contains("COGS"))
                    {
                        rowBuilder.Append("<td align=\"center\"><input name=\"" + cogsKey + "\" type=\"text\" value=\"" + variant.CostOfGoods.LSCurrencyFormat("F2") + "\" class= \"" + smallExpands + "\" /></td>\r\n");
                    }
                    string checkedAttribute = string.Empty;
                    if (names.Contains("Available"))
                    {
                        if (variant.Available)
                        {
                            checkedAttribute = " checked=\"true\"";
                        }
                        rowBuilder.Append("<td align=\"center\"><input name=\"" + availKey + "\" type=\"checkbox\"" + checkedAttribute + " value=\"1\" /><input name=\"" + availKey + "\" type=\"hidden\"" + checkedAttribute + " value=\"0\" /></td>");
                    }
                    if (_ShowInventory)
                    {
                        if (names.Contains("InStock"))
                        {
                            rowBuilder.Append("<td align=\"center\"><input name=\"" + instockKey + "\" type=\"text\" value=\"" + variant.InStock.ToString("F0") + "\" class= \"" + smallExpands + "\" /></td>\r\n");
                        }
                        if (names.Contains("Availability"))
                        {
                            rowBuilder.Append("<td align=\"center\"><input name=\"" + availDateKey + "\" type=\"text\" value=\"" + ((variant.AvailabilityDate.HasValue && variant.AvailabilityDate != DateTime.MinValue) ? variant.AvailabilityDate.Value.ToShortDateString() : string.Empty) + "\" style=\"width:90px;\" class=\"pickerAndCalendar\" /></td>\r\n");
                        }
                        if (names.Contains("LowStock"))
                        {
                            rowBuilder.Append("<td align=\"center\"><input name=\"" + restockKey + "\" type=\"text\" value=\"" + variant.InStockWarningLevel.ToString("F0") + "\" class= \"" + smallExpands + "\" /></td>\r\n");
                        }
                    }
                    if (names.Contains("Image"))
                    {
                        rowBuilder.Append("<td align=\"center\"><input name=\"" + imageKey + "\" type=\"text\" value=\"" + variant.ImageUrl + "\" class= \"" + autoExpand + "\" /><input name=\"" + imageKey + "B\" alt=\"Browse\" onclick=\"return PickImage('" + imageKey + "');\" type=\"image\" align=\"absmiddle\" src=\"" + _IconPath + "find.gif\" /></td>\r\n");
                    }
                    if (names.Contains("Thumbnail"))
                    {
                        rowBuilder.Append("<td align=\"center\"><input name=\"" + thumbKey + "\" type=\"text\" value=\"" + variant.ThumbnailUrl + "\" class= \"" + autoExpand + "\" /><input name=\"" + thumbKey + "B\" alt=\"Browse\" onclick=\"return PickImage('" + thumbKey + "');\" type=\"image\" align=\"absmiddle\" src=\"" + _IconPath + "find.gif\" /></td>\r\n");
                    }
                    if (names.Contains("Icon"))
                    {
                        rowBuilder.Append("<td align=\"center\"><input name=\"" + iconKey + "\" type=\"text\" value=\"" + variant.IconUrl + "\" class= \"" + autoExpand + "\" /><input name=\"" + iconKey + "B\" alt=\"Browse\" onclick=\"return PickImage('" + iconKey + "');\" type=\"image\" align=\"absmiddle\" src=\"" + _IconPath + "find.gif\" /></td>\r\n");
                    }
                    rowBuilder.Append("</tr>\r\n");
                    phVariantRow.Controls.Add(new LiteralControl(rowBuilder.ToString()));
                }
            }
        }
示例#15
0
        protected string GetLastUpdateDate(object value)
        {
            DateTime dt = AlwaysConvert.ToDateTime(value);

            return(dt == DateTime.MinValue ? "N/A" : dt.ToString());
        }
示例#16
0
        public void ProcessRequest(HttpContext context)
        {
            //GET REFERENCE TO REQUEST
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;
            TraceContext trace    = context.Trace;

            //RECORD FORM VALUES TO TRACE OUTPUT
            foreach (string key in request.Form)
            {
                context.Trace.Write(key + ":" + request.Form[key]);
            }
            //SETUP DEFAULT REDIRECT URL
            string redirectUrl = "~/Default.aspx";
            //INITIALIZE THE PAYPAL PROVIDER
            PaymentGateway paypalGateway = PayPalProvider.GetPayPalPaymentGateway(true);

            if (paypalGateway == null)
            {
                response.Redirect(redirectUrl);
            }
            //LOOK FOR ORDER ID
            int    orderId;
            string customValue = request.Form["custom"];

            if (!String.IsNullOrEmpty(customValue))
            {
                int index = customValue.IndexOf(":");
                if (index > 0)
                {
                    orderId = AlwaysConvert.ToInt(customValue.Substring(0, index));
                }
                else
                {
                    orderId = AlwaysConvert.ToInt(customValue);
                }
            }
            else
            {
                // TRY TO LOCATE ORDER ID AS QUERY STRING PARAMETER
                orderId = AlwaysConvert.ToInt(request.QueryString["OrderId"]);
            }

            //IF ORDER ID WAS NOT IN CUSTOM, SEE IF WE CAN FIND THE ORDER VIA TRANSACTION ID
            if (orderId == 0)
            {
                trace.Write("OrderId not found in custom field; lookup via transaction ID");
                string parentTransactionId = IpnProcessor.GetFormValue(request.Form, "parent_txn_id");
                if (!string.IsNullOrEmpty(parentTransactionId) && (paypalGateway != null))
                {
                    trace.Write("Query for parent transaction " + parentTransactionId);
                    orderId = FindPayPalOrderId(paypalGateway.PaymentGatewayId, parentTransactionId);
                    if (orderId != 0)
                    {
                        trace.Write("Order ID Found: " + orderId.ToString());
                    }
                }
            }
            //TRY TO LOAD ORDER
            Order order = OrderDataSource.Load(orderId);

            //IF ORDER LOAD FAILS, STOP PROCESSING AND REDIRECT
            if (order == null)
            {
                response.Redirect(redirectUrl);
            }
            //ORDER LOAD SUCCESSFUL, UPDATE DEFAULT REDIRECT URL
            redirectUrl = "~/Members/MyOrder.aspx?OrderId=" + orderId.ToString();
            //IF GATEWAY NOT FOUND, STOP PROCESSING AND REDIRECT
            PayPalProvider provider = (PayPalProvider)paypalGateway.GetInstance();
            //GET TRANSACTION AMOUNT
            LSDecimal curSignedPayment = AlwaysConvert.ToDecimal(request.Form["mc_gross"]);
            LSDecimal curPayment       = Math.Abs((Decimal)curSignedPayment);

            context.Trace.Write("Transaction Amount is " + curPayment.ToString());
            if (curPayment != 0)
            {
                //VERIFY PAYMENT NOTIFICATION WITH PAYPAL
                bool valid = provider.ValidateNotification(request.Form.ToString());
                if (!valid)
                {
                    response.Redirect(redirectUrl);
                }
                //VERIFY THE RECEIVER EMAIL
                string lowerReceiverEmail   = AlwaysConvert.ToString(request.Form["receiver_email"]).ToLowerInvariant();
                string lowerProviderAccount = provider.PayPalAccount.ToLowerInvariant();
                if (lowerReceiverEmail != lowerProviderAccount)
                {
                    context.Trace.Write("Receiver Email (" + lowerReceiverEmail + ") does not match Primary Account (" + lowerProviderAccount + ")");
                    response.Redirect(redirectUrl);
                }
                //CHECK WHETHER TRANSACTION IS ALREADY PRESENT IN DATABASE
                string paypalTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                string authTransactionId   = IpnProcessor.GetFormValue(request.Form, "auth_id");
                string paymentStatus       = IpnProcessor.GetFormValue(request.Form, "payment_status").ToUpperInvariant();
                string authStatus          = IpnProcessor.GetFormValue(request.Form, "auth_status").ToUpperInvariant();
                context.Trace.Write("Transaction ID Is " + paypalTransactionId);
                context.Trace.Write("Payment Status Is " + paymentStatus);
                context.Trace.Write("Auth Status Is " + authStatus);

                //CHECK FOR THIS PAYPAL TRANSACTION (MATCHING PROVIDER, PAYPAL TRANSACTION ID, AND PAYMENT STATUS)
                Payment     payment            = null;
                Transaction pendingTransaction = null;
                if (!string.IsNullOrEmpty(paypalTransactionId))
                {
                    TransactionCollection matchingTransactions = TransactionDataSource.LoadForProviderTransaction(paypalGateway.PaymentGatewayId, paypalTransactionId);
                    foreach (Transaction tx in matchingTransactions)
                    {
                        //WHEN PAYMENT IS BY ECHECK, IPN ISSUES A PENDING TRANSACTION
                        //SECOND IPN COMES FOR COMPLETED STATUS USING SAME TRANSACTION ID
                        if ((tx.ResponseCode == "PENDING") && (paymentStatus != "PENDING"))
                        {
                            //WE HAVE TO GET THE TRANSACTION VIA THE PAYMENT OBJECT
                            //OTHERWISE WE WILL HAVE PROBLEMS WITH DATA CONSISTENCY LATER
                            payment = tx.Payment;
                            foreach (Transaction ptx in payment.Transactions)
                            {
                                if (ptx.TransactionId == tx.TransactionId)
                                {
                                    pendingTransaction = ptx;
                                }
                            }
                        }
                        else if ((tx.TransactionType != TransactionType.Void) && (paymentStatus == "VOIDED"))
                        {
                            //IF WE VOID AN AUTHORIZATION, THE VOID HAS THE SAME TXID
                            //THE AUTHORIZATION WILL HAVE A BLANK RESPONSE CODE
                            //THE VOID SHOULD HAVE A 'VOIDED' RESPONSE CODE
                            //(THIS TRANSACTION IS NOT A MATCH AND SHOULD BE IGNORED)
                        }
                        else
                        {
                            //NO FURTHER PROCESSING, REDIR TO ORDER SCREEN
                            context.Trace.Write("Transaction ID " + paypalTransactionId + " Already Exists in Database");
                            response.Redirect(redirectUrl);
                        }
                    }
                }

                Transaction       transaction       = null;
                PaymentMethod     paypalMethod      = PayPalProvider.GetPayPalPaymentMethod(true);
                PaymentCollection orderPayments     = order.Payments;
                Transaction       authTransaction   = null;
                PaymentStatus[]   validAuthStatuses = { PaymentStatus.Unprocessed, PaymentStatus.AuthorizationPending };
                context.Trace.Write("Processing Payment Status: " + paymentStatus);
                switch (paymentStatus)
                {
                case "PENDING":
                    //THIS IS A PENDING TRANSACTION, GET PENDING REASON AND FIND OUT IF IT IS AN ECHECK WAITING TO CLEAR
                    string pendingReason          = IpnProcessor.GetFormValue(request.Form, "pending_reason").ToLowerInvariant();
                    bool   isPendingeCheck        = (pendingReason == "echeck");
                    bool   isPendingAuthorization = (pendingReason == "authorization");
                    context.Trace.Write("Pending Reason: " + pendingReason);
                    context.Trace.Write("Is Pending eCheck: " + isPendingeCheck.ToString());
                    context.Trace.Write("Is Pending Authorization: " + isPendingAuthorization.ToString());
                    //FIND THE PAYPAL PAYMENT THAT IS UNPROCESSED OR PENDING AUTHORIZATION
                    payment = FindPaypalPayment(paypalMethod.PaymentMethodId, orderPayments, validAuthStatuses);
                    if (payment != null)
                    {
                        //SEE IF WE CAN FIND A PENDING PAYPAL TRANSACTION WITHOUT A TXID
                        foreach (Transaction tx in payment.Transactions)
                        {
                            if ((tx.ResponseCode == "PENDING") && string.IsNullOrEmpty(tx.ProviderTransactionId))
                            {
                                transaction = tx;
                            }
                        }
                    }
                    //IF WE DID NOT FIND AN EXISTING TRANSACTION, CREATE A NEW ONE
                    if (transaction == null)
                    {
                        transaction = new Transaction();
                    }
                    //UPDATE THE TRANSACTION VALUES
                    transaction.TransactionType       = (isPendingeCheck ? TransactionType.Capture : TransactionType.Authorize);
                    transaction.PaymentGatewayId      = paypalGateway.PaymentGatewayId;
                    transaction.ProviderTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                    transaction.TransactionDate       = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                    transaction.Amount            = AlwaysConvert.ToDecimal(IpnProcessor.GetFormValue(request.Form, "mc_gross"));
                    transaction.TransactionStatus = TransactionStatus.Successful;
                    if (isPendingAuthorization)
                    {
                        //THIS IS AN EXPECTED RESPONSE, NO NEED TO SAVE THE REASON CODES
                        transaction.ResponseMessage = string.Empty;
                        transaction.ResponseCode    = string.Empty;
                    }
                    else
                    {
                        transaction.ResponseMessage = pendingReason;
                        transaction.ResponseCode    = "PENDING";
                    }
                    transaction.AuthorizationCode = IpnProcessor.GetFormValue(request.Form, "auth_id");
                    transaction.RemoteIP          = IpnProcessor.GetFormValue(request.ServerVariables, "REMOTE_ADDR");
                    transaction.Referrer          = IpnProcessor.GetFormValue(request.ServerVariables, "HTTP_REFERER");
                    //CREATE A PAYMENT IF AN EXISTING ONE WAS NOT FOUND
                    if (payment == null)
                    {
                        payment                   = new Payment();
                        payment.OrderId           = orderId;
                        payment.PaymentMethodId   = paypalMethod.PaymentMethodId;
                        payment.PaymentMethodName = paypalMethod.Name;
                        order.Payments.Add(payment);
                    }
                    //UPDATE PAYMENT DETAILS
                    payment.ReferenceNumber = IpnProcessor.GetFormValue(request.Form, "payer_email");
                    payment.Amount          = transaction.Amount;
                    payment.PaymentDate     = transaction.TransactionDate;
                    if (isPendingAuthorization)
                    {
                        payment.PaymentStatus       = PaymentStatus.Authorized;
                        payment.PaymentStatusReason = string.Empty;
                    }
                    else
                    {
                        payment.PaymentStatus       = (isPendingeCheck ? PaymentStatus.CapturePending : PaymentStatus.AuthorizationPending);
                        payment.PaymentStatusReason = transaction.ResponseMessage;
                    }
                    //ADD IN TRANSACTION
                    payment.Transactions.Add(transaction);
                    break;

                case "COMPLETED":
                    //IF THIS IS A CAPTURE FROM AN AUTHORIZATION, FIND THE AUTHORIZATION TRANSACTION
                    //AND UPDATE THE STATUS ACCORDINGLY, DEPENDING ON WHETHER ADDITIONAL SETTLEMENT TRANSACTIONS REMAIN (INTREMSETTLE > 0)
                    authTransaction   = null;
                    authTransactionId = IpnProcessor.GetFormValue(request.Form, "auth_id");
                    if (!string.IsNullOrEmpty(authTransactionId))
                    {
                        TransactionCollection matchingTransactions = TransactionDataSource.LoadForProviderTransaction(paypalGateway.PaymentGatewayId, authTransactionId);
                        //SHOULD ONLY BE ONE
                        if (matchingTransactions.Count > 0)
                        {
                            authTransaction = matchingTransactions[0];
                        }
                    }
                    //IF PAYPAL IS RUNNING IN CAPTURE MODE, WE MAY HAVE A COMPLETED PAYMENT
                    //WITH A PENDING OR UNPROCESSED PAYMENT ALREADY ASSOCIATED TO ORDER
                    if (pendingTransaction == null)
                    {
                        //FIND THE PAYPAL PAYMENT THAT IS UNPROCESSED OR PENDING
                        payment = FindPaypalPayment(paypalMethod.PaymentMethodId, orderPayments, validAuthStatuses);
                        if (payment != null)
                        {
                            //SEE IF WE CAN FIND A PENDING PAYPAL TRANSACTION WITHOUT A TXID
                            foreach (Transaction tx in payment.Transactions)
                            {
                                if ((tx.ResponseCode == "PENDING") && string.IsNullOrEmpty(tx.ProviderTransactionId))
                                {
                                    pendingTransaction = tx;
                                }
                            }
                        }
                    }
                    //SEE IF THIS TRANSACTION WAS PENDING (SUCH AS A CHECK WAITING TO CLEAR)
                    if (pendingTransaction != null)
                    {
                        //GET THE PENDING TRANSACTION AND PAYMENT
                        payment     = order.Payments[order.Payments.IndexOf(pendingTransaction.PaymentId)];
                        transaction = payment.Transactions[payment.Transactions.IndexOf(pendingTransaction.TransactionId)];
                    }
                    else
                    {
                        //THIS IS NOT A PENDING TRANSACTION
                        //LOCATE THE APPROPRIATE PAYMENT
                        if (authTransaction != null)
                        {
                            payment = order.Payments[order.Payments.IndexOf(authTransaction.PaymentId)];
                        }
                        else
                        {
                            //FIND THE PAYPAL PAYMENT THAT CAN BE CAPTURED
                            PaymentStatus[] validCaptureStatuses = { PaymentStatus.Unprocessed, PaymentStatus.AuthorizationPending, PaymentStatus.Authorized, PaymentStatus.CaptureFailed, PaymentStatus.CapturePending };
                            payment = FindPaypalPayment(paypalMethod.PaymentMethodId, orderPayments, validCaptureStatuses);
                            //CREATE A PAYMENT IF AN EXISTING ONE WAS NOT FOUND
                            if (payment == null)
                            {
                                payment                   = new Payment();
                                payment.OrderId           = orderId;
                                payment.PaymentMethodId   = paypalMethod.PaymentMethodId;
                                payment.PaymentMethodName = paypalMethod.Name;
                                order.Payments.Add(payment);
                            }
                        }
                        //CREATE A NEW TRANSACTION RECORD
                        transaction           = new Transaction();
                        transaction.PaymentId = payment.PaymentId;
                    }
                    //UPDATE THE TRANSACTION DETAILS
                    transaction.TransactionType       = TransactionType.Capture;
                    transaction.PaymentGatewayId      = paypalGateway.PaymentGatewayId;
                    transaction.TransactionDate       = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                    transaction.RemoteIP              = IpnProcessor.GetFormValue(request.ServerVariables, "REMOTE_ADDR");
                    transaction.Referrer              = IpnProcessor.GetFormValue(request.ServerVariables, "HTTP_REFERER");
                    transaction.TransactionStatus     = TransactionStatus.Successful;
                    transaction.ProviderTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                    transaction.AuthorizationCode     = IpnProcessor.GetFormValue(request.Form, "auth_id");
                    transaction.Amount          = AlwaysConvert.ToDecimal(IpnProcessor.GetFormValue(request.Form, "mc_gross"));
                    transaction.ResponseCode    = paymentStatus;
                    transaction.ResponseMessage = string.Empty;

                    //HANDLE PARTIAL / FINAL CAPTURES
                    int remainingSettle = AlwaysConvert.ToInt(IpnProcessor.GetFormValue(request.Form, "remaining_settle"));
                    if (remainingSettle == 0)
                    {
                        //THIS IS A FINAL CAPTURE
                        transaction.TransactionType = TransactionType.Capture;
                        //SET PAYMENT AMOUNT TO SUM OF ALL CAPTURES
                        LSDecimal totalCaptures = 0;
                        foreach (Transaction tx in payment.Transactions)
                        {
                            if ((transaction.TransactionId != tx.TransactionId) &&
                                (tx.TransactionType == TransactionType.PartialCapture || tx.TransactionType == TransactionType.Capture))
                            {
                                totalCaptures += tx.Amount;
                            }
                        }
                        totalCaptures += transaction.Amount;
                        payment.Amount = totalCaptures;
                    }
                    else
                    {
                        //THIS IS A PARTIAL CAPTURE
                        transaction.TransactionType = TransactionType.PartialCapture;
                        //LEAVE PAYMENT AMOUNT ALONE (AMOUNT OF AUTHORIZATION)
                    }

                    //UPDATE PAYMENT DETAILS
                    payment.PaymentDate         = transaction.TransactionDate;
                    payment.PaymentStatus       = (remainingSettle == 0) ? PaymentStatus.Captured : PaymentStatus.Authorized;
                    payment.PaymentStatusReason = string.Empty;

                    //ADD IN TRANSACTION IF NEEDED
                    if (transaction.TransactionId == 0)
                    {
                        payment.Transactions.Add(transaction);
                    }
                    break;

                case "REFUNDED":
                case "REVERSED":
                    //GET THE REFUND AMOUNT
                    LSDecimal refundAmount = Math.Abs(AlwaysConvert.ToDecimal(IpnProcessor.GetFormValue(request.Form, "mc_gross")));
                    //TRY TO LOCATE THE CORRECT PAYMENT BASED ON CAPTURE TRANSACITON ID
                    payment = FindPayPalPayment(paypalGateway.PaymentGatewayId, orderPayments, IpnProcessor.GetFormValue(request.Form, "parent_txn_id"));
                    if (payment == null)
                    {
                        //SEE IF WE CAN FIND THE PAYMENT VIA AUTH TRANSACTION ID
                        payment = FindPayPalPayment(paypalGateway.PaymentGatewayId, orderPayments, IpnProcessor.GetFormValue(request.Form, "auth_id"));
                    }
                    //CREATE A REFUND TRANSACTION
                    transaction = new Transaction();
                    //CREATE A PAYMENT IF AN EXISTING ONE WAS NOT FOUND
                    if (payment == null)
                    {
                        payment                     = new Payment();
                        payment.OrderId             = orderId;
                        payment.PaymentMethodId     = paypalMethod.PaymentMethodId;
                        payment.PaymentMethodName   = paypalMethod.Name;
                        payment.Amount              = -1 * refundAmount;
                        transaction.TransactionType = TransactionType.Refund;
                        order.Payments.Add(payment);
                    }
                    else
                    {
                        if (payment.Amount == refundAmount)
                        {
                            //FULL REFUND
                            transaction.TransactionType = TransactionType.Refund;
                            payment.PaymentStatus       = PaymentStatus.Refunded;
                        }
                        else
                        {
                            //PARTIAL REFUND
                            transaction.TransactionType = TransactionType.PartialRefund;
                            payment.Amount       -= refundAmount;
                            payment.PaymentStatus = PaymentStatus.Captured;
                        }
                    }
                    transaction.PaymentGatewayId      = paypalGateway.PaymentGatewayId;
                    transaction.ProviderTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                    transaction.TransactionDate       = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                    transaction.TransactionStatus     = TransactionStatus.Successful;
                    transaction.AuthorizationCode     = IpnProcessor.GetFormValue(request.Form, "auth_id");
                    transaction.RemoteIP = IpnProcessor.GetFormValue(request.ServerVariables, "REMOTE_ADDR");
                    transaction.Referrer = IpnProcessor.GetFormValue(request.ServerVariables, "HTTP_REFERER");
                    transaction.Amount   = refundAmount;
                    string responseMessage = IpnProcessor.GetFormValue(request.Form, "reason_code");
                    if (responseMessage != "refund")
                    {
                        transaction.ResponseCode    = paymentStatus;
                        transaction.ResponseMessage = responseMessage;
                    }
                    //UPDATE PAYMENT DETAILS
                    payment.PaymentDate         = transaction.TransactionDate;
                    payment.PaymentStatusReason = string.Empty;
                    //ADD IN TRANSACTION
                    payment.Transactions.Add(transaction);
                    break;

                case "VOIDED":
                    //SEE IF WE CAN FIND THE PAYMENT VIA AUTH TRANSACTION ID
                    payment = FindPayPalPayment(paypalGateway.PaymentGatewayId, orderPayments, IpnProcessor.GetFormValue(request.Form, "auth_id"));
                    //WE ONLY NEED TO CONTINUE IF A PAYMENT TO VOID WAS FOUND
                    if (payment != null)
                    {
                        //PAYPAL DOES NOT SEND THE AMOUNT OF THE VOID
                        //SO IF THIS PAYMENT WAS PARTIALLY CAPTURED, WE NEED TO KNOW HOW MUCH TO VOID
                        LSDecimal remainingAuthorization = payment.Transactions.GetRemainingAuthorized();
                        if (remainingAuthorization > 0)
                        {
                            //CREATE A VOID TRANSACTION
                            transaction = new Transaction();
                            transaction.TransactionType       = TransactionType.Void;
                            transaction.Amount                = remainingAuthorization;
                            transaction.PaymentGatewayId      = paypalGateway.PaymentGatewayId;
                            transaction.ProviderTransactionId = IpnProcessor.GetFormValue(request.Form, "txn_id");
                            transaction.TransactionDate       = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                            transaction.TransactionStatus     = TransactionStatus.Successful;
                            transaction.AuthorizationCode     = IpnProcessor.GetFormValue(request.Form, "auth_id");
                            transaction.RemoteIP              = IpnProcessor.GetFormValue(request.ServerVariables, "REMOTE_ADDR");
                            transaction.Referrer              = IpnProcessor.GetFormValue(request.ServerVariables, "HTTP_REFERER");
                            //UPDATE PAYMENT DETAILS
                            payment.PaymentDate         = transaction.TransactionDate;
                            payment.PaymentStatusReason = string.Empty;
                            if (payment.Amount == remainingAuthorization)
                            {
                                //FULL VOID, CHANGE PAYMENT STATUS TO VOID
                                payment.PaymentStatus = PaymentStatus.Void;
                            }
                            else
                            {
                                //PARTIAL VOID, REDUCE PAYMENT AMOUNT BY VOID
                                payment.Amount -= remainingAuthorization;
                                //PAYMENT HAS NO REMAINING AUTHORIZATION AND SO IT IS CAPTURED
                                payment.PaymentStatus = PaymentStatus.Captured;
                            }
                            //ADD IN TRANSACTION
                            payment.Transactions.Add(transaction);
                        }
                    }
                    break;

                case "FAILED":
                    //THIS IS A FAILED E-CHECK
                    //PENDINGTRANSACTION SHOULD HAVE BEEN OBTAINED ABOVE
                    if (payment != null && pendingTransaction != null)
                    {
                        pendingTransaction.TransactionStatus = TransactionStatus.Failed;
                        //MAKE SURE TO CLEAR OUT PENDING RESPONSECODE
                        pendingTransaction.ResponseCode = string.Empty;
                        //GET THE CURRENT TRANSACTION DATE
                        pendingTransaction.TransactionDate = AlwaysConvert.ToDateTime(request.Form["payment_date"], DateTime.UtcNow).ToUniversalTime();
                        //UPDATE PAYMENT DETAILS
                        payment.PaymentDate         = pendingTransaction.TransactionDate;
                        payment.PaymentStatus       = (IsVoidableFailure(payment) ? PaymentStatus.Void : PaymentStatus.CaptureFailed);
                        payment.PaymentStatusReason = string.Empty;
                        //SAVE PAYMENT (AND CHILD TRANSACTIONS)
                        payment.Save();
                    }
                    break;

                default:
                    Logger.Warn("PayPal IPN transaction " + paypalTransactionId + " with a \"" + paymentStatus + "\" status was unhandled.");
                    break;
                }

                //IF PAYMENT IS SET, SAVE UPDATES
                if (payment != null)
                {
                    payment.Save();
                }
            }
            response.Redirect(redirectUrl);
        }
示例#17
0
        public static Basket GetAcBasket(AutoGen.ShoppingCart shoppingcart, bool clearShipNTax)
        {
            TraceContext trace    = WebTrace.GetTraceContext();
            string       traceKey = "GoogleCheckout.AC.AcHelper";

            trace.Write(traceKey, "Begin AcHelper.GetAcBasket");

            int basketId = AcHelper.GetAcBasketId(shoppingcart);

            trace.Write(traceKey, "Look for basket ID " + basketId.ToString());
            Basket basket = BasketDataSource.Load(basketId, false);

            if (basket == null)
            {
                trace.Write(traceKey, "Basket not found. Creating New Basket.");
                basket = new Basket();
            }
            else
            {
                //basket found. check if content hash matches
                string contentHash = GetReportedBasketHash(shoppingcart);
                if (contentHash.Equals(GetAcBasketHash(basket)))
                {
                    //hash matched. basket has not changed.
                    if (clearShipNTax)
                    {
                        ClearShippingAndTaxes(basket);
                    }
                    return(basket);
                }
            }

            trace.Write(traceKey, "Clear existing Basket contents and populate with Google Input.");
            basket.Clear();

            if (shoppingcart.items != null)
            {
                trace.Write(traceKey, "Looping " + shoppingcart.items.Length.ToString() + " items in Google cart");
            }
            foreach (Item thisItem in shoppingcart.items)
            {
                trace.Write(traceKey, "itemName: " + thisItem.itemname);
                BasketItem basketItem = new BasketItem();
                basketItem.Name     = thisItem.itemname;
                basketItem.Quantity = (short)thisItem.quantity;
                basketItem.Price    = thisItem.unitprice.Value;

                XmlNode[] privateNodes = thisItem.merchantprivateitemdata.Any;
                foreach (XmlNode privateNode in privateNodes)
                {
                    trace.Write(traceKey, "privateNode.Name: " + privateNode.Name);
                    switch (privateNode.Name)
                    {
                    case "productId":
                        basketItem.ProductId = AlwaysConvert.ToInt(privateNode.InnerText);
                        break;

                    case "orderItemType":
                        basketItem.OrderItemType = (OrderItemType)AlwaysConvert.ToEnum(typeof(OrderItemType), privateNode.InnerText, OrderItemType.Product, true);
                        break;

                    case "shippable":
                        basketItem.Shippable = (Shippable)AlwaysConvert.ToEnum(typeof(Shippable), privateNode.InnerText, Shippable.Yes, true);
                        break;

                    case "taxCodeId":
                        basketItem.TaxCodeId = AlwaysConvert.ToInt(privateNode.InnerText);
                        break;

                    case "weight":
                        basketItem.Weight = AlwaysConvert.ToDecimal(privateNode.InnerText);
                        break;

                    case "wrapStyleId":
                        basketItem.WrapStyleId = AlwaysConvert.ToInt(privateNode.InnerText);
                        break;

                    case "optionList":
                        basketItem.OptionList = privateNode.InnerText;
                        break;

                    case "giftMessage":
                        basketItem.GiftMessage = privateNode.InnerText;
                        break;

                    case "lineMessage":
                        basketItem.LineMessage = privateNode.InnerText;
                        break;

                    case "lastModifiedDate":
                        basketItem.LastModifiedDate = AlwaysConvert.ToDateTime(privateNode.InnerText, LocaleHelper.LocalNow);
                        break;

                    case "orderBy":
                        basketItem.OrderBy = AlwaysConvert.ToInt16(privateNode.InnerText);
                        break;

                    case "parentItemId":
                        basketItem.ParentItemId = AlwaysConvert.ToInt(privateNode.InnerText);
                        break;

                    case "sku":
                        basketItem.Sku = privateNode.InnerText;
                        break;

                    case "wishlistItemId":
                        basketItem.WishlistItemId = AlwaysConvert.ToInt(privateNode.InnerText);
                        break;

                    case "basketItemKitProducts":
                        List <string> kitList = new List <string>();
                        foreach (XmlNode subNode in privateNode.ChildNodes)
                        {
                            if (subNode.Name.Equals("kitProductId"))
                            {
                                int        kitProductId = AlwaysConvert.ToInt(subNode.InnerText);
                                KitProduct kitProd      = KitProductDataSource.Load(kitProductId);
                                if (kitProd != null)
                                {
                                    kitList.Add(kitProductId.ToString());
                                }
                            }
                        }
                        if (kitList.Count > 0)
                        {
                            basketItem.KitList = string.Join(",", kitList.ToArray());
                        }
                        break;

                    case "inputs":
                        foreach (XmlNode subNode in privateNode.ChildNodes)
                        {
                            if (subNode.Name.Equals("itemInput"))
                            {
                                int inputFieldId = 0;
                                foreach (XmlAttribute attr in subNode.Attributes)
                                {
                                    if (attr.Name.Equals("inputFieldId"))
                                    {
                                        inputFieldId = AlwaysConvert.ToInt(attr.InnerText);
                                        break;
                                    }
                                }
                                InputField inputField = InputFieldDataSource.Load(inputFieldId);
                                if (inputField != null)
                                {
                                    BasketItemInput bInput = new BasketItemInput();
                                    bInput.InputFieldId = inputFieldId;
                                    bInput.InputValue   = subNode.InnerText;
                                    basketItem.Inputs.Add(bInput);
                                }
                            }
                        }
                        break;

                    case "couponCode":
                        basketItem.Sku = privateNode.InnerText;
                        break;
                    }
                }
                basket.Items.Add(basketItem);
            }
            trace.Write(traceKey, "Saving basket");
            basket.Save();

            string key = "Basket_" + basket.BasketId.ToString();

            ContextCache.SetObject(key, basket);

            trace.Write(traceKey, "Basket created, returning to caller (End GetAcBasket)");
            return(basket);
        }