internal static DiscountItem ConvertToDiscountItem(int discountTypeInt, int manualDiscountTypeInt, int customerDiscountTypeInt, decimal effectiveAmount, decimal dealPrice, decimal discountAmount, decimal percentage, string offerId, string offerName, string discountCode) { DiscountTypes discountType = (DiscountTypes)discountTypeInt; bool isManualTotal = manualDiscountTypeInt == (int)ManualDiscountType.TotalDiscountAmount || manualDiscountTypeInt == (int)ManualDiscountType.TotalDiscountPercent; DiscountItem discountItem = (DiscountItem)SalesOrder.InternalApplication.BusinessLogic.Utility.CreateDiscountItem(discountType, isManualTotal); discountItem.EffectiveAmount = effectiveAmount; discountItem.DealPrice = dealPrice; discountItem.Amount = discountAmount; discountItem.Percentage = percentage; PeriodicDiscountItem periodicDiscountItem; CustomerDiscountItem customerDiscountItem; LineDiscountItem lineDiscountItem; if ((lineDiscountItem = discountItem as LineDiscountItem) != null) { lineDiscountItem.LineDiscountType = (LineDiscountItem.DiscountTypes)discountType; if ((periodicDiscountItem = discountItem as PeriodicDiscountItem) != null) { periodicDiscountItem.DiscountCode = discountCode; periodicDiscountItem.OfferId = offerId; periodicDiscountItem.OfferName = offerName; } else if ((customerDiscountItem = discountItem as CustomerDiscountItem) != null) { CustomerDiscountTypes customerDiscountType = (CustomerDiscountTypes)customerDiscountTypeInt; customerDiscountItem.CustomerDiscountType = (CustomerDiscountItem.CustomerDiscountTypes)(customerDiscountType); } } return(discountItem); }
public async Task <EntityApiResponse <DiscountDetail> > UpdateDiscountAsync(DiscountDetail discountDetail, string currentUserId) { if (discountDetail is null) { throw new ArgumentNullException(nameof(discountDetail)); } if (discountDetail.DiscountItems is null || discountDetail.DiscountItems.Count < 1) { return(new EntityApiResponse <DiscountDetail>(error: "Discount has no items")); } if (discountDetail.StartDate >= discountDetail.EndDate) { return(new EntityApiResponse <DiscountDetail>(error: "The start date should be earlier than the end date")); } var discount = await _discountRepository.GetByIdAsync(discountDetail.Id); if (discount is null) { return(new EntityApiResponse <DiscountDetail>(error: "Discount does not exist")); } // Delete the current items for the discount await _discountItemRepository.DeleteAsync(discount.DiscountItems); // Add the new ones to the discount foreach (var discountItem in discountDetail.DiscountItems) { var stock = await _stockRepository.GetByIdAsync(discountItem.Stock?.Id); if (stock is null) { continue; } var newDiscountItem = new DiscountItem { StockId = stock.Id, DiscountId = discount.Id, CreatedById = currentUserId, ModifiedById = currentUserId }; await _discountItemRepository.InsertAsync(newDiscountItem); } discount.StartDate = discountDetail.StartDate.ToUniversalTime(); discount.EndDate = discountDetail.EndDate.ToUniversalTime(); discount.ModifiedById = currentUserId; discount.LastModifiedDate = DateTime.UtcNow; discount.Value = discountDetail.Value; discount.Description = discountDetail.Description?.Trim(); await _discountRepository.UpdateAsync(discount); return(new EntityApiResponse <DiscountDetail>(entity: new DiscountDetail(discount))); }
private BillDiscount ProcessDiscount(long itemQuantity) { DiscountItem discountItem = _offerItem.discountItem; double itemPrice = _priceList.GetPriceOf(discountItem.name); double discountValue = CalculateDiscount(itemQuantity, itemPrice, discountItem.discountPercent); return(new BillDiscount(discountItem.name, discountItem.discountPercent, discountValue)); }
public DiscountItemDetail(DiscountItem discountItem) { Id = discountItem.Id; Stock = new StockDetail(discountItem.Stock); Discount = new DiscountDetail { Id = discountItem.Discount.Id }; }
/* * Queries the service to see if a discount is running for today. If so, it will update the view's discount banner */ private void CheckForDiscounts() { double discountPercentage = 0; DiscountItem discount = _service.GetDiscount(DateTime.Now); if (discount != null) { discountPercentage = Math.Round(discount.Size * 100, 0); String bannerText = String.Format("{0}% sale ends on {1}!", discountPercentage.ToString(), discount.End.ToShortDateString()); _view.SetDiscountBanner(bannerText); } }
public Discount MapToModel(DiscountViewModel viewModel) { Discount model = new Discount(); PropertyCopier <DiscountViewModel, Discount> .Copy(viewModel, model); model.DiscountOne = viewModel.discountOne; model.DiscountTwo = viewModel.discountTwo; model.EndDate = viewModel.endDate; model.StartDate = viewModel.startDate; model.StoreCategory = viewModel.storeCategory; model.Information = viewModel.storeCategory; model.StoreCode = viewModel.store.code; model.StoreId = viewModel.store.id; model.StoreName = viewModel.store.name; model.Items = new List <DiscountItem>(); //List<DiscountItem> discountItems = new List<DiscountItem>(); //List<DiscountDetail> discountDetails = new List<DiscountDetail>(); foreach (DiscountItemViewModel i in viewModel.items) { DiscountItem discountItem = new DiscountItem(); PropertyCopier <DiscountItemViewModel, DiscountItem> .Copy(i, discountItem); discountItem.RealizationOrder = i.realizationOrder; discountItem.Details = new List <DiscountDetail>(); foreach (DiscountDetailViewModel d in i.details) { DiscountDetail discountDetail = new DiscountDetail(); PropertyCopier <DiscountDetailViewModel, DiscountDetail> .Copy(d, discountDetail); discountDetail.ArticleRealizationOrder = d.dataDestination.ArticleRealizationOrder; discountDetail.Code = d.dataDestination.code; discountDetail.DomesticCOGS = d.DomesticCOGS; discountDetail.DomesticRetail = d.DomesticRetail; discountDetail.DomesticSale = d.DomesticSale; discountDetail.DomesticWholesale = d.DomesticWholesale; discountDetail.InternationalCOGS = d.InternationalCOGS; discountDetail.InternationalRetail = d.InternationalRetail; discountDetail.InternationalSale = d.InternationalSale; discountDetail.InternationalWholesale = d.DomesticWholesale; discountDetail.ItemId = d.dataDestination._id; discountDetail.Name = d.dataDestination.name; discountDetail.Size = d.dataDestination.Size; discountDetail.Uom = d.dataDestination.Uom; discountItem.Details.Add(discountDetail); } model.Items.Add(discountItem); } return(model); }
/* * Queries the service for all catalog items which match the brand and type filter (if any) */ public void LoadCatalogItems(int brandIdFilter, int typeIdFilter) { _view.ClearGrid(); IEnumerable <CatalogItem> items = _service.GetCatalogItems(brandIdFilter, typeIdFilter); double discountVal = 0; DiscountItem discount = _service.GetDiscount(DateTime.Now); if (discount != null) { discountVal = discount.Size; } _view.SetCatalogItems(items, discountVal); }
public static bool AddDiscountItem(long basketId, string discountCode, GustafsGalleryStoreContext context) { Order order = OrderHelper.GetOrder(basketId, context); Discount discount = DiscountCodeHelper.GetDiscount(discountCode, context); DiscountItem discountItem = new DiscountItem() { OrderId = order.Id, DiscountId = discount.Id }; if (!order.Discounts.Contains(discountItem)) { context.Add(discountItem); context.SaveChanges(); return(true); } return(false); }
internal static CustomerOrderTransaction GetTransactionFromInfo(CustomerOrderInfo orderInfo, SalesOrder salesOrderService) { CustomerOrderTransaction transaction = (CustomerOrderTransaction)SalesOrder.InternalApplication.BusinessLogic.Utility.CreateCustomerOrderTransaction( ApplicationSettings.Terminal.StoreId, ApplicationSettings.Terminal.StoreCurrency, ApplicationSettings.Terminal.TaxIncludedInPrice, SalesOrder.InternalApplication.Services.Rounding, salesOrderService); // Get all the defaults SalesOrder.InternalApplication.BusinessLogic.TransactionSystem.LoadTransactionStatus(transaction); // General header properties transaction.OrderId = orderInfo.Id; transaction.OrderType = orderInfo.OrderType; if (orderInfo.OrderType == CustomerOrderType.Quote) { transaction.QuotationId = orderInfo.Id; } transaction.OriginalOrderType = orderInfo.OrderType; switch (orderInfo.OrderType) { case CustomerOrderType.Quote: transaction.OrderStatus = GetSalesStatus((SalesQuotationStatus)orderInfo.Status); break; case CustomerOrderType.SalesOrder: transaction.OrderStatus = GetSalesStatus((SalesOrderStatus)orderInfo.Status, (DocumentStatus)orderInfo.DocumentStatus); break; default: transaction.OrderStatus = SalesStatus.Unknown; NetTracer.Information("SalesOrder::CustomerOrderTransaction: CustomerOrderInfo OrderType is unknown: {0}", orderInfo.OrderType); break; } transaction.LockPrices = true; transaction.ExpirationDate = ParseDateString(orderInfo.ExpiryDateString, DateTime.Today); // RequestedDeliveryDate is directly input from user. It is stored in the local timezone transaction.RequestedDeliveryDate = ParseDateString(orderInfo.RequestedDeliveryDateString, DateTime.Today); // CreationDate is stored in UTC. It needs to be converted to local time zone where order is accessed. ((IPosTransactionV2)transaction).BeginDateTime = ParseDateString(orderInfo.CreationDateString, DateTime.UtcNow, DateTimeStyles.AdjustToUniversal).ToLocalTime(); transaction.LocalHourOfDay = orderInfo.LocalHourOfDay; ((IPosTransactionV2)transaction).Comment = orderInfo.Comment; // Header delivery DM.StoreDataManager storeDataManager = new DM.StoreDataManager( SalesOrder.InternalApplication.Settings.Database.Connection, SalesOrder.InternalApplication.Settings.Database.DataAreaID); transaction.WarehouseId = orderInfo.WarehouseId; transaction.DeliveryMode = storeDataManager.GetDeliveryMode(orderInfo.DeliveryMode); transaction.CurrencyCode = orderInfo.CurrencyCode; foreach (var code in orderInfo.DiscountCodes) { transaction.DiscountCodes.AddLast(code); } // Header affiliation DM.AffiliationDataManager affiliationDataManager = new DM.AffiliationDataManager( SalesOrder.InternalApplication.Settings.Database.Connection, SalesOrder.InternalApplication.Settings.Database.DataAreaID); if (orderInfo.Affiliations != null && orderInfo.Affiliations.Any()) { foreach (AffiliationInfo affiliationInfo in orderInfo.Affiliations) { transaction.AffiliationLines.AddLast( new AffiliationItem() { RecId = affiliationInfo.AffiliationId, LoyaltyTier = affiliationInfo.LoyaltyTierId, AffiliationType = affiliationInfo.AffiliationType }); } } // Customer info ICustomerSystem customerSystem = SalesOrder.InternalApplication.BusinessLogic.CustomerSystem; DM.CustomerDataManager customerDataManager = new DM.CustomerDataManager( SalesOrder.InternalApplication.Settings.Database.Connection, SalesOrder.InternalApplication.Settings.Database.DataAreaID); DE.ICustomer customer = customerSystem.GetCustomerInfo(orderInfo.CustomerAccount); // try to get the customer from transaction service if (customer == null || customer.IsEmptyCustomer()) { DE.ICustomer tempCustomer = SalesOrder.GetCustomerFromAX(orderInfo.CustomerAccount, customerSystem, customerDataManager); if (tempCustomer != null) { customer = tempCustomer; } } DE.ICustomer invoicedCustomer = customerSystem.GetCustomerInfo(customer.InvoiceAccount); // try to get the invoicedCustomer from transaction service if (invoicedCustomer == null || invoicedCustomer.IsEmptyCustomer()) { DE.ICustomer tempinvoicedCustomer = SalesOrder.GetCustomerFromAX(customer.InvoiceAccount, customerSystem, customerDataManager); if (tempinvoicedCustomer != null) { invoicedCustomer = tempinvoicedCustomer; } } // If InvoiceCustomer is *still* blank/empty then fallback to Customer so that the UI fields are populated. if (invoicedCustomer == null || invoicedCustomer.IsEmptyCustomer()) { invoicedCustomer = customer; } customerSystem.SetCustomer(transaction, customer, invoicedCustomer); if (transaction.DeliveryMode != null && !string.IsNullOrWhiteSpace(orderInfo.AddressRecordId)) { DE.IAddress shippingAddress = customerDataManager.GetAddress(Int64.Parse(orderInfo.AddressRecordId)); customerSystem.SetShippingAddress(transaction, shippingAddress); } if (!string.IsNullOrEmpty(orderInfo.SalespersonStaffId)) { // Sets the sales person id and name according to AX values // This is done because we do not know whether the sales person information is available on this store transaction.SalesPersonId = orderInfo.SalespersonStaffId; transaction.SalesPersonName = orderInfo.SalespersonName; DM.EmployeeDataManager employees = new DM.EmployeeDataManager( SalesOrder.InternalApplication.Settings.Database.Connection, SalesOrder.InternalApplication.Settings.Database.DataAreaID); Employee employee = employees.GetEmployee(ApplicationSettings.Terminal.StoreId, orderInfo.SalespersonStaffId); if (employee != null) { transaction.SalesPersonId = employee.StaffId; transaction.SalesPersonName = employee.Name; transaction.SalesPersonNameOnReceipt = employee.NameOnReceipt; } } transaction.ChannelReferenceId = orderInfo.ChannelReferenceId; if (transaction.LoyaltyItem != null && !string.IsNullOrEmpty(orderInfo.LoyaltyCardId)) { transaction.LoyaltyItem.LoyaltyCardNumber = orderInfo.LoyaltyCardId; } transaction.ReceiptEmailAddress = orderInfo.Email; transaction.TotalManualDiscountAmount = orderInfo.TotalManualDiscountAmount; transaction.TotalManualPctDiscount = orderInfo.TotalManualDiscountPercentage; DateTime earliestDeliveryDate = DateTime.MaxValue; // Items foreach (ItemInfo item in orderInfo.Items) { Collection <Tax.MiscellaneousCharge> lineCharges = new Collection <Tax.MiscellaneousCharge>(); foreach (ChargeInfo charge in item.Charges) { Tax.MiscellaneousCharge lineCharge = (Tax.MiscellaneousCharge)SalesOrder.InternalApplication.BusinessLogic.Utility.CreateMiscellaneousCharge( charge.Amount, charge.SalesTaxGroup, charge.TaxGroup, charge.Code, string.Empty, transaction); lineCharges.Add(lineCharge); } // add item SaleLineItem lineItem = (SaleLineItem)SalesOrder.InternalApplication.BusinessLogic.Utility.CreateSaleLineItem( ApplicationSettings.Terminal.StoreCurrency, SalesOrder.InternalApplication.Services.Rounding, transaction); lineItem.Found = true; lineItem.OrderLineRecordId = item.RecId; lineItem.ItemId = item.ItemId; lineItem.Quantity = item.Quantity; lineItem.ReturnQtyAllowed = item.Quantity; lineItem.SalesOrderUnitOfMeasure = item.Unit; lineItem.Price = item.Price; lineItem.NetAmount = item.NetAmount; lineItem.QuantityOrdered = item.Quantity; lineItem.QuantityPickedUp = item.QuantityPicked; lineItem.DeliveryMode = storeDataManager.GetDeliveryMode(item.DeliveryMode); lineItem.DeliveryDate = ParseDateString(item.RequestedDeliveryDateString, DateTime.Today); lineItem.DeliveryStoreNumber = item.StoreId; lineItem.DeliveryWarehouse = item.WarehouseId; lineItem.SerialId = item.SerialId; lineItem.BatchId = item.BatchId; lineItem.HasBeenRecalled = true; lineItem.SalesMarkup = item.SalesMarkup; lineItem.Comment = string.IsNullOrEmpty(item.Comment) ? string.Empty : item.Comment; lineItem.LineStatus = GetSalesStatus((SalesOrderStatus)item.Status); lineItem.LineDiscount = item.LineDscAmount; lineItem.PeriodicDiscount = item.PeriodicDiscount; lineItem.PeriodicPctDiscount = item.PeriodicPercentageDiscount; lineItem.LineManualDiscountAmount = item.LineManualDiscountAmount; lineItem.LineManualDiscountPercentage = item.LineManualDiscountPercentage; lineItem.TotalDiscount = item.TotalDiscount; lineItem.TotalPctDiscount = item.TotalPctDiscount; foreach (Tax.MiscellaneousCharge charge in lineCharges) { lineItem.MiscellaneousCharges.Add(charge); } if (lineItem.DeliveryMode != null && !string.IsNullOrWhiteSpace(item.AddressRecordId)) { lineItem.ShippingAddress = customerDataManager.GetAddress(Int64.Parse(item.AddressRecordId)); } lineItem.Dimension.VariantId = item.VariantId; lineItem.Dimension.ColorId = item.ColorId; lineItem.Dimension.StyleId = item.StyleId; lineItem.Dimension.SizeId = item.SizeId; lineItem.Dimension.ConfigId = item.ConfigId; lineItem.Dimension.ColorName = item.ColorName; lineItem.Dimension.StyleName = item.StyleName; lineItem.Dimension.SizeName = item.SizeName; lineItem.Dimension.ConfigName = item.ConfigName; if (!string.IsNullOrEmpty(lineItem.Dimension.VariantId)) { Dimensions dimension = (Dimensions)SalesOrder.InternalApplication.BusinessLogic.Utility.CreateDimension(); dimension.VariantId = lineItem.Dimension.VariantId; SalesOrder.InternalApplication.Services.Dimension.GetDimensionForVariant(dimension); lineItem.Dimension = dimension; } if (item.Discounts.Count > 0) { lineItem.QuantityDiscounted = item.Quantity; lineItem.LinePctDiscount = lineItem.CalculateLinePercentDiscount(); } // create discount line from discount info object foreach (DiscountInfo discountInfo in item.Discounts) { DiscountItem discountItem = ConvertToDiscountItem( discountInfo.DiscountOriginType, discountInfo.ManualDiscountType, discountInfo.CustomerDiscountType, discountInfo.EffectiveAmount, discountInfo.DealPrice, discountInfo.DiscountAmount, discountInfo.Percentage, discountInfo.PeriodicDiscountOfferId, discountInfo.OfferName, discountInfo.DiscountCode); SalesOrder.InternalApplication.Services.Discount.AddDiscountLine(lineItem, discountItem); } // Set other default properties for this item SalesOrder.InternalApplication.Services.Item.ProcessItem(lineItem, bypassSerialNumberEntry: true); // Set tax info after defaults, as it may have been overridden. lineItem.SalesTaxGroupId = item.SalesTaxGroup; lineItem.SalesTaxGroupIdOriginal = item.SalesTaxGroup; lineItem.TaxGroupId = item.ItemTaxGroup; lineItem.TaxGroupIdOriginal = item.ItemTaxGroup; // Add it to the transaction transaction.Add(lineItem); if (lineItem.DeliveryDate < earliestDeliveryDate) { earliestDeliveryDate = lineItem.DeliveryDate.HasValue ? lineItem.DeliveryDate.Value : earliestDeliveryDate; } } // Once Items are populated - Reset Customer Tax Group //GRW Linea comentada para poder recoger la orden de venta en una tienda distinta a la configurada en AX //customerSystem.ResetCustomerTaxGroup(transaction); // The order can be created through some other channel other than POS which has set header delivery date as NoDate. // This must not be interpreted as a valid date. Instead the earliestDeliveryDate is used. if (transaction.RequestedDeliveryDate == NoDate) { transaction.RequestedDeliveryDate = earliestDeliveryDate; } // Charges foreach (ChargeInfo charge in orderInfo.Charges) { // add charges Tax.MiscellaneousCharge newCharge = (Tax.MiscellaneousCharge)SalesOrder.InternalApplication.BusinessLogic.Utility.CreateMiscellaneousCharge( charge.Amount, charge.SalesTaxGroup, charge.TaxGroup, charge.Code, string.Empty, transaction); transaction.Add(newCharge); } SalesOrder.InternalApplication.BusinessLogic.ItemSystem.CalculatePriceTaxDiscount(transaction); transaction.CalculateAmountDue(); // Payments // - total up amounts // - add history entries transaction.PrepaymentAmountPaid = decimal.Zero; transaction.PrepaymentAmountInvoiced = decimal.Zero; decimal nonPrepayments = decimal.Zero; PaymentInfo pinfo = new PaymentInfo(); pinfo.Amount = -111; pinfo.Currency = "MXN"; orderInfo.Payments.Add(pinfo); foreach (PaymentInfo payment in orderInfo.Payments) { // sum up payments decimal amount = (string.IsNullOrWhiteSpace(payment.Currency)) ? payment.Amount : (SalesOrder.InternalApplication.Services.Currency.CurrencyToCurrency( payment.Currency, ApplicationSettings.Terminal.StoreCurrency, payment.Amount)); if (payment.Prepayment) { // Sum prepayments to track total deposits paid transaction.PrepaymentAmountPaid += amount; } else { // Sum non-prepayments as base for calculating deposits applied to pickups nonPrepayments += amount; } CustomerOrderPaymentHistory paymentHistory = (CustomerOrderPaymentHistory)SalesOrder.InternalApplication.BusinessLogic.Utility.CreateCustomerOrderPaymentHistory(); paymentHistory.Amount = payment.Amount; paymentHistory.Currency = payment.Currency; paymentHistory.Date = ParseDateString(payment.DateString, DateTime.MinValue); paymentHistory.Balance = transaction.NetAmountWithTaxAndCharges - transaction.PrepaymentAmountPaid; transaction.PaymentHistory.Add(paymentHistory); } // Prepayment/Deposit override info transaction.PrepaymentAmountOverridden = orderInfo.PrepaymentAmountOverridden; if (transaction.PrepaymentAmountOverridden) { transaction.PrepaymentAmountRequired = transaction.PrepaymentAmountPaid; } // Amount that has been previously invoiced (picked-up) transaction.PreviouslyInvoicedAmount = orderInfo.PreviouslyInvoicedAmount; // Portion of the prepayment that has been applied to invoices. // If .PrepaymentAmountApplied is non-NULL then use the explicit amount, otherwise fall back to computing the amount based on payment history. transaction.PrepaymentAmountInvoiced = orderInfo.PrepaymentAmountApplied ?? (transaction.PreviouslyInvoicedAmount - nonPrepayments); transaction.HasLoyaltyPayment = orderInfo.HasLoyaltyPayment; return(transaction); }
/// <summary> /// 确认按钮 /// </summary> public void button_ok() { if (this.TxtDiscount.Text != null && this.TxtDiscount.Text != "") { PassValue.Percent = Int32.Parse(this.TxtDiscount.Text); if (PassValue.Percent != 0) { Discount ds = new Discount(); ds.type = "partial"; ds.percent = PassValue.Percent; List <DiscountItem> items = new List <DiscountItem>(); if (PassValue.listItemID.Count == 0) { for (int count = 0; count < PassValue.listItemIDBefore.Count; count++) { DiscountItem im = new DiscountItem(); im.id = PassValue.listItemIDBefore[count].ToString(); PassValue.listItemID.Add(PassValue.listItemIDBefore[count].ToString()); im.percent = PassValue.Percent; items.Add(im); } } else { for (int count = 0; count < PassValue.listItemID.Count; count++) { DiscountItem im = new DiscountItem(); im.id = PassValue.listItemID[count].ToString(); im.percent = PassValue.Percent; items.Add(im); } } ds.items = new DiscountItem[items.Count]; int t = 0; foreach (DiscountItem itm in items) { ds.items[t++] = itm; } PassValue.discounts.Add(ds); } PassValue.Infor_payment.discounts = new Discount[PassValue.discounts.Count]; int i = 0; foreach (Discount ds in PassValue.discounts) { PassValue.Infor_payment.discounts[i++] = ds; } HttpResult httpResult = httpReq.HttpPatch(string.Format("consumptions/{0}", partConsumptionid), PassValue.Infor_payment); if ((int)httpResult.StatusCode == 401) { LoginBusiness lg = new LoginBusiness(); lg.LoginAgain(); return; } else if ((int)httpResult.StatusCode == 0) { MessageBox.Show(string.Format("{0}{1}", httpResult.StatusDescription, httpResult.OtherDescription), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } Form_Esc(); } }
public ServiceResult ValidateDiscount(DiscountItem discount) { ServiceResult result = new ServiceResult(); try { if (discount is RedemptionCode) { var rCode = (RedemptionCode)discount; if (rCode.ResultingRegistrationId != null) { result.AddServiceError("This code has already been used."); } return(result); } if (discount is Coupon) { var cCode = (Coupon)discount; int useCount = 0; switch (cCode.CouponType) { case CouponType.Registration: useCount = _repository.CartItems.Filter(x => x.DiscountItemId == cCode.DiscountItemId).Count(); break; } if (!cCode.IsActive) { result.AddServiceError("This discount is not currently active"); } if (cCode.IsReusable && cCode.MaxRegistrantCount.HasValue && useCount >= cCode.MaxRegistrantCount) { result.AddServiceError("This discount has exceeded the max number of allowable uses."); } if (!cCode.IsReusable && useCount > 0) { result.AddServiceError("This discount has already been used."); } if (DateTime.Now < cCode.StartDateTime || (cCode.EndDateTime.HasValue ? DateTime.Now > cCode.EndDateTime: true)) { result.AddServiceError("This discount is not currently active."); } return(result); } result.AddServiceError("The coupon entered does not exist."); } catch (Exception ex) { result.AddServiceError(Utilities.GetInnerMostException(ex)); } return(result); }
private bool ApplyDiscount(CartSummary cartSummary, SessionCart currentCart) { DiscountItem discount = _repository.DiscountItems.Find(x => x.Code.ToLower() == currentCart.DiscountCode.ToLower()); if (discount != null) { if (cartSummary.TotalCost == 0) { discount = null; currentCart.DiscountCode = null; cartSummary.SummaryMessages.Add("You cannot apply a discount code to this cart. There are no charges."); } if (discount is RedemptionCode) { var discountableRegList = cartSummary.CartItems.Where(x => x.PurchaseType == PurchaseType.Registration && x.Discountable == true).OrderByDescending(x => x.ItemCost).ToList(); if (discountableRegList.Count() > 0) { RedemptionCode code = (RedemptionCode)discount; IDiscountService discountService = new DiscountService(this._repository, false); ServiceResult validationResult = discountService.ValidateDiscount(code); if (validationResult.Success) { var cost = discountableRegList[0].ItemCost; var discountValue = code.DiscountType == DiscountType.Dollars ? code.Value : cost * (code.Value / 100); discountableRegList[0].DiscountItemId = code.DiscountItemId; discountableRegList[0].DiscountDescription = code.Code; discountableRegList[0].DiscountType = code.DiscountType; discountableRegList[0].DiscountValue = discountableRegList[0].ItemTotal <= 0 ? cost : discountValue; if (NeedToRemoveProcessingFee(currentCart, code)) { RemoveProcessingFee(cartSummary); } } else { cartSummary.SummaryMessages.Add(validationResult.GetServiceErrors().First().ErrorMessage); } } else { cartSummary.SummaryMessages.Add("There are no applicable items for this discount."); } } if (discount is Coupon) { Coupon coupon = (Coupon)discount; IDiscountService discountService = new DiscountService(this._repository, false); ServiceResult validationResult = discountService.ValidateDiscount(coupon); if (validationResult.Success) { switch (coupon.CouponType) { case CouponType.Registration: var discountableRegList = cartSummary.CartItems.Where( x => x.PurchaseType == PurchaseType.Registration && x.Discountable == true && x.EventId == ((coupon.EventId.HasValue) ? coupon.EventId.Value : x.EventId)).OrderByDescending(x => x.ItemCost).ToList(); if (discountableRegList.Any()) { var cost = discountableRegList[0].ItemCost; var discountValue = coupon.DiscountType == DiscountType.Dollars ? coupon.Value : cost * (coupon.Value / 100); var discountedCost = cost - discountValue; discountableRegList[0].DiscountItemId = coupon.DiscountItemId; discountableRegList[0].DiscountDescription = coupon.Code; discountableRegList[0].DiscountType = coupon.DiscountType; discountableRegList[0].DiscountValue = discountableRegList[0].ItemTotal <= 0 ? cost : discountValue; if (NeedToRemoveProcessingFee(currentCart, coupon)) { RemoveProcessingFee(cartSummary); } } else { cartSummary.SummaryMessages.Add("There are no applicable items for this discount."); } break; } } else { cartSummary.SummaryMessages.Add(validationResult.GetServiceErrors().First().ErrorMessage); } } } else { cartSummary.SummaryMessages.Add("This discount does not exist."); } return(cartSummary.SummaryMessages.Count <= 0); }
public async Task <EntityApiResponse <DiscountDetail> > CreateDiscountAsync(DiscountDetail discountDetail, string currentUserId) { if (discountDetail is null) { throw new ArgumentNullException(nameof(discountDetail)); } if (discountDetail.DiscountItems is null || discountDetail.DiscountItems.Count < 1) { return(new EntityApiResponse <DiscountDetail>(error: "Discount has no items")); } if (discountDetail.StartDate >= discountDetail.EndDate) { return(new EntityApiResponse <DiscountDetail>(error: "The start date should be earlier than end date")); } var org = await _orgRepository.GetByIdAsync(discountDetail.OrganizationId); if (org is null) { return(new EntityApiResponse <DiscountDetail>(error: "Organization does not exist")); } var discount = new Discount { Description = discountDetail.Description?.Trim(), Value = discountDetail.Value, StartDate = discountDetail.StartDate.ToUniversalTime(), EndDate = discountDetail.EndDate.ToUniversalTime(), CreatedById = currentUserId, ModifiedById = currentUserId, OrganizationId = org.Id }; await _discountRepository.InsertAsync(discount); foreach (var discountItem in discountDetail.DiscountItems) { if (discountItem.Stock is null) { continue; } var stock = _stockRepository.TableNoTracking.FirstOrDefault(s => s.Id == discountItem.Stock.Id); if (stock is null) { continue; } var newDiscountItem = new DiscountItem { StockId = stock.Id, DiscountId = discount.Id, CreatedById = currentUserId, ModifiedById = currentUserId, OrganizationId = org.Id }; await _discountItemRepository.InsertAsync(newDiscountItem); } return(new EntityApiResponse <DiscountDetail>(entity: new DiscountDetail(discount))); }
protected override void UnpackResponse() { base.UnpackResponse(); // Create the streams we will be reading from. var responseStream = new MemoryStream(m_responsePayload); var responseReader = new BinaryReader(responseStream, Encoding.Unicode); // Check the response length. if (responseStream.Length < MinResponseMessageLength) { throw new MessageWrongSizeException("Get Discount Item"); } decimal?tempDecimal = null; // Try to unpack the data. try { // Seek past return code. responseReader.BaseStream.Seek(sizeof(int), SeekOrigin.Begin); // Get the count. ushort itemCount = responseReader.ReadUInt16(); // Clear the Item array. DiscountItems.Clear(); // Get all the Items for (ushort x = 0; x < itemCount; x++) { var discount = new DiscountItem(); //discount ID discount.DiscountId = responseReader.ReadInt32(); //Discount Type Id discount.Type = (DiscountType)responseReader.ReadInt32(); // Discount Amount tempDecimal = ReadDecimal(responseReader); if (tempDecimal.HasValue) { discount.DiscountAmount = tempDecimal.Value; } else { throw new ServerCommException("'Discount Amount' is not a valid decimal"); } // Points Per Dollar tempDecimal = ReadDecimal(responseReader); if (tempDecimal.HasValue) { discount.PointsPerDollar = tempDecimal.Value; } else { throw new ServerCommException("'Points Per Dollar' is not a valid decimal"); } // Discount Name discount.DiscountName = ReadString(responseReader); //discount award type ID discount.DiscountAwardType = (DiscountItem.AwardTypes)responseReader.ReadInt32(); //requires player discount.IsPlayerRequired = responseReader.ReadBoolean(); //Is Active discount.IsActive = responseReader.ReadBoolean(); //Spend Level count ushort spendLevelCount = responseReader.ReadUInt16(); //Read Spend level List for (int i = 0; i < spendLevelCount; i++) { var spendLevel = new DiscountItem.SpendLevel(); //sequence number spendLevel.Sequence = responseReader.ReadInt32(); //min value tempDecimal = ReadDecimal(responseReader); if (tempDecimal.HasValue) { spendLevel.SpendMinValue = tempDecimal.Value; } else { throw new ServerCommException(String.Format("'Spend level {0} min value' is not a valid decimal", i)); } //max value tempDecimal = ReadDecimal(responseReader); if (tempDecimal.HasValue) { spendLevel.SpendMaxValue = tempDecimal.Value; } else { throw new ServerCommException(String.Format("'Spend level {0} max value' is not a valid decimal", i)); } //spend value tempDecimal = ReadDecimal(responseReader); if (tempDecimal.HasValue) { spendLevel.SpendValue = tempDecimal.Value; } else { throw new ServerCommException(String.Format("'Spend level {0} spend value' is not a valid decimal", i)); } discount.SpendLevels.Add(spendLevel); } //restricted product count ushort restrictedProductCount = responseReader.ReadUInt16(); for (int i = 0; i < restrictedProductCount; i++) { //restricted Product Id var productId = responseReader.ReadInt32(); discount.RestrictedProductIds.Add(productId); } // Start Date if (responseReader.ReadBoolean()) { discount.StartDate = ReadDateTime(responseReader); } // End Date if (responseReader.ReadBoolean()) { discount.EndDate = ReadDateTime(responseReader); } // Allow Partial Discounts discount.AllowPartialDiscounts = responseReader.ReadBoolean(); // Maximum Discount tempDecimal = ReadDecimal(responseReader); if (tempDecimal.HasValue) { discount.MaximumDiscount = tempDecimal.Value; } //else // throw new ServerCommException("'Maximum Discount' is not a valid decimal"); // for testing // Minimum Spend tempDecimal = ReadDecimal(responseReader); if (tempDecimal.HasValue) { discount.MinimumSpend = tempDecimal.Value; } discount.MinimumPacks = responseReader.ReadByte(); ushort qtyContributingPackCount = responseReader.ReadUInt16(); for (int i = 0; i < qtyContributingPackCount; i++) { var packageId = responseReader.ReadInt32(); discount.MinimumPacksEligibleIds.Add(packageId); } //else // throw new ServerCommException("'Minimum Spend' is not a valid decimal"); // for testing // Schedule list RALLY US4617 ushort scheduleCount = responseReader.ReadUInt16(); for (int i = 0; i < scheduleCount; i++) { byte tmp = 0; DiscountItem.Schedule sched = new DiscountItem.Schedule(); // Day of Week tmp = responseReader.ReadByte(); if (tmp == 0) { sched.DayOfWeek = null; } else { sched.DayOfWeek = (DayOfWeek)(tmp - 1); } // Session Number sched.SessionNumber = responseReader.ReadByte(); if (sched.SessionNumber.Value == 0) { sched.SessionNumber = null; } discount.DiscountSchedule.Add(sched); } //US4320 Maximum Use Per Session discount.MaximumUsePerSession = responseReader.ReadByte(); // US4942 Ignore Validations for ignored packages discount.IgnoreValidationsForIgnoredPackages = responseReader.ReadBoolean(); // US4942 Restricted Package Count ushort packageCount = responseReader.ReadUInt16(); for (int i = 0; i < packageCount; i++) { //restricted Package Id discount.RestrictedPackageIds.Add(responseReader.ReadInt32()); } //US4321 //advance type discount.AdvancedType = (DiscountItem.AdvanceDiscountType)responseReader.ReadInt32(); //US4321 buy quantity discount.AdvancedQuantityDiscount.BuyQuantity = responseReader.ReadInt32(); //US4321 buy package ID discount.AdvancedQuantityDiscount.BuyPackageId = responseReader.ReadInt32(); //US4321 get quantity discount.AdvancedQuantityDiscount.GetQuantity = responseReader.ReadInt32(); //US4321 get package ID discount.AdvancedQuantityDiscount.GetPackageId = responseReader.ReadInt32(); DiscountItems.Add(discount); } } catch (EndOfStreamException e) { throw new MessageWrongSizeException("Get Discount Item", e); } catch (ServerCommException e) { throw e; } catch (Exception e) { throw new ServerException("Get Discount Item", e); } // Close the streams. responseReader.Close(); }