/// <summary> /// Creates an item used to populate the class _cart. This method does not add items to the database. /// </summary> /// <param name="_item_number">Item Number</param> /// <param name="_cartId">Cart Id from the table cart</param> /// <param name="_price">Price of the item in the cart</param> /// <param name="_qty">Quantity of this line item</param> /// <param name="_addressId">Address Id of the Address to ship to</param> /// <param name="addTime">The add time.</param> /// <param name="session">_session to attach this item to</param> public CartItem( string _item_number, Guid _cartId, decimal _price, int _qty, Guid _addressId, DateTime addTime, Session session ) { if(Inputs == null) { Inputs = new List<Input>(); } Item = Main.Site.Item( _item_number ); CartId = _cartId; Price = _price; Qty = _qty; AddressId = _addressId; XMLId = _cartId.EncodeXMLId(); XMLAddressId = _addressId.EncodeXMLId(); AddedOn = addTime; }
/// <summary> /// logs the current session off /// </summary> /// <returns>{error:0,desc:""}.</returns> public static Dictionary<string, object> LogOff( Dictionary<string, object> args ) { /* user is trying to log off */ Dictionary<string, object> j = new Dictionary<string, object>(); Session session = null; if( args.ContainsKey( "sessionId" ) ) { session = new Session( Main.Site, new Guid( ( string )args[ "sessionId" ] ) ); } else { session = Main.GetCurrentSession(); } ( "REQUEST:Log off" ).Debug( 9 ); using(SqlConnection cn = Site.CreateConnection(true, true)) { cn.Open(); using(SqlCommand cmd = new SqlCommand("dbo.logoff @sessionId", cn)) { cmd.Parameters.Add("@sessionId", SqlDbType.UniqueIdentifier).Value = new Guid(session.Id.ToString()); cmd.ExecuteNonQuery(); } } Main.GetCurrentSession().Refresh( false ); j.Add( "error", 0 ); j.Add( "description", "Logoff successful" ); return j; }
/// <summary> /// Executes the AJAX responders. /// </summary> /// <param name="current">The current HttpContext.</param> /// <param name="session">The session.</param> /// <returns></returns> static bool executeResponders(HttpContext current, Session session) { string executionFilePath = current.Request.AppRelativeCurrentExecutionFilePath; try { /* if this is a request for the Admin responder page */ if(executionFilePath.Contains(Main.AdminResponder)) { if(session.Administrator) { /* check if the user is trying to upload a file */ if(current.Request.ContentType.Contains("multipart/form-data")) { /* full trust/iis6 upload */ Admin.Iis6Upload(); return true; } else { if(current.Response.ContentType == "text/html") { current.Response.ContentType = "application/json"; } current.Response.Write(ExecuteJSONResponders(true)); current.ApplicationInstance.CompleteRequest(); return true; } } else { /* user tried to access admin responder without admin access */ setStatusCode(current, 403); current.ApplicationInstance.CompleteRequest(); return true; } } else if(executionFilePath.Contains(Main.Responder)) { if(current.Response.ContentType == "text/html") { current.Response.ContentType = "application/json"; } current.Response.Write(ExecuteJSONResponders(false)); current.ApplicationInstance.CompleteRequest(); return true; } return false; } catch(Exception ex) { ("EVENT -> BeginRequest -> responder -> Exception: " + ex.Message).Debug(3); return false; } }
/// <summary> /// Returns a _cart_item AND adds the selected item to the user's cart within a transaction /// </summary> /// <param name="item_number">Number of the item you want to add to the user's cart</param> /// <param name="item_qty">Quantity of the item you want to add</param> /// <param name="session">session</param> /// <param name="args">The args.</param> /// <param name="price">The price.</param> /// <param name="allowPreorder">if set to <c>true</c> [allow preorder].</param> /// <param name="allow_price_override">if set to <c>true</c> [allow_price_override].</param> /// <param name="cn">The connection being used.</param> /// <param name="trans">The transaction being used.</param> /// <returns> /// Returns an empty string rather than a null from the Request[] object. /// </returns> internal static Commerce.CartItem addToCartProc(string item_number, int item_qty, Session session, Dictionary<string, object> args, object price, bool allowPreorder, bool allow_price_override, SqlConnection cn, SqlTransaction trans) { ("FUNCTION /w SP:Add to cart").Debug(10); Guid cartId = Guid.Empty; int error = -1; string itemNumber = ""; decimal r_price = 0; int qty = 0; Guid r_addressId = Guid.Empty; string errorDesc = ""; Commerce.Item item = Main.Site.Item(item_number); if(Site.AbortDefaultEvent == true) { Site.AbortDefaultEvent = false; return null; } /* if the item exists in the database */ if(!(item != null)) { return null; }; string addressId = Guid.Empty.ToString(); if(args.ContainsKey("addressId")) { if(args["addressId"] != null) { if(Utilities.GuidPattern.IsMatch(args["addressId"].ToString())) { addressId = args["addressId"].ToString(); } } } string commandText = @"dbo.addToCart @itemnumber, @qty, @sessionid, @userid, @wholesale, @allow_Preorders, @unique_siteId, @new_price, @override_Price, @overrideAddressId, @override_allow_preorder"; SqlCommand cmd; if(cn == null) { cmd = new SqlCommand(commandText, Site.SqlConnection); } else { cmd = new SqlCommand(commandText, cn, trans); } /* don't let people put items with zero qty in their cart */ if(qty == 0) { qty = 1; } cmd.Parameters.Add("@itemnumber", SqlDbType.VarChar, 50).Value = item_number; cmd.Parameters.Add("@qty", SqlDbType.Int).Value = item_qty; cmd.Parameters.Add("@sessionid", SqlDbType.UniqueIdentifier).Value = new Guid(session.Id.ToString()); cmd.Parameters.Add("@userid", SqlDbType.Int).Value = session.UserId; cmd.Parameters.Add("@wholesale", SqlDbType.Bit).Value = session.Wholesale; cmd.Parameters.Add("@allow_Preorders", SqlDbType.Bit).Value = session.AllowPreorders; cmd.Parameters.Add("@unique_siteId", SqlDbType.UniqueIdentifier).Value = new Guid(Site.Id.ToString()); cmd.Parameters.Add("@new_price", SqlDbType.Money).Value = price; cmd.Parameters.Add("@override_Price", SqlDbType.Bit).Value = allow_price_override; cmd.Parameters.Add("@overrideAddressId", SqlDbType.UniqueIdentifier).Value = new Guid(addressId); cmd.Parameters.Add("@override_allow_preorder", SqlDbType.Bit).Value = allowPreorder; using(SqlDataReader d = cmd.ExecuteReader()) { d.Read(); cartId = d.GetGuid(1); error = d.GetInt32(2); errorDesc = d.GetString(3); itemNumber = d.GetString(4); qty = d.GetInt32(5); r_addressId = d.GetGuid(6); r_price = d.GetDecimal(7); } cmd.Dispose(); if(error != 0) { Commerce.CartItem i = new Commerce.CartItem(item_number, Guid.Empty, 0, 0, Guid.Empty, DateTime.Now, Main.GetCurrentSession()); i.Error_Description = errorDesc; i.Error_Id = error; return i; } else { List<Commerce.Input> formInputs = null; if(item.Form != null) { formInputs = item.Form.Inputs; String.Format("Add to Cart > Using form {0} for item {1}.", item.Form.Name, item.Number).Debug(8); } else { String.Format("Add to Cart > No form found for item {0}.", item.Number).Debug(8); }; /* add item to cart */ Commerce.CartItem citm = new Commerce.CartItem(itemNumber, cartId, r_price, qty, r_addressId, DateTime.Now, session); /* save forms */ if(args.ContainsKey("orderId")) { if(item.Form != null) { /* add forms that may end up on order to the line forms table now */ commandText = "dbo.insertOrderLineForm @cartId,@sourceCode,@formName"; if(cn == null) { cmd = new SqlCommand(commandText, Site.SqlConnection); } else { cmd = new SqlCommand(commandText, cn, trans); } cmd.Parameters.Add("@cartId", SqlDbType.UniqueIdentifier).Value = new Guid(citm.CartId.ToString()); cmd.Parameters.Add("@sourceCode", SqlDbType.VarChar).Value = item.Form.SourceCode; cmd.Parameters.Add("@formName", SqlDbType.VarChar).Value = item.Form.Name; cmd.ExecuteNonQuery(); cmd.Dispose(); } } try { if(formInputs != null) { /* add form inputs if any to _cart_item we're returning as well as the database */ Guid newCartId = new Guid(cartId.ToString()); for(int x = 0; formInputs.Count > x; x++) { Commerce.Input i = formInputs[x]; if(args.ContainsKey(i.Name)) { i.Value = Convert.ToString(args[i.Name]); } else { i.Value = ""; } citm.Item.Form.Inputs.Find(delegate(Commerce.Input inp) { return inp.Name.l() == i.Name.l(); }).Value = i.Value; String.Format("Add to Cart > Adding input {0}, value {1}", i.Name, i.Value).Debug(8); commandText = "dbo.insertCartDetail @cartDetailId,@cartId,@inputName,@value,@sessionId;"; if(cn == null) { cmd = new SqlCommand(commandText, Site.SqlConnection); } else { cmd = new SqlCommand(commandText, cn, trans); } Guid newCartDetailId = Guid.NewGuid(); i.Id = newCartDetailId; cmd.Parameters.Add("@cartId", SqlDbType.UniqueIdentifier).Value = new Guid(newCartId.ToString()); cmd.Parameters.Add("@sessionId", SqlDbType.UniqueIdentifier).Value = new Guid(session.Id.ToString()); cmd.Parameters.Add("@cartDetailId", SqlDbType.UniqueIdentifier).Value = new Guid(newCartDetailId.ToString()); cmd.Parameters.Add("@inputName", SqlDbType.VarChar).Value = i.Name; cmd.Parameters.Add("@value", SqlDbType.VarChar).Value = i.Value; cmd.ExecuteNonQuery(); cmd.Dispose(); } } else { ("Add to Cart > No form inputs found.").Debug(8); } } catch(Exception ex) { String.Format("Add to Cart > An exception occured {0}", ex.Message).Debug(0); } return citm; } }
/// <summary> /// Cancels or backorders the items in an existing order. /// </summary> /// <param name="args">The args.</param> /// <param name="cancel">if set to <c>true</c> [cancel] else backorder</param> /// <returns>{error:0,desc:""}</returns> private static Dictionary<string, object> CancelBackorderItems(List<object> args, bool cancel) { /*TODO: backorder procedure has uncertain payment stuff going on here * cancel works, backorder works, but changing * */ Dictionary<string, object> j = new Dictionary<string, object>(); using(SqlConnection cn = Site.CreateConnection(true, true)) { cn.Open(); using(SqlTransaction cancelBackorderTransaction = cn.BeginTransaction("Backorder or Cancel")) { bool rollback = true; try { foreach(object line in args) { Dictionary<string, object> fields = (Dictionary<string, object>)line; // never used -->Dictionary<string,object> flag; if(!fields.ContainsKey("serialId") || !fields.ContainsKey("qty")) { Exception e = new Exception("key serialId or qty is missing"); throw e; } int serialId = Convert.ToInt32(fields["serialId"].ToString()); int qty = Convert.ToInt32(fields["qty"].ToString()); /* update the cart table with the number of items to be backordered. */ using(SqlCommand cmd = new SqlCommand("update cart set returnToStock = @return where serialId = @serialId", cn, cancelBackorderTransaction)) { cmd.Parameters.Add("@serialId", SqlDbType.Int).Value = serialId; cmd.Parameters.Add("@return", SqlDbType.Int).Value = qty; cmd.ExecuteNonQuery(); } /* now add the flag that will trigger serial_line.TR_LINE_DEPLETE_INVENTORY*/ /* flag -11 is backorder, flag -12 is cancel */ using(SqlCommand cmd = new SqlCommand("dbo.backorderCancel @serialId,@cancel,@backorder", cn, cancelBackorderTransaction)) { cmd.Parameters.Add("@serialId", SqlDbType.Int).Value = serialId; cmd.Parameters.Add("@cancel", SqlDbType.Bit).Value = cancel; cmd.Parameters.Add("@backorder", SqlDbType.Bit).Value = !cancel; cmd.ExecuteNonQuery(); } /* if this is a cancelation don't create a new order or add to an existing order */ if(cancel) { AddFlagWithTransaction("0", "line", serialId.ToString(), "Quantity of " + qty + " canceled", cn, cancelBackorderTransaction); } else { /* first check to see if an order is already the child of this order * if so, then just add this item to the child order (backorder) * if there is no child order than create the child order now. */ Commerce.Order childOrder; List<Commerce.Order> childOrders = Commerce.Order.GetChildOrdersBySerialId(serialId, cn, cancelBackorderTransaction); if(childOrders.Count == 0) { childOrder = null; } else { childOrder = childOrders[0]; } Commerce.Order order = Commerce.Order.GetOrderBySerialId(serialId, cn, cancelBackorderTransaction); if(childOrder == null) { /* create a new order and add the item's qty to the new order */ /* get the line that will be added to the backorder */ List<Commerce.Line> sourceLines = order.Lines.FindAll(delegate(Commerce.Line ln) { return ln.SerialId == serialId && ln.KitAllocationCartId == ln.CartId; }); /* sort the items by int kitAllocationId */ sourceLines.Sort(delegate(Commerce.Line l1, Commerce.Line l2) { return l1.KitAllocationId.CompareTo(l2.KitAllocationId); }); /* when there is more than one source line, always pick the one with the larget id * this will be the parent/virtual item that needs to be added to the backorder */ Commerce.Line sourceLine = sourceLines[sourceLines.Count - 1]; /* create a new session for the new order */ Session session = new Session(Main.Site, cn, cancelBackorderTransaction); Site.LogOn(order.UserId, session, cn, cancelBackorderTransaction); session.Refresh(false, cn, cancelBackorderTransaction); AddToCartArguments addTocartArgs = new AddToCartArguments(); addTocartArgs["itemNumber"] = sourceLine.ItemNumber; addTocartArgs["qty"] = fields["qty"].ToString(); addTocartArgs["customerLineNumber"] = sourceLine.CustomLineNumber; addTocartArgs["sessionId"] = session.Id.ToString(); addTocartArgs["price"] = sourceLine.Price; addTocartArgs["allowPreorder"] = true; /* add all of the inputs as arguments */ Dictionary<string, object> addToCartArgs = Cart.AddToCart(addTocartArgs, cn, cancelBackorderTransaction); if(Convert.ToInt32(addToCartArgs["error"]) != 0) { Exception e = new Exception(addToCartArgs["description"].ToString()); throw e; } Guid newCartId = new Guid(addToCartArgs["cartId"].ToString()); /* copy all of the order header data into the new order */ using(SqlCommand cmd = new SqlCommand("dbo.duplicateCartDetail @sourceCartId,@targetCartId", cn, cancelBackorderTransaction)) { cmd.Parameters.Add("@sourceCartId", SqlDbType.UniqueIdentifier).Value = new Guid(sourceLine.CartId.ToString()); cmd.Parameters.Add("@targetCartId", SqlDbType.UniqueIdentifier).Value = new Guid(newCartId.ToString()); cmd.ExecuteNonQuery(); } OrderArguments newOrderArgs = new OrderArguments(); newOrderArgs["billToFirstName"] = order.BillToAddress.FirstName; newOrderArgs["billToLastName"] = order.BillToAddress.LastName; newOrderArgs["billToAddress1"] = order.BillToAddress.Address1; newOrderArgs["billToAddress2"] = order.BillToAddress.Address2; newOrderArgs["billToCity"] = order.BillToAddress.City; newOrderArgs["billToState"] = order.BillToAddress.State; newOrderArgs["billToZip"] = order.BillToAddress.Zip; newOrderArgs["billToCountry"] = order.BillToAddress.Country; newOrderArgs["billToHomePhone"] = order.BillToAddress.HomePhone; newOrderArgs["billToWorkPhone"] = order.BillToAddress.WorkPhone; newOrderArgs["billToCompany"] = order.BillToAddress.Company; newOrderArgs["billToComments"] = order.BillToAddress.Comments; newOrderArgs["billToSpecialInstructions"] = order.BillToAddress.SpecialInstructions; newOrderArgs["billToSendShipmentUpdates"] = order.BillToAddress.SendShipmentUpdates; newOrderArgs["FOB"] = order.FOB; newOrderArgs["termId"] = order.TermId; newOrderArgs["userId"] = session.User.UserId; newOrderArgs["manifestNumber"] = order.Manifest; newOrderArgs["purchaseOrder"] = Utilities.Iif(order.PurchaseOrder.Length > 0, order.PurchaseOrder + ">" + order.OrderNumber, ""); newOrderArgs["sessionId"] = session.Id.ToString(); newOrderArgs["shipToRateId"] = -1;/* never put a shipping method on backorders */ newOrderArgs["billToRateId"] = -1; newOrderArgs["shipToEmailAds"] = false; newOrderArgs["billToEmailAds"] = false; newOrderArgs["billToSendShipmentUpdates"] = false; newOrderArgs["shipToFirstName"] = order.ShipToAddress.FirstName; newOrderArgs["shipToLastName"] = order.ShipToAddress.LastName; newOrderArgs["shipToAddress1"] = order.ShipToAddress.Address1; newOrderArgs["shipToAddress2"] = order.ShipToAddress.Address2; newOrderArgs["shipToCity"] = order.ShipToAddress.City; newOrderArgs["shipToState"] = order.ShipToAddress.State; newOrderArgs["shipToZip"] = order.ShipToAddress.Zip; newOrderArgs["shipToCountry"] = order.ShipToAddress.Country; newOrderArgs["shipToHomePhone"] = order.ShipToAddress.HomePhone; newOrderArgs["shipToWorkPhone"] = order.ShipToAddress.WorkPhone; newOrderArgs["shipToCompany"] = order.ShipToAddress.Company; newOrderArgs["shipToComments"] = order.ShipToAddress.Comments; newOrderArgs["shipToSpecialInstructions"] = order.ShipToAddress.SpecialInstructions; newOrderArgs["shipToSendShipmentUpdates"] = order.ShipToAddress.SendShipmentUpdates; newOrderArgs["parentOrderId"] = order.OrderId; newOrderArgs["comments"] = "This order is a backorder from Order " + order.OrderNumber; newOrderArgs.Add("backorder", true); /* place the new backorder */ Dictionary<string, object> newOrder = Commerce.Order.PlaceOrderWithTransaction(newOrderArgs, cn, cancelBackorderTransaction); if(Convert.ToInt32(newOrder["error"]) != 0) { Exception e = new Exception(newOrder["description"].ToString()); throw e; } childOrder = Commerce.Order.GetOrderByOrderNumber((string)newOrder["orderNumber"], cn, cancelBackorderTransaction); j.Add("childOrder", childOrder.GetOrderJson()); } else { /* the child order (backorder) already existed, so add the item to the backorder */ Commerce.Line sourceLine = order.Lines.Find(delegate(Commerce.Line ln) { return ln.SerialId == serialId; }); /* create a new session for the new order */ Session session = new Session(Main.Site, cn, cancelBackorderTransaction); Site.LogOn(childOrder.UserId, session, cn, cancelBackorderTransaction); session.Refresh(false, cn, cancelBackorderTransaction); AddToCartArguments addTocartArgs = new AddToCartArguments(); addTocartArgs["itemNumber"] = sourceLine.ItemNumber; addTocartArgs["qty"] = fields["qty"].ToString(); addTocartArgs["customerLineNumber"] = sourceLine.CustomLineNumber; addTocartArgs["sessionId"] = session.Id.ToString(); addTocartArgs["addressId"] = sourceLine.AddressId.ToString(); addTocartArgs["price"] = sourceLine.Price; addTocartArgs["allowPreorder"] = true; /* add all of the inputs as arguments */ Dictionary<string, object> addToCartArgs = Cart.AddToCart(addTocartArgs, cn, cancelBackorderTransaction); if(Convert.ToInt32(addToCartArgs["error"]) != 0) { Exception e = new Exception(addToCartArgs["description"].ToString()); throw e; } Guid newCartId = new Guid(addToCartArgs["cartId"].ToString()); /* copy all of the order header data into the new order */ using(SqlCommand cmd = new SqlCommand("dbo.duplicateCartDetail @sourceCartId,@targetCartId", cn, cancelBackorderTransaction)) { cmd.Parameters.Add("@sourceCartId", SqlDbType.UniqueIdentifier).Value = new Guid(sourceLine.CartId.ToString()); cmd.Parameters.Add("@targetCartId", SqlDbType.UniqueIdentifier).Value = new Guid(newCartId.ToString()); cmd.ExecuteNonQuery(); } Dictionary<string, object> recalculateArgs = new Dictionary<string, object>(); recalculateArgs.Add("userId", childOrder.UserId); recalculateArgs.Add("orderSessionId", childOrder.SessionId.ToString()); recalculateArgs.Add("cartSessionId", session.Id.ToString()); recalculateArgs.Add("cardType", ""); recalculateArgs.Add("cardNumber", ""); recalculateArgs.Add("expMonth", ""); recalculateArgs.Add("expYear", ""); recalculateArgs.Add("secNumber", ""); recalculateArgs.Add("nameOnCard", ""); recalculateArgs.Add("billToAddressId", childOrder.BillToAddress.Id.ToString()); recalculateArgs.Add("shipToAddressId", childOrder.ShipToAddress.Id.ToString()); recalculateArgs.Add("preview", false); recalculateArgs.Add("purchaseOrder", childOrder.PurchaseOrder); recalculateArgs.Add("backorder", true); Dictionary<string, object> recalculatedOrder = RecalculateOrder(recalculateArgs, cn, cancelBackorderTransaction); if((int)recalculatedOrder["error"] != 0) { Exception e = new Exception(recalculatedOrder["description"].ToString()); throw e; } Commerce.Order _order = Commerce.Order.GetOrderByOrderNumber((string)recalculatedOrder["orderNumber"], cn, cancelBackorderTransaction); j.Add("childOrder", _order.GetOrderJson()); } AddFlagWithTransaction("0", "line", serialId.ToString(), "Quantity of " + qty + " added to backorder " + childOrder.OrderNumber, cn, cancelBackorderTransaction); } } rollback = false; cancelBackorderTransaction.Commit(); j.Add("error", 0); j.Add("description", ""); } catch(Exception e) { rollback = true; j.Add("error", -1); j.Add("description", e.Message); } finally { if(rollback) { cancelBackorderTransaction.Rollback(); } } } } return j; }
/// <summary> /// Recalculates the selected cart by its SessionId /// </summary> /// <param name="args">The args.</param> /// <returns> /// {error:int,errorDescription:string,subTotal:float,taxTotal:float,estShipTotal:float,discountTotal:float,grandTotal:float}. /// </returns> public static Dictionary<string, object> Recalculate(Dictionary<string, object> args) { ("FUNCTION recalculate (cart)").Debug(10); Dictionary<string, object> j = new Dictionary<string, object>(); Session session; if(args.ContainsKey("sessionId")) { session = new Session(Main.Site, new Guid(args["sessionId"].ToString())); } else { session = Main.GetCurrentSession(); } if(args.ContainsKey("billToContactId") || args.ContainsKey("shipToContactId")) { /* gather bill to and ship to data, if any, from the request */ Dictionary<string, object> btAddr = new Dictionary<string, object>(); Dictionary<string, object> stAddr = new Dictionary<string, object>(); foreach(KeyValuePair<string, object> field in args as Dictionary<string, object>) { if(field.Key.StartsWith("shipTo")) { stAddr.Add(field.Key.Replace("shipTo", ""), field.Value); } else if(field.Key.StartsWith("billTo")) { btAddr.Add(field.Key.Replace("billTo", ""), field.Value); } } if(args.ContainsKey("shipToContactId")) { stAddr.Add("contactId", stAddr["ContactId"].ToString()); stAddr.Remove("ContactId"); } if(args.ContainsKey("billToContactId")) { btAddr.Add("contactId", btAddr["ContactId"].ToString()); btAddr.Remove("ContactId"); } /* update the bill to and ship to addresses in the database * if the Address does not exist, validate it and insert it. */ if(stAddr.Count > 0) { stAddr.Add("sessionId", session.Id.ToString()); stAddr.Add("userId", session.UserId.ToString()); Address.UpdateContact(stAddr); } if(btAddr.Count > 0) { btAddr.Add("sessionId", session.Id.ToString()); btAddr.Add("userId", session.UserId.ToString()); Address.UpdateContact(btAddr); } } /* if the cart isn't populated, do that now */ if(session.Cart.Items.Count == 0) { session.Cart.Refresh(); } /* execute recalculateCart events */ RecalculateCartEventArgs ev = new RecalculateCartEventArgs(session.Cart, session, HttpContext.Current, args); Main.Site.raiseOnrecalculatecart(ev); /* refresh again to reflect changes in the addresses */ session.Cart.Refresh(); j.Add("error", 0); j.Add("description", ""); j.Add("subTotal", (float)session.Cart.SubTotal); j.Add("taxTotal", (float)session.Cart.TaxTotal); j.Add("estShipTotal", (float)session.Cart.EstShipTotal); j.Add("discountTotal", (float)session.Cart.DiscountTotal); j.Add("grandTotal", (float)session.Cart.GrandTotal); j.Add("addresses", session.Cart.Addresses); return j; }
/// <summary> /// updates an item or items in the selected sessions cart /// </summary> /// <param name="args">Dictionary Object containing sessionId, cartId, qty, and form inputs {key/value...}</param> /// <returns>Json Item Description with cart totals.</returns> public static Dictionary<string, object> UpdateCartItem(Dictionary<string, object> args) { ("FUNCTION /w SP updateCartItem").Debug(10); Dictionary<string, object> j = new Dictionary<string, object>(); Session session = null; if(args.ContainsKey("sessionId")) { session = new Session(Main.Site, new Guid((string)args["sessionId"])); } else { session = Main.GetCurrentSession(); } Guid cartId; if(args.ContainsKey("cartId")) { if(args["cartId"].ToString().Contains("_")) { cartId = Convert.ToString(args["cartId"]).DecodeXMLId(); } else { cartId = new Guid(args["cartId"].ToString()); } if(cartId == Guid.Empty) { cartId = new Guid(Convert.ToString(args["cartId"])); } } else { /* cartId not found */ j.Add("error", -6); j.Add("description", "cartId key not found"); return j; } session.Cart.Refresh(); Commerce.CartItem ci = session.Cart.GetItemById(cartId); if(ci == null) { /* item not found */ j.Add("error", -5); j.Add("description", "cartId " + cartId.ToString() + "not found"); return j; } else { int qty = ci.Qty; decimal price = ci.Price; if(args.ContainsKey(ci.XMLId)) { if(!int.TryParse(args[ci.XMLId].ToString(), out qty)) { qty = ci.Qty; } } else if(args.ContainsKey("qty")) { if(!int.TryParse(args["qty"].ToString(), out qty)) { qty = ci.Qty; } } bool setPrice = false; /* allow changing prices when the user is an administrator or when the site is a POS */ if(session.Administrator || Main.Site.Defaults.SiteUrl == "POS") { if(args.ContainsKey("price")) { price = Convert.ToDecimal(args["price"]); setPrice = true; } } Guid addressId = Guid.Empty; if(args.ContainsKey("addressId")) { addressId = new Guid(args["addressId"].ToString()); } /* update quantity */ SqlCommand cmd = new SqlCommand(Cart.UPDATE_CART_QUERY, Site.SqlConnection); cmd.Parameters.Add("@qty", SqlDbType.Int).Value = qty; cmd.Parameters.Add("@price", SqlDbType.Money).Value = price; cmd.Parameters.Add("@cartId", SqlDbType.UniqueIdentifier).Value = new Guid(ci.CartId.ToString()); cmd.Parameters.Add("@setPrice", SqlDbType.Bit).Value = setPrice; cmd.Parameters.Add("@addressId", SqlDbType.UniqueIdentifier).Value = addressId; cmd.ExecuteNonQuery(); cmd.Dispose(); if(ci.Item.Form != null) { UpdateCartDetail(ci, args); } session.Cart.Refresh(); ci = session.Cart.GetItemById(cartId); j.Add("error", 0); j.Add("description", ""); j.Add("subTotal", (float)session.Cart.SubTotal); j.Add("taxTotal", (float)session.Cart.TaxTotal); j.Add("estShipTotal", (float)session.Cart.EstShipTotal); j.Add("discountTotal", (float)session.Cart.DiscountTotal); j.Add("grandTotal", (float)session.Cart.GrandTotal); j.Add("addresses", session.Cart.Addresses); if(ci != null) { j.Add("itemNumber", ci.Item.Number); j.Add("price", (float)ci.Price); j.Add("qty", ci.Qty); j.Add("cartId", ci.CartId.ToString()); j.Add("addressId", ci.Item.Number); j.Add("sessionId", session.Id.ToString()); j.Add("packingSlipImage", ci.Item.PackingSlipImage); j.Add("auxillaryImage", ci.Item.AuxillaryImage); j.Add("cartImage", ci.Item.CartImage); j.Add("detailImage", ci.Item.DetailImage); j.Add("fullSizeImage", ci.Item.FullSizeImage); j.Add("listingImage", ci.Item.ListingImage); j.Add("listing2Image", ci.Item.Listing2Image); j.Add("item_description", ci.Item.Description); j.Add("form", ci.Item.FormName); } return j; } }
/// <summary> /// Creates an account and returns the new userId and error state /// </summary> /// <param name="args">The args.</param> /// <returns>{success:true,userId:userId}.</returns> public static Dictionary<string, object> CreateAccount( Dictionary<string, object> args ) { ( "FUNCTION /w SP createAccount" ).Debug( 10 ); /*user is trying to create an account */ Dictionary<string, object> j = new Dictionary<string, object>(); Session session = null; string password = ""; int userId = -1; if( args.ContainsKey( "sessionId" ) ) { session = new Session( Main.Site, new Guid( ( string )args[ "sessionId" ] ) ); } else { session = Main.GetCurrentSession(); } if( args.ContainsKey( "logon" ) ) { userId = Convert.ToInt32( args[ "logon" ] ); } if( args.ContainsKey( "password" ) ) { password = GetHash( args[ "password" ] ); } using(SqlConnection cn = Site.CreateConnection(true, true)) { cn.Open(); using(SqlCommand cmd = new SqlCommand("dbo.logon @email,@password,@sessionid,@createaccount,@unique_siteID,@userId,@referenceSessionId", cn)) { cmd.Parameters.Add("@email", SqlDbType.VarChar).Value = Convert.ToString(args["email"]); cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = password; cmd.Parameters.Add("@sessionid", SqlDbType.UniqueIdentifier).Value = new Guid(session.Id.ToString()); cmd.Parameters.Add("@createaccount", SqlDbType.Bit).Value = true; cmd.Parameters.Add("@unique_siteID", SqlDbType.UniqueIdentifier).Value = new Guid(Site.Id); cmd.Parameters.Add("@userId", SqlDbType.Int).Value = userId; if(System.Web.HttpContext.Current != null) { cmd.Parameters.Add("@referenceSessionId", SqlDbType.UniqueIdentifier).Value = new Guid(Main.GetCurrentSession().Id.ToString()); } else { cmd.Parameters.Add("@referenceSessionId", SqlDbType.UniqueIdentifier).Value = Guid.Empty; } using(SqlDataReader d = cmd.ExecuteReader()) { d.Read(); if(d.GetInt32(0) == -1) { /* Logon error -1 account already exists */ j.Add("error", -10); j.Add("description", "Account already exists"); return j; } else { /* user logged on - new information is avaliable to the session - requery the session */ int newUserId = d.GetInt32(0); j.Add("error", 0); j.Add("description", "Create account successful"); j.Add("userId", newUserId); /* ... becuase an account was created the local cache must be refreshed */ Commerce.RefreshUserById(newUserId); if(System.Web.HttpContext.Current != null) { Main.GetCurrentSession().Refresh(false);/* don't reprocess requests */ } if(args.ContainsKey("showSessionData")) { if(Convert.ToBoolean(args["showSessionData"])) { j.Add("session", session); } } if(args.ContainsKey("showUserData")) { if(Convert.ToBoolean(args["showUserData"])) { j.Add("user", session.User); } } } } } } return j; }
/// <summary> /// Gets the form info. /// </summary> /// <param name="args">The args.</param> /// <returns></returns> public static Dictionary<string, object> GetFormInfo( Dictionary<string, object> args ) { ( "FUNCTION /w SP,fileSystem getFormInfo" ).Debug( 10 ); Dictionary<string, object> j = new Dictionary<string, object>(); Commerce.Item item = null; string formName = ""; if( args.ContainsKey( "formName" ) ) { /* lookup using the form name */ formName = Convert.ToString( args[ "formName" ] ); } else if( args.ContainsKey( "cartId" ) ) { /* if this order has been placed lookup using the stored form */ formName = null; } else if( args.ContainsKey( "itemNumber" ) ) { /* lookup using the items form */ item = Main.Site.Items.List.Find( delegate( Commerce.Item b ) { if( Convert.ToString( args[ "itemNumber" ] ).ToLower() == b.ItemNumber.ToLower() ) { return true; } return false; } ); formName = item.FormName; } if( formName != null ) { Commerce.Form form = new Commerce.Form( item, Main.PhysicalApplicationPath + "forms\\" + formName.Trim().ToLower() ); if( form != null ) { j.Add( "name", form.Name ); j.Add( "inputs", form.Inputs ); j.Add( "HTML", form.Html ); j.Add( "error", 0 ); j.Add( "description", "" ); } else { ( "getFormInfo error -1 ==> form not found:" + formName.Trim() ).Debug( 2 ); j.Add( "error", -1 ); j.Add( "description", "Form not found" ); } } else if( args.ContainsKey( "cartId" ) ) { string sourceCode = ""; Guid cartId = new Guid( Convert.ToString( args[ "cartId" ] ) ); Guid sessionId = Guid.Empty; if(args.ContainsKey("sessionId")) { sessionId = new Guid(Convert.ToString(args["sessionId"])); } using(SqlConnection cn = Site.CreateConnection(true, true)) { cn.Open(); /* check if this is an order or a cart item */ bool existingOrder = false; using(SqlCommand cmd = new SqlCommand(@"select 0 from cart with (nolock) where cartId = @cartId and not orderId = -1", cn)) { cmd.Parameters.Add("@cartId", SqlDbType.UniqueIdentifier).Value = cartId; using(SqlDataReader d = cmd.ExecuteReader()) { existingOrder = d.HasRows; } } if(!existingOrder && sessionId != Guid.Empty) { Session session = new Session(Main.Site, sessionId, cn, null); session.Cart.Refresh(); /* find the selected id */ Commerce.CartItem cartItem = session.Cart.Items.Find(delegate(Commerce.CartItem it) { return it.CartId == cartId; }); if(cartItem == null) { j.Add("error", -1); j.Add("description", "No data for cartId " + args["cartId"].ToString()); return j; } if(cartItem.Form == null) { j.Add("error", 0);/* this isn't really an error becuase items might contain no form data */ j.Add("description", "No form data for cartId " + args["cartId"].ToString()); } else { j.Add("name", cartItem.Form.Name); j.Add("inputs", cartItem.Inputs); j.Add("HTML", cartItem.HtmlWithValues); j.Add("emptyHTML", cartItem.Item.Form.Html); j.Add("error", 0); j.Add("description", ""); } return j; }else{ using(SqlCommand cmd = new SqlCommand("dbo.getOrderForm @cartId", cn)) { cmd.Parameters.Add("@cartId", SqlDbType.UniqueIdentifier).Value = cartId; formName = ""; string itemNumber = ""; using(SqlDataReader d = cmd.ExecuteReader()) { if(d.HasRows) { d.Read(); sourceCode = d.GetValue(0).ToString(); formName = d.GetValue(1).ToString(); itemNumber = d.GetValue(2).ToString(); } } } /* find the order */ Commerce.Order order = Commerce.Order.GetOrderByCartId(cartId, cn, null); /* find the line */ Commerce.Line line = order.Lines.Find(delegate(Commerce.Line l) { return l.CartId == cartId; }); /* return the data */ if(line.Form != null) { j.Add("name", line.Form.Name); j.Add("inputs", line.Form.Inputs); j.Add("HTML", line.Form.HtmlWithValues()); j.Add("emptyHTML", line.Form.Html); j.Add("error", 0); j.Add("description", ""); } else { j.Add("error", 0);/* this isn't really an error becuase items might contain no form data */ j.Add("description", "No form data for cartId " + args["cartId"].ToString()); } } } } return j; }
/// <summary> /// log a session onto an account without using a password /// </summary> /// <param name="userId">The user id.</param> /// <param name="session">The session.</param> /// <param name="cn">The sql connection.</param> /// <param name="trns">The sql transaction.</param> /// <returns></returns> public static bool LogOn( int userId, Session session, SqlConnection cn, SqlTransaction trns ) { return LogOn( userId, session.Id, cn, trns ); }
/// <summary> /// Logs off the specified session. /// </summary> /// <param name="session">The session.</param> /// <returns></returns> public int LogOff(Session session) { Dictionary<string, object> j = new Dictionary<string, object>(); j.Add("sessionId",session.Id.ToString()); Dictionary<string, object> r = LogOff(j); return (int)r["error"]; }
/// <summary> /// log a session onto an account without using a password /// </summary> /// <param name="userId">The user id.</param> /// <param name="session">The session.</param> /// <returns></returns> public static bool LogOn( int userId, Session session ) { return LogOn( userId, session.Id, null, null ); }
/// <summary> /// logs the current session on /// </summary> /// <param name="args">The arguments (sessionid, hostSessionId, userId, email, password).</param> /// <param name="cn">The cn.</param> /// <param name="trns">The TRNS.</param> /// <returns>{error:0,desc:""}.</returns> public static Dictionary<string, object> LogOn( Dictionary<string, object> args, SqlConnection cn, SqlTransaction trns ) { int userId = -1; string login = ""; string password = ""; string hostSessionId = ""; ( "REQUEST:Log on try >" ).Debug( 9 ); Dictionary<string, object> j = new Dictionary<string, object>(); Session session = null; if( args.ContainsKey( "sessionId" ) ) { if( cn == null ) { session = new Session( Main.Site, new Guid( ( string )args[ "sessionId" ] ) ); } else { session = new Session( Main.Site, new Guid( ( string )args[ "sessionId" ] ), cn, trns ); } } else { session = Main.GetCurrentSession(); } if( args.ContainsKey( "hostSessionId" ) ) { hostSessionId = args[ "hostSessionId" ].ToString(); } else { hostSessionId = Main.GetCurrentSession().Id.ToString(); } if( args.ContainsKey( "userId" ) ) { try { userId = Convert.ToInt32( args[ "userId" ] ); } catch( Exception e ) { e.Message.Debug( 5 ); ( "logon failure > userId key is in the incorrect format > ip:" + session.Ip + ",sessionId:" + session.Id.ToString() ).Debug( 5 ); /* Logon error -4 incorrect userId format */ j.Add( "error", -40 ); j.Add( "description", "userId key is in the incorrect format." ); return j; } } if( args.ContainsKey( "logon" ) ) { if( !int.TryParse( args[ "logon" ].ToString(), out userId ) ) { userId = -1; } } if( args.ContainsKey( "email" ) ) { login = Convert.ToString( args[ "email" ] ); } if( args.ContainsKey( "password" ) ) { password = GetHash( args[ "password" ] ); } /* execute SP logon */ string commandText = "dbo.logon @email,@password,@sessionid,@createaccount,@unique_siteID,@userId,@referenceSessionId"; SqlCommand cmd; if( cn == null ) { cmd = new SqlCommand( commandText, Site.SqlConnection ); } else { cmd = new SqlCommand( commandText, cn, trns ); } cmd.Parameters.Add( "@email", SqlDbType.VarChar ).Value = login; cmd.Parameters.Add( "@password", SqlDbType.VarChar ).Value = password; cmd.Parameters.Add( "@sessionid", SqlDbType.UniqueIdentifier ).Value = new Guid( session.Id.ToString() ); cmd.Parameters.Add( "@createaccount", SqlDbType.Bit ).Value = false; cmd.Parameters.Add( "@unique_siteID", SqlDbType.UniqueIdentifier ).Value = new Guid( Site.Id.ToString() ); cmd.Parameters.Add( "@userId", SqlDbType.Int ).Value = userId; cmd.Parameters.Add( "@referenceSessionId", SqlDbType.UniqueIdentifier ).Value = new Guid( hostSessionId ); int logonError = -1;/* there is an error if there is no recordset returned */ using( SqlDataReader d = cmd.ExecuteReader() ) { d.Read(); logonError = d.GetInt32( 0 ); } cmd.Dispose(); if( logonError != -1 ) { j.Add( "error", 0 ); j.Add( "description", "Logon successful" ); if( cn == null ) { session.Refresh( false ); } else { session.Refresh( false, cn, trns ); } string _msg = String.Format( "logon success > user:{0}, ip:{1}, sessionId:{2}.", session.UserId, session.Ip, session.Id ); _msg.Debug( 5 ); if( args.ContainsKey( "showSessionData" ) ) { if( Convert.ToBoolean( args[ "showSessionData" ] ) ) { j.Add( "session", session ); } } if( args.ContainsKey( "showUserData" ) ) { if( Convert.ToBoolean( args[ "showUserData" ] ) ) { j.Add( "user", session.User ); } } } else { string _msg = String.Format( "logon failure > user:{0}, ip:{1}, sessionId:{2}.", session.UserId, session.Ip, session.Id ); _msg.Debug( 5 ); /* Logon error -2 incorrect password */ j.Add( "error", -20 ); j.Add( "description", "incorrect name/password" ); } return j; }
/// <summary> /// Logons the specified user. /// </summary> /// <param name="userName">User name.</param> /// <param name="password">The password.</param> /// <param name="session">Session to logon.</param> /// <returns></returns> public static int LogOn(string userName, string password, Session session ) { Dictionary<string, object> j = new Dictionary<string, object>(); j.Add( "sessionId", session.Id.ToString() ); j.Add( "email", userName ); j.Add( "password", password ); Dictionary<string, object> r = LogOn(j,null,null); return (int)r["error"]; }
/// <summary> /// Adds an item to the selected sessions cart with transactions /// </summary> /// <param name="args">{itemnumber:string,qty:int,sessionid:Guid,other misc item form inputs}</param> /// <param name="cn">The connection being used.</param> /// <param name="trans">The transaction being used.</param> /// <returns> /// {itemNumber:string,price:float,qty:int,cartId:Guid,addressId:Guid /// sessionId:Guid,packingSlipImage:string,auxillaryImage:string,cartImage:string,detailImage:string, /// fullSizeImage:string,listingImage:string,listing2Image:string,description:string, /// form:string,error_id:int,error_desc:string,inputs:Dictionary}. /// </returns> public static Dictionary<string, object> AddToCart(Dictionary<string, object> args, SqlConnection cn, SqlTransaction trans) { ("FUNCTION:Add to Cart > Result object to JSON").Debug(10); Dictionary<string, object> j = new Dictionary<string, object>(); Session session = null; if(args.ContainsKey("sessionId")) { if(cn == null) { session = new Session(Main.Site, new Guid((string)args["sessionId"])); } else { session = new Session(Main.Site, new Guid((string)args["sessionId"]), cn, trans); } } else { session = Main.GetCurrentSession(); } Commerce.Item item = Main.Site.Items.List.Find(delegate(Commerce.Item itm) { return itm.ItemNumber.ToLower() == ((string)args["itemNumber"]).ToLower(); }); if(item == null) { j.Add("error", -1); string passedItem = ((string)args["itemNumber"]).MaxLength(50, true); j.Add("description", "Item number " + passedItem + " (itemNumber argument length:" + passedItem.Length.ToString() + ") does not exist."); return j; } if(!args.ContainsKey("itemNumber")) { j.Add("error", -2); j.Add("description", "the key itemNumber is missing from the collection."); return j; } int qty = 1; if(args.ContainsKey("qty")) { if(!int.TryParse(args["qty"].ToString(), out qty)) { qty = 1; } } /* figure out the price that should be set. The user can override the price if: * They are an administrator (session.administrator) * An administrator is entering the order (instatitationSession.administrator) * The order is entered via EDI transmission (HttpContext.Current==null) */ decimal price = (decimal)0.00; bool allowPreorder = false; bool allowPriceOverride = false; bool allowPreorderOverride = false; bool overridePrice = false; if(session.Wholesale == 1) { price = item.WholeSalePrice; } else if(item.IsOnSale) { price = item.SalePrice; } /* check if the user is an administrator or */ if(session.Administrator || HttpContext.Current == null) { allowPriceOverride = true; } /* check if this item is being added by someone else */ if(HttpContext.Current != null) { Session instatitationSession = Main.GetCurrentSession(); if(instatitationSession != null) { /* are they an administrator (What else would they be? But what the hell.) */ if(instatitationSession.Administrator) { allowPriceOverride = true; } } } if(allowPriceOverride) { if(args.ContainsKey("price")) { /* if the key is present, try and convert it into a decimal, * if that doesn't work enter price 0 to throw an exception */ if(!decimal.TryParse(args["price"].ToString(), out price)) { price = 0; } else { /* only override the price if a valid price was provided */ overridePrice = true; } } } if(allowPreorderOverride) { if(args.ContainsKey("allowPreorder")) { /* check if somthing silly was put in the key, if not allow the user to change allowPreorder */ if(!bool.TryParse(args["allowPreorder"].ToString(), out allowPreorder)) { allowPreorder = false; } } } BeforeAddToCartEventArgs e = new BeforeAddToCartEventArgs(item, session, cn, trans, HttpContext.Current); Main.Site.raiseOnBeforeAddtoCart(e); Commerce.CartItem i = addToCartProc( (string)args["itemNumber"], qty, session, args, price, allowPreorder, overridePrice, cn, trans ); string form = ""; if(i.Item.Form == null) { form = ""; } else { form = i.Item.Form.Html; }; /* spit a json object out to the console that initiated the request */ j.Add("itemNumber", i.Item.Number); j.Add("price", (double)i.Price); j.Add("qty", i.Qty); j.Add("cartId", i.CartId.ToString()); j.Add("addressId", i.AddressId.ToString()); j.Add("sessionId", session.Id.ToString()); j.Add("packingSlipImage", i.Item.PackingSlipImage); j.Add("auxillaryImage", i.Item.AuxillaryImage); j.Add("cartImage", i.Item.CartImage); j.Add("detailImage", i.Item.FullSizeImage); j.Add("fullSizeImage", i.Item.FullSizeImage); j.Add("listingImage", i.Item.ListingImage); j.Add("listing2Image", i.Item.Listing2Image); j.Add("item_description", i.Item.Description); j.Add("formName", i.Item.FormName); j.Add("error_id", i.Error_Id); j.Add("error_desc", i.Error_Description); j.Add("error", i.Error_Id); j.Add("description", i.Error_Description); if(i.Item.Form != null) { Dictionary<string, object> k = new Dictionary<string, object>(); for(var x = 0; i.Inputs.Count > x; x++) { if(!k.ContainsKey(i.Inputs[x].Name)) { k.Add(i.Inputs[x].Name, i.Inputs[x].Value); } } j.Add("inputs", k); j.Add("formHTML", form); } else { j.Add("inputs", false); } AddToCartEventArgs f = new AddToCartEventArgs(i, session.Cart, cn, trans, session, HttpContext.Current); Main.Site.raiseOnAddToCart(f); return j; }
/// <summary> /// creates a review for a hash match object accessable later thru _site._reviews /// </summary> /// <param name="args">JSON Object containging ///review_rating, ///review_message, ///review_objId, ///review_objType</param> /// <returns>{reviewId:Guid,userId:Int,rating:Int,value:string,archive:bool /// addDate:date,refType:string,refId:string,error:int,errorDesc:string}.</returns> public static Dictionary<string, object> AddReview(Dictionary<string, object> args) { ("FUNCTION /w SP addReview").Debug(10); Dictionary<string, object> j = new Dictionary<string, object>(); Session session = null; if(args.ContainsKey("sessionId")) { session = new Session(Main.Site, new Guid((string)args["sessionId"])); } else { session = Main.GetCurrentSession(); } Guid reviewId = Guid.NewGuid(); SqlCommand cmd = new SqlCommand("dbo.insertReview @reviewId,@userId,@rating,@message,@refId,@archive,@addDate,@refType", Site.SqlConnection); cmd.Parameters.Add("@reviewId", SqlDbType.UniqueIdentifier).Value = new Guid(reviewId.ToString()); cmd.Parameters.Add("@userId", SqlDbType.Int).Value = session.UserId; cmd.Parameters.Add("@rating", SqlDbType.Int).Value = Convert.ToInt32(args["rating"]); cmd.Parameters.Add("@message", SqlDbType.VarChar).Value = Convert.ToString(args["message"]); cmd.Parameters.Add("@refId", SqlDbType.VarChar, 50).Value = Convert.ToString(args["objId"]); cmd.Parameters.Add("@archive", SqlDbType.Bit).Value = false; cmd.Parameters.Add("@addDate", SqlDbType.DateTime).Value = DateTime.Now; cmd.Parameters.Add("@refType", SqlDbType.VarChar, 50).Value = Convert.ToString(args["objType"]); cmd.ExecuteNonQuery(); cmd.Dispose(); /* add to review list in memory */ Commerce.Review rev = new Commerce.Review(reviewId, Main.GetCurrentSession().UserId, (float)Convert.ToInt32(args["rating"]), Convert.ToString(args["message"]), false, DateTime.Now, Convert.ToString(args["objId"]), Convert.ToString(args["objType"]), Main.Site); Main.Site.Reviews.List.Add(rev); if(Convert.ToString(args["objType"]).l() == "itemnumber") { Commerce.Item i = Main.Site.Items.List.Find(delegate(Commerce.Item itm) { return itm.ItemNumber.l() == Convert.ToString(args["objId"]).l(); }); /* refresh item item in-memory as well*/ if(i != null) { i.RefreshReviews(); } } j.Add("reviewId", rev.Id.ToString()); j.Add("userId", rev.UserId); j.Add("rating", rev.Rating); j.Add("message", rev.Value); j.Add("archive", rev.Archive); j.Add("addDate", rev.Date); j.Add("refType", rev.RefType); j.Add("refId", rev.RefId); j.Add("error", 0); j.Add("errorDesc", ""); return j; }
/// <summary> /// empty the selected cart /// </summary> /// <param name="sessionId">Guid sessionId.</param> /// <returns>{success:bool}.</returns> public static Dictionary<string, object> EmptyCart(string sessionId) { ("FUNCTION /w SP emptyCart").Debug(10); Dictionary<string, object> j = new Dictionary<string, object>(); Session session = null; if(sessionId.IsGuid()) { session = new Session(Main.Site, new Guid(sessionId)); } else { session = Main.GetCurrentSession(); } SqlCommand cmd = new SqlCommand("dbo.emptyCart @sessionId", Site.SqlConnection); cmd.Parameters.Add("@sessionId", SqlDbType.UniqueIdentifier).Value = session.Id; cmd.ExecuteNonQuery(); j.Add("error", 0); j.Add("description", ""); cmd.Dispose(); return j; }
/// <summary> /// Saves the Address. /// </summary> /// <param name="session">The session.</param> public void Save( Session session ) { Save( session, null, null ); }
/// <summary> /// Updates the cart based on the dictionary provided. /// Pass the quantity of the item as qty+jguid(cartId) or as the jguid(cartId) /// All other form variables should be passed using their cartDetailId. /// </summary> /// <param name="args">The args.</param> /// <returns>{error:0,desc:"error description",items:item Collection,subTotal:x,taxTotal:x,estShipTotal:x,discountTotal:x,grandTotal:x,addresses:addressCollection}.</returns> public static Dictionary<string, object> UpdateCart(Dictionary<string, object> args) { ("FUNCTION /w SP updateCart").Debug(10); Dictionary<string, object> j = new Dictionary<string, object>(); Session session = null; if(args.ContainsKey("sessionId")) { session = new Session(Main.Site, new Guid((string)args["sessionId"])); } else { session = Main.GetCurrentSession(); } if(session.Cart.Items.Count == 0) { session.Cart.Refresh(); } foreach(Commerce.CartItem i in session.Cart.Items) { /* check for each QTY key, if the key exists then update this item. */ if(args.ContainsKey(i.CartId.EncodeXMLId())) { string formId = i.CartId.EncodeXMLId(); int qty = 0;/* if a qty was passed, and it turns out not to be numeric, then you loose the item */ if(!int.TryParse(args[formId].ToString(), out qty)) { qty = 0; } Guid addressId = Guid.Empty; if(args.ContainsKey("addressId")) { addressId = new Guid(args["addressId"].ToString()); } SqlCommand cmd = new SqlCommand(Cart.UPDATE_CART_QUERY, Site.SqlConnection); cmd.Parameters.Add("@qty", SqlDbType.Int).Value = args[i.CartId.EncodeXMLId()]; cmd.Parameters.Add("@price", SqlDbType.Money).Value = 0; cmd.Parameters.Add("@cartId", SqlDbType.UniqueIdentifier).Value = new Guid(i.CartId.ToString()); cmd.Parameters.Add("@setPrice", SqlDbType.Bit).Value = false; cmd.Parameters.Add("@addressId", SqlDbType.UniqueIdentifier).Value = addressId; cmd.ExecuteNonQuery(); cmd.Dispose(); UpdateCartDetail(i, args); } } session.Cart.Refresh(); List<object> items = new List<object>(); foreach(Commerce.CartItem i in session.Cart.Items) { Dictionary<string, object> jt = new Dictionary<string, object>(); jt.Add("cartId", i.CartId); jt.Add("price", i.Price); jt.Add("qty", i.Qty); jt.Add("addressId", i.AddressId); jt.Add("inputs", i.Inputs); items.Add(jt); } j.Add("items", items); j.Add("subTotal", (float)session.Cart.SubTotal); j.Add("taxTotal", (float)session.Cart.TaxTotal); j.Add("estShipTotal", (float)session.Cart.EstShipTotal); j.Add("discountTotal", (float)session.Cart.DiscountTotal); j.Add("grandTotal", (float)session.Cart.GrandTotal); j.Add("addresses", session.Cart.Addresses); j.Add("error", 0); j.Add("description", ""); return j; }
/// <summary> /// Saves the Address. /// </summary> /// <param name="session">The session.</param> /// <param name="cn">The cn.</param> /// <param name="trans">The trans.</param> private void Save( Session session, SqlConnection cn, SqlTransaction trans ) { Dictionary<string, object> args = new Dictionary<string, object>(); args.Add( "sessionId", session.Id.ToString() ); args.Add( "contactId", Id.ToString() ); args.Add( "userId", session.UserId ); args.Add( "FirstName", FirstName ); args.Add( "LastName", LastName ); args.Add( "Address1", Address1 ); args.Add( "Address2", Address2 ); args.Add( "City", City ); args.Add( "State", State ); args.Add( "Zip", Zip ); args.Add( "Country", Country ); args.Add( "HomePhone", HomePhone ); args.Add( "WorkPhone", WorkPhone ); args.Add( "Email", Email ); args.Add( "SpecialInstructions", SpecialInstructions ); args.Add( "Comments", Comments ); args.Add( "SendShipmentUpdates", SendShipmentUpdates ); args.Add( "EmailAds", EmailAds ); args.Add( "Rate", Rate ); args.Add( "DateCreated", DateCreated ); args.Add( "Company", Company ); UpdateContactWithTransaction( args, cn, trans ); }
/// <summary> /// Returns a _cart_item AND adds the selected item to the user's cart /// </summary> /// <param name="item_number">Number of the item you want to add to the user's cart</param> /// <param name="item_qty">Quantity of the item you want to add</param> /// <param name="session">session</param> /// <param name="args">The args.</param> /// <param name="price">The price.</param> /// <param name="allowPreorder">if set to <c>true</c> [allow preorder].</param> /// <param name="allow_priceOverride">if set to <c>true</c> [allow_price override].</param> /// <returns> /// Returns an empty string rather than a null from the Request[] object. /// </returns> internal static Commerce.CartItem AddToCartProc(string item_number, int item_qty, Session session, Dictionary<string, object> args, object price, bool allowPreorder, bool allow_priceOverride) { return addToCartProc(item_number, item_qty, session, args, price, allowPreorder, allow_priceOverride, null, null); }
/// <summary> /// Adds a reply to the reply or Blog matching the replyId key. /// Uses a SQL transaction to roll back changes if the boolean key "preview" /// is true, but still shows what would have happened. /// </summary> /// <param name="args">The argument dictionary { /// replyId /// email /// subject /// rating /// userId /// comment /// addedOn /// parentId /// reference /// disabled /// approves /// disapproves /// flaggedInappropriate /// message /// }</param> /// <returns>Dictionary containing {error:0,desc:"",subject:"blah",message:"blah"} when successfull or the error. </returns> public static Dictionary<string, object> AddReply(Dictionary<string, object> args) { ("FUNCTION /w SP addReply").Debug(10); Dictionary<string, object> j = new Dictionary<string, object>(); Session session = null; bool preview = false; if(args.ContainsKey("sessionId")) { session = new Session(Main.Site, new Guid((string)args["sessionId"])); } else { session = Main.GetCurrentSession(); } using(SqlConnection cn = Site.CreateConnection(true, true)) { cn.Open(); using(SqlTransaction trans = cn.BeginTransaction("reply")) { if(args.ContainsKey("preview")) { preview = (bool)args["preview"]; } string replyId = Guid.NewGuid().ToString(); Guid parentId; if(args.ContainsKey("replyId")) { replyId = args["replyId"].ToString(); } if(args.ContainsKey("parentId")) { parentId = new Guid(args["parentId"].ToString()); } else { j.Add("error", 2); j.Add("description", "Key parentId is not present."); return j; } /* email the Blog to which this reply belongs, if they like that sort of thing. */ //int nestCount = 0; /* BlogEntry entry = null; while(entry == null) { entry = Main.Site.Blogs.AllEntries.Find(delegate(BlogEntry be) { return be.Id == parentId; }); if(entry == null) { Reply reply = Main.Site.Replies.List.Find(delegate(Commerce.Reply rp) { return rp.Id == parentId; }); if(reply == null) { j.Add("error", 4); j.Add("description", "Could not find parent.."); return j; } // step up until the parent is a Blog parentId = reply.ParentId; } nestCount++; } if(!entry.AllowComments) { j.Add("error", 5); j.Add("description", "This Blog does not allow comments."); return j; } */ string email = args.KeyOrDefault("email", "").ToString(); string subject = args.KeyOrDefault("subject", "").ToString(); string rating = args.KeyOrDefault("rating", "").ToString(); string comment = args.KeyOrDefault("message", "").ToString(); string addedOn = args.KeyOrDefault("addedOn", DateTime.Now.ToString()).ToString(); string reference = args.KeyOrDefault("reference", "").ToString(); /* accept all messages instantly in test mode */ string disabled = args.KeyOrDefault("disabled", false).ToString(); string approves = args.KeyOrDefault("approves", 0).ToString(); string disapproves = args.KeyOrDefault("disapproves", 0).ToString(); string flaggedInappropriate = args.KeyOrDefault("flaggedInappropriate", false).ToString(); string commandText = @"dbo.insertReply @replyId, @email, @subject, @rating, @userId, @comment, @addedOn, @parentId, @reference, @disabled, @approves, @disapproves, @flaggedInappropriate"; using(SqlCommand cmd = new SqlCommand(commandText, cn, trans)) { cmd.Parameters.Add("@replyId", SqlDbType.UniqueIdentifier).Value = new Guid(replyId); cmd.Parameters.Add("@email", SqlDbType.VarChar).Value = email; cmd.Parameters.Add("@subject", SqlDbType.VarChar).Value = subject; cmd.Parameters.Add("@rating", SqlDbType.VarChar).Value = rating; cmd.Parameters.Add("@userId", SqlDbType.Int).Value = session.UserId; cmd.Parameters.Add("@comment", SqlDbType.VarChar).Value = comment; cmd.Parameters.Add("@addedOn", SqlDbType.DateTime).Value = Convert.ToDateTime(addedOn); cmd.Parameters.Add("@parentId", SqlDbType.UniqueIdentifier).Value = new Guid(parentId.ToString()); cmd.Parameters.Add("@reference", SqlDbType.VarChar).Value = reference; cmd.Parameters.Add("@disabled", SqlDbType.Bit).Value = Convert.ToBoolean(disabled); cmd.Parameters.Add("@approves", SqlDbType.Int).Value = Convert.ToInt32(approves); cmd.Parameters.Add("@disapproves", SqlDbType.Int).Value = Convert.ToInt32(disapproves); cmd.Parameters.Add("@flaggedInappropriate", SqlDbType.Int).Value = 0; cmd.ExecuteNonQuery(); j.Add("subject", args["subject"].ToString()); j.Add("message", args["message"].ToString()); j.Add("replyId", replyId); if(preview) { trans.Rollback(); } else { trans.Commit(); } } /* if(!preview) { Main.Site.Replies = new Commerce.Replies(Main.Site); Main.Site.Blogs = new Commerce.Blogs(Main.Site); Guid gReplyId = new Guid(replyId); Commerce.Reply newReply = Main.Site.Replies.List.Find(delegate(Commerce.Reply rp) { return rp.Id == gReplyId; }); if(entry.EmailUpdates) { CreateEmailEventArgs emailArgs = new CreateEmailEventArgs("commentAdded", Main.Site.site_operator_email, entry.Author.Email, Main.Site.site_log_email, entry.Author, session, newReply, entry); DefaultEmails.CommentAdded(ref emailArgs); Main.Site.raiseOncreateemail(emailArgs); SendEmailArgResult(emailArgs, cn, null); } } */ j.Add("blogEntryId", parentId); j.Add("error", 0); j.Add("description", ""); } } return j; }
/// <summary> /// Initializes a new instance of the <see cref="Cart"/> class. /// </summary> /// <param name="f_session">The f_session.</param> /// <param name="f_site">The f_site.</param> public Cart( Session f_session, Site f_site ) { EstShippingCost = 0; EstShipTotal = 0; SubTotal = 0; GrandTotal = 0; TaxTotal = 0; DiscountTotal = 0; Items = new List<CartItem>(); Addresses = new List<Address>(); Session = f_session; Site = f_site; }
/// <summary> /// Process JSON messages. /// Map some messages to methods. /// Map some messages to embedded resources. /// Secondary HTTP Pipeline. /// </summary> /// <param name="httpApp">The Http app.</param> /// <returns>When true, a AJAX responder was called</returns> private static bool processHTTPRequest(HttpApplication httpApp) { /* get the current http context */ bool _JSONResponse = false; HttpContext current = HttpContext.Current; /* start a Timer */ DateTime startHTTPRequest = DateTime.Now; current.Items.Add("startHTTPRequest", startHTTPRequest); /* create a reference to the session object */ Session session = null; string executionFilePath = current.Request.AppRelativeCurrentExecutionFilePath; bool _isVirtualResourcePath = IsVirtualResourcePath(executionFilePath); /* ***1*** make sure user's don't request an invalid file resource by redirecting */ if(Main.AdminDirectory == executionFilePath) { current.Response.Redirect(Main.AdminDirectory + "/", false); current.ApplicationInstance.CompleteRequest(); goto End; } /* ***2*** if this is not a request for a /Admin or /responder directory * implement the rewriter directives */ if(!_isVirtualResourcePath) { /* try to redirect the URL */ if(redirectUrl(current)) { goto End; }; /* try to rewrite the URL */ if(RewriteUrl(current)) { goto End; }; /* site section rewrites */ if(RewriteSiteSection(current)) { goto End; }; /* check for category rewrites */ if(RewriteCategory(current)) { goto End; }; /* check for item rewrites */ if(RewriteItem(current)) { goto End; }; } /* ***3*** don't try and examine the physical path until _after_ the rewrite */ string physicalPath = current.Request.PhysicalPath; bool _isResourceFile = IsResourceFile(physicalPath); /* if this is an image or other non dynamic resource file * and not used in a virtual path than don't do any further processing */ if(_isResourceFile && !_isVirtualResourcePath) { sendNeverExpiresHeaders(); goto End; } /* if this is a public resource, give up the resource now */ foreach(string file in Main.PublicFiles) { if(executionFilePath == file || executionFilePath.StartsWith(Main.AdminDirectory + "/img")) { sendNeverExpiresHeaders(); getResxResource(current); goto End; } } /* no rewrite or redirect so now check if the file exists */ if(!File.Exists(physicalPath) && !_isVirtualResourcePath) { ErrorPage(current, 404, String.Format("Cannot find {0}", physicalPath)); goto End; } /* the file or resource exists (probably) * create a Session * this is resource consuming */ session = new Session(Site); /* place the session object in an object that is only good as long as the http pipeline lasts */ current.Items.Add("currentSession", session); /* raise the after authentication event */ AfterAuthenticationEventArgs args = new AfterAuthenticationEventArgs(session, current); Main.Site.raiseOnAfterAuthentication(args); /* execute AJAX responders - if a responder was executed then end. */ try { if(executeResponders(current, session)) { _JSONResponse = true; goto End; }; } catch(Exception ex) { String.Format("executeResponders exception =>{0}", ex.Message).Debug(0); goto End; } /* check if this is a request for the Admin directory or Admin responder virtual page */ if(_isVirtualResourcePath) { /* don't do anything for people who arn't logged on as administrators, unless we're in setup mode */ if(!session.Administrator) { /* 401 forbidden, and ask for a username / password */ /* RFC 2617 HTTP Authentication: Basic and Digest Access Authentication */ if(current.Request.Headers["Authorization"] != null) { /* user is sending logon attempt via HTTP auth */ string _raw_header = current.Request.Headers["Authorization"]; string[] _hprams = _raw_header.Split(' '); string method = _hprams[0]; string enc_auth = _hprams[1]; /* decode base 64 auth string */ string _raw_auth = Encoding.ASCII.GetString(Convert.FromBase64String(enc_auth)); string[] _auth = _raw_auth.Split(':'); string userName = _auth[0]; string password = _auth[1]; /* try to logon using the provided authentication creditials */ if(session.LogOn(userName, password) == 0) { session.Refresh(); } } /* check again */ if(!session.Administrator) { if(!UseFormsBasedAuth) { current.Response.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", current.Request.Url.DnsSafeHost)); ErrorPage(current, 401, String.Format("Only administrators can access the {0} virtual directory.", Main.AdminDirectory));/* 401 unauthorized */ current.ApplicationInstance.CompleteRequest(); goto End; } else { current.Response.Redirect(Main.PublicDirectory + "/logon.html?rdr=" + executionFilePath.UrlEncode()); current.ApplicationInstance.CompleteRequest(); goto End; } } } sendNeverExpiresHeaders(); /* if this is a request for the Admin directory tree respond with the given Admin resource */ if(!executionFilePath.Contains(Main.AdminResponder)) { getResxResource(current); goto End; } } End: /* fire off events */ EndRequestEventArgs endRequestargs = new EndRequestEventArgs(session, current); Site.raiseOnendrequest(endRequestargs); DateTime endHTTPRequest = DateTime.Now; current.Items.Add("finish_processHTTPRequest", endHTTPRequest); return _JSONResponse; }
/// <summary> /// Gets the current session requesting the HTTP resource. /// </summary> /// <returns>Session</returns> internal static Session GetCurrentSession() { HttpContext current = HttpContext.Current; if(current==null){return null;} Session session = ((Session)current.Items["currentSession"]); /* if the value isn't loaded then get it */ if(session==null){ session = new Session( Site ); /* place the session object in an object that is only good as long as the http pipeline lasts */ if( !current.Items.Contains( "currentSession" ) ) { current.Items.Add( "currentSession", session ); } else { current.Items[ "currentSession" ] = session; } } return session; }
/// <summary> /// Places an order once a cart has been filled with items using the specified sessionId within a transaction. /// </summary> /// <param name="args">JSON Object that can contain the following keys (even if blank) /// sessionId /// userId /// nameOnCard /// cardType /// cardNumber /// expMonth /// expYear /// secNumber /// soldBy /// requisitionedBy /// parentOrderId /// deliverBy /// purchaseOrder /// manifestNumber /// vendorAccountNumber /// Fob /// scannedImage /// comments /// billToContactId /// billToFirstName /// billToLastName /// billToAddress1 /// billToAddress2 /// billToCity /// billToState /// billToZip /// billToCountry /// billToCompany /// billToEmail /// billToSendShipmentUpdates /// billToHomePhone /// billToWorkPhone /// billToSpecialInstructions /// billToEmailAds /// billToComments /// billToRateId /// shipToContactId /// shipToFirstName /// shipToLastName /// shipToAddress1 /// shipToAddress2 /// shipToCity /// shipToState /// shipToZip /// shipToCountry /// shipToCompany /// shipToEmail /// shipToSendShipmentUpdates /// shipToHomePhone /// shipToWorkPhone /// shipToSpecialInstructions /// shipToComments /// shipToEmailAds /// shipToRateId</param> /// <param name="fcn">The FCN.</param> /// <param name="trans">The transaction being used.</param> /// <returns> /// {billToAddressId:Guid,paymentMethodId:Guid,orderNumber:string,subTotal:float,grandTotal:float,taxTotal:float,shipTotal:float, /// discounted:Guid,printState:string,concatSerialNumbers:string,concatShipmentNumbers:float,concatSerialIds:float, /// concatShipmentIds:Guid,error:Guid,errorDescription:string,orderId:float,discountPct:float, /// discountCode:Guid,termId:int,userId:int,approvedBy:int,scannedImage:string}. /// </returns> public static Dictionary<string, object> PlaceOrderWithTransaction(Dictionary<string, object> args, SqlConnection fcn, SqlTransaction trans) { /* do not put debug statements before the transaction start */ int requisitionedBy = -1; int approvedBy = -1; int soldBy = -1; int parentOrderId = -1; bool backorderMode = false; DateTime SQLMin = DateTime.Parse("1/1/1900 00:00:00.000"); DateTime deliverBy = SQLMin; DateTime orderDate = SQLMin; string customOrderNumber = ""; string vtDesc = ""; Commerce.CreditCard card = null; Commerce.Cash cash = null; Commerce.Wire wire = null; // never used -> Commerce.PayPal PayPal = null; Commerce.Check check = null; Commerce.PromiseToPay promiseToPay = null; Dictionary<string, object> vt = null; Dictionary<string, object> o = new Dictionary<string, object>(); /* last chance to reject before transaction starts */ SqlConnection cn; if(fcn == null) { /* create a seperate connection so we can control the transaction process (MARS will confict) */ cn = Site.CreateConnection(false, true); cn.Open(); } else { cn = fcn; } string transSessionId = Guid.NewGuid().ToFileName(); SqlCommand cmd; SqlTransaction orderTransaction; if(fcn == null) { orderTransaction = cn.BeginTransaction(transSessionId); } else { orderTransaction = trans; } /* debug statements OK after this */ ("FUNCTION /w SP,CN,TRANS placeOrder").Debug(10); bool rollback = false; int termId = 0; /* check all keys to make sure the keys are present */ string[] keys = { "userId","nameOnCard","cardType","cardNumber","expMonth","expYear","secNumber","soldBy", "requisitionedBy","parentOrderId","deliverBy","purchaseOrder","manifestNumber", "vendorAccountNumber","FOB","comments","billToContactId", "billToFirstName","billToLastName","billToAddress1","billToAddress2", "billToCity","billToState","billToZip","billToCountry","billToCompany", "billToEmail","billToSendShipmentUpdates","billToHomePhone","billToWorkPhone", "billToSpecialInstructions","billToEmailAds","billToComments","billToRateId", "shipToContactId","shipToFirstName","shipToLastName","shipToAddress1", "shipToAddress2","shipToCity","shipToState","shipToZip","shipToCountry", "shipToCompany","shipToEmail","shipToSendShipmentUpdates","shipToHomePhone", "shipToWorkPhone","shipToSpecialInstructions","shipToComments","shipToEmailAds", "shipToRateId","termId","approvedBy","scannedImage","orderDate", "eraseVisitorHistory","backorder"}; string[] requiredKeys = { }; Session session = null; if(args.ContainsKey("sessionId")) { if(fcn == null) { session = new Session(Main.Site, new Guid((string)args["sessionId"])); } else { session = new Session(Main.Site, new Guid((string)args["sessionId"]), cn, orderTransaction); } } else { session = Main.GetCurrentSession(); } foreach(string keyName in requiredKeys) { if(!args.ContainsKey(keyName)) { string errMsg = "The key \"" + keyName + "\" is missing from the argument dictionary. All required keys must be present."; o.Add("error", -4010); o.Add("description", errMsg); Exception e = new Exception(errMsg); e.Message.Debug(1); throw e; } } foreach(string keyName in keys) { if(!args.ContainsKey(keyName)) { args.Add(keyName, ""); } } /* gather bill to and ship to data, if any, from the request */ Dictionary<string, object> btAddr = new Dictionary<string, object>(); Dictionary<string, object> stAddr = new Dictionary<string, object>(); foreach(KeyValuePair<string, object> field in args as Dictionary<string, object>) { if(field.Key.StartsWith("shipTo")) { stAddr.Add(field.Key.Replace("shipTo", ""), field.Value); } else if(field.Key.StartsWith("billTo")) { btAddr.Add(field.Key.Replace("billTo", ""), field.Value); } } if(!(session.User.AccountType == 0 || session.User.AccountType == 1)) { Exception e = new Exception(string.Format("Only users with account type 0 or 1 can place orders. " + "The account type of userId {0} is {1}.", session.UserId, session.User.AccountType)); e.Message.Debug(1); throw e; } /* if the cart isn't populated, do that now */ if(session.Cart.Items.Count == 0) { session.Cart.Refresh(cn, orderTransaction); } if(session.Cart.Items.Count == 0) { string _msg = String.Format("No items found in cart. UserId:{0}, SessionId:{1}", session.UserId, session.Id); o.Add("error", -2016); o.Add("description", "No items found in cart."); rollback = true; Exception e = new Exception(_msg); e.Message.Debug(1); throw e; } /* update the bill to and ship to addresses in the database * if the Address does not exist, validate it and insert it. */ if(stAddr.Count > 0) { stAddr.Remove("ContactId"); stAddr.Add("contactId", session.Cart.Items[0].AddressId.ToString()); stAddr.Add("sessionId", session.Id.ToString()); stAddr.Add("userId", session.UserId.ToString()); Address.UpdateContactWithTransaction(stAddr, cn, orderTransaction); } if(btAddr.Count > 0) { btAddr.Remove("ContactId"); btAddr.Add("contactId", session.Id.ToString()); btAddr.Add("sessionId", session.Id.ToString()); btAddr.Add("userId", session.UserId.ToString()); Address.UpdateContactWithTransaction(btAddr, cn, orderTransaction); } /* refresh again to reflect changes in the addresses */ session.Cart.Refresh(cn, orderTransaction); Commerce.Address billToAddress = session.Cart.Addresses.Find(delegate(Commerce.Address adr) { return adr.Id == session.Id; }); Commerce.Address shipToAddress = session.Cart.Addresses.Find(delegate(Commerce.Address adr) { return adr.Id != session.Id; }); /* if there is no shipToAddress, or billToAddress then reject now */ if(billToAddress == null) { o.Add("error", -2001); o.Add("description", "No bill to Address found for session."); rollback = true; string _msg = String.Format("No bill to Address found for session. UserId:{0}, SessionId:{1}", session.UserId, session.Id); Exception e = new Exception(_msg); e.Message.Debug(1); throw e; } if(shipToAddress == null) { o.Add("error", -2002); o.Add("description", "No ship to Address found for session."); rollback = true; string _msg = String.Format("No ship to Address found. UserId:{0}, SessionId:{1}", session.UserId, session.Id); Exception e = new Exception(_msg); e.Message.Debug(1); throw e; } ("Begin place order transaction >").Debug(7); PlaceOrderEventArgs ev = new PlaceOrderEventArgs(session.Cart, cn, orderTransaction, session, HttpContext.Current); Main.Site.raiseOnbeforeplaceorder(ev); try { bool transactionSucsessStatus = false; int errorId = -1; string errorDescription = ""; int orderId = -1; string orderNumber = ""; Guid newSessionId = Guid.Empty; if(!DateTime.TryParse(args["orderDate"].ToString(), out orderDate)) { orderDate = DateTime.Now; } /* if the date is today at 12:00, change the date to now. Some functions * want to pretend there is no such thing as time of day, this is bad behaviour. */ if(orderDate == DateTime.Today) { orderDate = DateTime.Now; } /* validate order */ if(HttpContext.Current != null) { /* if this is a web user, check that they have permission for these keys */ int _term; if(!int.TryParse(args["termId"].ToString(), out _term)) { termId = session.User.TermId; } /* is the person who owns the order an administrator? If not they gota use their account terms. */ if(!session.User.Administrator) { termId = session.User.TermId; } /* is the person who is submitting the order an administrator? */ Session submitter = Main.GetCurrentSession(); if(submitter != null) { if(submitter.User.Administrator) { termId = _term; } } } else { /* if this isn't a web user (EDI) then see if they passed a valid termId, or use the user's default */ termId = session.User.TermId; if(!int.TryParse(args["termId"].ToString(), out termId)) { termId = session.User.TermId; } } String.Format("Place Order > Set termId {0} for userId {1}", termId, session.UserId).Debug(7); /* try to create a paymentMethodId */ Guid paymentMethodId = Guid.NewGuid(); if(!bool.TryParse(args["backorder"].ToString(), out backorderMode)) { backorderMode = false; } if(termId == 0 && backorderMode == false) {/*this is a prepaid credit card transaction - termId 0 */ String.Format("Place Order > Begin CC Transaction for userId {0}", session.UserId).Debug(7); card = new Commerce.CreditCard( args["cardType"].ToString().MaxLength(50, true), args["cardNumber"].ToString().MaxLength(100, true), args["nameOnCard"].ToString().MaxLength(100, true), args["secNumber"].ToString().MaxLength(7, true), args["expMonth"].ToString().MaxLength(4, true), args["expYear"].ToString().MaxLength(4, true) ); List<int> orderIds = new List<int>(); orderIds.Add(orderId); card.Insert(paymentMethodId, session.Id, session.UserId, session.Id, termId, "", session.Cart.GrandTotal, orderDate, orderIds, "", cn, orderTransaction); } else if(termId == 9 && backorderMode == false /* this is a COD Check transaction - termId 9 */ ) { check = new Commerce.Check( args["checkNumber"].ToString().MaxLength(50, true), args["routingNumber"].ToString().MaxLength(50, true), args["bankAccountNumber"].ToString().MaxLength(50, true), args["checkNotes"].ToString().MaxLength(50, true) ); List<int> orderIds = new List<int>(); orderIds.Add(orderId); check.Insert(paymentMethodId, session.UserId, session.Id, termId, "", session.Cart.GrandTotal, orderDate, orderIds, "", cn, orderTransaction); } else if(termId == 20 && backorderMode == false /* this is a wire transfer - termId 20 */ ) { wire = new Commerce.Wire( args["swift"].ToString().MaxLength(50, true), args["bankName"].ToString().MaxLength(50, true), args["routingTransitNumber"].ToString().MaxLength(50, true) ); List<int> orderIds = new List<int>(); orderIds.Add(orderId); wire.Insert(paymentMethodId, session.UserId, session.Id, termId, "", session.Cart.GrandTotal, orderDate, orderIds, "", cn, orderTransaction); } else if(termId == 13 && backorderMode == false /* this order is prepaid in cash */) { List<int> orderIds = new List<int>(); orderIds.Add(orderId); cash = new Commerce.Cash(); /*don't you wish it was really that easy?*/ cash.Insert(paymentMethodId, session.UserId, session.Id, termId, "", session.Cart.GrandTotal, orderDate, orderIds, "", cn, orderTransaction); } else { /* this order is an accrued order, post a 0 payment as a placeholder */ List<int> orderIds = new List<int>(); orderIds.Add(orderId); promiseToPay = new Commerce.PromiseToPay(); promiseToPay.Insert(paymentMethodId, session.UserId, session.Id, termId, "", session.Cart.GrandTotal, orderDate, orderIds, "", cn, orderTransaction); } /* save forms */ for(var x = 0; session.Cart.Items.Count > x; x++) { if(session.Cart.Items[x].Item.Form != null) { cmd = new SqlCommand("dbo.insertOrderLineForm @cartId,@sourceCode,@formName", cn, orderTransaction); cmd.Parameters.Add("@cartId", SqlDbType.UniqueIdentifier).Value = new Guid(session.Cart.Items[x].CartId.ToString()); cmd.Parameters.Add("@sourceCode", SqlDbType.VarChar).Value = session.Cart.Items[x].Item.Form.SourceCode; cmd.Parameters.Add("@formName", SqlDbType.VarChar).Value = session.Cart.Items[x].Item.Form.Name.MaxLength(50, true); cmd.ExecuteNonQuery(); cmd.Dispose(); } } /* place order */ o = ExecPlaceOrder( new Guid(session.Id.ToString()), session.UserId, paymentMethodId, Main.Site.test_mode, new Guid(Main.Site.Defaults.SiteId.ToString()), Guid.Empty, args["purchaseOrder"].ToString(), orderDate, termId, session.Cart.DiscountTotal, cn, orderTransaction ); errorId = (int)o["error"]; errorDescription = (string)o["description"]; if(errorId == 0) {/* these keys will be absent in the event of an error */ orderId = (int)o["orderId"]; orderNumber = (string)o["orderNumber"]; } if(errorId == 0) { /* if termId == 0 then this is a credit card and we can actaully automate the payment. */ if(termId == 0 && session.User.AccountType == 0/*AR accounts only*/) { if(card.Error == 0) { ("starting payment gateway...").Debug(5); vt = Commerce.VirtualTerminal.ChargeCreditCard( billToAddress, shipToAddress, card, session.Cart.GrandTotal, session.Id, orderNumber, args["purchaseOrder"].ToString(), cn, orderTransaction ); if(vt == null) { o.Add("error", -1754); o.Add("description", "Internal virtual terminal error. Unable to create virtual terminal object."); rollback = true; Exception e = new Exception("Invalid credit card passed to local system"); e.Message.Debug(5); throw e; } transactionSucsessStatus = vt["error"].ToString() == "0"; vtDesc = vt["description"].ToString(); } else { o.Add("error", -1744); o.Add("description", "Invalid credit card passed to local system"); rollback = true; Exception e = new Exception("Invalid credit card passed to local system"); e.Message.Debug(5); throw e; } } else { /* if this was anything else we can't really tell if the payment is good or bad so we just assume it's good */ ("Non credit card order - assume payment is OK").Debug(7); transactionSucsessStatus = true; } if(transactionSucsessStatus || Main.Site.test_mode == true) { /* add info to the order now that it has been placed */ if(args.ContainsKey("orderNumber")) { if(args["orderNumber"].ToString() != "") { customOrderNumber = args["orderNumber"].ToString(); } } if(!Int32.TryParse(args["soldBy"].ToString(), out soldBy)) { soldBy = -1; } if(!Int32.TryParse(args["requisitionedBy"].ToString(), out requisitionedBy)) { requisitionedBy = -1; } if(!Int32.TryParse(args["approvedBy"].ToString(), out soldBy)) { approvedBy = -1; } if(!Int32.TryParse(args["parentOrderId"].ToString(), out parentOrderId)) { parentOrderId = -1; } if(!DateTime.TryParse(args["deliverBy"].ToString(), out deliverBy)) { deliverBy = SQLMin; } string discountCode = ""; object s_code = session.GetProperty("discountCode"); object s_desc = session.GetProperty("discountDescription"); if(s_desc != null) { discountCode = s_desc.ToString().MaxLength(50, true); } else if(s_code != null) { string t_code = s_code.ToString().ToLower().Trim(); /* if ther was a discount code enter the description into the order now */ Discount orderDiscount = Main.Site.Discounts.List.Find(delegate(Discount d) { return d.Code == t_code; }); if(orderDiscount != null) { discountCode = orderDiscount.Comments.MaxLength(50, true); } } ("Execute SP [dbo].[updateExtOrderInfo]").Debug(7); using(cmd = new SqlCommand(@"dbo.updateExtOrderInfo @orderId,@purchaseOrder,@soldBy,@manifestNumber,@requisitionedBy, @deliverBy,@vendorAccountNumber,@fob,@parentOrderId,@scannedImage,@comments,@approvedBy,@oldSessionId, @uniqueSiteId,@customOrderNumber,@discountCode", cn, orderTransaction)) { cmd.Parameters.Add("@orderId", SqlDbType.Int).Value = orderId; cmd.Parameters.Add("@purchaseOrder", SqlDbType.VarChar).Value = Convert.ToString(args["purchaseOrder"]).MaxLength(100, true); cmd.Parameters.Add("@soldBy", SqlDbType.Int).Value = soldBy; cmd.Parameters.Add("@manifestNumber", SqlDbType.VarChar).Value = Convert.ToString(args["manifestNumber"]).MaxLength(100, true); cmd.Parameters.Add("@requisitionedBy", SqlDbType.Int).Value = soldBy; cmd.Parameters.Add("@deliverBy", SqlDbType.DateTime).Value = deliverBy; cmd.Parameters.Add("@vendorAccountNumber", SqlDbType.VarChar).Value = Convert.ToString(args["vendorAccountNumber"]).MaxLength(50, true); cmd.Parameters.Add("@fob", SqlDbType.VarChar).Value = Convert.ToString(args["FOB"]).MaxLength(50, true); cmd.Parameters.Add("@parentOrderId", SqlDbType.Int).Value = parentOrderId; cmd.Parameters.Add("@scannedImage", SqlDbType.VarChar).Value = Convert.ToString(args["scannedImage"]).MaxLength(50, true); cmd.Parameters.Add("@approvedBy", SqlDbType.Int).Value = approvedBy; cmd.Parameters.Add("@comments", SqlDbType.VarChar).Value = Convert.ToString(args["comments"]).MaxLength(10000, true); cmd.Parameters.Add("@oldSessionId", SqlDbType.UniqueIdentifier).Value = new Guid(session.Id.ToString()); cmd.Parameters.Add("@uniqueSiteId", SqlDbType.UniqueIdentifier).Value = new Guid(Site.Id.ToString()); cmd.Parameters.Add("@customOrderNumber", SqlDbType.VarChar).Value = customOrderNumber; cmd.Parameters.Add("@discountCode", SqlDbType.VarChar).Value = discountCode; cmd.ExecuteNonQuery(); } bool eraseVisitorHistory = false; if(!bool.TryParse(args["eraseVisitorHistory"].ToString(), out eraseVisitorHistory)) { eraseVisitorHistory = false; } if(eraseVisitorHistory) { /* TODO: erase Visitor History. This was causing a deadlock. maybe do it later? */ } /* if there was a scaned image attached move it now */ if(((string)args["scannedImage"]).Length > 0) { Admin.StoreScannedImage((string)args["scannedImage"], orderNumber); } if(Main.Site.test_mode) { rollback = true; Exception e = new Exception("placeOrder > __TEST MODE__ - ORDER SUCCESS - __TEST MODE__ >> ROLLBACK!" + " Order Number:" + orderNumber + ",SessionId:" + session.Id.ToString()); e.Message.Debug(7); throw e; } else { /* if they had a discount code, remove that now */ session.RemoveProperty("discountCode", cn, orderTransaction); session.RemoveProperty("discountDescription", cn, orderTransaction); if(fcn == null) {/* commit transaction if there was no caller transaction */ orderTransaction.Commit(); } Commerce.Order order = Commerce.Order.GetOrderByOrderId(orderId, cn, orderTransaction); ("placeOrder > $$$$$$$$$$ <CHA CHING> - ORDER SUCCESS - <CHA CHING> $$$$$$$$$$ Order Number:" + orderNumber).Debug(7); AfterPlaceOrderEventArgs f = new AfterPlaceOrderEventArgs(order, cn, orderTransaction, session, HttpContext.Current); Main.Site.raiseOnplaceorder(f); if(args.ContainsKey("sendOrderConfirmEmail")) { if(((bool)args["sendOrderConfirmEmail"]) == true) { try { Dictionary<string, object> emailArgs = new Dictionary<string, object>(); emailArgs.Add("orderId", orderId); PlacedOrderEmail(order, cn, orderTransaction); } catch(Exception e) { String.Format("Could not send email for orderId {0}. {1}" , orderId, e.Message).Debug(1); } } } } if(fcn == null) { cn.Dispose(); } return o; } else { if(fcn == null) { rollback = true; } /* the order failed becuase the user could not provide a convincing enough payment method */ o.Remove("error"); o.Remove("description"); o.Add("error", -2000); o.Add("description", vtDesc); rollback = true; Exception e = new Exception(vtDesc); e.Message.Debug(3); throw e; } } else { /* error occured, error in in the object o */ o.Remove("error"); o.Remove("description"); o.Add("error", errorId); o.Add("description", errorDescription); rollback = true; Exception e = new Exception(errorId.ToString() + ":" + errorDescription); e.Message.Debug(1); throw e; } } catch(Exception ex) { o.Remove("error"); o.Remove("description"); o.Add("error", -500); o.Add("description", ex.Message); ("Exception:" + ex.Message + " SessionId:" + session.Id.ToString()).Debug(1); rollback = true; return o; } finally { if(rollback) { if(fcn == null) { orderTransaction.Rollback(transSessionId); } } } }