internal static UserCoupon GetUserCoupon(int userId, int couponId) { var item = new UserCoupon(); string commandText = @"select * from usercoupon where userId = ?userId and couponId = ?couponId;"; List <MySqlParameter> parameters = new List <MySqlParameter>(); parameters.Add(new MySqlParameter("?userId", userId)); parameters.Add(new MySqlParameter("?couponId", couponId)); try { using (var conn = new MySqlConnection(GlobalConfig.DbConn)) { MySqlDataReader reader = MySqlHelper.ExecuteReader(conn, CommandType.Text, commandText, parameters.ToArray()); while (reader.Read()) { item.Id = reader.GetInt32(0); item.UserId = (int)reader["UserId"]; item.CouponId = (int)reader["CouponId"]; item.SellerId = (int)reader["SellerId"]; item.CreateTime = (DateTime)reader["CreateTime"]; item.Status = (int)reader["Status"]; } } } catch (System.Exception ex) { throw; } return(item); }
/// <summary> /// 添加用户 /// </summary> /// <param name="model"></param> /// <returns></returns> public bool AddUserInfo(UserInfo model) { using (var transaction = _context.Database.BeginTransaction()) { try { var entityEntry = _context.Set <UserInfo>().Add(model); _context.SaveChanges(); var couponModel = _context.Set <CouponInfo>().FirstOrDefault(e => e.CouponType == "000001" && e.IsDel == 0); if (couponModel != null) { UserCoupon userCoupon = new UserCoupon() { CouponId = couponModel.Id, UserId = entityEntry.Entity.Id, HighestDeduction = couponModel.DiscountedPrice, ValidityPeriod = DateTime.Now.AddDays(couponModel.EffectiveLong) }; _context.Set <UserCoupon>().Add(userCoupon); } transaction.Commit(); return(true); } catch (Exception) { transaction.Rollback(); return(false); } } }
/// <summary> /// 添加用户优惠券 /// </summary> /// <param name="uc"></param> /// <returns></returns> private int AddUserCoupon(UserCoupon uc) { int data = 0; string strsql = @"insert into [UserCoupon](UserId, CouponCode, PlanId, BeginTime, EndTime, FromType, State, SubTime) values(@UserId, @CouponCode, @PlanId, @BeginTime, @EndTime, @FromType, @State, getdate());"; SqlParameter[] sp = new SqlParameter[] { new SqlParameter("@UserId", uc.UserId), new SqlParameter("@CouponCode", uc.CouponCode), new SqlParameter("@PlanId", uc.PlanId), new SqlParameter("@BeginTime", uc.BeginTime), new SqlParameter("@EndTime", uc.EndTime), new SqlParameter("@FromType", uc.FromType), new SqlParameter("@State", uc.State) }; try { data = SqlHelper.ExecuteNonQuery(strsql, sp); } catch (Exception) { throw; } return(data); }
public async Task <IActionResult> AddUserCoupons([FromRoute] string id, [FromBody] UserCoupon coupon) { if (id != coupon.UserId) { return(BadRequest(new[] { "User Id is wrong." })); } var code = coupon.Coupon.Trim(); var validationResult = await ValidateUserAndPromotionCodeAsync(id, code).ConfigureAwait(false); if (!string.IsNullOrEmpty(validationResult)) { return(BadRequest(new[] { validationResult })); } var existingCode = await _dbContext.UserCoupons.FirstOrDefaultAsync(x => x.UserId == id && x.Coupon.Equals(code, StringComparison.OrdinalIgnoreCase)).ConfigureAwait(false); if (existingCode != null) { return(BadRequest(new[] { $"This user already has the promotion code {code}." })); } await _dbContext.UserCoupons.AddAsync(new UserCoupon { UserId = id, Coupon = code }).ConfigureAwait(false); await _dbContext.SaveChangesAsync().ConfigureAwait(false); return(Ok()); }
public void LotteryProcess(UserLottery ul, Prize winprize) { _context.LotteryRecords.Add(new LotteryRecord { LotteryID = ul.LotteryID, UserID = ul.UserID, Prize = winprize }); if (winprize.Type == 0 && winprize.Points > 0) { dynamic extdata = new ExpandoObject(); extdata.Points = winprize.Points; extdata.ShortMark = winprize.Lottery.Name + "奖励";//"抽奖"; var res = IntegralProcess(ul.User.UserIntegral, null, extdata); } else { if (winprize.Type == 1 && winprize.Coupon != null) { var uc = new UserCoupon(); uc.Coupon = winprize.Coupon; uc.User = ul.User; uc.ExpiredTime = winprize.Coupon.ExpiredTime ?? DateTime.Now.AddDays(winprize.Coupon.ValidDays ?? 30); uc = _context.UserCoupons.Add(uc); } } }
internal static void CreateUserCoupon(UserCoupon userCoupon) { string connectionString = GlobalConfig.DbConn; string commandText = @"INSERT INTO usercoupon ( UserId, CouponId, CreateTime, Status, SellerId ) VALUES ( ?UserId, ?CouponId, ?CreateTime, ?Status, ?SellerId )"; List <MySqlParameter> parameters = new List <MySqlParameter>(); parameters.Add(new MySqlParameter("?UserId", userCoupon.UserId)); parameters.Add(new MySqlParameter("?CouponId", userCoupon.CouponId)); parameters.Add(new MySqlParameter("?CreateTime", DateTime.Now)); parameters.Add(new MySqlParameter("?SellerId", userCoupon.SellerId)); parameters.Add(new MySqlParameter("?Status", userCoupon.Status));//刚领取 未使用 MySqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, commandText, parameters.ToArray()); }
public void UpdateUserCoupon(UserCoupon userCoupon) { UserCoupon targetUserCoupon = context.UserCoupons.Find(userCoupon.UserCouponID); if (targetUserCoupon != null) { targetUserCoupon.Quantity = userCoupon.Quantity; } }
public void DeleteUserCoupon(int userCouponId) { UserCoupon targetUserCoupon = context.UserCoupons.Find(userCouponId); if (targetUserCoupon != null) { context.UserCoupons.Remove(targetUserCoupon); } }
public async Task AddUserCoupon(UserCoupon userCoupon) { try { await _context.UserCoupon.AddAsync(userCoupon); } catch (Exception ex) { // log or manage the exception throw ex; } }
public bool AddCouponCode(UserCoupon code) { try { if (code != null) { _context.UserCoupon.Add(code); } return(true); } catch (Exception ex) { throw ex; } }
private void UserCoupon() { int couponid = GetInt("couponid"); int userId = GetInt("uid"); try { var coupon = CouponHelper.GetItem(couponid); if (coupon == null) { ReturnCorrectMsg(string.Format("优惠券不存在couponid:{0}", couponid)); } var user = AccountHelper.GetUser(userId); var userCoupon = new UserCoupon() { CouponId = couponid, UserId = userId, Status = 0, SellerId = coupon.SellerId }; var old = CouponHelper.GetUserCoupon(userId, couponid); if (old != null && old.Id != 0) { ReturnErrorMsg("已领取过该优惠券"); return; } if (coupon.Extcredit > user.Integral) { ReturnErrorMsg("积分不足"); return; } user.Integral -= coupon.Extcredit; AccountHelper.SaveAccount(user); CouponHelper.CreateUserCoupon(userCoupon); coupon.DownloadTimes++; CouponHelper.Update(coupon); } catch { throw; } ReturnCorrectMsg("领取优惠券成功"); }
public int CreateCouponCode(int code) { try { var returnCode = 0; UserCoupon couponCode = _context.UserCoupon.FirstOrDefault(r => r.couponCode == code); if (couponCode != null) { returnCode = couponCode.userCouponId; } return(returnCode); } catch (Exception ex) { throw ex; } }
public async Task Create([FromBody] ResponseJsonPayload payload) { try { if (payload != null && payload.responseDetails != null) { UserResponse user = new UserResponse(); user.surveyId = payload.surveyId; user.userName = payload.userName; user.userPhone = payload.userPhone; user.userEmail = payload.userEmail; user.optIn = payload.optIn; await _surveyResponseRepository.AddResponseUser(user); // get _id of inserted item var newUserId = user.userResponseId; // construct response and user objects var responseDetails = payload.responseDetails; foreach (var rd in responseDetails) { SurveyResponse responseObj = new SurveyResponse(); responseObj.surveyId = rd.surveyId; responseObj.questionId = rd.questionId; responseObj.choice = rd.choice; responseObj.userResponseId = newUserId; await _surveyResponseRepository.AddResponse(responseObj); } // generate random coupon code and insert into couponCode collection int randomNum = GenerateRandomNo(); UserCoupon coupon = new UserCoupon(); coupon.responseUserId = newUserId; coupon.couponCode = randomNum; await _surveyResponseRepository.AddUserCoupon(coupon); } } catch (Exception ex) { throw ex; } }
// public static async Task<byte[]> GenerateImage(ApplicationDbContext context, ITemplateService templateService, ICouponService couponService, Guid couponId, string userId) // { // var currentUserCoupon = couponService.GetUserCoupon(userId, couponId); // var currentCoupon = await couponService.GetCouponById(couponId); // string documentContent = await templateService.RenderTemplateAsync( //"Coupons/CouponPdf", ConvertUserCouponToPdfViewModel(currentUserCoupon, currentCoupon)); // var htmlToImageConv = new NReco.ImageGenerator.HtmlToImageConverter(); // var jpegBytes = htmlToImageConv.GenerateImage(documentContent, ImageFormat.Jpeg); // return jpegBytes; // } // public static async Task<byte[]> GenerateImageTest(ApplicationDbContext context, ITemplateService templateService, ICouponService couponService) // { // string documentContent = await templateService.RenderTemplateAsync( //"Coupons/CouponPdf", new CouponPdfViewModel() //{ // Caption = "TEST" //}); // var htmlToImageConv = new NReco.ImageGenerator.HtmlToImageConverter(); // var jpegBytes = htmlToImageConv.GenerateImage(documentContent, ImageFormat.Jpeg); // return jpegBytes; // } // public static async Task<byte[]> GenerateImage(ApplicationDbContext context, ITemplateService templateService, ICouponService couponService, Guid couponId, string userId) // { // var currentUserCoupon = couponService.GetUserCoupon(context, userId, couponId); // var currentCoupon = await couponService.GetCouponById(context, couponId); // var converter = new BasicConverter(new PdfTools()); // string documentContent = await templateService.RenderTemplateAsync( //"Coupons/CouponPdf", ConvertUserCouponToPdfViewModel(currentUserCoupon, currentCoupon)); // var output = converter.Convert(new HtmlToPdfDocument() // { // Objects = // { // new ObjectSettings() // { // HtmlContent = documentContent // } // } // }); // try // { // using (var document = PdfiumViewer.PdfDocument.Load(new MemoryStream(output))) // { // var image = document.Render(0, 300, 300, true); // //image.Save(@"output.png", ImageFormat.Png); // } // } // catch (Exception ex) // { // // handle exception here; // } // return output; // } public static CouponPdfViewModel ConvertUserCouponToPdfViewModel(UserCoupon userCoupon, Coupon coupon) { var networkBarcode = coupon.NetworkBarcodes. FirstOrDefault(x => x.Networks.FirstOrDefault(y => y.Id == userCoupon.NetworkId) != null); var images = networkBarcode.Networks.Select(x => x.LogoImage).ToList(); var vm = new CouponPdfViewModel { Caption = coupon.Caption, Discount = coupon.Discount, DiscountType = coupon.DiscountType, EndDate = coupon.EndDate, StartDate = coupon.StartDate, Image = coupon.Image, NetworkImages = images, BarcodeLink = BarcodeGenerator.GenerateBarcode(networkBarcode.BarcodeType, networkBarcode.BarcodeValue) }; return(vm); }
/// <summary> /// 结算优惠券填充 /// </summary> /// <param name="table"></param> /// <returns></returns> public List <UserCoupon> FillUableList(DataTable table) { var list = new List <UserCoupon>(); foreach (DataRow item in table.Rows) { var coupon = new UserCoupon() { CouponName = item["couponName"].ToString().Trim(), CouponCode = int.Parse(item["couponCode"].ToString()), CouponsNumber = int.Parse(item["couponsNumber"].ToString()), StartingTime = item["startingTime"].ToString().Trim(), EndTime = item["endTime"].ToString().Trim(), TypeCoding = int.Parse(item["typeCoding"].ToString()), Status = int.Parse(item["status"].ToString()), ReceivingType = int.Parse(item["receivingType"].ToString()), SceneCoding = int.Parse(item["SceneCoding"].ToString()), IsDel = int.Parse(item["IsDel"].ToString()), ProductCode = item["ProductCode"].ToString().Trim(), AllAmout = decimal.Parse(item["AllAmount"].ToString()), Num = item["Num"].ToString().Trim(), Types = int.Parse(item["types"].ToString()), SceneId = item["SceneId"].ToString().Trim(), FullAmount = decimal.Parse(item["fullAmount"].ToString()), Deduction = decimal.Parse(item["deduction"].ToString()), MaximumAmount = decimal.Parse(item["maximumAmount"].ToString()), Discount = decimal.Parse(item["discount"].ToString()), Number = item["number"].ToString().Trim(), TypeName = item["Name"].ToString().Trim(), GoodsName = item["goodsname"].ToString(), UserCouponId = int.Parse(item["UserCouponId"].ToString()), SceneName = item["SceneName"].ToString().Trim(), Area = item["area"].ToString().Trim() }; list.Add(coupon); } return(list); }
/// <summary> /// 设置被邀请码 /// </summary> /// <param name="code"></param> /// <returns></returns> public IActionResult SetBeInvitationCode(string code) { try { var userModel = _userInfoRepository.FindBy(e => e.InvitationCode == code && e.IsDel == false).FirstOrDefault(); if (userModel != null) { var myUserId = CurrentUser.Id; var myUser = _userInfoRepository.GetSingle(myUserId); myUser.BeInvitationCode = code; _userInfoRepository.Update(myUser); var couponModel = _couponInfoRepository.FindBy(e => e.CouponType == "000002" && e.IsDel == false).FirstOrDefault(); if (couponModel != null) { UserCoupon userCoupon = new UserCoupon() { CouponId = couponModel.Id, UserId = userModel.Id, HighestDeduction = couponModel.DiscountedPrice, ValidityPeriod = DateTime.Now.AddDays(couponModel.EffectiveLong) }; _userCouponRepository.Add(userCoupon); } } else { return(JsonError("未找到对应邀请码的用户")); } return(JsonOk("添加成功")); } catch (Exception ex) { return(JsonError(ex.Message)); } }
private void UserCoupon() { int cid = GetInt("couponid"); int userId = GetInt("uid"); int index = GetInt("start"); int size = GetInt("limit"); JsonTransfer jt = new JsonTransfer(); try { var userCoupon = new UserCoupon() { CouponId = cid, UserId = userId //CreateTime = DateTime.Now }; var old = CouponHelper.GetUserCoupon(userId, cid); if (old != null && old.Id != 0) { jt.Add("status", 0); jt.Add("message", "用户已经使用过该优惠券"); Response.Write(DesEncrypt(jt).ToLower()); Response.End(); return; } CouponHelper.CreateUserCoupon(userCoupon); } catch { throw; } jt.AddSuccessParam(); Response.Write(DesEncrypt(jt).ToLower()); Response.End(); }
public void InsertUserCoupon(UserCoupon userCoupon) { context.UserCoupons.Add(userCoupon); }
/// <summary> /// 新增定单 /// </summary> /// <param name="orderProduct"></param> /// <param name="isShoppingCart"></param> /// <param name="productOrder"></param> /// <param name="addressID"></param> /// <returns></returns> public StateCode Save(List <JsonOrderProduct> orderProduct, ProductOrder productOrder, long addressID, bool isShoppingCart) { string freight_str = ""; decimal freight = 0; long deliveryModeID = 0; //如果是自提则不计算运费 if (productOrder.logistic_method == 0) { StateCode code = ServiceIoc.Get <DeliveryModeService>().GetDefaultFreight(orderProduct, addressID, out freight_str); if (code != StateCode.State_200) { return(code); } //运费 freight = decimal.Parse(freight_str.Split('#')[1]); //运费模板ID deliveryModeID = int.Parse(freight_str.Split('#')[0]); } using (ISession s = SessionFactory.Instance.CreateSession()) { try { s.StartTransaction(); //订单商品较验 foreach (var op in orderProduct) { //较验商品规格是否存在 ProductSku sku = s.Get <ProductSku>("where product_id = @0 and dbo.fn_check_specset(specset,@1) = 1 ", op.product_id, op.specset); if (sku == null) { productOrder = null; s.RollBack(); return(StateCode.State_1); } //较验商品是否存在 Product product = s.Get <Product>("where id = @0 ", sku.product_id); if (product == null) { productOrder = null; s.RollBack(); return(StateCode.State_1); } //较验商品库存 if (op.qty > sku.stock) { productOrder = null; s.RollBack(); return(StateCode.State_502); } //较验商品状态 if (!((bool)product.is_shelves && !(bool)product.is_delete && (DateTime.Now > product.shelves_sdate && DateTime.Now < product.shelves_edate))) { productOrder = null; s.RollBack(); return(StateCode.State_505); } //商品库存处理 sku.stock = sku.stock - op.qty; s.Update <ProductSku>(sku); } //创建订单 productOrder.serial_no = AlgorithmHelper.CreateNo(); productOrder.status = OrderStatus.WaitingPayment; productOrder.delete_status = 0; productOrder.created_date = DateTime.Now; productOrder.total_amount = 0; productOrder.actual_amount = 0; productOrder.cost_price = 0; productOrder.delivery_mode_id = deliveryModeID; s.Insert <ProductOrder>(productOrder); //总金额,成本价,优惠卷金额 decimal totalProdutPrice = 0, costProdutPrice = 0; //商品的总重量,包邮商品的总重量 int total_weight = 0, sum_total_weight = 0; int index = 0; foreach (var op in orderProduct) { //商品规格 ProductSku sku = s.Get <ProductSku>("where product_id = @0 and dbo.fn_check_specset(specset,@1) = 1", op.product_id, op.specset); //商品 Product product = s.Get <Product>(sku.product_id); string[] arr = StringHelper.StringToArray(sku.specset); StringBuilder specinfo = new StringBuilder(); foreach (string i in arr) { int specname_id = 0; int specvalue_id = 0; if (i.IndexOf("_") != -1) { int.TryParse(i.Split('_')[0], out specname_id); int.TryParse(i.Split('_')[1], out specvalue_id); SpecName specname = s.Get <SpecName>("where id = @0 ", specname_id); SpecValue specvalue = s.Get <SpecValue>("where id = @0 ", specvalue_id); if (specname != null && specvalue != null) { specinfo.Append(string.Format("{0}:{1}; ", specname.name, specvalue.val)); } else { throw new Exception("商品规格信息异常"); } } } //当前当商品成本 decimal cost_sum = sku.cost_price * op.qty; //押金 decimal sum = sku.sale_price * op.qty; totalProdutPrice += sum; costProdutPrice += cost_sum; //该商品是否包邮 if (!product.is_postage) { sum_total_weight += sku.weight * op.qty; } //计算重量 total_weight += sku.weight * op.qty; //获取产品主图片 string mainPic = ""; List <Img> pictures = s.List <Img>("where biz_type = @0 and biz_id = @1", ImgType.Product_Cover, product.id); Img img = pictures.Where(p => p.is_main).SingleOrDefault(); if (img != null) { mainPic = img.is_webimg ? img.webimg_url : img.getThmImgUrl(); } //创建订单明细 ProductOrderDetail orderDetail = new ProductOrderDetail() { order_id = productOrder.id, product_id = product.id, specset = op.specset, product_name = product.name, product_en_name = product.en_name, product_img_url = mainPic, spec_msg = specinfo.ToString().Trim(), unit_price = sku.sale_price, count = op.qty, total_weight = sku.weight * op.qty, order_index = ++index, cost_price = cost_sum, total_amount = sum, actual_amount = sum }; s.Insert(orderDetail); //购物车删除商品 if (isShoppingCart) { s.ExcuteUpdate("delete tb_ord_shoppingcart where user_id = @0 and product_id = @1 and dbo.fn_check_specset(specset,@2) = 1", productOrder.created_user_id, orderDetail.product_id, orderDetail.specset ?? ""); } } #region 会员折扣模块 //会员折扣优惠金额 decimal discount = 0; //累计消费金额 object user_total_amount = s.ExecuteScalar("select COALESCE(SUM(total_amount),0) from tb_odr_order where created_user_id = @0 and is_pay = @1", productOrder.created_user_id, true); //累计消费金额 decimal amount = decimal.Parse(user_total_amount.ToString()); //获取等级列表 List <MemberLevelSetting> levels = s.List <MemberLevelSetting>("order by total_amount desc"); foreach (var level in levels) { if (amount >= level.total_amount) { discount = totalProdutPrice * (100 - level.discount) / 100; break; } } //会员折扣 productOrder.discount_amount = discount; #endregion #region 优惠卷模块 if (productOrder.user_coupon_id != 0) { //存在未使用的优惠卷 string coupon_sql = "where id = @0 and is_used = @1 and full_amount <= @2"; UserCoupon userCoupon = s.Get <UserCoupon>(coupon_sql, productOrder.user_coupon_id, false, totalProdutPrice); if (userCoupon != null) { //优惠卷金额 productOrder.coupon_amount = userCoupon.coupon_amount; //修改会员优惠卷状态 s.ExcuteUpdate("update tb_user_aty_coupon set is_used = @0 where id = @1", true, userCoupon.id); } } #endregion #region 发货单 ShoppingAddress sa = s.Get <ShoppingAddress>(addressID); if (sa == null) { throw new Exception("收货地址不存在"); } //订单发货信息 OrderDelivery orderDelivery = new OrderDelivery(); orderDelivery.order_id = productOrder.id; orderDelivery.province = sa.province; orderDelivery.city = sa.city; orderDelivery.area = sa.area; orderDelivery.address = sa.address; orderDelivery.contact = sa.contact; orderDelivery.mobile = sa.mobile; orderDelivery.postal_code = sa.postal_code; orderDelivery.tel = sa.tel; s.Insert <OrderDelivery>(orderDelivery); #endregion //总计金额(商品总金额+物流费用) var totalPrice = totalProdutPrice + freight; //成本价 productOrder.cost_price = costProdutPrice; //配送费 productOrder.freight = freight; //总金额 productOrder.total_amount = totalPrice; //实付金额 productOrder.actual_amount = totalPrice - productOrder.coupon_amount - discount; //总重量 productOrder.total_weight = total_weight; //更新订单 s.Update <ProductOrder>(productOrder); s.Commit(); return(StateCode.State_200); } catch (Exception ex) { s.RollBack(); return(StateCode.State_500); } } }
public ApplyCouponEvent(UserCoupon userCoupon) { UserCoupon = userCoupon; }
public UseCouponEvent(UserCoupon userCoupon) { UserCoupon = userCoupon; }
/// <summary> /// 用户注册 /// </summary> /// <param name="dto"></param> /// <param name="request"></param> public ApiResult <LoginResDto> UserRegister(RegisterReqDto dto, HttpRequestMessage request) { string password = Tool.GetMD5(dto.Password); string ip = Tool.GetIP(); string regsql = @" insert into UserInfo(UserName, Name, Password, Mobile, Coin, Money, Integral, SubTime, LastLoginTime, State,Pid,RegisterIP) values(@UserName, @Name, @Password, @Mobile, 0,0, 0, getdate(), getdate(), 0,@Pid,@RegisterIP);select @@identity "; SqlParameter[] regsp = new SqlParameter[] { new SqlParameter("@UserName", dto.Phone), new SqlParameter("@Name", dto.NickName), new SqlParameter("@Password", password), new SqlParameter("@Mobile", dto.Phone), new SqlParameter("@Pid", dto.InviteCode.HasValue ? dto.InviteCode.Value : 0), new SqlParameter("@RegisterIP", ip) }; object obj = SqlHelper.ExecuteScalar(regsql, regsp); if (obj == null) { throw new ApiException(50000, "注册失败,请重试"); } int userId = Convert.ToInt32(obj); var couponModel = GetCoupon("A0001"); DateTime beginTime = DateTime.Now; DateTime endTime = DateTime.Now.AddDays(couponModel.ExpiryDate); #region 注册时,添加一张查看卷 UserCoupon uc = new UserCoupon(); uc.UserId = userId; uc.CouponCode = "A0001"; uc.PlanId = 0; uc.BeginTime = beginTime; uc.EndTime = endTime; uc.FromType = 1; uc.State = 1; AddUserCoupon(uc); #endregion //TODO:事务优化处理 #region 发放邀请注册奖励 if (dto.InviteCode.HasValue) { try { var inviteUser = GetUserInfo(dto.InviteCode.Value); if (inviteUser != null) { //受邀奖励 int myReward = GetRadomReward(3); AddCoinReward(userId, inviteUser.Id.ToString(), 6, myReward, 1); //邀请奖励 int upReward = GetRadomReward(1); AddCoinReward((int)inviteUser.Id, userId.ToString(), 7, upReward, 1); //添加邀请任务记录 AddUserTask((int)dto.InviteCode.Value, 105); //上级的上级奖励 if (inviteUser.Pid.HasValue && inviteUser.Pid > 0) { var superUser = GetUserInfo(inviteUser.Pid.Value); if (superUser != null) { int superReward = GetRadomReward(2); AddCoinReward((int)superUser.Id, inviteUser.Id.ToString(), 7, superReward, userId); } } #region 邀请注册时,邀请人添加一张查看卷 UserCoupon uc1 = new UserCoupon(); uc1.UserId = (int)inviteUser.Id; uc1.CouponCode = "A0001"; uc1.PlanId = 0; uc1.BeginTime = beginTime; uc1.EndTime = endTime; uc1.FromType = 2; uc1.State = 1; AddUserCoupon(uc1); #endregion } } catch (Exception ex) { LogHelper.Error("发放邀请注册奖励异常", ex); } } #endregion #region 发登录token string webHost = ConfigurationManager.AppSettings["webHost"]; string avater = string.Format("{0}/images/default_avater.png", webHost); IdentityInfo authInfo = new IdentityInfo() { UserId = userId, UserAccount = dto.Phone, UserStatus = 0, UserName = dto.NickName, IsTemp = false, Avater = avater }; var tokenAuth = new QiuxunTokenAuthorizer(new ApiAuthContainer(request)); tokenAuth.Authorize(authInfo); #endregion LoginResDto resDto = new LoginResDto() { Account = dto.Phone, Avater = avater, UserId = userId, Mobile = dto.Phone, NickName = dto.NickName }; return(new ApiResult <LoginResDto>() { Data = resDto }); }
/// <summary> /// Seeds Transactional Data /// </summary> /// <param name="dataClientConfig"></param> /// <returns></returns> private async Task TransactionalDataDemoAsync(Config.DataClientConfig dataClientConfig) { try { using (DataClient dataClient = new DataClient(dataClientConfig)) { if (dataClient.TransactionalData != null) { TransactionalData transactionalData = dataClient.TransactionalData; // Explicit loading. When the entity is first read, related data isn't retrieved. // Example code that retrieves the related data. It impacts retrieval performance hence only use if it's needed. await transactionalData.ClientUsers.Include(clientUser => clientUser.Client) .Include(clientUser => clientUser.User).LoadAsync(); await transactionalData.UserCoupons.Include(userCoupon => userCoupon.User) .Include(userCoupon => userCoupon.Coupon).LoadAsync(); ///////// DB seeding with demo content ///////// // Look for any Clients if (transactionalData.ClientUsers.Any()) { string log = "Total ClientUsers found: " + transactionalData.ClientUsers.LongCount() + " | " + "Total UserCoupons found: " + transactionalData.UserCoupons.LongCount(); Context.Logger.LogLine("[TransactionalData Summary]"); Context.Logger.LogLine(log); return; // DB has been seeded already } // DB save operation Context.Logger.LogLine("[Adding contents for TransactionalData]"); // Adding ClientUsers var clientUsers = new ClientUser[] { new ClientUser { ClientID = 1, UserID = 1 } }; foreach (ClientUser clientUser in clientUsers) { transactionalData.ClientUsers.Add(clientUser); } Context.Logger.LogLine("1 ClientUser added"); // Adding UserCoupons var userCoupons = new UserCoupon[] { new UserCoupon { UserID = 1, CouponID = 1 } }; foreach (UserCoupon userCoupon in userCoupons) { transactionalData.UserCoupons.Add(userCoupon); } Context.Logger.LogLine("1 UserCoupon added"); // SAVING the changes into physical DB await transactionalData.SaveChangesAsync(); } } } catch (Exception ex) { Context.Logger.LogLine("TransactionalData ERROR: " + ex.Message); } }
public IActionResult Post([FromBody] UserCoupon body) { var entity = _manager.Add(body); return(ResponseJson(entity)); }
public IActionResult Put([FromBody] UserCoupon body) { var entity = _manager.Update(body); return(ResponseJson(_manager.Update(entity))); }