예제 #1
0
 public IActionResult AddEdit(int productId, int importId)
 {
     if (productId <= 0)
     {
         return(RedirectToAction("Listing", "Product"));
     }
     if (productId > 0)
     {
         var pro = _productService.GetFullProductById(productId);
         if (pro != null)
         {
             var model = new ProductImport();
             model.ProductId = productId;
             ViewBag.Product = pro;
             if (importId > 0)
             {
                 model = _importService.Get(importId);
             }
             else
             {
                 model.ImportDate = DateTime.Now;
             }
             return(View(model));
         }
     }
     return(RedirectToAction("Listing", "Product"));
 }
예제 #2
0
        public ActionResult ImportCollection(FBImportCollection collection)
        {
            var importer   = new ProductImport();
            var pinfos     = new List <ProductInfo>();
            var resultlist = new List <ImportResult>();

            foreach (var product in collection.products)
            {
                // check if product has already been imported
                var fbid  = product.id;
                var count =
                    repository.GetProducts(subdomainid.Value).SelectMany(x => x.facebook_imports).Where(
                        y => y.facebookID == fbid).Count();
                if (count != 0)
                {
                    var result = new ImportResult
                    {
                        id      = product.id.ToString(),
                        message = "already imported",
                        success = false
                    };
                    resultlist.Add(result);
                }
                else
                {
                    var pinfo = importer.ImportFacebook(product, collection.access_token, subdomainid.Value);
                    pinfos.Add(pinfo);
                    var result = new ImportResult
                    {
                        id      = product.id.ToString(),
                        success = true
                    };
                    resultlist.Add(result);
                }
            }

            // add collection
            var pcollection = new product_collection {
                name = collection.title, subdomainid = subdomainid.Value
            };

            if (resultlist.Select(x => x.success).Count() > 0)
            {
                // some products to add so we add collection
                var collectionid = repository.AddProductCollection(pcollection, subdomainid.Value);

                // update products to add with collection id
                foreach (var productInfo in pinfos)
                {
                    var pmember = new productCollectionMember();
                    pmember.collectionid = collectionid;
                    productInfo.p.productCollectionMembers.Add(pmember);
                }
            }

            repository.AddProducts(pinfos, subdomainid.Value);
            return(Json(resultlist.ToJsonOKData()));
        }
예제 #3
0
파일: ImportService.cs 프로젝트: 1412579/PM
 public bool Update(ProductImport model)
 {
     try
     {
         _importRepository.Update(model);
         _unitOfWork.SaveChange();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
예제 #4
0
파일: ImportService.cs 프로젝트: 1412579/PM
 public bool Create(ProductImport model)
 {
     try
     {
         _importRepository.Add(model);
         _unitOfWork.SaveChange();
         return(true);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
예제 #5
0
        public ActionResult ImportProduct(FBImportSingle sproduct)
        {
            // check if product has already been imported
            var count =
                repository.GetProducts(subdomainid.Value).SelectMany(x => x.facebook_imports).Count(y => y.facebookID == sproduct.product.id);

            if (count != 0)
            {
                return(Json("Product has already been imported".ToJsonFail()));
            }
            var importer = new ProductImport();
            var pinfo    = importer.ImportFacebook(sproduct.product, sproduct.access_token, subdomainid.Value);

            repository.AddProduct(pinfo, subdomainid.Value);
            return(Json(sproduct.product.id.ToJsonOKData()));
        }
예제 #6
0
        public ActionResult CancelImport(int model)
        {
            if (ModelState.IsValid)
            {
                ProductImport import = db.ProductImports.Find(model);
                import.Status = ImportStatus.Cancelled;

                foreach (ImportDetail detail in import.ImportDetails)
                {
                    db.Products.Find(detail.ProductId).InStock -= detail.Quantity;
                }
                db.SaveChanges();
                return(Json("Hủy phiếu nhập hàng thành công"));
            }
            return(Json("Có lỗi khi hủy phiếu nhập hàng"));
        }
예제 #7
0
        public ActionResult AddImport(ProductImport model)
        {
            if (ModelState.IsValid)
            {
                db.ProductImports.Add(model);
                db.SaveChanges();

                foreach (ImportDetail detail in model.ImportDetails)
                {
                    db.Products.Find(detail.ProductId).InStock += detail.Quantity;
                }
                db.SaveChanges();

                return(Json("Lập phiếu nhập thành công"));
            }
            return(Json("Lập phiếu nhập thất bại"));
        }
예제 #8
0
        public IActionResult AddEdit(ProductImport model)
        {
            if (ModelState.IsValid)
            {
                ViewBag.Product = _productService.GetFullProductById(model.ProductId);
                var isValid = false;
                var msg     = "";
                var IsEdit  = model.ImportId > 0;
                if (IsEdit)
                {
                    var pro = _importService.Get(model.ImportId);
                    if (pro != null)
                    {
                        pro.ImportFrom  = model.ImportFrom;
                        pro.Price       = model.Price;
                        pro.Quantity    = model.Quantity;
                        pro.ImportDate  = DateTime.Now;
                        pro.Description = model.Description;
                        isValid         = _importService.Update(pro);
                        msg             = "Đã cập nhật đơn nhập thành công!";
                    }
                }
                else
                {
                    isValid = _importService.Create(model);
                    msg     = "Đã tạo đơn nhập thành công!";
                }

                if (isValid)
                {
                    ViewBag.Msg = msg;
                    ModelState.Remove("InvalidAuth");
                    if (!IsEdit)
                    {
                        model = new ProductImport();
                    }
                }
                else
                {
                    ModelState.AddModelError("InvalidAuth", "Đã có lỗi xảy ra, liên hệ IT.");
                }

                return(View(model));
            }
            return(View(model));
        }
예제 #9
0
 protected void sqlInsert(ProductImport product)
 {
     using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionloja"].ConnectionString))
     {
         string sql = "INSERT INTO products([title], [description], [posted], [published], [id_category], [stock_status], [price]) VALUES (@title, @description, @posted, @published, @id_category, @stock_status, @price)";
         using (SqlCommand cmd = new SqlCommand(sql, con))
         {
             con.Open();
             try
             {
                 bool status = false;
                 if (product.Stock > 0)
                 {
                     status = true;
                 }
                 else if (product.Stock == 0)
                 {
                     status = false;
                 }
                 DateTime   date   = DateTime.Now;
                 SqlCommand cmdIns = new SqlCommand(sql, con);
                 cmdIns.Parameters.Add("@title", product.Title);
                 cmdIns.Parameters.Add("@description", product.Description);
                 cmdIns.Parameters.Add("@posted", date);
                 cmdIns.Parameters.Add("@published", false);
                 cmdIns.Parameters.Add("@id_category", product.Category);
                 cmdIns.Parameters.Add("@stock_status", status);
                 cmdIns.Parameters.Add("@price", product.Price);
                 cmdIns.ExecuteNonQuery();
                 cmdIns.Dispose();
                 cmdIns = null;
             }
             catch (Exception ex)
             {
                 //throw new Exception(ex.ToString(), ex);
             }
             finally
             {
                 con.Close();
             }
         }
     }
 }
예제 #10
0
        public ActionResult Import(bool active, bool scheduled, bool unsold)
        {
            var importedcount  = 0;
            var duplicatecount = 0;
            var token          = repository.GetOAuthToken(subdomainid.Value, OAuthTokenType.EBAY, true);

            if (token == null)
            {
                return(Json("Please connect your account with eBay first".ToJsonFail()));
            }

            try
            {
                var service  = new UserService(token.token_key);
                var entries  = service.GetMyEbaySelling(active, scheduled, unsold);
                var importer = new ProductImport();
                foreach (var entry in entries)
                {
                    var ebayid = entry.id;
                    if (repository.GetProducts(subdomainid.Value).Any(y => y.ebayID.HasValue && y.ebay_product.ebayid == ebayid))
                    {
                        duplicatecount++;
                    }
                    else
                    {
                        var pinfo = importer.ImportEbay(entry, subdomainid.Value);

                        repository.AddProduct(pinfo, subdomainid.Value);

                        importedcount++;
                    }
                }
            }
            catch (Exception ex)
            {
                return(SendJsonErrorResponse(ex));
            }

            return(Json(string.Format("{0} products imported. {1} duplicates.", importedcount, duplicatecount).ToJsonOKMessage()));
        }
예제 #11
0
        public ActionResult Import(string id)
        {
            try
            {
                Stream inputStream;
                if (Request.Files.Count != 0)
                {
                    inputStream = Request.Files[0].InputStream;
                }
                else
                {
                    inputStream = Request.InputStream;
                }
                inputStream.Position = 0;
                List <ProductInfo> productsList;
                using (var stream = inputStream)
                {
                    var importer = new ProductImport();
                    productsList = importer.Import(stream, sessionid.Value, subdomainid.Value);
                }

                // need to identifiy duplicates in database
                var dbduplicates = productsList.Where(x => repository.GetProductVariants(x.p.subdomainid).Select(y => y.sku).Contains(x.p.product_variants[0].sku)).ToArray();
                var duplicateSKU = dbduplicates.SelectMany(x => x.p.product_variants.Select(y => y.sku)).ToArray();
                productsList.RemoveAll(dbduplicates.Contains);

                repository.AddProducts(productsList, subdomainid.Value);

                // update total of out of stock items
                repository.UpdateProductsOutOfStock(subdomainid.Value);
                repository.Save();

                return(Json(duplicateSKU.ToJsonOKData()));
            }
            catch (Exception ex)
            {
                return(SendJsonErrorResponse(ex));
            }
        }
예제 #12
0
    protected void insertProduct(string url)
    {
        string[]      product = new string[5];
        XmlTextReader r       = new XmlTextReader(url);

        while (r.Read())
        {
            if (r.MoveToContent() == XmlNodeType.Element && r.Name == "title")
            {
                product[0] = r.ReadString();
            }
            if (r.MoveToContent() == XmlNodeType.Element && r.Name == "description")
            {
                product[1] = r.ReadString();
            }
            if (r.MoveToContent() == XmlNodeType.Element && r.Name == "category")
            {
                product[2] = r.ReadString();
            }
            if (r.MoveToContent() == XmlNodeType.Element && r.Name == "stock")
            {
                product[3] = r.ReadString();
            }
            if (r.MoveToContent() == XmlNodeType.Element && r.Name == "price")
            {
                product[4] = r.ReadString();
                try
                {
                    ProductImport productA = new ProductImport(product[0], product[1], Convert.ToInt32(product[2]), Convert.ToInt32(product[3]), Convert.ToDouble(product[4]));
                    sqlInsert(productA);
                    xmlCompleteLabel.Text = "Import successfully.";
                }
                catch (Exception)
                {
                    xmlCompleteLabel.Text = "An error ocurred. Please check your database to make sure nothing funny happened.";
                }
            }
        }
    }
예제 #13
0
        public void WhenDoALocationImportAndCheckImportedLocationCount()
        {
            new MainPage(TestSetup.Driver)
            .SelectImportLocation();

            var fileId = $"Location-{RandomString(12)}";

            Console.WriteLine($"uploaded file ID: {fileId}");

            var p = Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "Assets", "LocationCreate.xlsx");

            var p2 = Path.Combine(TestSetup.Config.DownloadFolder, $"{fileId}.xlsx");

            File.Copy(p, p2);

            new LocationImport(TestSetup.Driver)
            .UploadFile(p2);

            Poll("Wait for file to be uploaded", 240, 5,
                 () =>
            {
                var page   = new LocationImport(TestSetup.Driver).Refresh();
                var name   = page.UploadTableFirstFileName;
                var status = page.UploadTableFirstStatus;
                return(name.StartsWith(fileId + "_") && status == "Complete");
            },
                 x => x
                 ).ShouldBeTrue();

            var importPage = new ProductImport(TestSetup.Driver);

            importPage.UploadTableFirstProcessed.ShouldBe(2);
            importPage.UploadTableFirstSuccess.ShouldBe(2);
        }
예제 #14
0
        public ActionResult demo_create()
        {
            var account = new Account(repository, "*****@*****.**", "1234%^&*", "1234%^&*", "demo", AccountPlanType.ULTIMATE, "");
            var status  = account.CreateAccountWithLoginPassword();

            if (!status.success)
            {
                return(Json(status));
            }

            // add currency and timezoneinfo
            var sd = repository.GetSubDomains().Single(x => x.name == "demo");

            sd.organisation.name = "Demo Company";
            sd.currency          = 432; // USD
            sd.flags            |= (int)SubdomainFlags.STORE_ENABLED;

            var creator = sd.organisation.users.First();

            creator.timezone = "Eastern Standard Time";
            creator.role     = (int)UserRole.ADMIN;

            repository.Save("demo_create");

            // add test org
            var o = new organisation
            {
                subdomain = sd.id,
                address   = "12 Demo Road",
                phone     = "012 345678",
                name      = "Acme & Co.",
                fax       = "87 654321",
                postcode  = "12345",
            };
            var addedOrgID = repository.AddOrganisation(o);

            // add user
            var u = new user
            {
                created      = DateTime.UtcNow,
                email        = "*****@*****.**",
                passwordHash = Utility.ComputePasswordHash("*****@*****.**"),
                firstName    = "demo",
                lastName     = "account",
                organisation = addedOrgID,
                viewid       = Utility.GetRandomString(),
                permissions  = (int)(UserPermission.NETWORK_STORE |
                                     UserPermission.INVENTORY_ADD |
                                     UserPermission.INVENTORY_MODIFY |
                                     UserPermission.INVENTORY_VIEW |
                                     UserPermission.INVOICES_ADD |
                                     UserPermission.TRANSACTION_MODIFY |
                                     UserPermission.TRANSACTION_VIEW |
                                     UserPermission.ORDERS_ADD |
                                     UserPermission.CONTACTS_ADD |
                                     UserPermission.CONTACTS_MODIFY |
                                     UserPermission.CONTACTS_VIEW),
                role = (int)UserRole.USER
            };

#if !DEBUG
            // not created when debugging because we want to test product import

            u.timezone = "Eastern Standard Time";
#else
            u.permissions |= (int)UserPermission.NETWORK_SETTINGS;
#endif

            repository.AddUser(u);

            // log activity
            repository.AddActivity(u.id,
                                   new ActivityMessage(u.id, u.id,
                                                       ActivityMessageType.CONTACT_NEW,
                                                       new HtmlLink(u.ToEmailName(true), u.id).ToContactString()), sd.id);

            // update total contacts count
            repository.UpdateCounters(sd.id, 1, CounterType.CONTACTS_PRIVATE);

            // import demo products
            List <ProductInfo> productsList;
            using (var fs =
                       new FileStream(
                           GeneralConstants.APP_ROOT_DIR + "/Content/templates/demo/demo_products.xls",
                           FileMode.Open, FileAccess.Read))
            {
                var importer = new ProductImport();
                productsList = importer.Import(fs, u.id, sd.id);
            }
            repository.AddProducts(productsList, sd.id);

            return(Json("Demo account created".ToJsonOKMessage()));
        }
예제 #15
0
        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
                }
            }
        }
예제 #16
0
        internal static List<ProductImport> GetAllProducts()
        {
            var products = new List<ProductImport>();

            bool boolSessionBegun = false;
            QBSessionManager sessionManager = new QBSessionManager();
            IItemInventoryRet itemInventoryRet = null;
            try
            {
                IMsgSetRequest requestMsgSet;
                IMsgSetResponse responseMsgSet;
                sessionManager.OpenConnection("", _appName);
                sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare);
                boolSessionBegun = true;
                requestMsgSet = GetLatestMsgSetRequest(sessionManager);
                requestMsgSet.Attributes.OnError = ENRqOnError.roeStop;
                IItemInventoryQuery itemInventoryQ = requestMsgSet.AppendItemInventoryQueryRq();
                responseMsgSet = sessionManager.DoRequests(requestMsgSet);

                IResponse response = responseMsgSet.ResponseList.GetAt(0);
                IItemInventoryRetList itemInventoryRetList = response.Detail as IItemInventoryRetList;

               
                    if (itemInventoryRetList != null && itemInventoryRetList.Count > 0)
                    {
                        for (int i = 0; i < itemInventoryRetList.Count; i++)
                        {
                            itemInventoryRet = itemInventoryRetList.GetAt(i);
                            if(itemInventoryRet!=null)
                            {
                                var product = new ProductImport();
                                product.pDesc = itemInventoryRet.FullName.GetValue();
                                product.pCode = itemInventoryRet.Name.GetValue();
                                product.exfactory = itemInventoryRet.PurchaseCost != null
                                                        ? Convert.ToDecimal(itemInventoryRet.PurchaseCost.GetAsString())
                                                        : 0m;

                               
                                products.Add(product);
                            }
                            
                        }
                        
                    }

                sessionManager.EndSession();
                boolSessionBegun = false;
                sessionManager.CloseConnection();
            }
            catch (Exception ex)
            {
                if (boolSessionBegun)
                {
                    sessionManager.EndSession();
                    sessionManager.CloseConnection();
                }
                string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application");
                Log(error);
                MessageBox.Show(error);

            }
            return products;
        }
예제 #17
0
        internal static void Products()
        {
            int productbrandcount = 0;
            int productsubbrandcount = 0;
            int productcount = 1;

            bool boolSessionBegun = false;
            QBSessionManager sessionManager = new QBSessionManager();
            try
            {
                IMsgSetRequest requestMsgSet;
                IMsgSetResponse responseMsgSet;
                sessionManager.OpenConnection("", _appName);
                sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare);
                boolSessionBegun = true;
                requestMsgSet = GetLatestMsgSetRequest(sessionManager);
                requestMsgSet.Attributes.OnError = ENRqOnError.roeStop;
               // ISalesTaxCodeRetList
                IItemInventoryQuery itemInventoryQ = requestMsgSet.AppendItemInventoryQueryRq();
               
                responseMsgSet = sessionManager.DoRequests(requestMsgSet);
                
               
                IResponse response = responseMsgSet.ResponseList.GetAt(0);
                IItemInventoryRetList itemInventoryRetList = response.Detail as IItemInventoryRetList;
                List<ProductImport> items= new List<ProductImport>();
                List<ProductPricing> pricings=new List<ProductPricing>();
                 List<Packaging> packagings=new List<Packaging>();
                List<ProductBrand> brands=new List<ProductBrand>();
                if (itemInventoryRetList != null && itemInventoryRetList.Count > 0)
                {
                   
                    for (var i = 0; i < itemInventoryRetList.Count; i++)
                    {
                        IItemInventoryRet inventoryRet = itemInventoryRetList.GetAt(i);
                        if(!inventoryRet.Sublevel.IsSet())
                        {
                            productbrandcount++;
                        }
                        if (inventoryRet.Sublevel.IsSet())
                        {
                            productsubbrandcount++;
                        }
                        if (inventoryRet.UnitOfMeasureSetRef!=null)
                        {
                            productcount++;
                        }

                        if (inventoryRet != null && inventoryRet.IsActive.GetValue())
                        {
                            var p = new ProductImport
                                        {
                                            pCode = inventoryRet.FullName != null ? inventoryRet.Name.GetValue() : "",
                                            pDesc =
                                                inventoryRet.SalesDesc != null ? inventoryRet.SalesDesc.GetValue() : "",
                                            exfactory = inventoryRet.PurchaseCost != null
                                                            ? Convert.ToDecimal(inventoryRet.PurchaseCost.GetAsString())
                                                            : 0m,
                                            vatclassName = inventoryRet.SalesTaxCodeRef != null
                                                               ? inventoryRet.SalesTaxCodeRef.FullName.GetValue()
                                                               : "",
                                            packagingTypeName = inventoryRet.UnitOfMeasureSetRef !=null?inventoryRet.UnitOfMeasureSetRef.FullName.GetValue():"",
                                            productBrandName = 
                                           inventoryRet.ParentRef != null ? inventoryRet.ParentRef.FullName.GetValue() : ""
                                        };
                            items.Add(p);
                            if (inventoryRet.ParentRef != null && inventoryRet.ParentRef.FullName != null )
                            {
                                IItemInventoryRet b = GetInventoryByNameFilter(inventoryRet.ParentRef.FullName.GetValue());
                                if (b != null )
                                {
                                    var brand = new ProductBrand
                                    {
                                        Code = b.FullName != null ? b.FullName.GetValue() : "",
                                        Name = b.SalesDesc != null ? b.SalesDesc.GetValue() : "",
                                        Description = b.SalesDesc != null ? b.SalesDesc.GetValue() : "",
                                        supplierName = "NESTLE KENYA LIMITED"   //b.PrefVendorRef.FullName.GetValue()
                                    };
                                    if (!string.IsNullOrEmpty(brand.Code) && brands.All(n => n.Code != brand.Code))
                                        brands.Add(brand);

                                    brands.Select(n => new {});
                                }
                                
                            }
                            if(inventoryRet!=null && inventoryRet.UnitOfMeasureSetRef!=null)//p !=null && items.Any(n=>n.pCode==p.pCode))
                            {
                                //Michael Added Code
                              //  if(p.exfactory==0) continue;
                                //End of Michael Added Code
                                var pricing = new ProductPricing
                                {
                                    ProductCode = inventoryRet.FullName != null ? inventoryRet.Name.GetValue() : "",
                                    Exfactory = inventoryRet.PurchaseCost != null
                                                            ? Convert.ToDecimal(inventoryRet.PurchaseCost.GetAsString())
                                                            : 0m,
                                    SellingPrice = inventoryRet.SalesPrice !=null?Convert.ToDecimal(inventoryRet.SalesPrice.GetValue()):0m,
                                    StartDate = DateTime.Today.ToShortDateString(),
                                    TierNameCode = "Default"
                                };
                                pricings.Add(pricing); 
                            }
                            

                        }

                    }

                    
                }

                sessionManager.EndSession();
                boolSessionBegun = false;
                sessionManager.CloseConnection();
                if (items.Any())
                {
                    DumpExportFilesAsync(items.Where(p=>!string.IsNullOrEmpty(p.productBrandName) && p.exfactory >0m).ToCsv(), MasterDataCollective.SaleProduct.ToString());
                }
                if (pricings.Any())
                {
                    DumpExportFilesAsync(pricings.ToCsv(), MasterDataCollective.Pricing.ToString());
                }
                if (packagings.Any())
                {
                    DumpExportFilesAsync(packagings.ToCsv(), MasterDataCollective.ProductPackaging.ToString());
                }

                if (brands.Any())
                {
                    DumpExportFilesAsync(brands.ToCsv(), MasterDataCollective.ProductBrand.ToString());
                }
            }
            catch (Exception ex)
            {
                if (boolSessionBegun)
                {
                    sessionManager.EndSession();
                    sessionManager.CloseConnection();
                }
                string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application");
                Log(error);
                MessageBox.Show(error);

            }
          
        }