Inheritance: INotifyPropertyChanged
 private static void CheckPromotionStatus(SaleItem item)
 {
     if (!item.PromotionState)
     {
         item.CompletePromotion();
     }
 }
        private bool HasPromotionStarted(SaleItem item)
        {
            var lowerLimit = item.OriginalPrice - (item.OriginalPrice * LowerPercentage);
            var upperLimit = item.OriginalPrice - (item.OriginalPrice * UpperPercentage);

            return item.SalePrice <= lowerLimit && item.SalePrice >= upperLimit && item.CalculatedPriceDuration >= DurationLength + item.PreviousPromotionDuration;
        }
 void initCartData()
 {
     var cart = new Cart()
     {
         CreateTime = DateTime.Now,
         Id = 1,
     };
     SaleItem saleItem = new SaleItem()
     {
         Cart = cart,
         CartId = 1,
         Id = 1,
         ProductId = 1,
         Quantity = 10
     };
     SaleItem saleItem2 = new SaleItem()
     {
         Cart = cart,
         CartId = 1,
         Id = 2,
         ProductId = 2,
         Quantity = 10
     };
     cart.SaleItems.Add(saleItem);
     cart.SaleItems.Add(saleItem2);
     fakeShoppingCartDbContext.Carts.Add(cart);
     fakeShoppingCartDbContext.SaleItems.Add(saleItem);
     fakeShoppingCartDbContext.SaleItems.Add(saleItem2);
 }
Example #4
0
 public async Task<Boolean> AddToCart(int cartId, Product product, int Quantity)
 {
     using (var db = ResolveDBContextFactory())
     {
         var cart = db.Carts.FirstOrDefault(o => o.Id == cartId);
         if (cart != null)
         {
             var existingsaleitem =
                 await db.SaleItems.FirstOrDefaultAsync(o => o.CartId == cart.Id && o.ProductId == product.Id);
             if (existingsaleitem != null)
             {
                 existingsaleitem.Quantity += Quantity;
             }
             else
             {
                 SaleItem item = new SaleItem() {
                     ProductId = product.Id,
                     Quantity = Quantity,
                     CartId = cartId,
                     Cart = cart
                 };
                 db.SaleItems.Add(item); 
             }
             await db.SaveChangesAsync();
             return true;
         }
         throw  new Exception("no active shopping cart is found");
     }
 }
        public void AddPromotionDurationDays(SaleItem item, int numDays)
        {
            item.SalePriceDuration += numDays;

            item.PromotionState = item.SalePriceDuration <= PromotionDurationLength;

            CheckPromotionStatus(item);
        }
 public frmEditSalesItem(SaleItem saleItem)
 {
     InitializeComponent();
     bsSuppliers = new BindingSource();
     bsProducts = new BindingSource();
     dgvSuppliers.DataSource = bsSuppliers;
     dgvProducts.DataSource = bsProducts;
     dgvSuppliers.AutoGenerateColumns = false;
     dgvProducts.AutoGenerateColumns = false;
     this.item = saleItem;
 }
        public void SetItemSalePrice(SaleItem item, double discountPercentage)
        {
            item.SalePrice = item.SalePrice > 0
                ? item.SalePrice - (item.SalePrice*discountPercentage)
                : item.OriginalPrice - (item.OriginalPrice*discountPercentage);

            item.PromotionState = !(discountPercentage < 0) && HasPromotionStarted(item);

            if (item.PromotionState && item.SalePriceDuration <= 0)
            {
                item.SalePriceDuration = 0;
            }

            CheckPromotionStatus(item);
        }
 void InitData()
 {
     //Init Cart data
     Cart cart = new Cart()
     {
         CreateTime = DateTime.Now,
         Id = 1
     };
     shoppingCartDbContext.Carts.Add(cart);
     //Init Sale Item
     SaleItem sale = new SaleItem()
     {
         Cart = cart,
         CartId = 1,
         ProductId = 1,
         Id = 1,
         Quantity = 10
     };
     shoppingCartDbContext.SaleItems.Add(sale);
     shoppingCartDbContext.SaveChanges();
 }
Example #9
0
        private SaleItem CreateSaleItem(Product product, int qtySold, float discount)
        {
            var saleItem =
                new SaleItem
                {
                    ProductName = product.ProductName,
                    ProductId = product.ProductId,
                    QtySold = qtySold,
                    UnitPriceIn = product.UnitPriceIn,
                    ProductDisplayName =
                        string.IsNullOrEmpty(product.Description) ?
                        product.ProductName + "\r" + product.ProductCode :
                        product.Description + "\r" + product.ProductCode,
                    QtyBonus = CalculateQtyBonus(
                        qtySold,
                        Int32.Parse(product.QtyPromotion.ToString("N0", AppContext.CultureInfo)),
                        Int32.Parse(product.QtyBonus.ToString("N0", AppContext.CultureInfo)))
                };

            //Control the quantity of product to be sold
            if(product.QtyInStock < (saleItem.QtySold + saleItem.QtyBonus))
                return null;

            if (!string.IsNullOrEmpty(product.ForeignCode))
                saleItem.ProductDisplayName += " (" + product.ForeignCode + ")";

            var unitPriceIn =
                float.Parse(Math.Round(product.UnitPriceIn, 3).ToString("N3", AppContext.CultureInfo),
                            AppContext.CultureInfo);

            var publicUnitPriceOut =
                product.ExtraPercentage != 0 ?
                unitPriceIn + ((unitPriceIn * product.ExtraPercentage) / 100) :
                product.UnitPriceOut;

            saleItem.UnitPriceOut =
                float.Parse(
                    publicUnitPriceOut.ToString("N", AppContext.CultureInfo),
                    AppContext.CultureInfo);
            //publicUnitPriceOut =
            //    publicUnitPriceOut -
            //    ((publicUnitPriceOut * product.DiscountPercentage) / 100);
            publicUnitPriceOut =
                publicUnitPriceOut -
                ((publicUnitPriceOut * discount) / 100);

            if (publicUnitPriceOut == product.UnitPriceIn)
                publicUnitPriceOut = product.UnitPriceOut;

            //publicUnitPriceOut =
            //    float.Parse(Math.Round(publicUnitPriceOut, 0).ToString("N", AppContext.CultureInfo),
            //                AppContext.CultureInfo);
            publicUnitPriceOut =
                float.Parse(
                    publicUnitPriceOut.ToString("N", AppContext.CultureInfo),
                    AppContext.CultureInfo);

            //float.Parse(Math.Round(saleItem.PublicUPOut, 0).ToString("N", AppContext.CultureInfo),
            //            AppContext.CultureInfo);
            saleItem.PublicUpOut = publicUnitPriceOut;
            saleItem.Discount = discount;
            saleItem.SubTotal =
                saleItem.QtySold * publicUnitPriceOut;

            if (string.IsNullOrEmpty(product.PhotoPath))
                saleItem.ProdPicture = Resources.NoImage;
            else
            {
                var fileInfo = new FileInfo(product.PhotoPath);
                saleItem.ProdPicture = fileInfo.Exists ? Image.FromFile(product.PhotoPath) : Resources.NoImage;
            }
            cmbProduct.SelectedIndex = -1;
            saleItem.FkProduct = product;
            return saleItem;
        }
Example #10
0
 public static StateTransitionResult <SaleState, SaleEvent> Fire(Sale sale, SaleEvent saleEvent, SaleItem saleItem)
 {
     return(_saleStateManager.FireTrigger(sale, saleEvent, saleItem));
 }
        private void btnRemoveFurnitureFromSale_Click(object sender, RoutedEventArgs e)
        {
            SaleItem <Furniture> furniture = (SaleItem <Furniture>)dgFurnitureForSale.SelectedItem;

            furnitureForSale.Remove(furniture);
        }
 public virtual void UpdateSaleItem(SaleItem saleItem)
 {
     UpdateObject(saleItem);
 }
Example #13
0
        private static Sale CreateTestSale()
        {
            MaterialGroup materialGroup = new MaterialGroup();

            materialGroup.AdditionalDescriptionEnglish = String.Empty;
            materialGroup.AdditionalDescriptionGerman  = String.Empty;
            materialGroup.DescriptionEnglish           = String.Empty;
            materialGroup.DescriptionGerman            = String.Empty;
            materialGroup.EbayAuctionHtmlTemplate      = String.Empty;
            materialGroup.IntroductionEnglish          = String.Empty;
            materialGroup.IntroductionGerman           = String.Empty;
            materialGroup.Name = "MaterialGroup";
            MyDataContext.Default.MaterialGroups.Add(materialGroup);
            MyDataContext.Default.SaveChanges();

            Supplier supplier = new Supplier();

            supplier.EmailAddress = "*****@*****.**";
            supplier.Name         = "SupplierName";
            MyDataContext.Default.Suppliers.Add(supplier);
            MyDataContext.Default.SaveChanges();

            Article article = new Article();

            article.ArticleNumber              = "123";
            article.DescriptionEnglish         = "DescriptionEnglish";
            article.DescriptionGerman          = "DescriptionGerman";
            article.MaterialGroup              = materialGroup;
            article.NameEnglish                = "NameEnglish";
            article.NameGerman                 = "NameGerman";
            article.NameIntern                 = "NameIntern";
            article.PictureName1               = String.Empty;
            article.PictureName2               = String.Empty;
            article.PictureName3               = String.Empty;
            article.SellingPriceGross          = 123.45m;
            article.SellingPriceWholesaleGross = 12.34m;
            article.Supplier = supplier;
            article.SupplierArticleNumber = "SupplierArticleNumber";
            article.SyncTechnicalInfo     = String.Empty;
            article.Tags = String.Empty;
            article.EAN  = String.Empty;
            article.EbayArticleNumber = String.Empty;
            MyDataContext.Default.Articles.Add(article);
            MyDataContext.Default.SaveChanges();

            StockMovement movement = new StockMovement(article);

            movement.Amount = 10;
            movement.Reason = "Incoming";
            MyDataContext.Default.StockMovements.Add(movement);
            MyDataContext.Default.SaveChanges();

            Sale sale = new Sale();

            sale.DateOfPayment    = new DateTime(2015, 09, 03);
            sale.DateOfSale       = new DateTime(2015, 09, 03);
            sale.EbayName         = "ebay - komakommander";
            sale.SourceId         = "123456";
            sale.EMailAddress     = "*****@*****.**";
            sale.InvoiceCity      = "InvoiceCity";
            sale.InvoiceCountry   = "InvoiceCountry";
            sale.InvoiceName      = "InvoiceName";
            sale.InvoicePostcode  = "InvoicePostcode";
            sale.InvoiceRegion    = "InvoiceRegion";
            sale.InvoiceStreet1   = "InvoiceStreet1";
            sale.InvoiceStreet2   = "InvoiceStreet2";
            sale.IsCashSale       = false;
            sale.ManuallyChanged  = false;
            sale.NameOfBuyer      = "NameOfBuyer";
            sale.Notes            = "Notes";
            sale.PhoneNumber      = "PhoneNumber";
            sale.ShippingCity     = "ShippingCity";
            sale.ShippingCountry  = "ShippingCountry";
            sale.ShippingName     = "ShippingName";
            sale.ShippingPostcode = "ShippingPostcode";
            sale.ShippingPrice    = 123.45m;
            sale.ShippingRegion   = "ShippingRegion";
            sale.ShippingStreet1  = "ShippingStreet1";
            sale.ShippingStreet2  = "ShippingStreet2";
            sale.Source           = SaleSources.Ebay;
            MyDataContext.Default.Sales.Add(sale);

            SaleItem saleItem = new SaleItem(sale, article, 19.0m);

            MyDataContext.Default.SaleItems.Add(saleItem);
            MyDataContext.Default.SaveChanges();

            NumberGenerator generator = new NumberGenerator();

            generator.CurrentNumber = 1;
            generator.Name          = "Invoices";
            generator.StepWidth     = 1;
            MyDataContext.Default.NumberGenerators.Add(generator);
            MyDataContext.Default.SaveChanges();

            Mailing.CreateFromUnsentSales();
            sale.Mailing.ShippingMethod = ShippingMethods.DPD;
            MyDataContext.Default.SaveChanges();

            Invoice.CreateFromUnbilledSales();
            sale.Invoice.InvoiceNumber = "20175272335";
            MyDataContext.Default.SaveChanges();

            return(sale);
        }
Example #14
0
        public async Task <MobileServiceFile> GetItemPhotoAsync(SaleItem item)
        {
            IEnumerable <MobileServiceFile> files = await this.saleItemsTable.GetFilesAsync(item);

            return(files.FirstOrDefault());
        }
 public void Setup()
 {
     _promotionRulesEngine = new PromotionRulesEngine();
     _saleItem = new SaleItem(100.0);
 }
Example #16
0
        public async Task CreateAsync(SaleItem saleItem)
        {
            await db.SaleItems.AddAsync(saleItem);

            await db.SaveChangesAsync();
        }
Example #17
0
 public async Task UpdateAsync(SaleItem saleItem)
 {
     db.SaleItems.Update(saleItem);
     await db.SaveChangesAsync();
 }
 protected AdditiveSaleItemDecorator(SaleItem coffee)
     : base(coffee)
 {
 }
Example #19
0
        private void ProcessLine(string line, DataRowKind dataRowKind)
        {
            var row = line.Split(new[] { Constants.ROW_SEPARATOR }, StringSplitOptions.None);

            switch (dataRowKind)
            {
            case DataRowKind.Salesman:

                var salesman = new Salesman
                {
                    Cpf    = row.Get <string>(SalesmanColumns.Cpf),
                    Name   = row.Get <string>(SalesmanColumns.Name),
                    Salary = row.Get <decimal>(SalesmanColumns.Salary)
                };

                if (!this._flatFile.Salesmans.Any(x => x.Cpf.Equals(salesman.Cpf, StringComparison.OrdinalIgnoreCase)))
                {
                    this._flatFile.Salesmans.Add(salesman);
                }

                break;

            case DataRowKind.Customer:

                var customer = new Customer
                {
                    Cnpj         = row.Get <string>(CustomerColumns.Cnpj),
                    Name         = row.Get <string>(CustomerColumns.Name),
                    BusinessArea = row.Get <string>(CustomerColumns.BusinessArea)
                };

                if (!this._flatFile.Customers.Any(x => x.Cnpj.Equals(customer.Cnpj, StringComparison.OrdinalIgnoreCase)))
                {
                    this._flatFile.Customers.Add(customer);
                }

                break;

            case DataRowKind.Sales:

                var sale = new Sale
                {
                    SaleId       = row.Get <int>(SaleColumns.SaleId),
                    SalesmanName = row.Get <string>(SaleColumns.SalesmanName)
                };

                var saleItems = row.Get <string>(SaleColumns.SaleItens);

                var sb = new StringBuilder(saleItems);

                sb = sb.Replace(Constants.LEFT_BRACKET, string.Empty)
                     .Replace(Constants.RIGHT_BRACKET, string.Empty);

                sb = sb.Trim();

                saleItems = sb.ToString();

                var items = saleItems.Split(new[] { Constants.ITEM_SEPARATOR }, StringSplitOptions.None);

                foreach (var item in items)
                {
                    var values = item.Split(new[] { Constants.ITEM_VALUES_SEPARATOR }, StringSplitOptions.None);

                    var saleItem = new SaleItem
                    {
                        SaleItemId = values.Get <int>(SaleItemColumns.SaleItemId),
                        Quantity   = values.Get <int>(SaleItemColumns.Quantity),
                        Price      = values.Get <decimal>(SaleItemColumns.Price),
                        SaleId     = sale.SaleId
                    };

                    sale.SaleItems.Add(saleItem);
                }

                var foundSalesman = this._flatFile.Salesmans.Distinct().SingleOrDefault(x => x.Name.Equals(sale.SalesmanName, StringComparison.OrdinalIgnoreCase));

                if (foundSalesman != null)
                {
                    foundSalesman.Sales.Add(sale);
                }

                this._flatFile.Sales.Add(sale);
                break;
            }
        }
        public virtual void UpdateProduct(SaleItem saleItem)
        {
            var productList = _productDataAccess.GetProductById(saleItem.ProductId);
            if (productList == null)
                return;

            if (productList.Count == 0)
                return;

            var product = productList[0] as Model.Product.Product;
            if (product == null)
                return;

            product.QtyInStock -= (saleItem.QtySold + saleItem.QtyBonus);
            product.QtySold += (saleItem.QtySold + saleItem.QtyBonus);
            _productDataAccess.UpdateProduct(product);
        }
 private void NewSaleItem()
 {
     SaleItem item = new SaleItem();
     frmEditSalesItem frmEditSaleItem = new frmEditSalesItem(item);
     if (frmEditSaleItem.ShowDialog() == DialogResult.OK)
     {
         bsSaleItems.Add(item);
         bsSaleItems.MoveLast();
         dgvSaleItems.Invalidate();
     }
     else
     {
         bsSaleItems.Remove(item);
     }
 }
 /// <summary>
 /// this method drop the product in Sale
 /// </summary>
 /// <param name="saleItem"></param>
 private void DropProductInSale(SaleItem saleItem)
 {
     var manager = new InventoryManager(this);
     Inventory inventory;
     if (saleItem.ProductId.HasValue && saleItem.Product.DropCompositeInStock && saleItem.Sale.DepositId.HasValue)
     {
         inventory = manager.GetProductInventory(saleItem.CompanyId, (int)saleItem.ProductId,
                                                 saleItem.Sale.DepositId.Value);
         if (inventory != null)
         {
             inventory.ProductId = saleItem.ProductId.Value;
             inventory.CompanyId = saleItem.CompanyId;
             inventory.DepositId = saleItem.Sale.DepositId.Value;
             manager.InventoryDrop(inventory, saleItem.Quantity, (int)DropType.Sell, saleItem.SaleId);
         }
     }
 }
Example #23
0
        public ActionResult Edit(SaleViewModel model)
        {
            if (!ModelState.IsValid)
            {
                var pos = 0;
                foreach (var item in model.SaleItems)
                {
                    item.pos = pos++;
                }
                return(View(model));
            }

            try
            {
                using (var db = new SmDbContext())
                {
                    var tr     = db.Database.BeginTransaction();
                    var entity = db.Sales.FirstOrDefault(x => x.Id == model.Id);
                    if (entity == null)
                    {
                        entity = new Sale();
                        db.Sales.Add(entity);
                    }
                    if (entity.Processed)
                    {
                        throw new Exception("Документ уже проведен!");
                    }
                    entity.OrderId         = model.OrderId;
                    entity.Paytype         = model.Paytype;
                    entity.OperatorId      = db.AspNetUsers.First(x => x.UserName == User.Identity.Name).Id;
                    entity.RealizationDate = model.RealisationDate.Value;
                    entity.Processed       = model.Processed ?? false;
                    db.SaveChanges();

                    var existedIds = model.SaleItems.Select(x => x.Id);
                    foreach (var item in db.SaleItems.Where(x => x.SaleId == model.Id && !existedIds.Contains(x.Id)))
                    {
                        db.SaleItems.Remove(item);
                    }

                    foreach (var modelItem in model.SaleItems)
                    {
                        var entityItem = db.SaleItems.FirstOrDefault(x => x.Id == modelItem.Id);
                        if (entityItem == null)
                        {
                            entityItem = new SaleItem {
                                SaleId = entity.Id
                            };
                            db.SaleItems.Add(entityItem);
                        }
                        entityItem.Discount    = modelItem.Discount;
                        entityItem.OrderItemId = modelItem.OrderItemId;
                        entityItem.GoodsId     = modelItem.GoodsId;
                        entityItem.Amount      = modelItem.Amount;
                        entityItem.Price       = modelItem.Price;
                        entityItem.Discount    = modelItem.Discount;
                    }

                    db.SaveChanges();

                    // Если документ проведен, то обновим наличие на складе
                    if (model.Processed == true)
                    {
                        foreach (var item in model.SaleItems)
                        {
                            var goods = db.Goods.First(x => x.Id == item.GoodsId);
                            goods.Quantity -= item.Amount;
                            if (goods.Quantity < 0)
                            {
                                throw new Exception("Недостаточно наличия \"" + goods.Name + "\" на складе!");
                            }
                        }
                        db.SaveChanges();
                    }

                    tr.Commit();

                    //var t = 0;
                    //var a = 5 / t;
                }

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Id", ex);
                return(View());
            }
        }
Example #24
0
 public async Task Delete(SaleItem saleItem)
 {
     db.Remove(saleItem);
     await db.SaveChangesAsync();
 }
Example #25
0
 public void EditSaleItem(SaleItem s)
 {
     db.Entry(s).State = System.Data.Entity.EntityState.Modified;
     db.SaveChanges();
 }
Example #26
0
 public void AddItem(SaleItem saleItem)
 {
     _dbContext.SalesItems.Add(saleItem);
     _dbContext.SaveChanges();
 }
Example #27
0
 public Task RemoveSaleItem(SaleItem saleItem)
 {
     return(_saleItemsRepository.RemoveSaleItem(saleItem));
 }
Example #28
0
    protected void Query(int offset)
    {
        try
        {
            int        serverId = ServerDropDownList.SelectedServerId;
            GameServer server   = ServerDropDownList.SelectedGameServer;
            if (server == null)
            {
                LabelOpMsg.Text = string.Format(StringDef.MsgCannotBeNone, StringDef.GameServer);
                return;
            }
            if (!server.IsConnected)
            {
                LabelOpMsg.Text = StringDef.NoConnectionAlert;
                return;
            }

            ArrayList     tempParamList   = new ArrayList();
            ArrayList     paramList       = new ArrayList();
            StringBuilder searchCondition = new StringBuilder();

            searchCondition.Append(string.Format("WHERE LogEvent='{0}'", LogEvent.AuctionStatistic));

            _start = StartDate.SelectedDate;
            if (_start == DateTime.MinValue)
            {
                LabelOpMsg.Text = StringDef.ParameterInputError;
                return;
            }
            _end = EndDate.SelectedDate;
            if (_end == DateTime.MinValue)
            {
                LabelOpMsg.Text = StringDef.ParameterInputError;
                return;
            }

            searchCondition.Append(string.Format(" AND {0}>='{1}' AND {0}<'{2}'", FS2TableString.LogFieldLogTime, _start.ToString("yyyy-MM-dd HH:mm:ss"), _end.ToString("yyyy-MM-dd HH:mm:ss")));

            //ItemId¿ÉÒÔ²»Ìî
            string itemId = TextBoxItemId.Text.Trim();
            if (itemId != null && itemId.Length != 0)
            {
                searchCondition.Append(string.Format(" AND {0}='{1}'", FS2TableString.LogFieldLogKey2, itemId));
            }


            string baseCmdString = string.Format("SELECT LogKey2,SUM(LogKey6) AS SubSum FROM {0} {1} GROUP BY LogKey2",
                                                 "{0}", searchCondition.ToString());
            string addTableCmdString;
            WebUtil.AddTableNameToCmd(CurrentUser.Id, server, baseCmdString, tempParamList, _start, _end, out addTableCmdString, out paramList);
            if (addTableCmdString.Length == 0)
            {
                //
                return;
            }

            int    limitCount     = _recordPerPage;
            string limitStatement = string.Format(" LIMIT {0},{1}", offset, limitCount);

            string cmdString = "SELECT LogKey2,SUM(SubSum) AS Total FROM ({0}) AS A GROUP BY LogKey2 ORDER BY Total DESC {1}";

            SqlCommand cmd    = new SqlCommand(string.Format(cmdString, addTableCmdString, limitStatement), paramList.ToArray());
            SqlResult  result = WebUtil.QueryGameServerDb(CurrentUser.Id, server, cmd);
            if (result != null && result.Success)
            {
                Session[WebConfig.SessionQueryLogOffset] = offset;
                result.SetFieldType(new SqlDataType[] {
                    SqlDataType.String,
                    SqlDataType.Int32,
                });
                object[]  record = null;
                ArrayList infos  = new ArrayList();

                while ((record = result.ReadRecord()) != null)
                {
                    SaleItem info = new SaleItem();
                    info.itemTemplateId = record[0] as string;
                    info.saleNum        = (int)record[1];

                    infos.Add(info);
                }

                uint totalSaleNum = 0;

                string baseCmdTotalString = string.Format("SELECT SUM(LogKey6) AS SubSum FROM {0} {1}",
                                                          "{0}", searchCondition.ToString());
                string addTableCmdTotalString;
                WebUtil.AddTableNameToCmd(CurrentUser.Id, server, baseCmdTotalString, tempParamList, _start, _end, out addTableCmdTotalString, out paramList);

                if (addTableCmdTotalString.Length != 0)
                {
                    string     cmdTotalString = "SELECT SUM(SubSum) FROM ({0}) AS A";
                    SqlCommand sqlTotal       = new SqlCommand(string.Format(cmdTotalString, addTableCmdTotalString), paramList.ToArray());
                    SqlResult  sqlTotalResult = WebUtil.QueryGameServerDb(CurrentUser.Id, server, sqlTotal);

                    if (sqlTotalResult != null && sqlTotalResult.Success)
                    {
                        sqlTotalResult.SetFieldType(new SqlDataType[] {
                            SqlDataType.UInt32
                        });
                        record = sqlTotalResult.ReadRecord();
                        if (record != null && record[0] != null)
                        {
                            totalSaleNum = (uint)record[0];
                        }
                    }
                }

                ViewState[WebConfig.SessionQueryLogOffset] = offset;

                ButtonPreviousPage.Enabled = (offset > 0);
                ButtonFirstPage.Enabled    = (offset > 0);
                ButtonNextPage.Enabled     = (infos.Count >= limitCount);

                if (infos.Count != 0)
                {
                    PanelResult.Visible = true;
                    CreateSearchResultList((SaleItem[])infos.ToArray(typeof(SaleItem)), totalSaleNum);
                    LabelResult.Text = string.Format(StringDef.LabelStatisticResult, server.Group.Name,
                                                     server.Name, string.Empty, StringDef.Auction);
                }
                else
                {
                    PanelResult.Visible = false;
                    LabelOpMsg.Text     = StringDef.NoMatchingRecord;
                }
            }
            else
            {
                if (result == null)
                {
                    LabelOpMsg.Text = StringDef.QueryTimeOut;
                }
                else
                {
                    LabelOpMsg.Text = StringDef.OperationFail;
                }
            }
        }
        catch (Exception ex)
        {
            LabelOpMsg.Text     = ex.Message;
            PanelResult.Visible = false;
        }
    }
Example #29
0
        private void button_Add_Click(object sender, EventArgs e)
        {
            if (!RequiredFieldValid || SelectedItem == null) return;

            if (SelectedSaleItems.Any(itm => itm.StockItemTypeID == SelectedItem.StockItemTypeID))
            {
                BuzzleFunctions.ShowMessage("Item is already in the list", "Cannot add duplicate");
                return;
            }
            var selectedQuantity = int.Parse(textEdit_Quantity.EditValue.ToString());

            if (SelectedItem.QuantityInStock < selectedQuantity)
            {
                BuzzleFunctions.ShowMessage("Cannot sell more than the available " + SelectedItem.QuantityInStock, "");
                return;
            }

            var item = new SaleItem()
            {
                StockItemTypeID = SelectedItem.StockItemTypeID,
                UnitSoldPrice = int.Parse(textEdit_UnitPrice.EditValue.ToString()),
                Quantity = selectedQuantity,
                UnitPurchasePrice = SelectedItem.UnitPurchasePrice
            };
            item.TotalSoldPrice = item.UnitSoldPrice*item.Quantity;
            saleItemBindingSource.Add(item);
        }
Example #30
0
        public ObservableCollection <Sale> GetAll()
        {
            Dictionary <int, Sale> sales = new Dictionary <int, Sale>();

            using (con = new SqlConnection(ConfigurationManager.ConnectionStrings["FurnitureStore"].ConnectionString))
            {
                con.Open();

                //Prvo dobavim sve prodaje iz baze i smjesim ih u dictionary
                string commandText = @"SELECT * FROM Sale";

                SqlCommand command = con.CreateCommand();
                command.CommandText = commandText;

                using (SqlDataReader dataReader = command.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        int      id         = (int)dataReader["Id"];
                        DateTime dateOfSale = (DateTime)dataReader["DateOfSale"];
                        decimal  fullPrice  = (decimal)dataReader["FullPrice"];
                        string   buyer      = (string)dataReader["Buyer"];

                        Sale sale = new Sale()
                        {
                            Id         = id,
                            DateOfSale = dateOfSale,
                            FullPrice  = fullPrice,
                            Buyer      = buyer
                        };

                        sales.Add(sale.Id, sale);
                    }
                }

                //Dobavljam sve stavke namjestaja i kacim ih svaki u odgovarajucu prodaju
                commandText         = @"SELECT * FROM FurnitureSaleItem";
                command.CommandText = commandText;
                using (SqlDataReader dataReader = command.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        int furnitureId = (int)dataReader["FurnitureId"];
                        int pieces      = (int)(byte)dataReader["Pieces"];
                        int saleId      = (int)dataReader["SaleId"];

                        Furniture furniture = new FurnitureDAO().Get(furnitureId);

                        SaleItem <Furniture> furnitureSaleItem = new SaleItem <Furniture>();
                        furnitureSaleItem.ProductForSale = furniture;
                        furnitureSaleItem.Pieces         = pieces;

                        sales[saleId].FurnitureForSale.Add(furnitureSaleItem);
                    }
                }

                //Dobavljam sve stavke dodatnih usluga i kacim ih svaku u odgovarajucu prodaju
                commandText         = @"SELECT * FROM AdditionalServiceSaleItem";
                command.CommandText = commandText;
                using (SqlDataReader dataReader = command.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        int additionalServiceId = (int)dataReader["AdditionalServiceId"];
                        int pieces = (int)(byte)dataReader["Pieces"];
                        int saleId = (int)dataReader["SaleId"];

                        AdditionalService additionalService = new AdditionalServiceDAO().Get(additionalServiceId);

                        SaleItem <AdditionalService> additionalServiceSaleItem = new SaleItem <AdditionalService>();
                        additionalServiceSaleItem.ProductForSale = additionalService;
                        additionalServiceSaleItem.Pieces         = pieces;

                        sales[saleId].ServicesForSale.Add(additionalServiceSaleItem);
                    }
                }
            }
            return(new ObservableCollection <Sale>(sales.Values));
        }
 /// <summary>
 /// this method save a sale item as customer Equipment
 /// </summary>
 /// <param name="saleItem"></param>
 private void SaveSaleItemAsCustomerEquipment(SaleItem saleItem)
 {
     var customerManager = new CustomerManager(this);
     var customerEquipment = new CustomerEquipment();
     if (saleItem.Sale.CustomerId.HasValue && saleItem.ProductId.HasValue &&
         saleItem.Product.AddCustomerEquipmentInSale == true)
     {
         customerEquipment.CustomerId = saleItem.Sale.CustomerId.Value;
         customerEquipment.CompanyId = saleItem.CompanyId;
         customerEquipment.SerialNumber = saleItem.SerialNumber;
         customerEquipment.Name = saleItem.Product.Name;
         if (saleItem.Product.Manufacturer != null)
             customerEquipment.Manufacturer = saleItem.Product.Manufacturer.Name;
         customerManager.InsertCustomerEquipment(customerEquipment);
     }
 }
 public override ActionResult AddItem(SaleItem newItem)
 {
     throw new NotImplementedException();
 }
Example #33
0
        public void SyncToSale(TransactionType ebaySale)
        {
            Int32 ebayOrderSaleRecordNumber = 0;

            try
            {
                ebayOrderSaleRecordNumber =
                    (ebaySale.ContainingOrder == null || ebaySale.ContainingOrder.ShippingDetails == null) ?
                    ebaySale.ShippingDetails.SellingManagerSalesRecordNumber :
                    ebaySale.ContainingOrder.ShippingDetails.SellingManagerSalesRecordNumber;

                System.Diagnostics.Trace.WriteLine(String.Format("Begin sync of ebay sale {0}...", ebayOrderSaleRecordNumber));

                Sale sale = Sale.LoadByEbaySalesRecordNumber(ebayOrderSaleRecordNumber);
                if (sale == null)
                {
                    sale             = Sale.Create();
                    sale.Source      = SaleSources.Ebay;
                    sale.SourceId    = ebayOrderSaleRecordNumber.ToString();
                    sale.EbayName    = ebaySale.Buyer.UserID;
                    sale.NameOfBuyer = ebaySale.Buyer.BuyerInfo.ShippingAddress.Name ?? String.Empty;

                    var shippingPhone = GetStringFromTransaction(ebaySale.Buyer.BuyerInfo.ShippingAddress.Phone);
                    sale.PhoneNumber  = String.IsNullOrWhiteSpace(shippingPhone) ? "" : shippingPhone;
                    sale.EMailAddress = GetStringFromTransaction(ebaySale.Buyer.Email);
                    sale.DateOfSale   = ebaySale.CreatedDate;
                    Models.MyDataContext.Default.Sales.Add(sale);
                }

                // A sale item may occur in another (previously synced sale) and if so it must be deleted
                SaleItem oldSaleItem = SaleItem.LoadBySalesRecordNumber(ebaySale.ShippingDetails.SellingManagerSalesRecordNumber);
                if (oldSaleItem != null)
                {
                    if (oldSaleItem.Sale.Id != sale.Id)
                    {
                        Sale oldSale = null;

                        if (oldSaleItem.Sale.SaleItems.Count == 1)
                        {
                            oldSale = oldSaleItem.Sale;
                        }

                        oldSaleItem.IncreaseStock();
                        Models.MyDataContext.Default.SaleItems.Remove(oldSaleItem);

                        if (oldSale != null)
                        {
                            Models.MyDataContext.Default.Sales.Remove(oldSale);
                        }
                    }
                }

                SaleItem saleItem = SaleItem.LoadByEbaySalesRecordNumber(ebayOrderSaleRecordNumber, ebaySale.ShippingDetails.SellingManagerSalesRecordNumber);
                if (saleItem == null)
                {
                    saleItem = new SaleItem();
                    saleItem.EbaySalesRecordNumber = ebaySale.ShippingDetails.SellingManagerSalesRecordNumber;
                    saleItem.ExternalArticleName   = ebaySale.Item.Title;
                    saleItem.ExternalArticleNumber = ebaySale.Item.ItemID;
                    saleItem.InternalArticleNumber = ebaySale.Item.SKU;
                    saleItem.Article = Article.LoadByArticleNumber(ebaySale.Item.SKU);
                    if (saleItem.Article == null)
                    {
                        saleItem.Article = Article.LoadByEbayArticleNumber(ebaySale.Item.SKU);
                    }
                    saleItem.Amount              = ebaySale.QuantityPurchased;
                    saleItem.TaxRate             = ebaySale.VATPercentSpecified ? ebaySale.VATPercent : ShopperConfiguration.Default.CurrentTaxRate;
                    saleItem.SinglePriceGross    = Convert.ToDecimal(ebaySale.ConvertedTransactionPrice.Value);
                    saleItem.Sale                = sale;
                    saleItem.EbayOrderLineItemID = ebaySale.OrderLineItemID;
                    Models.MyDataContext.Default.SaleItems.Add(saleItem);
                    Models.MyDataContext.Default.SaveChanges();
                    saleItem.DecreaseStock();
                }

                if (sale.CanBeSynced)
                {
                    sale.InvoiceName     = ebaySale.Buyer.BuyerInfo.ShippingAddress.Name ?? String.Empty;
                    sale.InvoiceStreet1  = ebaySale.Buyer.BuyerInfo.ShippingAddress.Street1 ?? String.Empty;
                    sale.InvoiceStreet2  = ebaySale.Buyer.BuyerInfo.ShippingAddress.Street2 ?? String.Empty;
                    sale.InvoiceCity     = ebaySale.Buyer.BuyerInfo.ShippingAddress.CityName ?? String.Empty;
                    sale.InvoiceRegion   = ebaySale.Buyer.BuyerInfo.ShippingAddress.StateOrProvince ?? String.Empty;
                    sale.InvoicePostcode = ebaySale.Buyer.BuyerInfo.ShippingAddress.PostalCode ?? String.Empty;
                    sale.InvoiceCountry  = ebaySale.Buyer.BuyerInfo.ShippingAddress.CountryName ?? String.Empty;

                    sale.ShippingName     = ebaySale.Buyer.BuyerInfo.ShippingAddress.Name ?? String.Empty;
                    sale.ShippingStreet1  = ebaySale.Buyer.BuyerInfo.ShippingAddress.Street1 ?? String.Empty;
                    sale.ShippingStreet2  = ebaySale.Buyer.BuyerInfo.ShippingAddress.Street2 ?? String.Empty;
                    sale.ShippingCity     = ebaySale.Buyer.BuyerInfo.ShippingAddress.CityName ?? String.Empty;
                    sale.ShippingRegion   = ebaySale.Buyer.BuyerInfo.ShippingAddress.StateOrProvince ?? String.Empty;
                    sale.ShippingPostcode = ebaySale.Buyer.BuyerInfo.ShippingAddress.PostalCode ?? String.Empty;
                    sale.ShippingCountry  = ebaySale.Buyer.BuyerInfo.ShippingAddress.CountryName ?? String.Empty;

                    DateTime?ebayPayDate =
                        ebaySale.ContainingOrder == null ?
                        ebaySale.PaidTimeSpecified ? (DateTime?)ebaySale.PaidTime.Date : (DateTime?)null :
                        ebaySale.ContainingOrder.PaidTimeSpecified ? (DateTime?)ebaySale.ContainingOrder.PaidTime : (DateTime?)null;
                    sale.DateOfPayment = sale.DateOfPayment ?? ebayPayDate;
                    sale.ShippingPrice =
                        (ebaySale.ContainingOrder == null || ebaySale.ContainingOrder.Total == null || ebaySale.ContainingOrder.Subtotal == null) ?
                        GetShippingCosts(ebaySale) :
                        Convert.ToDecimal(ebaySale.ContainingOrder.Total.Value) - Convert.ToDecimal(ebaySale.ContainingOrder.Subtotal.Value);

                    DateTime?ebayCancelDate =
                        ebaySale.AdjustmentAmount.Value < 0.0 ?
                        (DateTime?)DateTime.Now :
                        (DateTime?)null;
                    saleItem.CancelDate = saleItem.CancelDate ?? ebayCancelDate;
                }

                Models.MyDataContext.Default.SaveChanges();
                System.Diagnostics.Trace.WriteLine(String.Format("Sync of ebay sale {0} successful!", ebayOrderSaleRecordNumber));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(String.Format("Sync of ebay sale {0} failed!", ebayOrderSaleRecordNumber));
                throw new SalesImportException(String.Format("Error at Ebay-Prot-Number: {0}.", ebayOrderSaleRecordNumber.ToString()),
                                               ex);
            }
        }
        public static async Task <SaleItem> UpdateSaleItemAsync(IRestDataMapper mapper, SaleItem data)
        {
            SaleItem reds = new SaleItem();

            if (mapper == null)
            {
                return(reds);
            }
            string url = $"selling/api/v1/sales/item/{data.id}";

            reds = await mapper.PutDataAsync(url, data);

            return(reds);
        }
 internal override ActionResult AddItem(SaleItem newItem)
 {
     return(new ActionResult(isSuccess: false, $"Cannot add item to a {StatusName.ToLower()} sale"));
 }
Example #36
0
 public Result SaveSaleItem(SaleItem req)
 {
     return(bll.SaveSaleItem(req));
 }
        private void btnRemoveServiceFromSale_Click(object sender, RoutedEventArgs e)
        {
            SaleItem <AdditionalService> additionalService = (SaleItem <AdditionalService>)dgServicesForSale.SelectedItem;

            servicesForSale.Remove(additionalService);
        }
Example #38
0
        public void Total_SingleItem_ReturnsUnitPrice()
        {
            var saleItem = new SaleItem(new Product("A", 1));

            Assert.Equal(1, saleItem.GetPrice().Total);
        }
Example #39
0
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     base.OnNavigatedTo(e);
     this.item = new SaleItem();
 }
Example #40
0
 public virtual void UpdateSaleItem(SaleItem saleItem)
 {
     UpdateObject(saleItem);
 }
Example #41
0
        SaleItem GetLayoutData(double width, double height)
        {
            Size size = new Size(width, height);

            // Check if cached information is available.
            if (layoutDataCache.ContainsKey(size))
            {
                return(layoutDataCache[size]);
            }

            int      visibleChildCount = 0;
            Size     maxChildSize      = new Size();
            int      rows       = 0;
            int      columns    = 0;
            SaleItem layoutData = new SaleItem();

            // Enumerate through all the children.
            foreach (View child in Children)
            {
                // Skip invisible children.
                if (!child.IsVisible)
                {
                    continue;
                }

                // Count the visible children.
                visibleChildCount++;

                // Get the child's requested size.
                SizeRequest childSizeRequest = child.Measure(Double.PositiveInfinity, Double.PositiveInfinity);

                // Accumulate the maximum child size.
                maxChildSize.Width  = Math.Max(maxChildSize.Width, childSizeRequest.Request.Width);
                maxChildSize.Height = Math.Max(maxChildSize.Height, childSizeRequest.Request.Height);
            }

            if (visibleChildCount != 0)
            {
                // Calculate the number of rows and columns.
                if (Double.IsPositiveInfinity(width))
                {
                    columns = visibleChildCount;
                    rows    = 1;
                }
                else
                {
                    columns = (int)((width + ColumnSpacing) / (maxChildSize.Width + ColumnSpacing));
                    columns = Math.Max(1, columns);
                    rows    = (visibleChildCount + columns - 1) / columns;
                }

                // Now maximize the cell size based on the layout size.
                Size cellSize = new Size();

                if (Double.IsPositiveInfinity(width))
                {
                    cellSize.Width = maxChildSize.Width;
                }
                else
                {
                    cellSize.Width = (width - ColumnSpacing * (columns - 1)) / columns;
                }

                if (Double.IsPositiveInfinity(height))
                {
                    cellSize.Height = maxChildSize.Height;
                }
                else
                {
                    cellSize.Height = (height - RowSpacing * (rows - 1)) / rows;
                }

                layoutData = new SaleItem(visibleChildCount, cellSize, rows, columns);
            }

            layoutDataCache.Add(size, layoutData);
            return(layoutData);
        }
Example #42
0
 public virtual void InsertSaleItem(SaleItem saleItem)
 {
     InsertObject(saleItem);
 }
Example #43
0
 public void SaveSaleItem(SaleItem s)
 {
     db.SaleItems.Add(s);
     db.SaveChanges();
 }
Example #44
0
    bool CreateSearchResultList(SaleItem[] infos, uint total)
    {
        if (infos != null && infos.Length != 0)
        {
            foreach (SaleItem info in infos)
            {
                TableRow row = new TableRow();

                TableCell cell = new TableCell();
                FS2ItemData itemData = FS2GameDataManager.TheInstance.GetItemData(info.itemTemplateId);
                if (itemData != null)
                {
                    string colorStr = "Black";
                    switch (itemData.Quality)
                    {
                        case FS2ItemQuality.White:
                            colorStr = "Black";
                            break;
                        case FS2ItemQuality.Blue:
                            colorStr = "#3165FF";
                            break;
                        case FS2ItemQuality.Green:
                            colorStr = "#00FB00";
                            break;
                        case FS2ItemQuality.Yellow:
                            colorStr = "Yellow";
                            break;
                        case FS2ItemQuality.Orange:
                            colorStr = "#F8952C";
                            break;
                    }

                    cell.Text = string.Format("<span onmouseover='{0}' style='color:{1};'>{2}</span>",
                        string.Format("updateRoleItemInfo(\"{0}\")", itemData.TemplateId), colorStr,
                        itemData.Name);
                }
                else
                    cell.Text = info.itemTemplateId;
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = info.saleNum.ToString();
                row.Cells.Add(cell);

                cell = new TableCell();
                if (total != 0)
                    cell.Text = Decimal.Round((decimal)info.saleNum / total, 3) * 100 + "%";
                else
                    cell.Text = "0";
                row.Cells.Add(cell);

                TableSearchResult.Rows.Add(row);                
            }
            TableRow rowTail = new TableRow();
            TableCell cellTail = new TableCell();
            cellTail.ColumnSpan = 5;
            cellTail.Font.Bold = true;
            cellTail.Text = StringDef.Total + StringDef.Colon + total;
            rowTail.Cells.Add(cellTail);

            TableSearchResult.Rows.Add(rowTail);
            return true;
        }
        return false;
    }
Example #45
0
        private static SaleItem CreateSaleItem()
        {
            var saleItem = new SaleItem
                               {
                                   ProductName = "productName",
                                   ProductDisplayName = "productName",
                                   ProductID = 1,
                                   QtySold = 1,
                                   UnitPriceIn = 1,
                                   PublicUPOut = 1,
                                   UnitPriceOut = 1,
                                   Discount = 0,
                                   SubTotal = 1,
                                   ProdPicture = Resources.NoImage,
                                   FKProduct = null
                               };

            return saleItem;
        }
Example #46
0
    protected void Query(int offset)
    {
        try
        {
            int serverId = ServerDropDownList.SelectedServerId;
            GameServer server = ServerDropDownList.SelectedGameServer;
            if (server == null)
            {
                LabelOpMsg.Text = string.Format(StringDef.MsgCannotBeNone, StringDef.GameServer);
                return;
            }
            if (!server.IsConnected)
            {
                LabelOpMsg.Text = StringDef.NoConnectionAlert;
                return;
            }
            
            ArrayList tempParamList = new ArrayList();
            ArrayList paramList = new ArrayList();
            StringBuilder searchCondition = new StringBuilder();

            searchCondition.Append(string.Format("WHERE LogEvent='{0}'", LogEvent.AuctionStatistic));
                        
            _start = StartDate.SelectedDate;
            if (_start == DateTime.MinValue)
            {
                LabelOpMsg.Text = StringDef.ParameterInputError;
                return;
            }            
            _end = EndDate.SelectedDate;
            if (_end == DateTime.MinValue)
            {
                LabelOpMsg.Text = StringDef.ParameterInputError;
                return;
            }

            searchCondition.Append(string.Format(" AND {0}>='{1}' AND {0}<'{2}'", FS2TableString.LogFieldLogTime, _start.ToString("yyyy-MM-dd HH:mm:ss"), _end.ToString("yyyy-MM-dd HH:mm:ss")));

            //ItemId¿ÉÒÔ²»Ìî
            string itemId = TextBoxItemId.Text.Trim();
            if (itemId != null && itemId.Length != 0)
            {
                searchCondition.Append(string.Format(" AND {0}='{1}'", FS2TableString.LogFieldLogKey2, itemId));
            }


            string baseCmdString = string.Format("SELECT LogKey2,SUM(LogKey6) AS SubSum FROM {0} {1} GROUP BY LogKey2",
                "{0}", searchCondition.ToString());
            string addTableCmdString;
            WebUtil.AddTableNameToCmd(CurrentUser.Id, server, baseCmdString, tempParamList, _start, _end, out addTableCmdString, out paramList);
            if (addTableCmdString.Length == 0)
            {
                //
                return;
            }

            int limitCount = _recordPerPage;
            string limitStatement = string.Format(" LIMIT {0},{1}", offset, limitCount);

            string cmdString = "SELECT LogKey2,SUM(SubSum) AS Total FROM ({0}) AS A GROUP BY LogKey2 ORDER BY Total DESC {1}";

            SqlCommand cmd = new SqlCommand(string.Format(cmdString, addTableCmdString, limitStatement), paramList.ToArray());
            SqlResult result = WebUtil.QueryGameServerDb(CurrentUser.Id, server, cmd);
            if (result != null && result.Success)
            {
                Session[WebConfig.SessionQueryLogOffset] = offset;
                result.SetFieldType(new SqlDataType[]{
                                    SqlDataType.String,
                                    SqlDataType.Int32,
                                    });
                object[] record = null;
                ArrayList infos = new ArrayList();

                while ((record = result.ReadRecord()) != null)
                {
                    SaleItem info = new SaleItem();
                    info.itemTemplateId = record[0] as string;
                    info.saleNum = (int)record[1];

                    infos.Add(info);
                }

                uint totalSaleNum = 0;

                string baseCmdTotalString = string.Format("SELECT SUM(LogKey6) AS SubSum FROM {0} {1}",
                    "{0}", searchCondition.ToString());
                string addTableCmdTotalString;
                WebUtil.AddTableNameToCmd(CurrentUser.Id, server, baseCmdTotalString, tempParamList, _start, _end, out addTableCmdTotalString, out paramList);

                if (addTableCmdTotalString.Length != 0)
                {
                    string cmdTotalString = "SELECT SUM(SubSum) FROM ({0}) AS A";
                    SqlCommand sqlTotal = new SqlCommand(string.Format(cmdTotalString, addTableCmdTotalString), paramList.ToArray());
                    SqlResult sqlTotalResult = WebUtil.QueryGameServerDb(CurrentUser.Id, server, sqlTotal);

                    if (sqlTotalResult != null && sqlTotalResult.Success)
                    {
                        sqlTotalResult.SetFieldType(new SqlDataType[]{
                                SqlDataType.UInt32
                            });
                        record = sqlTotalResult.ReadRecord();
                        if (record != null && record[0] != null) totalSaleNum = (uint)record[0];
                    }
                }

                ViewState[WebConfig.SessionQueryLogOffset] = offset;

                ButtonPreviousPage.Enabled = (offset > 0);
                ButtonFirstPage.Enabled = (offset > 0);
                ButtonNextPage.Enabled = (infos.Count >= limitCount);

                if (infos.Count != 0)
                {
                    PanelResult.Visible = true;
                    CreateSearchResultList((SaleItem[])infos.ToArray(typeof(SaleItem)), totalSaleNum);
                    LabelResult.Text = string.Format(StringDef.LabelStatisticResult, server.Group.Name,
                        server.Name, string.Empty, StringDef.Auction);
                }
                else
                {
                    PanelResult.Visible = false;
                    LabelOpMsg.Text = StringDef.NoMatchingRecord;
                }
            }
            else
            {
                if (result == null)
                    LabelOpMsg.Text = StringDef.QueryTimeOut;
                else
                    LabelOpMsg.Text = StringDef.OperationFail;
            }
        }
        catch (Exception ex)
        {
            LabelOpMsg.Text = ex.Message;
            PanelResult.Visible = false;
        }
    }
Example #47
0
 public Task UpdateAuctionPrice(SaleItem item, long newPrice)
 {
     return(_saleItemsRepository.UpdateItemAuctionPrice(item, newPrice, $"{_userManager.LoggedUser.FirstName} {_userManager.LoggedUser.Surname}"));
 }
Example #48
0
        protected void btnCompleteCheckout_Click(object sender, EventArgs e)
        {
            try
            {
                //save the customer
                Customer customer = new Customer
                {
                    CustomerName = txtCustName.Text,
                    Email        = txtEmail.Text,
                    Phone        = txtCustPhone.Text
                };

                //set the customer ID to either the phone or email depending on whats supplied
                customer.CustomerID = customer.Phone ?? customer.Email;

                //register customer
                Result result = SharedLogic.TcmpTestCore.RegisterCustomer(customer);

                //error on initiating a new sale
                if (result.StatusCode != SharedCommonsGlobals.SUCCESS_STATUS_CODE)
                {
                    lblInfoMsg.Text = (result.StatusDesc);
                    return;
                }

                //get items stored in session
                List <Item> shoppingCart = GetItemsAlreadyInShoppingCart();

                //oops..nothing in shopping cart
                if (shoppingCart.Count <= 0)
                {
                    lblInfoMsg.Text = ("No Items Found in Shopping Cart");
                    return;
                }

                //create a new sale
                Sale sale = new Sale
                {
                    SaleID     = GenerateTransactionIDIfNotExists(),
                    CustomerId = customer.CustomerID
                };

                //initiate a new sale
                result = SharedLogic.TcmpTestCore.RegisterSale(sale);

                //error on initiating a new sale
                if (result.StatusCode != SharedCommonsGlobals.SUCCESS_STATUS_CODE)
                {
                    lblInfoMsg.Text = (result.StatusDesc);
                    return;
                }

                List <SaleItem> saleItems = new List <SaleItem>();

                //go item by item in cart
                foreach (var item in shoppingCart)
                {
                    //attach each item to this sale
                    SaleItem saleItem = new SaleItem
                    {
                        ItemId = item.ItemCode,
                        SaleId = sale.SaleID
                    };
                    saleItems.Add(saleItem);
                }

                //attach sale item to new sale
                result = SharedLogic.TcmpTestCore.RegisterSaleItems(saleItems.ToArray());

                //error on initiating a new sale
                if (result.StatusCode != SharedCommonsGlobals.SUCCESS_STATUS_CODE)
                {
                    lblInfoMsg.Text = (result.StatusDesc);
                    return;
                }

                //success
                lblInfoMsg.Text = "Please Click ON Your Prefered Method of Payment";

                //make him select a payment method
                multiViewContent.SetActiveView(viewPaymentMethodChoice);
            }
            catch (Exception ex)
            {
                ShowErrorMsg(SharedLogic.INTERNAL_ERROR_MSG);

                //log error
                SharedLogic.TcmpTestCore.LogError($"EXCEPTION:{ex.Message}", $"{this.GetType().Name}-{SharedLogic.GetCurrentMethod()}", "N/A");
            }
        }
        public virtual IList GetSaleItems(IList depositItemList)
        {
            var saleItemList = new List<SaleItem>();
            foreach (DepositItem depositItem in depositItemList)
            {
                if (depositItem == null)
                    continue;

                var saleItem =
                    new SaleItem
                    {
                        SaleOrderId = depositItem.DepositId,
                        ProductId = depositItem.ProductId,
                        ProductName = depositItem.ProductName,
                        FkProduct = depositItem.FkProduct,
                        UnitPriceIn = depositItem.UnitPriceIn,
                        UnitPriceOut = depositItem.UnitPriceOut,
                        Discount = depositItem.Discount,
                        QtySold = depositItem.QtySold
                    };

                if (saleItem.FkProduct != null)
                {
                    saleItem.ProductName = saleItem.FkProduct.ProductName;

                    var extraPercentage = saleItem.FkProduct.ExtraPercentage;
                    var discountPercentage = depositItem.Discount;
                    var publicUnitPriceOut =
                        saleItem.UnitPriceIn + ((saleItem.UnitPriceIn * extraPercentage) / 100);
                    publicUnitPriceOut =
                        publicUnitPriceOut - ((publicUnitPriceOut * discountPercentage) / 100);
                    saleItem.PublicUpOut = publicUnitPriceOut;
                }

                saleItemList.Add(saleItem);
            }
            return saleItemList;
        }
    /// <summary>
    /// this method create and return a list of SaleItem 
    /// </summary>
    /// <returns></returns>
    private List<SaleItem> CreateSaleItemList()
    {
        List<SaleItem> list = new List<SaleItem>();
        DataTable basket = Session["basket"] as DataTable;
        if (basket == null)
            return list;
        //
        foreach (DataRow row in basket.Rows)
        {
            SaleItem item = new SaleItem();
            item.CompanyId = Company.CompanyId;
            item.ModifiedDate = DateTime.Now;
            item.Quantity = Convert.ToInt16(row["Quantity"]);
            item.SerialNumber = Convert.ToString(row["SerialNumber"]);
            item.UnitPrice = Convert.ToDecimal(row["UnitPrice"]);
            item.UnitCost = Convert.ToDecimal(row["UnitCost"]);

            if (row["ProductId"] == DBNull.Value || Convert.ToInt32(row["ProductId"]) == 0)
            {
                item.ProductId = null;
                if (row["ProductName"].ToString().Contains("&nbsp;"))
                    row["ProductName"] = row["ProductName"].ToString().Remove(row["ProductName"].ToString().IndexOf("&nbsp;"));

                item.SpecialProductName = Convert.ToString(row["ProductName"]);
            }
            else
                item.ProductId = Convert.ToInt32(row["ProductId"]);

            list.Add(item);
        }
        return list;
    }
 public virtual void InsertSaleItem(SaleItem saleItem)
 {
     InsertObject(saleItem);
 }
Example #52
0
        } //completed

        static void ShowAddSale()
        {
            Console.WriteLine("Satış əlavə edin");
            Sale addSale = new Sale();

            #region SaleNumber
            DateTime Date;
            int      itemCount;
            int      productCode;

            do
            {
                Console.WriteLine("Satışın Nömrəsini daxil edin: ");
                string inputNumber = Console.ReadLine();
                int    Number;
                while (!int.TryParse(inputNumber, out Number))
                {
                    Console.WriteLine("Yalnız rəqəm daxil edə bilərsiniz");
                    inputNumber = Console.ReadLine();
                }
                addSale.SaleNumber = Number;

                #endregion
                Console.WriteLine("Satış tarixini daxil edin");
                string inputDate = Console.ReadLine();

                while (!DateTime.TryParse(inputDate, out Date))
                {
                    Console.WriteLine("Düzgün tarix daxil edin");
                    inputDate = Console.ReadLine();
                }
                addSale.Date = Date;

                SaleItem saleItem = new SaleItem();

                #region SaleItemCount

                Console.WriteLine("İtem Miqdarını daxil edin");
                string inputItemCount = Console.ReadLine();

                while (!int.TryParse(inputItemCount, out itemCount))
                {
                    Console.WriteLine("Yalnız rəqəm daxil edə bilərsiniz");
                    inputItemCount = Console.ReadLine();
                }
                saleItem.SaleItemCount = itemCount;
                #endregion

                Product product = new Product();

                #region ProductCode

                Console.WriteLine("Kodu daxil edin: ");
                string inputItemCode = Console.ReadLine();
                while (!int.TryParse(inputItemCode, out productCode))
                {
                    Console.WriteLine("Yalnız rəqəm daxil edə bilərsiniz");
                    inputItemCode = Console.ReadLine();
                }
                product.ProductCode = productCode;
                #endregion ProductCode

                _marketableService.AddSale(productCode, itemCount, Number, Date);
            } while (itemCount == 0);
        } //completed
Example #53
0
        private static void UpdateStock(Repository repository, IEnumerable <Stock> stocks, SaleItem saleItem)
        {
            var newQuantity = saleItem.Quantity;
            var product     = saleItem.Product;
            var productId   = product.Id;
            var productName = product.Name;

            var stock = stocks.FirstOrDefault(it => it.ProductId == productId);

            if (stock == null)
            {
                throw new Exception(string.Format("Unknown product [{0}]", productName));
            }
            if (stock.Quantity < newQuantity)
            {
                throw new Exception(string.Format("Insufficient quantity for product [{0}]", productName));
            }

            stock.Quantity -= newQuantity;
            repository.SaveChanges();
        }
        /// <summary>
        /// Method to insert a Item in the saleItem
        /// This method verifies if you are trying to insert a composite product, and treat it
        /// insert a customerEquipment If the customer exists
        /// This method also, drop off the quantity in the inventory
        /// </summary>
        /// <param name="item"></param>
        /// <param name="sale"></param>
        public void InsertSaleItem(SaleItem saleItem, Sale sale)
        {
            DbContext.SaleItems.InsertOnSubmit(saleItem);
            DbContext.SubmitChanges();

            var product = new ProductManager(this).GetProduct(Convert.ToInt32(saleItem.ProductId),
                                                                             saleItem.CompanyId);
            if (product != null)
                saleItem.ProductId = product.ProductId;
            DbContext.SubmitChanges();

            SaveSaleItemAsCustomerEquipment(saleItem);
            DropProductInSale(saleItem);
        }