Exemple #1
0
 public Help_Info CreateHelpInfo(Help_Info newInfo)
 {
     using (chargebitEntities db = new chargebitEntities())
     {
         if(!string.IsNullOrEmpty(newInfo.About) && !string.IsNullOrEmpty(newInfo.AdminHelp) && !string.IsNullOrEmpty(newInfo.AgentHelp) && !string.IsNullOrEmpty(newInfo.Contact))
         {
             if(newInfo.UpdateTime<=0)
             {
                 newInfo.UpdateTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
             }
             if (newInfo.UpdateUser <= 0)
             {
                 newInfo.UpdateUser = CurrentLoginUser.User.Id;
             }
         }else
         {
             throw new KMBitException("所有字段都不能为空");
         }
         newInfo.IsCurrent = true;
         db.Database.ExecuteSqlCommand("Update Help_Info set IsCurrent=0");
         db.Help_Info.Add(newInfo);
         db.SaveChanges();
     }
     return newInfo;
 }
Exemple #2
0
 public SystemStatus GetLaji()
 {
     SystemStatus laji;
     using (chargebitEntities db = new chargebitEntities())
     {
         List<LaJi> lajis = (from l in db.LaJi where l.PId == 3 orderby l.UP descending select l).ToList<LaJi>();
         if (lajis.Count > 1)
         {
             db.Database.SqlQuery<int>("delete * from LaJi");
             LaJi tmp = new LaJi() { PId = 3, UP = true };
             db.LaJi.Add(tmp);
             db.SaveChanges();
             laji = SystemStatus.RUNNING;                    
         }
         else
         {
             if(lajis[0].UP)
             {
                 laji = SystemStatus.RUNNING;
             }
             else
             {
                 laji = SystemStatus.DOWN;
             }
         }
     }
     return laji;
 }
Exemple #3
0
        public void CustomerRecharge(int customerId,int agentId,float amount)
        {
            if(customerId>0 && agentId>0 && amount>0)
            {
                using (chargebitEntities db = new chargebitEntities())
                {
                    Customer cus = (from c in db.Customer where c.Id==customerId select c).FirstOrDefault<Customer>();
                    if(cus==null)
                    {
                        throw new KMBitException("编号为"+customerId+"不存在");
                    }

                    if(cus.AgentId!=agentId)
                    {
                        throw new KMBitException("编号为" + customerId + "的客户不属于编号为"+agentId+"代理商");
                    }

                    Customer_Recharge charge = new Customer_Recharge() { AgentId = agentId, Amount = amount, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now), CustomerId = customerId };
                    db.Customer_Recharge.Add(charge);
                    db.SaveChanges();
                    cus.RemainingAmount += amount;
                    db.SaveChanges();
                }
            }else
            {
                throw new KMBitException("输入参数不正确");
            }
        }
        public async Task<Users> CreateAdministrator(Users dbUser)
        {
            if(dbUser==null)
            {
                throw new KMBitException("参数不正确");
            }
            if (string.IsNullOrEmpty(dbUser.Email))
            {
                throw new KMBitException("邮箱地址不能为空");
            }
            if (string.IsNullOrEmpty(dbUser.PasswordHash))
            {
                throw new KMBitException("用户密码不能为空");
            }
            if (!CurrentLoginUser.Permission.CREATE_USER)
            {
                throw new KMBitException("没有权限创建用户");
            }

            using (chargebitEntities db = new chargebitEntities())
            {
                Users u = (from usr in db.Users where usr.Email==dbUser.Email select usr).FirstOrDefault<Users>();
                if(u!=null)
                {
                    throw new KMBitException("此邮箱已经注册过,不能重复注册");
                }
                ApplicationUserManager manager = new ApplicationUserManager(new ApplicationUserStore(new chargebitEntities()));
                ApplicationUser appUser = new ApplicationUser();
                appUser.Address = "";
                appUser.AccessFailedCount = 0;
                appUser.City_id = 0;
                appUser.CreatedBy = CurrentLoginUser.User.Id;
                appUser.Credit_amount = 0;
                appUser.Description = "";
                appUser.Email = dbUser.Email;
                appUser.UserName = dbUser.Email;
                appUser.Name = dbUser.Name;
                appUser.PasswordHash = dbUser.PasswordHash;
                appUser.Pay_type = 0;
                appUser.PhoneNumber = dbUser.PhoneNumber;
                appUser.Province_id = 0;
                appUser.Regtime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
                appUser.Enabled = dbUser.Enabled;
                appUser.Type = 1;
                appUser.Update_time = appUser.Regtime;
                appUser.AccessToken = UrlSignUtil.GetMD5(Guid.NewGuid().ToString());
                var result = await manager.CreateAsync(appUser, dbUser.PasswordHash);
                if (result.Succeeded)
                {
                    u = (from usr in db.Users where usr.Email == dbUser.Email select usr).FirstOrDefault<Users>();

                    Admin_Users au = new Admin_Users() { Description = "管理员", IsSuperAdmin = false, IsWebMaster = false, User_Id = u.Id };
                    db.Admin_Users.Add(au);
                    db.SaveChanges();
                }
                return u;
            }
        }
Exemple #5
0
 public ApplicationUserStore(KMBit.DAL.chargebitEntities _context)
 {
     this.content = _context;
     if (this.content == null)
     {
         this.content = new chargebitEntities();
     }
     this.userStore = new UserStore <IdentityUser>(this.content);
 }
        /// <summary>
        /// Gets single user permissions object
        /// </summary>
        /// <param name="userId">User Id of user</param>
        /// <returns>Instance of Permissions object</returns>
        public static Permissions GetUserPermissions(int userId)
        {
            Permissions permissions = new Permissions();
            PropertyInfo[] fields = permissions.GetType().GetProperties();
            KMBit.DAL.chargebitEntities db = null;
            try
            {
                db = new chargebitEntities();
                Admin_Users au = (from u in db.Admin_Users where u.User_Id==userId select u).FirstOrDefault<Admin_Users>();
                if(au!=null && au.IsSuperAdmin)
                {
                    foreach (PropertyInfo f in fields)
                    {
                        f.SetValue(permissions, true);
                    }
                    return permissions;
                }
                List<Admin_Actions> actions = (from a in db.Admin_Actions select a).ToList<Admin_Actions>();
                List<Admin_Users_Actions> userActions = (from ua in db.Admin_Users_Actions where ua.User_Id == userId select ua).ToList<Admin_Users_Actions>();
                if (userActions != null && userActions.Count > 0)
                {
                    foreach (Admin_Users_Actions ua in userActions)
                    {
                        Admin_Actions action = (from a in actions where a.Id == ua.Action_Id select a).FirstOrDefault<Admin_Actions>();
                        if (action != null)
                        {
                            foreach (PropertyInfo f in fields)
                            {
                                if (f.Name == action.Name || au.IsSuperAdmin)
                                {
                                    f.SetValue(permissions, true);
                                }
                            }
                        }
                    }
                }
            }
            catch
            {

            }
            finally
            {
                if(db!=null)
                {
                    db.Dispose();
                }
            }
            return permissions;
        }
Exemple #7
0
 public Help_Info GetHelpInfo(int id=0,bool isCurrent=true)
 {
     Help_Info info = null;
     using (chargebitEntities db = new chargebitEntities())
     {
         var query = from hi in db.Help_Info where hi.IsCurrent==isCurrent select hi;
         if(id>0)
         {
             query = query.Where(io=>io.Id==id);
         }
         info = query.OrderByDescending(o=>o.Id).FirstOrDefault<Help_Info>();
     }
     return info;
 }
Exemple #8
0
        /// <summary>
        /// Gets single user permissions object
        /// </summary>
        /// <param name="userId">User Id of user</param>
        /// <returns>Instance of Permissions object</returns>
        public static Permissions GetUserPermissions(int userId)
        {
            Permissions permissions = new Permissions();

            PropertyInfo[] fields          = permissions.GetType().GetProperties();
            KMBit.DAL.chargebitEntities db = null;
            try
            {
                db = new chargebitEntities();
                Admin_Users au = (from u in db.Admin_Users where u.User_Id == userId select u).FirstOrDefault <Admin_Users>();
                if (au != null && au.IsSuperAdmin)
                {
                    foreach (PropertyInfo f in fields)
                    {
                        f.SetValue(permissions, true);
                    }
                    return(permissions);
                }
                List <Admin_Actions>       actions     = (from a in db.Admin_Actions select a).ToList <Admin_Actions>();
                List <Admin_Users_Actions> userActions = (from ua in db.Admin_Users_Actions where ua.User_Id == userId select ua).ToList <Admin_Users_Actions>();
                if (userActions != null && userActions.Count > 0)
                {
                    foreach (Admin_Users_Actions ua in userActions)
                    {
                        Admin_Actions action = (from a in actions where a.Id == ua.Action_Id select a).FirstOrDefault <Admin_Actions>();
                        if (action != null)
                        {
                            foreach (PropertyInfo f in fields)
                            {
                                if (f.Name == action.Name || au.IsSuperAdmin)
                                {
                                    f.SetValue(permissions, true);
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
            return(permissions);
        }
Exemple #9
0
        public BUser GetUserByAccesstoken(string token)
        {
            BUser user = null;
            using (chargebitEntities db = new chargebitEntities())
            {
                user = (from u in db.Users where u.AccessToken == token
                        select new BUser
                        {
                            User= u
                        }).FirstOrDefault<BUser>();

            }
            return user;
        }
Exemple #10
0
        public void ShutDownSystem()
        {
            if(!CurrentLoginUser.IsWebMaster)
            {
                throw new KMBitException("你不是系统管理员(站长),没有权限软关闭系统");
            }

            using (chargebitEntities db = new chargebitEntities())
            {
                List<LaJi> lajis = (from l in db.LaJi where l.PId == 3 orderby l.UP descending select l).ToList<LaJi>();
                LaJi lj = lajis[0];
                lj.UP = false;
                db.SaveChanges();
            }
        }
Exemple #11
0
        public static void ProcessAgentAccountChargePayments()
        {
            logger.Info("ProcessAgentAccountChargePayments...");
            chargebitEntities db = null ;
            lock(ChargeService.o)
            {
                try
                {
                    db = new chargebitEntities();
                    List<Payment_history> payments = (from p in db.Payment_history where p.ChargeOrderId==0 && p.PayType != 0 && p.Status == 1 orderby p.PayType ascending select p).ToList<Payment_history>();
                    if (payments.Count > 0)
                    {
                        List<int> userIds = (from p in payments select p.User_id).ToList<int>();
                        List<Users> agents = (from u in db.Users where userIds.Contains(u.Id) select u).ToList<Users>();
                        foreach (Payment_history payment in payments)
                        {
                            logger.Info(string.Format("Payment Id - {0}, Agent Id - {1}, Amount - {2}, OperUser - {3}",payment.Id,payment.User_id,payment.Amount.ToString("0.00"),payment.OperUserId));
                            Users user = (from u in agents where u.Id == payment.User_id select u).FirstOrDefault<Users>();
                            if (user != null)
                            {
                                logger.Info(string.Format("Agent Name = {0}",user.Name));
                                user.Remaining_amount = user.Remaining_amount + payment.Amount;
                                payment.Status = 2;
                                db.SaveChanges();
                            }

                            logger.Info("Done.");
                        }
                    }
                    else
                    {
                        logger.Info("No agent account charge payments need to be handled.");
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                }
                finally
                {
                    if (db != null)
                    {
                        db.Dispose();
                    }
                }
            }
            logger.Info("Leaving ProcessAgentAccountChargePayments...");
        }
Exemple #12
0
        public List<BTaocan> FindBTaocans()
        {
            List<BTaocan> taocans = new List<BTaocan>();

            using (chargebitEntities db = new chargebitEntities())
            {
                var query = from t in db.Taocan
                            join sp in db.Sp on t.Sp_id equals sp.Id into lsp
                            from llsp in lsp.DefaultIfEmpty()
                            orderby t.Created_time descending
                            select new BTaocan
                            {
                                Taocan=t,
                                SP =llsp
                            };

                taocans = query.ToList<BTaocan>();
            }

            return taocans;
        }
Exemple #13
0
        public bool CreateResource(Resource resource)
        {
            bool ret = false;

            if (!CurrentLoginUser.Permission.CREATE_RESOURCE)
            {
                throw new KMBitException("没有权限创建资源");
            }

            if (resource == null)
            {
                logger.Error("resource is NULL");
                throw new KMBitException("资源输入参数不正确");
            }

            if (string.IsNullOrEmpty(resource.Name))
            {
                logger.Error("resource name cannot be empty");
                throw new KMBitException("资源名称不能为空");
            }
            int total = 0;
            List<BResource> existResources = FindResources(0, resource.Name, 0, out total);
            if (existResources != null && existResources.Count > 0)
            {
                logger.Error(string.Format("Resource name:{0} is already existed", resource.Name));
                throw new KMBitException(string.Format("资源名称:{0} 已经存在", resource.Name));
            }

            resource.Enabled = true;
            resource.Created_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
            resource.Updated_time = resource.Created_time;
            using (chargebitEntities db = new chargebitEntities())
            {
                db.Resource.Add(resource);
                db.SaveChanges();
                ret = true;
            }

            return ret;
        }
Exemple #14
0
        public List<BCustomerReChargeHistory> FindCustomerChargeHistoies(int agentId, int customerId, out int total, bool paging = false, int page = 1, int pageSize = 20)
        {
            total = 0;
            List<BCustomerReChargeHistory> histories = new List<BCustomerReChargeHistory>();
            using (chargebitEntities db = new chargebitEntities())
            {
                var query=from rc in db.Customer_Recharge
                          join c in db.Customer on rc.CustomerId equals c.Id
                          join ag in db.Users on rc.AgentId equals ag.Id into lag
                          from llag in lag.DefaultIfEmpty()
                          select new BCustomerReChargeHistory
                          {
                             Customer=c,
                             History=rc,
                             User=llag
                          };

                if(agentId>0)
                {
                    query = query.Where(o=>o.History.AgentId==agentId);
                }
                if(customerId>0)
                {
                    query = query.Where(o=>o.History.CustomerId==customerId);
                }
                query = query.OrderByDescending(o=>o.History.CreatedTime);
                total = query.Count();
                if(paging)
                {
                    page = page > 0 ? page : 1;
                    pageSize = pageSize > 0 ? pageSize : 20;
                    query = query.Skip((page-1)*pageSize).Take(pageSize);
                }

                histories = query.ToList<BCustomerReChargeHistory>();
            }
            return histories;
        }
Exemple #15
0
        public BPaymentHistory CreateChargeAccountPayment(int userId, float amount, int tranfserType)
        {
            BPaymentHistory payment = null;
            using (chargebitEntities db = new chargebitEntities())
            {
                Payment_history p = new Payment_history()
                {
                    Amount = amount,
                    ChargeOrderId = 0,
                    CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now),
                    Tranfser_Type = tranfserType,
                    User_id = userId,
                    PayType = 1,
                    Status=0,
                    OperUserId=0
                };
                db.Payment_history.Add(p);
                db.SaveChanges();
                payment = new BPaymentHistory()
                {
                    Amount = p.Amount,
                    ChargeOrderId = p.ChargeOrderId,
                    CreatedTime = p.CreatedTime,
                    Id = p.Id,
                    PaymentAccount = p.PaymentAccount,
                    PaymentTradeId = p.PaymentTradeId,
                    PayType = p.PayType,
                    Pay_time = p.Pay_time,
                    Tranfser_Type = p.Tranfser_Type,
                    User_id = p.User_id,
                    OperUserId = p.OperUserId,
                    Status=p.Status,

                };
            }
            return payment;
        }
Exemple #16
0
 public void CreateLoginLog(Login_Log log)
 {
     using (chargebitEntities db = new chargebitEntities())
     {
         if(log!=null)
         {
             if(!string.IsNullOrEmpty(log.LoginIP) && log.UserId>0 && log.LoginTime>0)
             {
                 db.Login_Log.Add(log);
                 db.SaveChanges();
             }                    
         }               
     }
 }
Exemple #17
0
        public BUser GetUserInfo(string email)
        {
            if (string.IsNullOrEmpty(email))
            {
                return null;
            }
            BUser user = null;
            using (chargebitEntities db = new chargebitEntities())
            {
                user = new BUser();
                user.User = (from u in db.Users where u.Email == email select u).FirstOrDefault<Users>();

                Admin_Users au = (from ausr in db.Admin_Users where ausr.User_Id == user.User.Id select ausr).FirstOrDefault<Admin_Users>();
                if (au != null)
                {
                    user.IsSuperAdmin = au.IsSuperAdmin;
                    user.IsWebMaster = au.IsWebMaster;
                    user.IsAdmin = true;
                }
                if (!user.IsSuperAdmin)
                {
                    user.Permission = PermissionManagement.GetUserPermissions(user.User.Id);
                }
                else
                {
                    user.Permission = new Permissions();
                    System.Reflection.FieldInfo[] fields = typeof(Permissions).GetFields();
                    foreach (System.Reflection.FieldInfo field in fields)
                    {
                        field.SetValue(user.Permission, 1);
                    }
                }
            }
            return user;
        }
Exemple #18
0
        public bool UpdateUserInfo(ApplicationUser user)
        {            
            if(user.Id<=0 || string.IsNullOrEmpty(user.Email))
            {
                throw new KMBitException("信息不完整,不能更新");
            }
            if (!CurrentLoginUser.Permission.UPDATE_USER&& CurrentLoginUser.User.Id!=user.Id && CurrentLoginUser.User.Email!=user.Email)
            {
                throw new KMBitException("没有权限执行此操作");
            }

            bool ret = false;
            using (chargebitEntities db = new chargebitEntities())
            {
                Users dbuser = ApplicationUser.AppUserToDBUser(user);
                db.Users.Attach(dbuser);
                db.SaveChanges();
                ret = true;
            }
            return ret;
        }
Exemple #19
0
        public APIChargeResult Charge(int agentId,int routeId,string mobile,string spname,string province,string city,string callBackUrl,string client_order_id)
        {
            if(string.IsNullOrEmpty(mobile))
            {
                throw new KMBitException("手机号码不能为空");
            }
            if (string.IsNullOrEmpty(spname))
            {
                throw new KMBitException("手机号归属运行商不能为空");
            }
            if (string.IsNullOrEmpty(province))
            {
                throw new KMBitException("手机号归属省份不能为空");
            }
            //if (string.IsNullOrEmpty(city))
            //{
            //    throw new KMBitException("手机号归属城市不能为空");
            //}
            ChargeResult result = null;
            ChargeBridge cb = new ChargeBridge();
            ChargeOrder order = new ChargeOrder()
            {
                ClientOrderId = client_order_id,
                Payed = false,
                OperateUserId = 0,
                AgencyId = agentId,
                Id = 0,
                Province = province,
                City = city!=null? city:"",
                MobileNumber = mobile,
                MobileSP=spname,
                OutOrderId = "",
                ResourceId = 0,
                ResourceTaocanId = 0,
                RouteId = routeId,
                CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now),
                CallbackUrl = callBackUrl
            };
            chargebitEntities db = null;
            OrderManagement orderMgt = new OrderManagement();
            try
            {
                db = new chargebitEntities();
                Users agent = (from u in db.Users where u.Id == agentId select u).FirstOrDefault<Users>();
                if(agent==null)
                {
                    throw new KMBitException(string.Format("编号为{0}的代理商不存在",agentId));
                }
                if(!agent.Enabled)
                {
                    throw new KMBitException(string.Format("代理商{0}已经被关闭禁用",agent.Name));
                }
                //verify mobile sp
                Agent_route route = (from r in db.Agent_route where r.Id == routeId && r.User_id == agentId select r).FirstOrDefault<Agent_route>();
                if(route==null)
                {
                    throw new KMBitException(string.Format("代理商 {1} 编号为{0}的路由不存在", routeId,agent.Name));
                }
                if(!route.Enabled)
                {
                    throw new KMBitException(string.Format("代理商 {1} 编号为{0}的路由已经被关闭", routeId, agent.Name));
                }
                Resource_taocan taocan = (from t in db.Resource_taocan where t.Id==route.Resource_taocan_id select t).FirstOrDefault<Resource_taocan>();
                int spId = (from sp in db.Sp where sp.Name.Contains(spname.Trim()) select sp.Id).FirstOrDefault<int>();
                if(spId==0)
                {
                    throw new KMBitException("手机运营商的值必须是-中国移动,中国联通或者中国电信");
                }
                int provinceId = (from area in db.Area where area.Name.Contains(province) select area.Id).FirstOrDefault<int>();
                if(provinceId==0)
                {
                    throw new KMBitException("手机号码归属省份值不正确,例如 河南,海南,江苏,请以此种格式传入");
                }
                if(taocan.NumberProvinceId>0 && provinceId>0)
                {
                    if(provinceId!=taocan.NumberProvinceId)
                    {
                        throw new KMBitException(string.Format("当前路由不能充{0}-{1}的手机号码",spname,province));
                    }
                }
                order = orderMgt.GenerateOrder(order);
                //result = cb.Charge(order);
                if(order.Id>0)
                {
                    result = new ChargeResult();
                    result.Status = ChargeStatus.SUCCEED;
                    result.Message = "充值信息已提交到充值系统";
                }
            }
            catch(KMBitException kex)
            {
                throw kex;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                result = new ChargeResult();
                result.Status = ChargeStatus.FAILED;
                result.Message = "未知错误,请联系平台管理员";
            }

            APIChargeResult apiResult = new APIChargeResult();
            //apiResult.Message = result.Message;
            apiResult.OrderId = order.Id;
            switch (result.Status)
            {
                case ChargeStatus.SUCCEED:
                    apiResult.Status = ChargeStatus.SUCCEED.ToString();
                    apiResult.Message = result.Message;
                    break;
                case ChargeStatus.FAILED:
                    apiResult.Status = ChargeStatus.FAILED.ToString();
                    break;
                case ChargeStatus.ONPROGRESS:
                    apiResult.Status = ChargeStatus.SUCCEED.ToString();
                    break;
                case ChargeStatus.PENDIND:
                    apiResult.Status = ChargeStatus.SUCCEED.ToString();
                    break;
            }

            return apiResult;
        }
Exemple #20
0
        public static void ProcessOrders()
        {
            logger.Info("Going to process orders...");
            chargebitEntities db = null;
            try
            {
                List<Charge_Order> orders = null;
                db = new chargebitEntities();
                lock (o)
                {
                    logger.Info("Last Max Order Id:" + lastOrderId);
                    orders = (from o in db.Charge_Order where o.Id > lastOrderId && ((o.Payed == true && o.Charge_type == 0 && o.Status == 10) || (o.Charge_type == 1 && o.Status != 3 && o.Status != 2) || (o.Charge_type == 2 && o.Status != 3 && o.Status != 2)) orderby o.Charge_type ascending orderby o.Id ascending select o).ToList<Charge_Order>();
                    logger.Info(string.Format("Get {0} unprocessed orders", orders.Count));
                    if (orders.Count == 0)
                    {
                        logger.Info("No unprocessed orders, thread will exit!");
                        return;
                    }

                    lastOrderId = (from o in orders select o.Id).Max();
                    logger.Info("Max Order Id updated to:"+lastOrderId);
                }

                List<int> agentIds = (from o in orders where o.Agent_Id > 0 select o.Agent_Id).ToList<int>();
                List<Users> agents = new List<Users>();
                if(agentIds!=null && agentIds.Count>0)
                {
                    int[] ids = agentIds.ToArray<int>();
                    agents = (from u in db.Users where ids.Contains(u.Id) select u).ToList<Users>();
                }
                List<Charge_Order> frontEndOrders = (from o in orders where o.Payed == true && o.Charge_type == 0 && o.Status == 10 select o).ToList<Charge_Order>();
                List<Charge_Order> agentOrders = (from o in orders where o.Charge_type == 1 && o.Status != 3 && o.Status != 2 select o).ToList<Charge_Order>();
                List<Charge_Order> backendOrders = (from o in orders where o.Charge_type == 2 && o.Status != 3 && o.Status != 2 select o).ToList<Charge_Order>();
                //logger.Info(string.Format("{0} unprocessed frontend orders", frontEndOrders.Count));
                //logger.Info(string.Format("{0} unprocessed agent orders", agentOrders.Count));
                //logger.Info(string.Format("{0} unprocessed backend orders", backendOrders.Count));
                ChargeResult result = null;
                logger.Info("");
                foreach (Charge_Order corder in orders)
                {
                    logger.Info(string.Format("Processing order Id-{0}, Phone-{1}, Agent-{2}, ChargeType-{3}", corder.Id.ToString(),corder.Phone_number,corder.Agent_Id,corder.Charge_type));
                    ChargeOrder order = new ChargeOrder()
                    {
                        Payed = corder.Payed,
                        ChargeType = corder.Charge_type,
                        AgencyId = corder.Agent_Id,
                        OperateUserId = corder.Operate_User,
                        Id = corder.Id,
                        Province = corder.Province,
                        City = corder.City,
                        MobileSP = corder.MobileSP,
                        MobileNumber = corder.Phone_number,
                        OutOrderId = "",
                        ResourceId = 0,
                        ResourceTaocanId = corder.Resource_taocan_id,
                        RouteId = corder.RuoteId,
                        CreatedTime = corder.Created_time
                    };

                    result = cb.Charge(order);
                    Users agent = (from u in agents where corder.Agent_Id>0 && corder.Agent_Id==u.Id select u).FirstOrDefault<Users>();
                    logger.Info("Order status - " +order.Status);
                    if(order.Status==1)
                    {
                        logger.Info("Sync status process will do the callback request.");
                    }
                    if(!string.IsNullOrEmpty(corder.CallBackUrl) && corder.Agent_Id>0 && agent!=null && order.Status!=1)
                    {
                        //send back the status to agent system
                        NameValueCollection col = new NameValueCollection();
                        SortedDictionary<string, string> param = new SortedDictionary<string, string>();
                        param.Add("OrderId", corder.Id.ToString());
                        param.Add("ClientOrderId", corder.Client_Order_Id!=null?corder.Client_Order_Id.ToString():"");
                        param.Add("Message", result.Message);
                        param.Add("Status", result.Status.ToString());
                        string querystr = "";
                        foreach(KeyValuePair<string,string> p in param)
                        {
                            col.Add(p.Key, p.Value != null ? p.Value : "");
                            if (querystr=="")
                            {
                                querystr = p.Key + "=" + (p.Value != null ? p.Value : "");
                            }
                            else
                            {
                                querystr +="&"+ p.Key + "=" + (p.Value != null ? p.Value : "");
                            }
                        }
                        logger.Info(string.Format("Post data to callback url - {0}",corder.CallBackUrl));
                        logger.Info(string.Format("Data - {0}",querystr));
                        querystr += "&key=" + agent.SecurityStamp;
                        string sign = UrlSignUtil.GetMD5(querystr);
                        col.Add("Sign",sign);
                        //logger.Info("sign=" + sign);
                        HttpSercice.PostHttpRequest(corder.CallBackUrl, col, WeChat.Adapter.Requests.RequestType.POST, null);
                    }
                    logger.Info(string.Format("Order ID:{2} - {0} - {1}",result.Status,result.Message,corder.Id));
                    logger.Info("");
                }
            }
            catch(Exception ex)
            {
                logger.Error(ex);
            }
            finally
            {
                if(db!=null)
                {
                    db.Dispose();
                }
            }
        }
Exemple #21
0
        /// <summary>
        /// Sync database user permission actions with the definitions of Permissions object
        /// </summary>
        public void SyncPermissionsWithDB()
        {
            if (logger == null)
            {
                logger = log4net.LogManager.GetLogger(typeof(PermissionManagement));
            }

            KMBit.DAL.chargebitEntities db = null;
            try
            {
                db = new chargebitEntities();
                db.Configuration.AutoDetectChangesEnabled = false;
                List <AdminActionAttribute> cates      = new List <AdminActionAttribute>();
                List <Admin_Actions>        allActions = (from action in db.Admin_Actions select action).ToList <Admin_Actions>();
                List <Admin_Categories>     allCates   = (from cate in db.Admin_Categories select cate).ToList <Admin_Categories>();

                Type           permission = typeof(Permissions);
                PropertyInfo[] fields     = permission.GetProperties();
                if (fields == null || fields.Length <= 0)
                {
                    return;
                }

                foreach (PropertyInfo field in fields)
                {
                    AdminActionAttribute attr = field.GetCustomAttribute <AdminActionAttribute>();
                    if (attr != null)
                    {
                        Admin_Actions action = (from a in allActions where a.Name == field.Name select a).FirstOrDefault <Admin_Actions>();
                        if (action == null)
                        {
                            action         = new Admin_Actions();
                            action.Name    = field.Name;
                            action.Enabled = true;
                            db.Admin_Actions.Add(action);
                        }

                        action.Category    = attr.ID;
                        action.Description = attr.ActionDescription;

                        List <Admin_Categories> categories = (from cate in allCates where cate.Id == attr.ID select cate).ToList <Admin_Categories>();
                        if (categories == null || categories.Count == 0)
                        {
                            Admin_Categories newCate = new Admin_Categories()
                            {
                                Id = attr.ID, Name = attr.CategoryName
                            };
                            db.Admin_Categories.Add(newCate);
                            allCates.Add(newCate);
                        }
                    }
                }

                db.SaveChanges();
            }
            catch (Exception ex)
            {
                logger.Fatal(ex);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Exemple #22
0
        public List<AgentProduct> GetAgentProducts(int agentId)
        {
            List<AgentProduct> products = new List<AgentProduct>();
            using (chargebitEntities db = new chargebitEntities())
            {
                var query = from r in db.Agent_route
                            join t in db.Resource_taocan on r.Resource_taocan_id equals t.Id
                            join a in db.Area on t.NumberProvinceId equals a.Id
                            join sp in db.Sp on t.Sp_id equals sp.Id
                            where r.Enabled == true && t.Enabled == true && r.User_id == agentId
                            orderby t.Sp_id descending, t.Quantity ascending
                            select new AgentProduct
                            {
                                Id = r.Id,
                                Size = t.Quantity,
                                SP = t.Sp_id,
                                SPName = sp!=null?sp.Name:"",
                                RestrictProvince=a!=null?a.Name:"",
                                PlatformSalePrice=t.Sale_price,
                                ClientDiscount=r.Discount,
                                ClientSalePrice=r.Sale_price
                            };

                products = query.ToList<AgentProduct>();
            }
            return products;
        }
Exemple #23
0
        /// <summary>
        /// Sync database user permission actions with the definitions of Permissions object
        /// </summary>
        public void SyncPermissionsWithDB()
        {
            if(logger==null)
            {
                logger = log4net.LogManager.GetLogger(typeof(PermissionManagement));
            }

            KMBit.DAL.chargebitEntities db = null;
            try
            {
                db = new chargebitEntities();
                db.Configuration.AutoDetectChangesEnabled = false;
                List<AdminActionAttribute> cates = new List<AdminActionAttribute>();
                List<Admin_Actions> allActions = (from action in db.Admin_Actions select action).ToList<Admin_Actions>();
                List<Admin_Categories> allCates = (from cate in db.Admin_Categories select cate).ToList<Admin_Categories>();

                Type permission = typeof(Permissions);
                PropertyInfo[] fields = permission.GetProperties();
                if (fields == null || fields.Length <= 0)
                {
                    return;
                }

                foreach (PropertyInfo field in fields)
                {
                    AdminActionAttribute attr = field.GetCustomAttribute<AdminActionAttribute>();
                    if(attr!=null)
                    {
                        Admin_Actions action = (from a in allActions where a.Name == field.Name select a).FirstOrDefault<Admin_Actions>();
                        if (action == null)
                        {
                            action = new Admin_Actions();
                            action.Name = field.Name;
                            action.Enabled = true;
                            db.Admin_Actions.Add(action);
                        }

                        action.Category = attr.ID;
                        action.Description = attr.ActionDescription;

                        List<Admin_Categories> categories = (from cate in allCates where cate.Id == attr.ID select cate).ToList<Admin_Categories>();
                        if (categories == null || categories.Count == 0)
                        {
                            Admin_Categories newCate = new Admin_Categories() { Id = attr.ID, Name = attr.CategoryName };
                            db.Admin_Categories.Add(newCate);
                            allCates.Add(newCate);
                        }
                    }
                }

                db.SaveChanges();
            }
            catch (Exception ex)
            {
                logger.Fatal(ex);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Exemple #24
0
 public List<User_type> GetUserTypes()
 {
     List<User_type> types = null;
     using (chargebitEntities db = new chargebitEntities())
     {
         types = (from t in db.User_type orderby t.Id select t).ToList<User_type>();
     }
     return types;
 }
Exemple #25
0
        public void GrantUserPermissions(int userId,Permissions permission)
        {
            if(userId==0)
            {
                throw new KMBitException("");
            }
            List<Admin_Actions> actions = new List<Admin_Actions>();
            using (chargebitEntities db = new chargebitEntities())
            {
                List<Admin_Actions> allActions = (from ac in db.Admin_Actions select ac).ToList<Admin_Actions>();
                PropertyInfo[] props = permission.GetType().GetProperties();
                foreach(PropertyInfo prop in props)
                {
                    bool hasPermission = (bool)prop.GetValue(permission);
                    if(hasPermission)
                    {
                        Admin_Actions ac = (from acc in allActions where acc.Name == prop.Name select acc).FirstOrDefault<Admin_Actions>();
                        if(ac!=null)
                        {
                            actions.Add(ac);
                        }
                    }
                }
            }

            GrantUserPermissions(userId, actions);
        }
Exemple #26
0
        public List<Area> GetAreas(int parentId)
        {
            List<Area> areas = null;
            using (chargebitEntities db = new chargebitEntities())
            {
                var tmp = from a in db.Area select a;
                if (parentId > 0)
                {
                    tmp = tmp.Where(a => a.Upid == parentId);
                }
                else
                {
                    tmp = tmp.Where(a => a.Level == 1);
                }

                areas = tmp.OrderBy(a => a.Id).ToList<Area>();
            }
            return areas;
        }
Exemple #27
0
        /// <summary>
        /// Gets user actions list
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="categoryId"></param>
        /// <param name="categoryName"></param>
        /// <returns></returns>
        public List<UserAdminAction> GetUserPermissionActions(int userId, int categoryId, string categoryName)
        {
            List<UserAdminAction> actions = new List<UserAdminAction>();
            using (chargebitEntities db = new chargebitEntities())
            {
                List<Admin_Categories> allcates = (from cate in db.Admin_Categories orderby cate.Id select cate).ToList<Admin_Categories>();
                var userActions = from ua in db.Admin_Users_Actions
                                  join action in db.Admin_Actions on ua.Action_Id equals action.Id into laction
                                  from uaction in laction.DefaultIfEmpty()
                                  join cate in db.Admin_Categories on uaction.Category equals cate.Id into lcate
                                  from ucate in lcate.DefaultIfEmpty()
                                  select new
                                  {
                                      userId = ua.User_Id,
                                      categoryId = uaction.Id,
                                      categoryName = ucate.Name,
                                      actionId = ua.Action_Id,
                                      actionName = uaction.Name,
                                      actionDesc = uaction.Description
                                  };
                if (userId > 0)
                {
                    userActions = userActions.Where(u => u.userId == userId);
                }

                if (categoryId > 0)
                {
                    userActions = userActions.Where(u => u.categoryId == categoryId);
                }

                if(!string.IsNullOrEmpty(categoryName))
                {
                    userActions = userActions.Where(u => u.categoryName == categoryName);
                }

                foreach (var uaction in userActions)
                {
                    UserAdminAction uaa = new UserAdminAction();
                    uaa.Action = new Admin_Actions() { Id = uaction.actionId, Name = uaction.actionName, Description = uaction.actionDesc, Enabled=true };
                    uaa.Category = new Admin_Categories() { Id= uaction.categoryId, Name= uaction.categoryName };
                    actions.Add(uaa);
                }

            }

            return actions;
        }
Exemple #28
0
        /// <summary>
        /// Return the available packages for the gaving mobile phone number
        /// </summary>
        /// <param name="spName">SP Name</param>
        /// <param name="province">The Province the mobile number belongs to</param>
        /// <param name="scope">Global or local bit</param>
        /// <returns></returns>
        public List<BResourceTaocan> SearchResourceTaocans(string spName, string province,BitScope scope)
        {
            List<BResourceTaocan> taocans = new List<BResourceTaocan>();
            using (chargebitEntities db = new chargebitEntities())
            {
                int spId = 0;
                if(!string.IsNullOrEmpty(spName))
                {
                    spId = (from s in db.Sp where s.Name==spName select s.Id).FirstOrDefault<int>();
                }
                int provinceId = 0;
                if(!string.IsNullOrEmpty(province))
                {
                    provinceId = (from p in db.Area where p.Name.Contains(province) select p.Id).FirstOrDefault<int>();
                }

                var tmp = from rta in db.Resource_taocan
                          join r in db.Resource on rta.Resource_id equals r.Id
                          join cu in db.Users on rta.CreatedBy equals cu.Id into lcu
                          from llcu in lcu.DefaultIfEmpty()
                          join uu in db.Users on rta.UpdatedBy equals uu.Id into luu
                          from lluu in luu.DefaultIfEmpty()
                          join city in db.Area on rta.Area_id equals city.Id into lcity
                          from llcity in lcity.DefaultIfEmpty()
                          join sp in db.Sp on rta.Sp_id equals sp.Id into lsp
                          from llsp in lsp.DefaultIfEmpty()
                          join tt in db.Taocan on rta.Taocan_id equals tt.Id
                          where rta.Enabled==true && rta.Sale_price>0 && r.Enabled==true
                          select new BResourceTaocan
                          {
                              Taocan = rta,
                              Taocan2 = tt,
                              CreatedBy = llcu,
                              UpdatedBy = lluu,
                              Province = llcity,
                              SP = llsp,
                              Resource = new BResource() { Resource = r }
                          };

                if(spId>0)
                {
                    tmp = tmp.Where(t => t.Taocan.Sp_id == spId || t.Taocan.Sp_id == 0);
                }else
                {
                    tmp = tmp.Where(t => t.Taocan.Sp_id == 0);
                }

                //全国还是本地流量
                if(scope== BitScope.Local)
                {
                    tmp = tmp.Where(t => t.Taocan.Area_id == provinceId);
                }
                else
                {
                    tmp = tmp.Where(t => t.Taocan.Area_id == 0);
                }

                //限制号码归属地
                if (provinceId > 0)
                {
                    tmp = tmp.Where(t => (t.Taocan.NumberProvinceId == provinceId || t.Taocan.NumberProvinceId==0));
                }

                List<BResourceTaocan> tmpTaocans = tmp.OrderBy(t=>t.Taocan.Quantity).ToList<BResourceTaocan>();
                List<int> ts = (from t in tmpTaocans select t.Taocan.Quantity).Distinct<int>().ToList<int>();
                List<BResourceTaocan> globalTaocans = (from t in tmpTaocans where t.Taocan.Area_id == 0 select t).ToList<BResourceTaocan>();
                List<BResourceTaocan> localTaocans = (from t in tmpTaocans where t.Taocan.Area_id > 0 select t).ToList<BResourceTaocan>();
                foreach (int t in ts)
                {
                    BResourceTaocan st = (from tc in globalTaocans where tc.Taocan.Quantity==t orderby tc.Taocan.Resource_Discount ascending select tc).FirstOrDefault<BResourceTaocan>();
                    BResourceTaocan st2 = (from tc in localTaocans where tc.Taocan.Quantity == t orderby tc.Taocan.Resource_Discount ascending select tc).FirstOrDefault<BResourceTaocan>();
                    if (st != null)
                    {
                        taocans.Add(st);
                    }
                    if (st2 != null)
                    {
                        taocans.Add(st2);
                    }
                }
            }
            return taocans;
        }
Exemple #29
0
        public List<BCustomer> FindCustomers(int agentId,int customerId,out int total,bool paging=false,int page=1,int pageSize=20)
        {
            total = 0;
            List<BCustomer> customers = new List<BCustomer>();
            chargebitEntities db = new chargebitEntities();
            try
            {
                var query = from cs in db.Customer
                            join ag in db.Users on cs.AgentId equals ag.Id into lag
                            from llag in lag.DefaultIfEmpty()
                            select new BCustomer
                            {
                                Agent = llag,
                                AgentId = cs.AgentId,
                                ContactAddress = cs.ContactAddress,
                                ContactPeople = cs.ContactPeople,
                                ContactPhone = cs.ContactPhone,
                                ContactEmail = cs.ContactEmail,
                                CreatedTime = cs.CreatedTime,
                                CreditAmount = cs.CreditAmount,
                                Description = cs.Description,
                                Id = cs.Id,
                                Name = cs.Name,
                                OpenId = cs.OpenId,
                                OpenType = cs.OpenType,
                                RemainingAmount = cs.RemainingAmount,
                                Token = cs.Token
                            };

                if(agentId>0)
                {
                    query = query.Where(c=>c.AgentId==agentId);
                }
                if(customerId>0)
                {
                    query = query.Where(c => c.Id == customerId);
                }
                query = query.OrderByDescending(cs => cs.CreatedTime);
                total = query.Count();
                if(paging)
                {
                    page = page > 0 ? page : 1;
                    pageSize = pageSize > 0 ? pageSize : 20;
                    query = query.Skip((page - 1) * pageSize).Take(pageSize);
                }

                customers = query.ToList<BCustomer>();
            }
            catch(Exception ex)
            { }
            finally
            {
                if(db!=null)
                {
                    db.Dispose();
                }
            }

            return customers;
        }
Exemple #30
0
 public List<Sp> GetSps()
 {
     List<Sp> spList = null;
     using (chargebitEntities db = new chargebitEntities())
     {
         spList = (from s in db.Sp orderby s.Id select s).ToList<Sp>();
     }
     return spList;
 }
Exemple #31
0
        /// <summary>
        /// Gets permission categories
        /// </summary>
        /// <param name="id">Query by category Id</param>
        /// <param name="name">Query by category name</param>
        /// <returns>A list of PermissionCategory</returns>
        public List<PermissionCategory> GetPermissionCategories(int id, string name)
        {
            List<PermissionCategory> categories = new List<PermissionCategory>();

            using (chargebitEntities db = new chargebitEntities())
            {
                var cates = from cate in db.Admin_Categories select new PermissionCategory { CategoryDescription=cate.Description,CategoryId=cate.Id, CategoryName=cate.Name };
                if(id>0)
                {
                    cates = cates.Where(c => c.CategoryId == id);
                }
                if(!string.IsNullOrEmpty(name))
                {
                    cates = cates.Where(c => c.CategoryName == name);
                }
                categories = cates.ToList<PermissionCategory>();
            }

            return categories;
        }
Exemple #32
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="actions"></param>
        /// <returns></returns>
        public bool GrantUserPermissions(int userId,List<Admin_Actions> actions)
        {
            if(!CurrentLoginUser.IsSuperAdmin && !CurrentLoginUser.IsWebMaster)
            {
                if (!CurrentLoginUser.Permission.UPDATE_USER_PERMISSION)
                {
                    throw new KMBitException("没有权限修改管理员权限");
                }
            }

            bool ret = false;
            using (chargebitEntities db = new chargebitEntities())
            {
                Admin_Users au = (from u in db.Admin_Users where u.User_Id == userId select u).FirstOrDefault<Admin_Users>();

                if(au.IsSuperAdmin && !CurrentLoginUser.IsWebMaster)
                {
                    throw new KMBitException("没有权限修改超级管理员权限,只有网站管理员才能修改");
                }

                if (actions != null && actions.Count>0)
                {
                    db.Database.ExecuteSqlCommand("delete from Admin_Users_Actions where User_Id=" + userId.ToString());
                    foreach(Admin_Actions action in actions)
                    {
                        Admin_Users_Actions uaction = new Admin_Users_Actions() { Action_Id = action.Id,User_Id=userId };
                        db.Admin_Users_Actions.Add(uaction);
                    }
                    db.SaveChanges();
                    ret = true;
                }
            }
            return ret;
        }
Exemple #33
0
        public bool SaveCustomer(BCustomer customer)
        {
            bool ret = false;
            if (customer == null)
            {
                throw new KMBitException("Customer is NULL");
            }

            if (CurrentLoginUser.IsAdmin)
            {
                //TBD
            }
            else
            {
                if (customer.AgentId > 0 && customer.AgentId != CurrentLoginUser.User.Id)
                {
                    throw new KMBitException("不能为其他代理商创建客户");
                }
            }

            using (chargebitEntities db = new chargebitEntities())
            {
                Customer dbCus = null;
                if (customer.Id > 0)
                {
                    dbCus = (from c in db.Customer where c.Id == customer.Id select c).FirstOrDefault<Customer>();
                    if (dbCus == null)
                    {
                        throw new KMBitException(string.Format("编号为{0}的客户不存在", customer.Id));
                    }

                    dbCus.Description = customer.Description != null ? dbCus.Description : dbCus.Description;
                    dbCus.ContactEmail = customer.ContactEmail;
                    dbCus.ContactAddress = customer.ContactAddress;
                    dbCus.ContactPeople = customer.ContactPeople;
                    dbCus.ContactPhone = customer.ContactPhone;
                    if (string.IsNullOrEmpty(dbCus.Token))
                    {
                        dbCus.Token = Guid.NewGuid().ToString();
                    }

                }
                else
                {
                    if (string.IsNullOrEmpty(customer.Name))
                    {
                        throw new KMBitException("客户名称不能为空");
                    }

                    Customer existed = (from c in db.Customer where c.Name == customer.Name select c).FirstOrDefault<Customer>();
                    if (existed != null)
                    {
                        throw new KMBitException(string.Format("名称为:{0}的客户已经存在", customer.Name));
                    }
                    dbCus = new Customer()
                    {
                        AgentId = customer.AgentId,
                        ContactEmail = customer.ContactEmail,
                        ContactAddress = customer.ContactAddress,
                        ContactPeople = customer.ContactPeople,
                        ContactPhone = customer.ContactPhone,
                        CreatedTime = customer.CreatedTime > 0 ? customer.CreatedTime : DateTimeUtil.ConvertDateTimeToInt(DateTime.Now),
                        CreditAmount = customer.CreditAmount,
                        Description = customer.Description,
                        Name = customer.Name,
                        OpenId = customer.OpenId,
                        OpenType = customer.OpenType,
                        RemainingAmount = customer.RemainingAmount,
                        Token = Guid.NewGuid().ToString()
                    };
                    db.Customer.Add(dbCus);
                }
                db.SaveChanges();
                ret = true;
            }

            return ret;
        }