Esempio n. 1
0
        public void SaveSale(SaleModel saleInfo, string cashierId)
        {
            List <SaleDetailDBModel> details = new List <SaleDetailDBModel>();
            ProductData products             = new ProductData(_config);
            var         taxRate = ConfigHelper.GetTaxRate() / 100;

            foreach (var item in saleInfo.SaleDetails)
            {
                var detail = new SaleDetailDBModel
                {
                    ProductId = item.ProductId,
                    Quantity  = item.Quantity
                };

                var productInfo = products.GetProductById(detail.ProductId);

                if (productInfo == null)
                {
                    throw new Exception($"The product Id of {detail.ProductId} could not be found in the database!");
                }

                detail.PurchasePrice = (productInfo.RetailPrice * detail.Quantity);

                if (productInfo.IsTaxable)
                {
                    detail.Tax = (detail.PurchasePrice * taxRate);
                }

                details.Add(detail);
            }

            SaleDBModel sale = new SaleDBModel
            {
                SubTotal  = details.Sum(x => x.PurchasePrice),
                Tax       = details.Sum(x => x.Tax),
                CashierId = cashierId
            };

            sale.Total = sale.SubTotal + sale.Tax;

            using (SqlDataAccess sql = new SqlDataAccess(_config))
            {
                try
                {
                    sql.StartTransaction("TRMData");

                    sql.SaveDataInTranscation("dbo.spSale_Insert", sale);

                    sale.Id = sql.LoadDataInTranscation <int, dynamic>("dbo.spSale_Lookup", new
                    {
                        sale.CashierId,
                        sale.SaleDate
                    }).FirstOrDefault();

                    foreach (var item in details)
                    {
                        item.SaleId = sale.Id;
                        sql.SaveDataInTranscation("dbo.spSaleDetail_Insert", item);
                    }

                    sql.CommitTranscation();
                }
                catch
                {
                    sql.RollbackTranscation();
                    throw;
                }
            }
        }