public ActionResult ConfirmOrder() { List <orderItem> lista = new List <orderItem>(); foreach (var VARIABLE in GlobalVariables.MyBasket.BasketIElements) { orderItem ordItem = new orderItem(); ordItem.ItemId = VARIABLE.Item.ItemId; ordItem.quantity = VARIABLE.Quantity; lista.Add(ordItem); } var ord = db.orders.Create(); var user = new User { Address = GlobalVariables.LoginUser.Address, Email = GlobalVariables.LoginUser.Email, Name = GlobalVariables.LoginUser.Name, Id = GlobalVariables.LoginUser.Id, Password = GlobalVariables.LoginUser.Password, Phone = GlobalVariables.LoginUser.Phone }; ord.Id = user.Id; ord.orderItems = lista; db.orders.Add(ord); db.SaveChanges(); return(View()); }
public async void Update(TableDetailItem newDetail, TableItem newTable) { if (table.id != 0) { var result = await apiNetwork.UnstateAsync(table.id); SetupData(); } detail = newDetail; table = newTable; CultureInfo cul = CultureInfo.GetCultureInfo("vi-VN"); // try with "en-US" if (newDetail.product_list != null) { for (int i = 0; i < newDetail.product_list.Count; i++) { orderItem p = newDetail.product_list[i]; string price = p.price.ToString("#,###", cul.NumberFormat); string sale_price = (p.sale_price == p.price || !p.sale_price.HasValue) ? "" : p.sale_price.Value.ToString("#,###", cul.NumberFormat); string[] row = new string[] { (i + 1).ToString(), p.name, p.quantity.ToString(), price, sale_price, p.sale_price != p.price ? (p.sale_price.Value * p.quantity).ToString("#,###", cul.NumberFormat) : (p.price * p.quantity).ToString("#,###", cul.NumberFormat) }; productGrid.Rows.Add(row); productGrid.Rows[i].ReadOnly = true; } } lblName.Text = "Table: " + newTable.name; lblTotal.Text = (newDetail.current_total ?? 0).ToString("#,###", cul.NumberFormat); lblDiscount.Text = (newDetail.current_total - newDetail.current_sale_total ?? 0).ToString("#,###", cul.NumberFormat); lblFinalTotal.Text = (newDetail.current_sale_total ?? 0).ToString("#,###", cul.NumberFormat); lblCreatedName.Text = newDetail.created_by_name != null ? "Created by: " + newDetail.created_by_name : ""; lblCreatedDate.Text = newDetail.created_at != null ? "Created at: " + newDetail.created_at : ""; lblExportTime.Text = newDetail.billing_at != null ? "Billing at: " + newDetail.billing_at : ""; }
public IActionResult makeOrder(string id, string address) { decimal totalPrice = 0; //make list of id's of his products and total price List <int> ids = new List <int>(); List <penddingOrder> penddings = context.penddingOrders.Select(x => x).ToList(); List <product> p = context.Products.Select(x => x).ToList(); foreach (var item in penddings) { if (item.user_id == id) { ids.Add(item.prod_id); foreach (var item2 in p) { if (item.prod_id == item2.productId) { totalPrice += item2.productPrice; } } } } //make order with user id order newOrder = new order { userId = id, orederDate = DateTime.Now, orderAddress = address, orderTotalPrice = totalPrice, orderStatus = "Open" }; context.orders.Add(newOrder); context.SaveChanges(); //id of order just created int o_id = newOrder.orderId; //make order items for order foreach (var item in ids) { product pr = context.Products.SingleOrDefault(x => x.productId == item); orderItem orderitem = new orderItem { orderId = o_id, productId = item, quantity = 1, subTotal = pr.productPrice }; context.orderItems.Add(orderitem); context.SaveChanges(); } //delete order from penndingOrder Because it aleady goes to order table foreach (var item in ids) { foreach (var item1 in penddings) { if (item == item1.prod_id) { penddingOrder pend = context.penddingOrders.Find(item1.pendingId); context.Remove(pend); context.SaveChanges(); } } } return(RedirectToAction("shoppingcart")); }
public void DeleteOrderItem(orderItem item) { var delta = -item.quantity; item.quantity = 0; // set to 0 so can detect deletions UpdateInventoryItem(item, delta); order.orderItems.Remove(item); }
public void AddOrderItem(orderItem oitem, products_digital digital) { order.orderItems.Add(oitem); // create digital entry if (digital != null) { var digitalOrderitem = new orderItems_digital(); digitalOrderitem.downloadid = Crypto.Utility.GetRandomString(); digitalOrderitem.downloadCount = 0; oitem.orderItems_digitals = digitalOrderitem; } }
public IHttpActionResult Postorder(order order) { try { //order.table if (order.orderID == 0) { db.orders.Add(order); } else { db.Entry(order).State = EntityState.Modified; } //order.items table foreach (var item in order.orderItems) { if (item.orderItemID == 0) { db.orderItems.Add(item); } else { db.Entry(item).State = EntityState.Modified; } } //Delete for OrderItems foreach (var id in order.deletedOrderItemIDs.Split(',').Where(x => x != "")) { orderItem x = db.orderItems.Find(Convert.ToInt64(id)); db.orderItems.Remove(x); } db.SaveChanges(); return(Ok()); //return CreatedAtRoute("DefaultApi", new { id = order.orderID }, order); } catch (Exception ex) { throw ex; } }
public ActionResult Edit(int idd, FormCollection frm) { List <basket> qsk = datas.baskets.Where(c => c.basketId == idd).ToList(); try { foreach (var item in qsk) { item.onay = Convert.ToInt32(frm["basliksec"]); } datas.SaveChanges(); if (Convert.ToInt32(frm["basliksec"]) == 1) { order ordr = new order(); ordr.date = DateTime.Now; ordr.uid = datas.baskets.Where(c => c.basketId == idd).FirstOrDefault().uid; ordr.status = 1; datas.orders.Add(ordr); datas.SaveChanges(); foreach (var item in qsk) { orderItem or = new orderItem(); or.oid = datas.orders.Max(u => u.id); or.pid = item.pid; or.piece = item.price; datas.orderItems.Add(or); datas.SaveChanges(); } } return(RedirectToAction("Index")); } catch { return(View()); } }
public IEnumerable <orderItem> GetOrderItemsByOrderId(IDbConnection conn, int id) { var cmd = conn.CreateCommand(); cmd.CommandText = $"SELECT * FROM dbo.OrderItems WHERE OrderId = {id}"; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var orderItem = new orderItem(); orderItem.Code = reader.GetString( reader.GetOrdinal(PropertyNameProvider.GetPropertyName(() => orderItem.Code))); orderItem.Description = reader.GetString( reader.GetOrdinal(PropertyNameProvider.GetPropertyName(() => orderItem.Description))); orderItem.Price = reader.GetFloat(reader.GetOrdinal(PropertyNameProvider.GetPropertyName(() => orderItem.Price))); yield return(orderItem); } } }
public ActionResult Save(string terms, long?id, long orderNumber, decimal?[] tax, long?[] itemid, int[] quantity, decimal[] unitPrice, string discount, string discountType, int currency, string shippingMethod, string shippingCost, long receiverOrgID, DateTime orderDate, long location, TransactionType type) { bool newOrder = !id.HasValue; var order_byOrderNumber = repository.GetOrderByOrderNumber(subdomainid.Value, type, orderNumber); Transaction transaction; if (!newOrder) { // update transaction = new Transaction(repository.GetOrder(subdomainid.Value, id.Value), repository, sessionid.Value); if (transaction.GetOrderStatus() != OrderStatus.DRAFT) { return(Json("Cannot edit sent orders".ToJsonFail())); } // verify that order or invoice number does not already exist if (order_byOrderNumber != null && order_byOrderNumber.id != id.Value) { var msg = string.Format("{0} Number #{1} already in use", type.ToDescriptionString(), orderNumber.ToString("D8")); return(SendJsonErrorResponse(msg)); } } else { if (accountLimits.invoices.HasValue && type == TransactionType.INVOICE) { var invoicesThisMonth = repository.GetMonthlyInvoiceCount(sessionid.Value); if (invoicesThisMonth >= accountLimits.invoices.Value) { return(SendJsonErrorResponse("Monthly invoice limit exceeded. Please upgrade your <a href=\"/dashboard/account/plan\">plan</a>.")); } } // create var receiver = repository.GetPrimaryUser(receiverOrgID); transaction = new Transaction(MASTERdomain, receiver, type, repository, sessionid.Value); transaction.CreateTransaction(orderNumber, orderDate.ToUniversalTime(), terms, currency); // verify that order or invoice number does not already exist if (order_byOrderNumber != null) { var msg = string.Format("{0} Number #{1} already in use", type.ToDescriptionString(), orderNumber.ToString("D8")); return(SendJsonErrorResponse(msg)); } } var posted_orderitems = new List <orderItem>(); if (itemid != null) { for (int i = 0; i < itemid.Length; i++) { var id_item = itemid[i]; if (!id_item.HasValue) { continue; } var item_quantity = quantity[i]; var unit_price = unitPrice[i]; var item = new orderItem() { quantity = item_quantity, unitPrice = unit_price, variantid = id_item.Value }; // invoice only if (tax != null) { item.tax = tax[i]; } // insert into order posted_orderitems.Add(item); } } if (posted_orderitems.Count == 0 || itemid == null) { return(Json("No items were specified".ToJsonFail())); } // update fields transaction.UpdateCurrency(currency); transaction.UpdateDiscount(discountType, discount); transaction.UpdateOrderNumber(orderNumber); transaction.UpdateShippingCost(shippingCost); transaction.UpdateShippingMethod(shippingMethod); transaction.UpdateTerms(terms); transaction.UpdateInventoryLocation(location); // email receiver of change if (transaction.GetOrderStatus() != OrderStatus.DRAFT) { var data = new ChangeHistory { documentType = type == TransactionType.INVOICE? ChangeHistoryType.INVOICE.ToDocumentType() : ChangeHistoryType.ORDERS.ToDocumentType(), documentName = transaction.GetOrderNumber(), documentLoc = accountHostname.ToDomainUrl(transaction.GetOrderLink()) }; var message = new Message(transaction.GetReceiver(), transaction.GetOwner(), subdomainid.Value); message.SendMessage(this, repository, EmailViewType.INVOICEORDER_CHANGED, data, data.documentType + " Updated", transaction.GetOrderLink()); } var variants = repository.GetProductVariants(subdomainid.Value).Where(x => itemid.Contains(x.id)); if (!newOrder) { // log activity repository.AddActivity(sessionid.Value, new ActivityMessage(transaction.GetID(), transaction.GetReceiver().id, type == TransactionType.ORDER? ActivityMessageType.ORDER_UPDATED : ActivityMessageType.INVOICE_UPDATED, new HtmlLink(transaction.GetOrderNumber(), transaction.GetID()).ToTransactionString(type)), subdomainid.Value); // handle deleted items first var orderItemsToDelete = transaction.GetOrderItems().Where(x => !itemid.Contains(x.variantid)).ToArray(); foreach (var entry in orderItemsToDelete) { var oitem = entry; transaction.DeleteOrderItem(oitem); } } // add order items foreach (var entry in posted_orderitems) { var variantid = entry.variantid; // try get from existing order var existingOrderitem = transaction.GetOrderItems().SingleOrDefault(x => x.variantid == variantid); int inventoryDelta; if (existingOrderitem == null) { // this is a new item so we need to add it var v = variants.Single(x => x.id == variantid); entry.description = v.ToProductFullTitle(); transaction.AddOrderItem(entry, v.product.products_digitals); inventoryDelta = entry.quantity; existingOrderitem = entry; } else { // get delta first inventoryDelta = entry.quantity - existingOrderitem.quantity; existingOrderitem.unitPrice = entry.unitPrice; existingOrderitem.quantity = entry.quantity; existingOrderitem.tax = entry.tax; } transaction.UpdateInventoryItem(existingOrderitem, inventoryDelta); } transaction.UpdateTotal(); if (!newOrder) { transaction.SaveUpdatedTransaction(); } else { transaction.SaveNewTransaction(); } return(Json(transaction.GetID().ToJsonOKData())); }
// json is true when checkout is done from an iframe, eg. facebook page public ActionResult create(CheckoutStatus status, string shippingmethod, string paymentmethod, bool isJson = false) { Debug.Assert(!cart.orderid.HasValue); var shop_owner = cart.MASTERsubdomain.organisation.users.First(); var currency = cart.MASTERsubdomain.currency.ToCurrency(); var buyer = cart.user; var transaction = new Transaction(cart.MASTERsubdomain, buyer, TransactionType.INVOICE, repository, sessionid.Value); transaction.CreateTransaction( repository.GetNewOrderNumber(subdomainid.Value, TransactionType.INVOICE), DateTime.UtcNow, cart.MASTERsubdomain.paymentTerms, currency.id); // mark as sent transaction.UpdateOrderStatus(OrderStatus.SENT); var shoppingcart = new ShoppingCart(currency.code) { shippingMethod = shippingmethod }; foreach (var item in cart.cartitems) { var checkOutItem = item.product_variant.ToCheckoutItem(item.quantity, sessionid); var orderItem = new orderItem { description = item.product_variant.ToProductFullTitle(), variantid = item.product_variant.id, unitPrice = item.product_variant.product.ToUserPrice(cart.userid.Value), tax = item.product_variant.product.tax, quantity = item.quantity }; transaction.AddOrderItem(orderItem, item.product_variant.product.products_digitals); // update inventory transaction.UpdateInventoryItem(orderItem, item.quantity); shoppingcart.items.Add(checkOutItem); } if (!cart.isDigitalOrder()) { shoppingcart.CalculateShippingCost(cart.cartitems.Select(x => x.product_variant).AsQueryable(), cart.MASTERsubdomain, buyer); if (cart.cartitems.Select(x => x.product_variant.product.shippingProfile).UseShipwire()) { transaction.UpdateShippingMethod(shoppingcart.shipwireShippingName, shoppingcart.shippingMethod); } else { transaction.UpdateShippingMethod(shoppingcart.shippingMethod); } } transaction.UpdateTotal(cart.coupon); transaction.SaveNewTransaction(); ////////////////////// SAVE INVOICE repository.AddActivity(buyer.id, new ActivityMessage(transaction.GetID(), shop_owner.id, ActivityMessageType.INVOICE_NEW, new HtmlLink(transaction.GetOrderNumber(), transaction.GetID()).ToTransactionString(TransactionType.INVOICE)), subdomainid.Value); // add checkout note as a comment if (!string.IsNullOrEmpty(cart.note)) { transaction.AddComment(cart.note, cart.userid.Value); } // add comment if shipping method not specified if (!transaction.HasShippingMethod() && !cart.isDigitalOrder()) { transaction.AddComment(OrderComment.SHIPPING_WAIT_FOR_COST); } // set cart as processed cart.orderid = transaction.GetID(); // save payment method if (!string.IsNullOrEmpty(paymentmethod)) { switch (paymentmethod) { case "paypal": cart.paymentMethod = PaymentMethodType.Paypal.ToString(); break; default: cart.paymentMethod = PaymentMethodType.Custom.ToString(); cart.paymentCustomId = long.Parse(paymentmethod); break; } } repository.Save(); // send emails // send mail to buyer var buyerEmailContent = new OrderReceipt() { viewloc = cart.MASTERsubdomain.ToHostName().ToDomainUrl(transaction.GetOrderLink()), shopname = cart.MASTERsubdomain.storeName, date = transaction.GetOrderDate().ToShortDateString(), shippingAddress = transaction.GetShippingAddress().ToHtmlString(), billingAddress = transaction.GetBillingAddress().ToHtmlString(), subtotal = string.Format("{0}{1}", currency.symbol, transaction.GetSubTotal().ToString("n" + currency.decimalCount)), shippingcost = string.Format("{0}{1}", currency.symbol, transaction.GetShippingCost().ToString("n" + currency.decimalCount)), discount = string.Format("{0}{1}", currency.symbol, transaction.GetDiscount().ToString("n" + currency.decimalCount)), totalcost = string.Format("{0}{1}{2}", currency.code, currency.symbol, transaction.GetTotal().ToString("n" + currency.decimalCount)), orderitems = transaction .GetOrderItems() .Select(x => string.Format("{0} x {1}{2} {3}", x.quantity, currency.symbol, x.unitPrice.Value.ToString("n" + currency.decimalCount), x.description)) }; // send mail to seller var sellerEmailContent = new NewOrderEmailContent { viewloc = cart.MASTERsubdomain.ToHostName().ToDomainUrl(transaction.GetOrderLink()), sender = buyer.organisation1.name }; string buyer_subject; string seller_subject; switch (status) { case CheckoutStatus.SHIPPING_FAIL: buyer_subject = string.Format("[{0}]Invoice #{1}", cart.MASTERsubdomain.name, transaction.GetOrderNumber()); seller_subject = string.Format("[{0}]New Invoice #{1} : ACTION REQUIRED", cart.MASTERsubdomain.name, transaction.GetOrderNumber()); buyerEmailContent.message = "Thank you for placing an order with us. Unfortunately, we are not able to provide a shipping cost at this moment. We will contact you once we have the shipping costs. You can check the status of your order by following the link below:"; sellerEmailContent.message = "A customer has placed an order on your online store. However, the shipping cost could not be calculated. You will need to manually update the invoice with the shipping cost. To update the invoice, follow the link below:"; break; case CheckoutStatus.SHIPPING_NONE: case CheckoutStatus.SHIPPING_OK: buyer_subject = string.Format("[{0}]Invoice #{1} confirmed", cart.MASTERsubdomain.name, transaction.GetOrderNumber()); seller_subject = string.Format("[{0}]New Invoice #{1}", cart.MASTERsubdomain.name, transaction.GetOrderNumber()); if (cart.isDigitalOrder()) { buyerEmailContent.message = "Download links will be provided once payment is confirmed"; } sellerEmailContent.message = "A customer has placed an order on your online store. To view the invoice, follow the link below:"; break; default: throw new ArgumentOutOfRangeException("status"); } this.SendEmail(EmailViewType.INVOICEORDER_NEW, sellerEmailContent, seller_subject, shop_owner.GetEmailAddress(), shop_owner.ToFullName(), buyer); this.SendEmail(EmailViewType.ORDER_RECEIPT, buyerEmailContent, buyer_subject, buyer.GetEmailAddress(), buyer.ToFullName(), shop_owner); // handle payment string redirecturl = ""; if (!string.IsNullOrEmpty(paymentmethod)) { switch (paymentmethod) { case "paypal": string returnUrl; if (isJson) { returnUrl = string.Format("{0}/checkout/order/{1}/close", GeneralConstants.HTTP_SECURE, cart.id); } else { returnUrl = string.Format("{0}/checkout/order/{1}", GeneralConstants.HTTP_SECURE, cart.id); } var pworker = new PaypalWorker(cart.id.ToString(), transaction, repository, cart.MASTERsubdomain.GetPaypalID(), transaction.GetCurrency().id, returnUrl); try { redirecturl = pworker.GetPaymentUrl(); } catch (Exception ex) { Syslog.Write(ex); return(RedirectToAction("Index", "Error")); } break; default: break; } } if (!string.IsNullOrEmpty(redirecturl)) { return(Redirect(redirecturl)); } if (isJson) { return(View("close")); } return(RedirectToAction("Index")); }
private void SaveEbayOrders(OrderTypeCollection collection) { using (var repository = new TradelrRepository()) { foreach (OrderType entry in collection) { Transaction transaction; // check if order already exists var existingEbayOrder = repository.GetSubDomain(sd.id).ebay_orders.SingleOrDefault(x => x.orderid == entry.OrderID); if (existingEbayOrder != null) { var order = existingEbayOrder.orders.Single(); transaction = new Transaction(order, repository, seller.id); // update order status existingEbayOrder.status = entry.OrderStatus.ToString(); } else { // check if user already exists var buyer = repository.GetUserByEbayID(entry.BuyerUserID); if (buyer == null) { // get receiver and add to contact db var userService = new UserService(token); // get by itemid as invalid request seems to be returned when get by userid var ebaybuyer = userService.GetUser(entry.BuyerUserID); // we assume that same buyer for all transactions so we get the first email address var buyeremail = entry.TransactionArray.ItemAt(0).Buyer.Email; buyer = SaveEbayBuyer(ebaybuyer, buyeremail); } // add a shipping and billing address if (entry.ShippingAddress != null) { var buyername = Utility.SplitFullName(entry.ShippingAddress.Name); var handler = new AddressHandler(buyer.organisation1, repository); handler.SetShippingAndBillingAddresses(buyername[0], buyername[1], entry.ShippingAddress.CompanyName ?? "", entry.ShippingAddress.Street1 + "\r\n" + entry.ShippingAddress.Street2, entry.ShippingAddress.CityName, null, entry.ShippingAddress.PostalCode, entry.ShippingAddress.Phone, entry.ShippingAddress.Country.ToString().ToCountry().id, entry.ShippingAddress.StateOrProvince, entry.ShippingAddress.StateOrProvince, entry.ShippingAddress.StateOrProvince, buyername[0], buyername[1], entry.ShippingAddress.CompanyName ?? "", entry.ShippingAddress.Street1 + "\r\n" + entry.ShippingAddress.Street2, entry.ShippingAddress.CityName, null, entry.ShippingAddress.PostalCode, entry.ShippingAddress.Phone, entry.ShippingAddress.Country.ToString().ToCountry().id, entry.ShippingAddress.StateOrProvince, entry.ShippingAddress.StateOrProvince, entry.ShippingAddress.StateOrProvince, true); } // add normal order transaction = new Transaction(sd, buyer, TransactionType.INVOICE, repository, seller.id); transaction.CreateTransaction(repository.GetNewOrderNumber(sd.id, TransactionType.INVOICE), entry.CreatedTime, "", entry.AmountPaid.currencyID.ToString().ToCurrency().id); // mark as sent var tradelr_orderstatus = GetOrderStatus(entry.OrderStatus); transaction.UpdateOrderStatus(tradelr_orderstatus); // add ebay specific order information var newEbayOrder = new ebay_order(); newEbayOrder.orderid = entry.OrderID; newEbayOrder.status = entry.OrderStatus.ToString(); newEbayOrder.created = entry.CreatedTime; newEbayOrder.subdomainid = sd.id; transaction.AddEbayOrderInformation(newEbayOrder); foreach (eBay.Service.Core.Soap.TransactionType trans in entry.TransactionArray) { var ebay_itemid = trans.Item.ItemID; // get product details var itemservice = new ItemService(token); var item = itemservice.GetItem(ebay_itemid); // add new product if necessary var existingproduct = repository.GetProducts(sd.id).SingleOrDefault(x => x.ebayID.HasValue && x.ebay_product.ebayid == ebay_itemid); if (existingproduct == null) { // add new product (triggered when synchronisation is carried out the first time) var newproduct = new Listing(); newproduct.Populate(item); var importer = new ProductImport(); var pinfo = importer.ImportEbay(newproduct, sd.id); repository.AddProduct(pinfo, sd.id); existingproduct = pinfo.p; } else { // if existing product is completed then we need to relist if (entry.OrderStatus == OrderStatusCodeType.Completed || entry.OrderStatus == OrderStatusCodeType.Shipped) { // see if product listing is still active if (item.SellingStatus.ListingStatus == ListingStatusCodeType.Completed || item.SellingStatus.ListingStatus == ListingStatusCodeType.Ended) { // set status to inactive existingproduct.ebay_product.isActive = false; // check if we should autorelist if (existingproduct.ebay_product.autorelist) { // check that product has enough stock if (existingproduct.HasStock(existingproduct.ebay_product.quantity)) { var exporter = new EbayExporter( existingproduct.ebay_product.siteid.ToEnum <SiteCodeType>(), sd.ToHostName(), token, sd); exporter.BuildItem(existingproduct.ebay_product); } } } } } // add tradelr order item var orderItem = new orderItem { description = item.Title, variantid = existingproduct.product_variants[0].id, unitPrice = (decimal)trans.TransactionPrice.Value, quantity = trans.QuantityPurchased }; if (trans.Taxes != null) { orderItem.tax = (decimal)(trans.Taxes.TotalTaxAmount.Value / trans.TransactionPrice.Value); } transaction.AddOrderItem(orderItem, null); // update inventory transaction.UpdateInventoryItem(orderItem, trans.QuantityPurchased); // add ebay order item var ebayorderitem = new ebay_orderitem(); ebayorderitem.lineid = trans.OrderLineItemID; newEbayOrder.ebay_orderitems.Add(ebayorderitem); } // update shipping transaction.UpdateShippingCost(entry.ShippingServiceSelected.ShippingServiceCost.Value.ToString()); transaction.UpdateShippingMethod(entry.ShippingServiceSelected.ShippingService); // update tax : ebay tax is the shipping tax which applies to the entire order total // may or may not include shipping cost if (entry.ShippingDetails.SalesTax != null) { transaction.UpdateOrderTax((decimal)entry.ShippingDetails.SalesTax.SalesTaxPercent, entry.ShippingDetails.SalesTax.ShippingIncludedInTax); } transaction.UpdateTotal(); transaction.SaveNewTransaction(); ////////////////////// SAVE INVOICE } // the following applies to both new and existing order var existingPayment = transaction.GetPayments().SingleOrDefault(x => x.reference == entry.OrderID); if (existingPayment != null) { var newstatus = GetPaymentStatus(entry.CheckoutStatus.Status); if (existingPayment.status != newstatus.ToString()) { transaction.UpdatePaymentStatus(existingPayment, newstatus); } } else { // if payment has been made then add payment if (entry.CheckoutStatus.Status == CompleteStatusCodeType.Complete) { var p = new DBML.payment(); p.status = GetPaymentStatus(entry.CheckoutStatus.Status).ToString(); p.method = entry.CheckoutStatus.PaymentMethod.ToString(); p.created = entry.CheckoutStatus.LastModifiedTime; p.notes = entry.BuyerCheckoutMessage; p.paidAmount = (decimal)entry.AmountPaid.Value; p.reference = entry.OrderID; transaction.AddPayment(p, false); } } // if there is a shipped date, mark as ship if not already done so if (transaction.GetOrderStatus() != OrderStatus.SHIPPED && entry.ShippedTimeSpecified) { transaction.UpdateOrderStatus(OrderStatus.SHIPPED); if (entry.ShippingDetails.ShipmentTrackingDetails.Count != 0) { foreach (ShipmentTrackingDetailsType trackentry in entry.ShippingDetails.ShipmentTrackingDetails) { var comment = string.Format(OrderComment.ORDER_SHIP_STANDARD, trackentry.ShippingCarrierUsed, trackentry.ShipmentTrackingNumber); transaction.AddComment(comment); } } else { transaction.AddComment(OrderComment.ORDER_SHIP, created: entry.ShippedTime); } } repository.Save(); // save per order } } }
public void UpdateInventoryItem(orderItem orderItem, int inventoryDelta) { // no need for updates if delta is zero if (inventoryDelta == 0) { return; } inventoryLocation location; // throws null if we just check on value. happens when creating a new order if (orderItem.order.inventoryLocation1 != null) { location = orderItem.order.inventoryLocation1; } else { if (orderItem.order.inventoryLocation.HasValue) { location = repository.GetInventoryLocation(orderItem.order.inventoryLocation.Value, senderDomain.id); } else { location = repository.GetInventoryLocation(GeneralConstants.INVENTORY_LOCATION_DEFAULT, senderDomain.id); } } inventoryLocationItem locationItem; bool trackInventory; bool isDigital; if (orderItem.product_variant == null) { var variant = repository.GetProductVariant(orderItem.variantid, senderDomain.id); locationItem = variant.inventoryLocationItems.SingleOrDefault(x => x.locationid == location.id); trackInventory = variant.product.trackInventory; isDigital = variant.IsDigital(); } else { locationItem = orderItem.product_variant.inventoryLocationItems.SingleOrDefault(x => x.locationid == location.id); trackInventory = orderItem.product_variant.product.trackInventory; isDigital = orderItem.product_variant.IsDigital(); } if (locationItem == null) { locationItem = new inventoryLocationItem { locationid = location.id, lastUpdate = DateTime.UtcNow }; if (orderItem.product_variant == null) { var variant = repository.GetProductVariant(orderItem.variantid, senderDomain.id); variant.inventoryLocationItems.Add(locationItem); } else { orderItem.product_variant.inventoryLocationItems.Add(locationItem); } } var isNewEntry = orderItem.id == 0; var isDelete = orderItem.quantity == 0; var invWorker = new InventoryWorker(locationItem, senderDomain.id, trackInventory, isDigital); var description = order.ToHtmlLink(); switch (GetOrderStatus()) { case OrderStatus.DRAFT: if (isNewEntry) { description += " created"; } else if (isDelete) { description += string.Format(": {0} deleted", orderItem.product_variant.ToHtmlLink()); } else { description += " updated"; } if (transactionType == TransactionType.INVOICE) { invWorker.SetValues(description, -inventoryDelta, // available null, // on order inventoryDelta, // reserved null); // sold } else { invWorker.SetValues(description, null, // available inventoryDelta, // on order null, // reserved null); // sold } break; case OrderStatus.SENT: if (transactionType == TransactionType.INVOICE) { if (isNewEntry) { invWorker.SetValues(order.ToHtmlLink() + " created", -inventoryDelta, // available null, // on order inventoryDelta, // reserved null); // sold } } else { if (isNewEntry) { invWorker.SetValues(order.ToHtmlLink() + " created", null, // available inventoryDelta, // on order null, // reserved null); // sold } } break; case OrderStatus.VIEWED: break; case OrderStatus.PARTIAL: break; case OrderStatus.PAID: if (transactionType == TransactionType.INVOICE) { if (isNewEntry) { throw new NotImplementedException(); } else { invWorker.SetValues(order.ToHtmlLink() + " paid", null, // available null, // on order -inventoryDelta, // reserved inventoryDelta); // sold } } break; case OrderStatus.SHIPPED: if (transactionType == TransactionType.ORDER) { if (isNewEntry) { throw new NotImplementedException(); } else { invWorker.SetValues(order.ToHtmlLink() + " received", inventoryDelta, // available -inventoryDelta, // on order null, // reserved null); // sold } } break; default: throw new ArgumentOutOfRangeException("status"); } }
public ActionResult DomainOrder(bool id_theft, string plans, string domain_name, string domain_ext) { // check that domain extension is supported if (!SupportedTLD.Extensions.Contains(domain_ext)) { throw new NotImplementedException(); } // get buyer var buyer = repository.GetUserById(sessionid.Value, subdomainid.Value); // check that user has all relevant fields filled up if (string.IsNullOrEmpty(buyer.firstName) || string.IsNullOrEmpty(buyer.lastName) || string.IsNullOrEmpty(buyer.organisation1.name) || string.IsNullOrEmpty(buyer.organisation1.address) || !buyer.organisation1.city.HasValue || string.IsNullOrEmpty(buyer.organisation1.state) || string.IsNullOrEmpty(buyer.organisation1.postcode) || !buyer.organisation1.country.HasValue || string.IsNullOrEmpty(buyer.organisation1.phone) || string.IsNullOrEmpty(buyer.email)) { return(Json("Please ensure that your personal & organisation details are complete".ToJsonFail())); } // get clear pixels domain var clearpixeldomain = repository.GetSubDomains().Single(x => x.name == "clearpixels"); var transaction = new Transaction(clearpixeldomain, buyer, TransactionType.INVOICE, repository, sessionid.Value); var ordernumber = repository.GetNewOrderNumber(clearpixeldomain.id, TransactionType.INVOICE); transaction.CreateTransaction(ordernumber, DateTime.UtcNow, "", CurrencyHelper.GetCurrencies().Single(x => x.code == "USD").id); transaction.UpdateOrderStatus(OrderStatus.SENT); // define id_theft order item var idtheft_variant = repository.GetProductVariant("id_theft", clearpixeldomain.id, null); var idtheft_orderitem = new orderItem() { description = idtheft_variant.product.title, variantid = idtheft_variant.id, unitPrice = idtheft_variant.product.sellingPrice, tax = idtheft_variant.product.tax }; int numberOfYears; product_variant variant; switch (plans) { case "one_year": variant = repository.GetProductVariant("one_year", clearpixeldomain.id, null); if (variant == null) { throw new NotImplementedException(); } numberOfYears = 1; break; case "two_year": variant = repository.GetProductVariant("two_year", clearpixeldomain.id, null); if (variant == null) { throw new NotImplementedException(); } numberOfYears = 2; break; case "five_year": variant = repository.GetProductVariant("five_year", clearpixeldomain.id, null); if (variant == null) { throw new NotImplementedException(); } numberOfYears = 5; break; case "ten_year": variant = repository.GetProductVariant("ten_year", clearpixeldomain.id, null); if (variant == null) { throw new NotImplementedException(); } numberOfYears = 10; break; default: throw new NotImplementedException(); } var orderitem = new orderItem() { description = string.Format("{0}{1} {2}", domain_name, domain_ext, variant.product.title), variantid = variant.id, unitPrice = variant.product.sellingPrice, tax = variant.product.tax, quantity = numberOfYears }; transaction.AddOrderItem(orderitem, null); if (id_theft) { idtheft_orderitem.quantity = numberOfYears; transaction.AddOrderItem(idtheft_orderitem, null); } // update order total transaction.UpdateTotal(); transaction.SaveNewTransaction(); // send email to seller Syslog.Write(string.Format("{0}{1} bought by subdomainid {2}", domain_name, domain_ext, subdomainid.Value)); // handle payment var uniqueid = string.Format("{0}{1}", domain_name, domain_ext); var pworker = new PaypalWorker(uniqueid, transaction, repository, clearpixeldomain.GetPaypalID(), transaction.GetCurrency().id, accountHostname.ToDomainUrl("/dashboard/account/DomainProcess?d=" + uniqueid)); var redirecturl = pworker.GetPaymentUrl(); return(Json(redirecturl.ToJsonOKData())); }
public ActionResult SSLOrder(string plans_ssl) { // get buyer var buyer = repository.GetUserById(sessionid.Value, subdomainid.Value); // check that user has all relevant fields filled up if (string.IsNullOrEmpty(buyer.firstName) || string.IsNullOrEmpty(buyer.lastName) || string.IsNullOrEmpty(buyer.organisation1.name) || string.IsNullOrEmpty(buyer.organisation1.address) || !buyer.organisation1.city.HasValue || string.IsNullOrEmpty(buyer.organisation1.state) || string.IsNullOrEmpty(buyer.organisation1.postcode) || !buyer.organisation1.country.HasValue || string.IsNullOrEmpty(buyer.organisation1.phone) || string.IsNullOrEmpty(buyer.email)) { return(Json("Please ensure that your personal & organisation details are complete".ToJsonFail())); } // get clear pixels domain var clearpixeldomain = repository.GetSubDomains().Single(x => x.name == "clearpixels"); var transaction = new Transaction(clearpixeldomain, buyer, TransactionType.INVOICE, repository, sessionid.Value); var ordernumber = repository.GetNewOrderNumber(clearpixeldomain.id, TransactionType.INVOICE); transaction.CreateTransaction(ordernumber, DateTime.UtcNow, "", CurrencyHelper.GetCurrencies().Where(x => x.code == "USD").Single().id); transaction.UpdateOrderStatus(OrderStatus.SENT); var variant = repository.GetProductVariant(plans_ssl, clearpixeldomain.id, null); var orderitem = new orderItem() { description = variant.product.title, variantid = variant.id, unitPrice = variant.product.sellingPrice, tax = variant.product.tax, quantity = 1 }; transaction.AddOrderItem(orderitem, null); // update order total transaction.UpdateTotal(); transaction.SaveNewTransaction(); // send email to seller Syslog.Write(string.Format("{0} bought by subdomainid {1}", plans_ssl, subdomainid.Value)); // handle payment var uniqueid = string.Format("{0}:{1}", accountSubdomainName, plans_ssl); var pworker = new PaypalWorker(uniqueid, transaction, repository, clearpixeldomain.GetPaypalID(), transaction.GetCurrency().id, accountHostname.ToDomainUrl("/dashboard/account/SSLProcess?d=" + plans_ssl)); var redirecturl = pworker.GetPaymentUrl(); return(Json(redirecturl.ToJsonOKData())); }