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 } } }
private void Update() { if (string.IsNullOrEmpty(warehouse)) { Syslog.Write(string.Format("Shipwire warehouse not specified: {0}", subdomainid)); return; } service.CreateInventoryUpdate(warehouse); var resp = service.SubmitInventoryUpdate(); if (resp != null) { // check for Error if (resp.Status == ShipwireService.StatusError && resp.ErrorMessage.ToLower().Contains("password")) { // clear invalid credentials using (var repository = new TradelrRepository()) { var sd = repository.GetSubDomain(subdomainid); if (sd != null) { sd.shipwireEmail = ""; sd.shipwirePassword = ""; repository.Save(); } } } // we want to create a location only if there are products if (resp.Products.Count != 0) { Debug.WriteLine(string.Format("{0}: {1} products", warehouse, resp.Products.Count)); using (var repository = new TradelrRepository()) { // if items not zero then we create inventory location if it does not already exist var inventoryloc = new inventoryLocation { subdomain = subdomainid, name = warehouse, lastUpdate = DateTime.UtcNow }; var locid = repository.AddInventoryLocation(inventoryloc, subdomainid); // we go through each product foreach (var product in resp.Products) { var variant = repository.GetProductVariant(product.code, subdomainid, ProductFlag.ARCHIVED); // if product exist and not archived if (variant != null) { Debug.WriteLine("Existing product: " + product.code); // then we just update the inventorylocitem var ilocitem = repository.GetInventoryLocationItems(locid, subdomainid).SingleOrDefault(x => x.variantid == variant.id); if (ilocitem == null) { // can be null from do these updates from Shipwire as we're doing on a per location basis // anyway create an entry ilocitem = new inventoryLocationItem { variantid = variant.id, locationid = locid, lastUpdate = DateTime.UtcNow, available = product.quantity }; repository.AddInventoryLocationItem(ilocitem, subdomainid); } else { // just update as this is a sync ilocitem.available = product.quantity; ilocitem.lastUpdate = DateTime.UtcNow; repository.Save("InventoryUpdate Update"); } } else { Debug.WriteLine("New product: " + product.code); // create new product var productInfo = new ProductInfo(); // do product var p = new product { subdomainid = subdomainid, title = product.code, details = "", created = DateTime.UtcNow }; productInfo.p = p; variant = new product_variant(); variant.sku = product.code; // do inventory location item var ilocitem = new inventoryLocationItem { variantid = variant.id, locationid = locid, lastUpdate = DateTime.UtcNow }; var invWorker = new InventoryWorker(ilocitem, subdomainid, true, false); // assume not digital invWorker.SetValues("Shipwire Update", product.quantity, null, null, null); variant.inventoryLocationItems.Add(ilocitem); productInfo.p.product_variants.Add(variant); // finally add to db repository.AddProduct(productInfo, subdomainid); } } } } else { //Syslog.Write(ErrorLevel.WARNING,string.Format("{0}: No products", warehouse)); } } else { Syslog.Write("No response from warehouse " + warehouse); } }
public override void StartSynchronisation(bool?upload) { // pull items var gbase = new GoogleBaseExporter(subdomainid, hostName, sessionid); gbase.GetAllProducts(); using (var repository = new TradelrRepository()) { // create network location var inventoryLocation = new inventoryLocation { name = LOCATIONNAME_GBASE, subdomain = subdomainid, lastUpdate = DateTime.UtcNow }; locationid = repository.AddInventoryLocation(inventoryLocation, subdomainid); // init some settings locationid = repository.GetInventoryLocation(LOCATIONNAME_GBASE, subdomainid).id; currency = repository.GetSubDomain(subdomainid).currency.ToCurrency(); var products = repository.GetProducts(subdomainid); foreach (var entry in gbase.entries) { ProductEntry entry1 = entry; var oldTypeEntry = products.SingleOrDefault(x => x.gbaseID == entry1.Id.AbsoluteUri); if (oldTypeEntry != null) { // old type entry exists // remove id oldTypeEntry.gbaseID = null; // create gbase entry, don't need to create a variant since one would already exist oldTypeEntry.gbase_product = CreateGbaseInformationEntry(entry); } else { var newtypeEntry = products.Where(x => x.gbase_product.externalid == entry1.Id.AbsoluteUri).Select( x => x.gbase_product).SingleOrDefault(); if (newtypeEntry != null) { // new type entry exists // update status newtypeEntry.expirydate = entry.ExpirationDate; if (entry.IsDraft) { newtypeEntry.flags |= (int)InventoryItemFlag.DRAFT; } else { newtypeEntry.flags &= ~(int)InventoryItemFlag.DRAFT; } } else { // entry does not exist // create and add entry to tradelr var p = CreateProductFromEntry(entry); // create variant var variants = new List <product_variant>(); var variant = new product_variant() { sku = string.Concat("GBASE", entry.Id.AbsoluteUri.Substring( entry.Id.AbsoluteUri.LastIndexOf('/') + 1)) }; variants.Add(variant); // add gbase info p.gbase_product = CreateGbaseInformationEntry(entry); p.product_variants.AddRange(variants); var pinfo = new ProductInfo() { p = p }; repository.AddProduct(pinfo, subdomainid); // images foreach (var link in entry.AdditionalImageLinks) { var image = link.Value.ReadAndSaveProductImageFromUrl(subdomainid, sessionid, p.id); p.thumb = image.id; } } } } // upload to google base for each entry that does not have a special entry if (upload.HasValue && upload.Value) { var newproducts = repository.GetProducts(subdomainid).Where( x => !x.gbase.HasValue && (x.flags & (int)ProductFlag.ARCHIVED) == 0); foreach (var p in newproducts) { var gb = new GoogleBaseExporter(subdomainid, hostName, sessionid); gb.InitValues(p); #if !DEBUG IEnumerable <Photo> productPhotos = repository.GetImages(PhotoType.PRODUCT, p.id).ToModel(Imgsize.LARGE); gb.AddProductImages(productPhotos); #endif var worker = new GoogleBaseWorker(gb); new Thread(worker.Post).Start(); } } // save repository.Save(); } }