public Line(Bike bike, int quantity) { Bike = bike; Quantity = quantity; TotalPrice = Bike.Price * quantity; DiscountInfo di = Bike.GetDiscount(quantity); // Round the numbers to 2 decimal places to make them print nicely switch (di.DiscountType) { case DiscountInfo.DiscountTypeFlag.None: TotalDiscountAmount = 0m; TotalDiscountPercentage = 0m; break; case DiscountInfo.DiscountTypeFlag.FixedAmount: // Dollar amount UnitDiscountAmount = Math.Round(di.Discount.Value, 2); TotalDiscountAmount = Math.Round(UnitDiscountAmount * quantity, 2); if (TotalDiscountAmount == 0m) { UnitDiscountPercentage = 0m; TotalDiscountPercentage = 0m; } else { UnitDiscountPercentage = Math.Round(UnitDiscountAmount / Bike.Price, 2); TotalDiscountPercentage = Math.Round(TotalDiscountAmount / TotalPrice, 2); } break; case DiscountInfo.DiscountTypeFlag.Percentage: // percentage value UnitDiscountPercentage = Math.Round(di.Discount.Value, 2); TotalDiscountPercentage = UnitDiscountPercentage; UnitDiscountAmount = Math.Round(Bike.Price * UnitDiscountPercentage, 2); TotalDiscountAmount = Math.Round(TotalPrice * TotalDiscountPercentage, 2); break; case DiscountInfo.DiscountTypeFlag.Expression: // JavaScript expression var engine = new Engine(); engine.SetValue("Bike", bike); engine.SetValue("Quantity", quantity); engine.SetValue("TotalPrice", TotalPrice); var res = (decimal)engine.Execute(di.Expression).GetCompletionValue().AsNumber(); UnitDiscountAmount = Math.Round((decimal)res, 2); UnitDiscountPercentage = Math.Round(UnitDiscountAmount / Bike.Price, 2); TotalDiscountAmount = Math.Round(Quantity * UnitDiscountAmount, 2); TotalDiscountPercentage = UnitDiscountPercentage; break; } TotalAmount = TotalPrice - TotalDiscountAmount; }
DiscountInfo CreateDiscountInfo(ApiDiscountViewModel inDiscountInfo) { var result = new DiscountInfo(); result.DiscountId = inDiscountInfo.DiscountId; result.Name = inDiscountInfo.Name; result.Code = inDiscountInfo.Code; result.DiscountType = inDiscountInfo.DiscountType; result.ImplicationType = inDiscountInfo.ImplicationType; result.Value = inDiscountInfo.Value; result.RoundToDecimalPlaces = inDiscountInfo.RoundToDecimalPlaces; result.DisplayAs = inDiscountInfo.DisplayAs; result.Description = inDiscountInfo.Description; result.DiscountGroup = inDiscountInfo.DiscountGroup.HasValue ? inDiscountInfo.DiscountGroup.Value : default(int); result.IsMembersOnlyDiscount = inDiscountInfo.IsMembersOnlyDiscount; result.IsMemberExemptDiscount = inDiscountInfo.IsMemberExemptDiscount; result.PriorityOrder = inDiscountInfo.PriorityOrder; result.AppearanceOrder = inDiscountInfo.AppearanceOrder; result.IsCategoryFilterApplicable = inDiscountInfo.IsCategoryFilterApplicable; result.MaximumValue = inDiscountInfo.MaximumValue.HasValue ? inDiscountInfo.MaximumValue.Value : default(decimal); result.MinimumNumberOfItemsAllowed = inDiscountInfo.MinimumNumberOfItemsAllowed.HasValue ? inDiscountInfo.MinimumNumberOfItemsAllowed.Value : default(int); result.MaximumNumberOfItemsAllowed = inDiscountInfo.MaximumNumberOfItemsAllowed.HasValue ? inDiscountInfo.MaximumNumberOfItemsAllowed.Value : default(int); result.DailyUsageAllowedPerMember = inDiscountInfo.DailyUsageAllowedPerMember.HasValue ? inDiscountInfo.DailyUsageAllowedPerMember.Value : default(int); result.ProductPriority = inDiscountInfo.ProductPriority; return(result); }
public DiscountInfo CalculationPromotion(DiscountInfo discountInfo) { discountInfo.DiscountList = new List <ME_DiscountList>(); decimal decAmount = 0M; decimal res = 0M; DiscountInfo info = new DiscountInfo(); //foreach (int i in Enum.GetValues(typeof(PromType))) //循环计算 //{ // int PromType = i; // info.DisAmount = 0; // info =NewObject<PromotionFactory>().MakePromotionType(discountInfo, PromType); // decAmount = decAmount + info.DisAmount; //} //类型优惠 info.DisAmount = 0; info = NewObject <PromotionFactory>().MakePromotionType(discountInfo, 2); decAmount = decAmount + info.DisAmount; //明细优惠 info.DisAmount = 0; info = NewObject <PromotionFactory>().MakePromotionType(discountInfo, 3); decAmount = decAmount + info.DisAmount; //总额优惠 info.DisAmount = 0; discountInfo.Amount = discountInfo.Amount - decAmount; //在总额中减去上两类优惠金后再计算总额优惠 info = NewObject <PromotionFactory>().MakePromotionType(discountInfo, 1); decAmount = decAmount + info.DisAmount; info.DisAmount = decAmount; if (discountInfo.IsSave == true) { SaveDiscountInfo(discountInfo.DiscountList); } return(info); }
public ServiceResponseData PromFeeCaculate() { int patTypeID = requestData.GetData <int>(0); // 病人类型ID int memberAccountID = requestData.GetData <int>(1); // 会员账号ID decimal totalFee = requestData.GetData <decimal>(2); // 费用总金额 int empId = requestData.GetData <int>(3); // 操作员ID int patListID = requestData.GetData <int>(4); // 病人登记ID DataTable largeProjectDt = NewDao <IIPManageDao>().GetFeeItemRecordGroupByStatID(patListID); DataTable feeItemDt = NewDao <IIPManageDao>().GetFeeItemRecordDetails(patListID); DiscountInfo discountinfo = new DiscountInfo(); discountinfo.AccountID = memberAccountID; discountinfo.CostType = patTypeID; discountinfo.PatientType = 2; discountinfo.Amount = totalFee; discountinfo.OperateID = empId; discountinfo.SettlementNO = "0"; discountinfo.DtDetail = feeItemDt; discountinfo.DtClass = largeProjectDt; discountinfo.IsSave = true; // 生成时间戳 TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); long aaa = Convert.ToInt64(ts.TotalSeconds); int te = Convert.ToInt32(ts.TotalSeconds); discountinfo.AccID = te; DiscountInfo resDiscountInfo = NewObject <PromotionManagement>().CalculationPromotion(discountinfo); responseData.AddData(resDiscountInfo); return(responseData); }
public void FetchApplicableDiscountsTest() { ProductQuantity[] productQuantites = new ProductQuantity[0]; var applicableDiscounts = DiscountInfo.FetchApplicableDiscounts(productQuantites).ToArray(); Assert.IsTrue(applicableDiscounts.Length == 0); productQuantites = new ProductQuantity[] { new ProductQuantity(1, 2), new ProductQuantity(3, 1) }; applicableDiscounts = DiscountInfo.FetchApplicableDiscounts(productQuantites).ToArray(); Assert.IsTrue(applicableDiscounts.Length == 1); Assert.IsTrue(applicableDiscounts[0].Id == 1); productQuantites = new ProductQuantity[] { new ProductQuantity(1, 2), new ProductQuantity(2, 3) }; applicableDiscounts = DiscountInfo.FetchApplicableDiscounts(productQuantites).ToArray(); Assert.IsTrue(applicableDiscounts.Length == 2); productQuantites = new ProductQuantity[] { new ProductQuantity(3, 1), new ProductQuantity(2, 3) }; applicableDiscounts = DiscountInfo.FetchApplicableDiscounts(productQuantites).ToArray(); Assert.IsTrue(applicableDiscounts.Length == 1); Assert.IsTrue(applicableDiscounts[0].Id == 2); productQuantites = new ProductQuantity[] { new ProductQuantity(3, 1) }; applicableDiscounts = DiscountInfo.FetchApplicableDiscounts(productQuantites).ToArray(); Assert.IsTrue(applicableDiscounts.Length == 0); }
public void LowestDiscountCalculationCheck() { Logger.GetInstance().LogLine($"STEP: Opening main page..."); MainPage mainPage = new MainPage(); mainPage.SelectCategory(FileUtils.GetLocalizedString("Indie")); Logger.GetInstance().LogLine($"STEP: Selected 'indie' category."); CategoryPage gameCategoryPage = new CategoryPage(FileUtils.GetLocalizedString("Indie")); gameCategoryPage.TopSellersButton.Click(); SingleWebDriver.ScrollTo(0, 1000); SteamGame gameWithLowestDiscount = gameCategoryPage.SelectGameWithLowestDiscount(); Logger.GetInstance().LogLine($"STEP: Game with lowest discount is got."); GamePage gamePage = new GamePage(); DiscountInfo discountInfoFromGamePage = gamePage.GetDiscountInfo(); Assert.Multiple(() => { Assert.AreEqual(gameWithLowestDiscount.DiscountInfo.Discount, discountInfoFromGamePage.Discount, $"Discount from category page {gameWithLowestDiscount.DiscountInfo.Discount} is not equal to discount from game page."); Assert.AreEqual(gameWithLowestDiscount.DiscountInfo.OldPrice, discountInfoFromGamePage.OldPrice, $"Old price from category page {gameWithLowestDiscount.DiscountInfo.OldPrice} is not equal to old price from game page."); Assert.AreEqual(gameWithLowestDiscount.DiscountInfo.NewPrice, discountInfoFromGamePage.NewPrice, $"New price from category page {gameWithLowestDiscount.DiscountInfo.NewPrice} is not equal to new price from game page."); }); Logger.GetInstance().LogLine($"STEP: Test complete."); }
public DiscountInfo Calculation(DiscountInfo discountInfo) { discountInfo.DisAmount = 0M; DataTable tempDt = NewDao <IPromotionProjectDao>().QueryPromotionDetail(PatientType, CostType, CardID, PromType); if (tempDt.Rows.Count > 0) { int PromBase = Convert.ToInt16(tempDt.Rows[0]["PromBase"]); //优惠基数 int Disco = Convert.ToInt16(tempDt.Rows[0]["DiscountNumber"]); //优惠数字 int PromID = Convert.ToInt16(tempDt.Rows[0]["PromID"]); //优惠方案ID string PromName = Convert.ToString(tempDt.Rows[0]["PromName"]); //优惠方案名称 int PromSunID = Convert.ToInt32(tempDt.Rows[0]["PromSunID"]); //优惠方案明细ID //当消费总额大于优惠基数时 if (discountInfo.Amount > PromBase) { if (Convert.ToInt16(tempDt.Rows[0]["Prom"]) == 1) //优惠方式为折扣方式 { discountInfo.DisAmount = discountInfo.Amount * Disco / 100; } else { if (discountInfo.Amount > Disco) //如果金额大于优惠 { discountInfo.DisAmount = Disco; } else { discountInfo.DisAmount = 0; } } } ME_DiscountList DiscountList = new ME_DiscountList(); DiscountList.PromID = PromID; DiscountList.AccountID = discountInfo.AccountID; DiscountList.SettlementNO = discountInfo.SettlementNO; DiscountList.PromName = PromName; DiscountList.PromSunID = PromSunID; DiscountList.CostTypeID = CostType; DiscountList.CardTypeID = CardID; //帐户表ID DiscountList.PatientType = PatientType; //病人类型门诊或住院 DiscountList.PromTypeID = PromType; //优惠类型 DiscountList.PromBase = PromBase; DiscountList.Prom = 1; // DiscountList.IsValid = 0; DiscountList.AccID = discountInfo.AccID; DiscountList.DiscountNumber = Disco; DiscountList.Amount = discountInfo.Amount; DiscountList.DiscountTotal = discountInfo.DisAmount; DiscountList.OperateDate = System.DateTime.Now; DiscountList.OperateID = discountInfo.OperateID; discountInfo.DiscountList.Add(DiscountList); } return(discountInfo); }
private void CreateOrderDiscounts() { OrderDiscount = Factory.NewOrderDiscount(10); OrderDiscount.DiscountUsesCoupons = true; OrderDiscount.Insert(); new CouponCodeInfo { CouponCodeDiscountID = OrderDiscount.DiscountID, CouponCodeCode = ORDER_COUPON_CODE, }.Insert(); }
public ServiceResponseData DischargeSettlement() { IP_CostHead costHead = requestData.GetData <IP_CostHead>(0); List <IP_CostPayment> costPayList = requestData.GetData <List <IP_CostPayment> >(1); DiscountInfo resDiscountInfo = requestData.GetData <DiscountInfo>(2); int workID = requestData.GetData <int>(3); DateTime patEnterHDate = requestData.GetData <DateTime>(4); string result = NewObject <CostManagement>().DischargeSettlement(patEnterHDate, costHead, costPayList, resDiscountInfo, workID); responseData.AddData(result); responseData.AddData(costPayList); return(responseData); }
public TotalData GetTotalCost() { TotalData td = new TotalData(); td.Data = s_data; double total = 0; // 1. total prices of items for (int ix = 0; ix < s_data.Count(); ix++) { ScanData data = s_data[ix]; total += CalcPrice(data); } // 2. apply count-based discounts (if any) if (s_discounts.Count() > 0) { double countDisc = 0; foreach (string code in s_discounts.Keys) { DiscountInfo di = s_discounts[code]; List <ScanData> items = s_data.Where(d => d.Code.Equals(code, StringComparison.InvariantCultureIgnoreCase)).ToList(); int num = 0; if (items.Count > 0) { num = items.Sum(d => d.Quantity); } if (num > di.TotalCount) { int mult = (num / di.TotalCount); int numFree = di.FreeCount * mult; double value = numFree * FetchPrice(code); countDisc += value; } } total -= countDisc; } // 3. apply percent-based discount (if any) if (s_percentDiscount.HasValue) { double discount = s_percentDiscount.Value / 100.0; total = total * (1 - discount); } td.Total = total; return(td); }
/// <summary> /// Create a discount line from the discount info object. /// </summary> /// <param name="discount">The discount info object.</param> /// <returns>The created discount line.</returns> private static DiscountLine CreateDiscountLine(DiscountInfo discount) { return(new DiscountLine { EffectiveAmount = discount.Amount, Amount = discount.DiscountAmount, DiscountLineType = (DiscountLineType)discount.DiscountOriginType, DiscountCode = discount.DiscountCode, CustomerDiscountType = (CustomerDiscountType)discount.CustomerDiscountType, ManualDiscountType = (ManualDiscountType)discount.ManualDiscountType, OfferId = discount.PeriodicDiscountOfferId, Percentage = discount.Percentage, DealPrice = discount.DealPrice, OfferName = discount.OfferName }); }
/// <summary> /// Add a single discount to the dictionary. /// </summary> /// <param name="quantity">Quantity level for discount to occur. Quantity can be -1 which indicates a default discount. Else the quantity must be grater than zero</param> /// <param name="di">Discount object</param> public void Add(int quantity, DiscountInfo di) { Debug.Assert(quantity > 0 || quantity == -1); if (quantity <= 0 && quantity != -1) { throw new ArgumentException("Must be greater than zero or -1 as a default catch all discount. " + "Typically used for complex discounts that can't be handled by simple addition or multiplaction.", nameof(quantity)); } if (Discounts.ContainsKey(quantity)) { throw new ArgumentException(string.Format("The key value [{0}] already exists. Duplicates are not allowed.", quantity), nameof(quantity)); } Discounts.Add(quantity, di); }
/// <summary> /// Gets the discount corresponding to the quantity sold /// </summary> /// <returns>The discount.</returns> /// <param name="quantity">Quantity must be greater than zero</param> public DiscountInfo GetDiscount(int quantity) { Debug.Assert(quantity > 0); if (quantity <= 0) { throw new ArgumentException("Must be greater than zero", nameof(quantity)); } // If no discount object just return zero discount if (DiscountObj is null) { return(DiscountInfo.CreateDiscountZeroAmount()); } return(DiscountObj.GetDiscount(quantity)); }
/// <summary> /// 添加类目折扣 /// </summary> /// <param name="info"></param> /// <returns></returns> public bool AddDiscountInfo(DiscountInfo info, List <string> areNum) { if (info.Id == Guid.Empty) { info.Id = Guid.NewGuid(); var model = _context.DiscountInfos.FirstOrDefault(x => x.TypeId == info.TypeId); if (model != null) { return(false); } _context.DiscountInfos.Add(info); } else { var model = _context.DiscountInfos.FirstOrDefault(x => x.Id == info.Id); model.StartTime = info.StartTime; model.EndTime = info.EndTime; model.Discount = info.Discount; model.UserTypes = info.UserTypes; model.TypeId = info.TypeId; model.TypeName = info.TypeName; } List <ManToArea> list = new List <ManToArea>(); var areaHis = _context.ManToAreas.Where(x => x.ActiveId == info.Id); areNum.ForEach(x => { var area = _context.Areas.FirstOrDefault(c => c.Num == x); if (area != null) { var newArea = new ManToArea(); newArea.ActiveId = info.Id; newArea.ActiveName = string.Empty; newArea.AreaNum = area.Num; newArea.AreaName = area.Name; list.Add(newArea); } }); _context.ManToAreas.RemoveRange(areaHis); _context.ManToAreas.AddRange(list); return(_context.SaveChanges() > 0); }
private DiscountInfo GetDiscountInfo(DataRow row) { if (row == null) { return(null); } var discountId = DataHelper.GetIntValue(row, DiscountInfo.TYPEINFO.IDColumn); var discount = discounts[discountId] as DiscountInfo; if (discount == null) { discount = new DiscountInfo(row); discounts[discount.DiscountID] = discount; } return(discount); }
public void CalculateTotalPriceTest() { decimal targetedPrice = 2.95m; var applicableDiscounts = new DiscountInfo[0]; var shoppingCart = new ShoppingCart(); shoppingCart.AddToCart(3, 1); shoppingCart.AddToCart(1, 1); shoppingCart.AddToCart(2, 1); var cartPrice = shoppingCart.CalculateTotalPrice(applicableDiscounts); Assert.IsTrue(cartPrice == targetedPrice); targetedPrice = 3.10m; applicableDiscounts = new DiscountInfo[1] { DiscountInfo.Fetch(1) }; shoppingCart = new ShoppingCart(); shoppingCart.AddToCart(1, 2); shoppingCart.AddToCart(3, 2); cartPrice = shoppingCart.CalculateTotalPrice(applicableDiscounts); Assert.IsTrue(cartPrice == targetedPrice); targetedPrice = 3.45m; applicableDiscounts = new DiscountInfo[1] { DiscountInfo.Fetch(2) }; shoppingCart = new ShoppingCart(); shoppingCart.AddToCart(2, 4); cartPrice = shoppingCart.CalculateTotalPrice(applicableDiscounts); Assert.IsTrue(cartPrice == targetedPrice); targetedPrice = 9.0m; applicableDiscounts = new DiscountInfo[2] { DiscountInfo.Fetch(1), DiscountInfo.Fetch(2) }; shoppingCart = new ShoppingCart(); shoppingCart.AddToCart(1, 2); shoppingCart.AddToCart(3, 1); shoppingCart.AddToCart(2, 8); cartPrice = shoppingCart.CalculateTotalPrice(applicableDiscounts); Assert.IsTrue(cartPrice == targetedPrice); }
/// <summary> /// Converts a collection of discount lines into a collection of discount information. /// </summary> /// <param name="discountLines">The collection of discount lines to be converted.</param> /// <param name="discountInfoCollection">The collection of discount info to have the new charges copied to.</param> private static void ConvertDiscountLineToDiscountInfos(IEnumerable <DiscountLine> discountLines, Collection <DiscountInfo> discountInfoCollection) { foreach (DiscountLine discountLine in discountLines) { DiscountInfo discountInfo = new DiscountInfo() { Amount = discountLine.EffectiveAmount, CustomerDiscountType = (int)discountLine.CustomerDiscountType, DiscountCode = discountLine.DiscountCode ?? string.Empty, DiscountOriginType = (int)discountLine.DiscountLineType, ManualDiscountType = (int)discountLine.ManualDiscountType, PeriodicDiscountOfferId = discountLine.OfferId ?? string.Empty, Percentage = discountLine.Percentage, DiscountAmount = discountLine.Amount, DealPrice = discountLine.DealPrice, }; discountInfoCollection.Add(discountInfo); } }
public HttpResponseMessage DiscountByCount([FromBody] DiscountInfoEx discInfoEx) { DiscountInfo di = DiscountInfo.Create(discInfoEx); if (!s_discounts.ContainsKey(discInfoEx.Code)) { s_discounts.Add(discInfoEx.Code, di); } else { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(string.Format("Repeated discount for Code '{0}'", discInfoEx.Code)), ReasonPhrase = "Repeat discount" }; throw new HttpResponseException(response); } return(Request.CreateResponse(HttpStatusCode.OK, "Successful discount")); }
public DiscountInfo MakePromotionType(DiscountInfo discountInfo, int PromType) { IPromotion MyProm = null; try { Type type = Type.GetType(ConvertToClass(PromType), true); MyProm = (IPromotion)Activator.CreateInstance(type); this.BindDb(MyProm); MyProm.PatientType = discountInfo.PatientType; MyProm.CardID = discountInfo.AccountID; MyProm.CostType = discountInfo.CostType; MyProm.PromType = PromType; return(MyProm.Calculation(discountInfo)); } catch (Exception err) { throw new Exception(err.Message); return(discountInfo); } }
public ActionResult SaveDiscount(DiscountInfo m, List <int> userType, string areaNums) { var areaList = areaNums.Split(',').ToList(); var loginUser = (UserInfo)ViewBag.User; m.UpdateTime = DateTime.Now; m.UpdateUserId = loginUser.UserId; m.UpdateUserName = loginUser.UserName; string userTypes = ""; userType.ForEach(x => { userTypes += x; userTypes += ","; }); m.UserTypes = userTypes; _active.AddDiscountInfo(m, areaList); Response.Redirect("DiscountList"); return(View()); }
public DiscountApplicationInfo ApplyDiscount(DiscountInfo discountInfo, CartModel cart) { var applications = _session.QueryOver <DiscountApplication>() .Where(application => application.Discount.Id == discountInfo.Discount.Id) .Cacheable() .List(); var discountApplicationInfo = new DiscountApplicationInfo(); foreach (var application in applications) { var fullName = application.GetType().FullName; if (!ApplicationApplierTypes.ContainsKey(fullName)) { continue; } var applier = _kernel.Get(ApplicationApplierTypes[fullName]) as DiscountApplicationApplier; if (applier != null) { discountApplicationInfo.Add(applier.Apply(application, cart, discountInfo.CheckLimitationsResult)); } } return(discountApplicationInfo); }
public decimal PromFeeCaculate() { try { Action <ClientRequestData> requestAction = ((ClientRequestData request) => { request.AddData(mIDischargeSettlement.PatTypeID); // 病人登记ID request.AddData(mIDischargeSettlement.MemberAccountID); // 会员账号ID request.AddData(mIPayMentInfo.TotalFee); // 住院费用总金额 request.AddData(LoginUserInfo.EmpId); // 操作员ID request.AddData(mIDischargeSettlement.PatListID); // 病人登记ID }); ServiceResponseData retdata = InvokeWcfService("IPProject.Service", "DischargeSettlementController", "PromFeeCaculate", requestAction); DiscountInfo resDiscountInfo = retdata.GetData <DiscountInfo>(0); mIDischargeSettlement.ResDiscountInfo = resDiscountInfo; return(resDiscountInfo.DisAmount); } catch (Exception err) { MessageBoxShowError(err.Message); return(0); } }
public DiscountInfo Calculation(DiscountInfo discountInfo) { decimal res = 0M; DataTable tempDt = NewDao <IPromotionProjectDao>().QueryPromotionDetail(PatientType, CostType, CardID, PromType);//获取优惠明细 for (int j = 0; j < tempDt.Rows.Count; j++) { int PromClass = Convert.ToInt16(tempDt.Rows[j]["PromClass"]); //优惠明细项目类别ID int Disco = Convert.ToInt16(tempDt.Rows[j]["DiscountNumber"]); //优惠额度 int promBase = Convert.ToInt16(tempDt.Rows[j]["PromBase"]); //优惠基数 string PromName = Convert.ToString(tempDt.Rows[0]["PromName"]); //优惠方案名称 int PromSunID = Convert.ToInt32(tempDt.Rows[0]["PromSunID"]); //优惠方案明细ID int PromID = Convert.ToInt16(tempDt.Rows[0]["PromID"]); //优惠方案ID decimal tempAount2 = 0; //当消费总额大于优惠基数时 DataRow[] drTemp = discountInfo.DtClass.Select(" ClassTypeID=" + PromClass); // decimal tempAount = 0; foreach (DataRow dr in drTemp) { //当消费总额大于优惠基数时 if (Convert.ToDecimal(dr["ClassAmount"]) > promBase) { if (Convert.ToInt32(tempDt.Rows[j]["Prom"]) == 1) //优惠方式为折扣方式 { tempAount = Convert.ToDecimal(dr["ClassAmount"]) * Disco / 100; } else { if (Convert.ToDecimal(dr["ClassAmount"]) > Disco) //如果金额大于优惠 { tempAount = Disco; } else { tempAount = 0; } } tempAount2 = tempAount2 + tempAount; dr["PromAmount"] = tempAount; } else { dr["PromAmount"] = 0M; } discountInfo.DtClass.AcceptChanges(); ME_DiscountList DiscountList = new ME_DiscountList(); DiscountList.AccountID = discountInfo.AccountID; DiscountList.PromID = PromID; DiscountList.SettlementNO = discountInfo.SettlementNO; DiscountList.PromName = PromName; DiscountList.PromSunID = PromSunID; DiscountList.CostTypeID = CostType; DiscountList.CardTypeID = CardID; //帐户表ID DiscountList.PatientType = PatientType; //病人类型门诊或住院 DiscountList.PromTypeID = PromType; //优惠类型 DiscountList.PromBase = promBase; DiscountList.PromClass = PromClass; DiscountList.Prom = 2; // DiscountList.IsValid = 0; DiscountList.AccID = discountInfo.AccID; DiscountList.DiscountNumber = Disco; DiscountList.Amount = discountInfo.Amount; DiscountList.DiscountTotal = tempAount; DiscountList.OperateDate = System.DateTime.Now; DiscountList.OperateID = discountInfo.OperateID; discountInfo.DiscountList.Add(DiscountList); } res = res + tempAount2; } discountInfo.DisAmount = res; return(discountInfo); }
protected object ugDiscounts_OnExternalDataBound(object sender, string sourceName, object parameter) { DataRowView discountRow = parameter as DataRowView; DiscountInfo discountInfo = null; if (discountRow != null) { discountInfo = new DiscountInfo(discountRow.Row); } switch (sourceName.ToLowerCSafe()) { // Append to a value field char '%' or site currency in case of flat discount case "value": if ((DiscountType == DiscountApplicationEnum.Shipping) && (!discountInfo.DiscountIsFlat) && (discountInfo.DiscountValue == 100)) { return(GetString("general.free")); } return((discountInfo.DiscountIsFlat) ? CurrencyInfoProvider.GetFormattedPrice(discountInfo.DiscountValue, discountInfo.DiscountSiteID) : discountInfo.DiscountValue + "%"); // Display discount status case "status": return(discountInfo.DiscountStatus.ToLocalizedString("com.discountstatus")); case "discountorder": // Ensure correct values for unigrid export if (sender == null) { return(discountInfo.DiscountOrder); } else { InlineEditingTextBox txtDiscountOrder = new InlineEditingTextBox(); txtDiscountOrder.Text = discountInfo.DiscountOrder.ToString(); txtDiscountOrder.Update += (s, e) => { CheckModifyPermission(); // Discount order must be double number double order = ValidationHelper.GetDouble(txtDiscountOrder.Text, -1); // Update price if new value is valid, must be higher or equal 1 if (order >= 1) { discountInfo.DiscountOrder = order; discountInfo.MakeComplete(true); discountInfo.Update(); ugDiscounts.ReloadData(); } else { txtDiscountOrder.ErrorText = GetString("com.discountedit.weightinvalid"); } }; return(txtDiscountOrder); } case "application": // Display blank value if discount don't use coupons if ((discountInfo == null) || !discountInfo.DiscountUsesCoupons) { return(String.Empty); } var tr = new ObjectTransformation("CouponsCounts", discountInfo.DiscountID) { DataProvider = couponCountsDataProvider, Transformation = "{% FormatString(GetResourceString(\"com.couponcode.appliedxofy\"), Convert.ToString(Uses, \"0\"), (UnlimitedCodeCount != 0)? GetResourceString(\"com.couponcode.unlimited\") : Convert.ToString(Limit, \"0\")) %}", NoDataTransformation = "{$com.discount.notcreated$}", EncodeOutput = false }; return(tr); case "orderamount": double totalPriceInMainCurrency = ValidationHelper.GetDouble(discountInfo.DiscountItemMinOrderAmount, 0); // Display blank value in the discount listing if order amount is not configured if (totalPriceInMainCurrency == 0) { return(string.Empty); } // Format currency string priceInMainCurrencyFormatted = CurrencyInfoProvider.GetFormattedPrice(totalPriceInMainCurrency, SiteContext.CurrentSiteID); return(HTMLHelper.HTMLEncode(priceInMainCurrencyFormatted)); } return(parameter); }
protected object ugDiscounts_OnExternalDataBound(object sender, string sourceName, object parameter) { DataRowView discountRow = parameter as DataRowView; DiscountInfo discountInfo = null; if (discountRow != null) { discountInfo = new DiscountInfo(discountRow.Row); } if (discountInfo == null) { return String.Empty; } switch (sourceName.ToLowerCSafe()) { // Append to a value field char '%' or site currency in case of flat discount case "value": if ((DiscountType == DiscountApplicationEnum.Shipping) && (!discountInfo.DiscountIsFlat) && (discountInfo.DiscountValue == 100)) { return GetString("general.free"); } return ((discountInfo.DiscountIsFlat) ? CurrencyInfoProvider.GetFormattedPrice(discountInfo.DiscountValue, discountInfo.DiscountSiteID) : discountInfo.DiscountValue + "%"); // Display discount status case "status": return new DiscountStatusTag(couponCountsDataProvider, discountInfo); case "discountorder": // Ensure correct values for unigrid export if ((sender == null) || !ECommerceContext.IsUserAuthorizedToModifyDiscount()) { return discountInfo.DiscountOrder; } return new PriorityInlineEdit { PrioritizableObject = discountInfo, Unigrid = ugDiscounts }; case "application": // Display blank value if discount don't use coupons if (!discountInfo.DiscountUsesCoupons) { return "—"; } var tr = new ObjectTransformation("CouponsCounts", discountInfo.DiscountID) { DataProvider = couponCountsDataProvider, Transformation = "{% FormatString(GetResourceString(\"com.couponcode.appliedxofy\"), Convert.ToString(Uses, \"0\"), (UnlimitedCodeCount != 0)? GetResourceString(\"com.couponcode.unlimited\") : Convert.ToString(Limit, \"0\")) %}", NoDataTransformation = "{$com.discount.notcreated$}", EncodeOutput = false }; return tr; case "orderamount": double totalPriceInMainCurrency = ValidationHelper.GetDouble(discountInfo.DiscountItemMinOrderAmount, 0); // Display blank value in the discount listing if order amount is not configured if (totalPriceInMainCurrency == 0) { return string.Empty; } // Format currency string priceInMainCurrencyFormatted = CurrencyInfoProvider.GetFormattedPrice(totalPriceInMainCurrency, SiteContext.CurrentSiteID); return HTMLHelper.HTMLEncode(priceInMainCurrencyFormatted); } return parameter; }
internal static CustomerOrderInfo GetInfoFromTransaction(CustomerOrderTransaction customerOrder) { CustomerOrderInfo parameters = new CustomerOrderInfo(); //GRW DAC odac = new DAC(SalesOrder.InternalApplication.Settings.Database.Connection); DataTable dt = odac.GetContactData(customerOrder.TransactionId, customerOrder.TerminalId, customerOrder.StoreId); if (dt.Rows.Count > 0) { parameters.CustName = dt.Rows[0]["NAME"].ToString(); parameters.CustPhone = dt.Rows[0]["PHONE"].ToString(); parameters.Email = dt.Rows[0]["EMAIL"].ToString(); } //GRW parameters.OrderType = customerOrder.OrderType; parameters.Id = customerOrder.OrderId; parameters.TransactionId = customerOrder.TransactionId; parameters.QuotationId = customerOrder.OrderId; parameters.AutoPickOrder = false; parameters.WarehouseId = customerOrder.WarehouseId; parameters.CurrencyCode = customerOrder.StoreCurrencyCode; parameters.StoreId = customerOrder.StoreId; parameters.TerminalId = customerOrder.TerminalId; parameters.LocalHourOfDay = customerOrder.LocalHourOfDay; parameters.AddressRecordId = (customerOrder.ShippingAddress != null) ? customerOrder.ShippingAddress.AddressRecId : string.Empty; parameters.CustomerAccount = (customerOrder.Customer != null) ? customerOrder.Customer.CustomerId : string.Empty; parameters.SalespersonStaffId = (customerOrder.SalesPersonId) ?? string.Empty; // The format must match the expected format in AX RetailTransactionService.CreateCustomerOrder: "dd/MM/yyyy" parameters.ExpiryDateString = customerOrder.ExpirationDate.ToString(FixedDateFormat); parameters.RequestedDeliveryDateString = customerOrder.RequestedDeliveryDate.ToString(FixedDateFormat); parameters.DeliveryMode = customerOrder.DeliveryMode != null ? customerOrder.DeliveryMode.Code : string.Empty; parameters.PrepaymentAmountOverridden = customerOrder.PrepaymentAmountOverridden; parameters.PrepaymentAmountApplied = customerOrder.NetAmountWithTaxAndCharges - customerOrder.AmountDue; parameters.TotalManualDiscountAmount = customerOrder.TotalManualDiscountAmount; parameters.TotalManualDiscountPercentage = customerOrder.TotalManualPctDiscount; //parameters.Email = customerOrder.ReceiptEmailAddress; parameters.Comment = ((IPosTransactionV1)customerOrder).Comment; parameters.ReturnReasonCodeId = customerOrder.ReturnReasonCodeId; parameters.LoyaltyCardId = (customerOrder.LoyaltyItem != null) ? customerOrder.LoyaltyItem.LoyaltyCardNumber : string.Empty; // If we do not have the channel reference identifier, we create a new receipt identifier instead. parameters.ChannelReferenceId = customerOrder.ChannelReferenceId; parameters.CreditCardToken = customerOrder.CreditCardToken; // Discount codes parameters.DiscountCodes = new Collection <string>(); foreach (string code in customerOrder.DiscountCodes) { parameters.DiscountCodes.Add(code); } // Line Items parameters.Items = new Collection <ItemInfo>(); foreach (SaleLineItem item in customerOrder.SaleItems) { if (!item.Voided) { string deliveryMode = parameters.DeliveryMode; if (item.DeliveryMode != null) { deliveryMode = item.DeliveryMode.Code; } string deliveryDateString = parameters.RequestedDeliveryDateString; if (item.DeliveryDate.HasValue) { deliveryDateString = item.DeliveryDate.Value.ToString(FixedDateFormat); } Collection <ChargeInfo> lineChargeInfo = new Collection <ChargeInfo>(); foreach (Tax.MiscellaneousCharge charge in item.MiscellaneousCharges) { lineChargeInfo.Add(new ChargeInfo() { Amount = charge.Amount, Code = charge.ChargeCode, SalesTaxGroup = charge.SalesTaxGroupId, TaxGroup = charge.TaxGroupId }); } // If no line-level warehouse is specified, fall back to the header warehouse string inventLocationId = string.IsNullOrWhiteSpace(item.DeliveryWarehouse) ? customerOrder.WarehouseId : item.DeliveryWarehouse; // AX SO line stores discount amount per item, POS stores for whole line, calculate per item discount amount decimal lineDiscount = (item.Quantity == 0M ? 0M : (item.TotalDiscount + item.LineDiscount + item.PeriodicDiscount) / (item.Quantity)); // Save all discount lines per sales line Collection <DiscountInfo> lineDiscountInfo = new Collection <DiscountInfo>(); foreach (DiscountItem discountLine in item.DiscountLines) { DiscountInfo discountInfo = new DiscountInfo(); discountInfo.DiscountCode = string.Empty; discountInfo.PeriodicDiscountOfferId = string.Empty; discountInfo.EffectiveAmount = discountLine.EffectiveAmount; discountInfo.DealPrice = discountLine.DealPrice; discountInfo.Percentage = discountLine.Percentage; discountInfo.DiscountAmount = discountLine.Amount; LineDiscountItem lineDiscountItem; PeriodicDiscountItem periodicDiscountItem; CustomerDiscountItem customerDiscountItem; if ((lineDiscountItem = discountLine as LineDiscountItem) != null) { discountInfo.DiscountOriginType = (int)lineDiscountItem.LineDiscountType; if ((periodicDiscountItem = discountLine as PeriodicDiscountItem) != null) { discountInfo.PeriodicDiscountOfferId = periodicDiscountItem.OfferId; discountInfo.DiscountCode = periodicDiscountItem.DiscountCode; } else if ((customerDiscountItem = discountLine as CustomerDiscountItem) != null) { discountInfo.CustomerDiscountType = (int)customerDiscountItem.CustomerDiscountType; } else { discountInfo.DiscountOriginType = (int)LineDiscountItem.DiscountTypes.Manual; discountInfo.ManualDiscountType = (int)discountLine.GetManualDiscountType(); } } if (discountLine is TotalDiscountItem) { discountInfo.DiscountOriginType = (int)LineDiscountItem.DiscountTypes.Manual; discountInfo.ManualDiscountType = (int)discountLine.GetManualDiscountType(); } lineDiscountInfo.Add(discountInfo); } parameters.Items.Add(new ItemInfo() { RecId = item.OrderLineRecordId, //quantity ItemId = item.ItemId, Quantity = item.Quantity, Unit = item.SalesOrderUnitOfMeasure, //pricing Price = item.Price, Discount = lineDiscount, NetAmount = item.NetAmount, ItemTaxGroup = item.TaxGroupId, SalesTaxGroup = item.SalesTaxGroupId, SalesMarkup = item.SalesMarkup, PeriodicDiscount = item.PeriodicDiscount, LineDscAmount = item.LineDiscount, LineManualDiscountAmount = item.LineManualDiscountAmount, LineManualDiscountPercentage = item.LineManualDiscountPercentage, TotalDiscount = item.TotalDiscount, TotalPctDiscount = item.TotalPctDiscount, PeriodicPercentageDiscount = item.PeriodicPctDiscount, //Comment Comment = item.Comment, //delivery WarehouseId = inventLocationId, AddressRecordId = item.ShippingAddress != null ? item.ShippingAddress.AddressRecId : null, DeliveryMode = deliveryMode, RequestedDeliveryDateString = deliveryDateString, //inventDim BatchId = item.BatchId, SerialId = item.SerialId, VariantId = item.Dimension.VariantId, ColorId = item.Dimension.ColorId, SizeId = item.Dimension.SizeId, StyleId = item.Dimension.StyleId, ConfigId = item.Dimension.ConfigId, //Return InvoiceId = item.ReturnInvoiceId, InventTransId = item.ReturnInvoiceInventTransId, //line-level misc. charges Charges = lineChargeInfo, //line-level discounts Discounts = lineDiscountInfo, }); } } // Header level Misc Charges parameters.Charges = new Collection <ChargeInfo>(); foreach (Tax.MiscellaneousCharge charge in customerOrder.MiscellaneousCharges) { parameters.Charges.Add(new ChargeInfo() { Code = charge.ChargeCode, Amount = charge.Amount, SalesTaxGroup = charge.SalesTaxGroupId, TaxGroup = charge.TaxGroupId }); } string CardType = ""; // Payments parameters.Payments = new Collection <PaymentInfo>(); foreach (ITenderLineItem tender in customerOrder.TenderLines) { CardType = ""; if (!tender.Voided) { ICardTenderLineItem cardTender = tender as ICardTenderLineItem; if (cardTender != null && cardTender.EFTInfo.IsAuthOnly) { // This is a Pre-Authorization record. IEFTInfo eft = cardTender.EFTInfo; parameters.Preauthorization = new Preauthorization() { PaymentPropertiesBlob = eft.PaymentProviderPropertiesXML }; } else if (tender.Amount != decimal.Zero) { // This is an actual payment record. DAC odac2 = new DAC(ApplicationSettings.Database.LocalConnection); CardType = odac2.getCardType(customerOrder.TransactionId, customerOrder.TerminalId, customerOrder.StoreId, tender.LineId, tender.TenderTypeId); parameters.Payments.Add(new PaymentInfo() { PaymentType = tender.TenderTypeId, Amount = string.IsNullOrEmpty(tender.CurrencyCode) ? tender.Amount : tender.ForeignCurrencyAmount, Currency = (tender.CurrencyCode) ?? string.Empty, CardType = string.IsNullOrEmpty(CardType) ? "":CardType }); } } } // Affiliations parameters.Affiliations = new Collection <AffiliationInfo>(); foreach (IAffiliation affiliation in customerOrder.AffiliationLines) { parameters.Affiliations.Add(new AffiliationInfo() { AffiliationId = affiliation.RecId, LoyaltyTierId = affiliation.LoyaltyTier }); } return(parameters); }
private static string GetDiscountGridValue(DiscountInfo discount) { return(discount.DiscountIsFlat ? CurrencyInfoProvider.GetFormattedPrice(discount.DiscountValue, discount.DiscountSiteID) : ECommerceHelper.GetFormattedPercentageValue(discount.DiscountValue, CultureHelper.PreferredUICultureInfo)); }
protected object ugDiscounts_OnExternalDataBound(object sender, string sourceName, object parameter) { DataRowView discountRow = parameter as DataRowView; DiscountInfo discountInfo = null; if (discountRow != null) { discountInfo = new DiscountInfo(discountRow.Row); } if (discountInfo == null) { return(String.Empty); } switch (sourceName.ToLowerCSafe()) { // Append to a value field char '%' or site currency in case of flat discount case "value": if ((DiscountType == DiscountApplicationEnum.Shipping) && (!discountInfo.DiscountIsFlat) && (discountInfo.DiscountValue == 100)) { return(GetString("general.free")); } return((discountInfo.DiscountIsFlat) ? CurrencyInfoProvider.GetFormattedPrice(discountInfo.DiscountValue, discountInfo.DiscountSiteID) : discountInfo.DiscountValue + "%"); // Display discount status case "status": // Ensure correct values for unigrid export if (sender == null) { return(discountInfo.DiscountStatus.ToLocalizedString("com.discountstatus")); } return(new DiscountStatusTag(couponCountsDataProvider, discountInfo)); case "discountorder": // Ensure correct values for unigrid export if ((sender == null) || !ECommerceContext.IsUserAuthorizedToModifyDiscount()) { return(discountInfo.DiscountOrder); } return(new PriorityInlineEdit { PrioritizableObject = discountInfo, Unigrid = ugDiscounts }); case "application": // Display blank value if discount don't use coupons if (!discountInfo.DiscountUsesCoupons) { return("—"); } var tr = new ObjectTransformation("CouponsCounts", discountInfo.DiscountID) { DataProvider = couponCountsDataProvider, Transformation = "{% FormatString(GetResourceString(\"com.couponcode.appliedxofy\"), Convert.ToString(Uses, \"0\"), (UnlimitedCodeCount != 0)? GetResourceString(\"com.couponcode.unlimited\") : Convert.ToString(Limit, \"0\")) %}", NoDataTransformation = "{$com.discount.notcreated$}", EncodeOutput = false }; return(tr); case "orderamount": double totalPriceInMainCurrency = ValidationHelper.GetDouble(discountInfo.DiscountItemMinOrderAmount, 0); // Display blank value in the discount listing if order amount is not configured if (totalPriceInMainCurrency == 0) { return(string.Empty); } // Format currency string priceInMainCurrencyFormatted = CurrencyInfoProvider.GetFormattedPrice(totalPriceInMainCurrency, SiteContext.CurrentSiteID); return(HTMLHelper.HTMLEncode(priceInMainCurrencyFormatted)); } return(parameter); }
public ServiceResponseData PromFeeCaculate() { try { int costPatTypeid = requestData.GetData <int>(0); int memberAccountID = requestData.GetData <int>(1); decimal totalFee = requestData.GetData <decimal>(2); List <Prescription> prescriptions = requestData.GetData <List <Prescription> >(3); int operatoreID = requestData.GetData <int>(4); int costHeadid = requestData.GetData <int>(5); #region 构造明细表 DataTable dtDetail = new DataTable(); DataColumn col = new DataColumn(); col.ColumnName = "ItemTypeID"; col.DataType = typeof(decimal); dtDetail.Columns.Add(col); col = new DataColumn(); col.ColumnName = "PresDetailId"; col.DataType = typeof(int); dtDetail.Columns.Add(col); col = new DataColumn(); col.ColumnName = "ItemAmount"; col.DataType = typeof(decimal); dtDetail.Columns.Add(col); col = new DataColumn(); col.ColumnName = "PromAmount"; col.DataType = typeof(decimal); dtDetail.Columns.Add(col); foreach (Prescription presc in prescriptions) { DataRow dr = dtDetail.NewRow(); dr["ItemTypeID"] = presc.ItemID; dr["PresDetailId"] = presc.PresDetailID; dr["ItemAmount"] = presc.TotalFee; dr["PromAmount"] = 0; dtDetail.Rows.Add(dr); } #endregion #region 构造分类表 var result = from p in prescriptions.AsEnumerable() group p by p.StatID into g select new { g.Key, SumValue = g.Sum(p => p.TotalFee) }; DataTable dtPromClass = new DataTable(); col = new DataColumn(); col.ColumnName = "ClassTypeID"; col.DataType = typeof(string); dtPromClass.Columns.Add(col); col = new DataColumn(); col.ColumnName = "ClassAmount"; col.DataType = typeof(decimal); dtPromClass.Columns.Add(col); col = new DataColumn(); col.ColumnName = "PromAmount"; col.DataType = typeof(decimal); dtPromClass.Columns.Add(col); foreach (var stat in result) { DataRow dr = dtPromClass.NewRow(); dr["ClassTypeID"] = stat.Key; dr["ClassAmount"] = stat.SumValue; dr["PromAmount"] = 0; dtPromClass.Rows.Add(dr); } #endregion DataTable outdtPromClass = new DataTable(); DataTable outDetail = new DataTable(); PromotionManagement promManager = NewObject <PromotionManagement>(); DiscountInfo discountinfo = new DiscountInfo(); discountinfo.AccountID = memberAccountID; discountinfo.CostType = costPatTypeid; discountinfo.PatientType = 1; discountinfo.Amount = totalFee; discountinfo.OperateID = operatoreID; discountinfo.SettlementNO = costHeadid.ToString(); discountinfo.DtDetail = dtDetail; discountinfo.DtClass = dtPromClass; discountinfo.IsSave = true; discountinfo.AccID = costHeadid;//结算ID DiscountInfo resDiscountInfo = promManager.CalculationPromotion(discountinfo); responseData.AddData(resDiscountInfo.DisAmount); return(responseData); } catch (Exception err) { throw new Exception(err.Message); } }
public DiscountDeleteEventData(int agencyId, DiscountInfo deletedDiscountInfo) { AgencyId = agencyId; DeletedDiscountInfo = deletedDiscountInfo; }
private void CreateShippingDiscounts() { ShippingDiscount = Factory.NewShippingDiscount(100, false, 50); ShippingDiscount.Insert(); }