Beispiel #1
0
        public bool UpdateResrouceInterface(Resrouce_interface api)
        {
            bool result          = false;
            chargebitEntities db = new chargebitEntities();

            try
            {
                Resrouce_interface oapi = (from a in db.Resrouce_interface where a.Resource_id == api.Resource_id select a).FirstOrDefault <Resrouce_interface>();
                if (oapi == null)
                {
                    db.Resrouce_interface.Add(api);
                }
                else
                {
                    oapi.APIURL        = api.APIURL;
                    oapi.CallBackUrl   = api.CallBackUrl;
                    oapi.Username      = api.Username;
                    oapi.Userpassword  = api.Userpassword;
                    oapi.ProductApiUrl = api.ProductApiUrl;
                }

                db.SaveChanges();
                result = true;
            }catch (Exception ex)
            {
            }finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
            return(result);
        }
Beispiel #2
0
 protected void RemoveQRCode(Charge_Order order)
 {
     if (order.MarketOrderId > 0)
     {
         chargebitEntities db = null;
         try
         {
             db = new chargebitEntities();
             Marketing_Orders mOrder = (from mo in db.Marketing_Orders where mo.Id == order.MarketOrderId select mo).FirstOrDefault <Marketing_Orders>();
             if (mOrder != null && !string.IsNullOrEmpty(mOrder.CodePath))
             {
                 string tmpPhysicalPath = System.IO.Path.Combine(settings.RootDirectory, mOrder.CodePath.Replace('/', '\\'));
                 if (System.IO.File.Exists(tmpPhysicalPath))
                 {
                     System.IO.File.Delete(tmpPhysicalPath);
                 }
             }
         }catch (Exception ex)
         {
             Logger.Fatal(ex);
         }finally
         {
             if (db != null)
             {
                 db.Dispose();
             }
         }
     }
 }
Beispiel #3
0
        public void SyncChargeStatus()
        {
            chargebitEntities db = new chargebitEntities();

            try
            {
                IStatus chargeMgr = null;
                List <Resrouce_interface> apis = (from api in db.Resrouce_interface where string.IsNullOrEmpty(api.CallBackUrl) orderby api.CallBackUrl select api).ToList <Resrouce_interface>();
                foreach (Resrouce_interface api in apis)
                {
                    object   o        = null;
                    Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                    Type     type     = assembly.GetType(api.Interface_classname);
                    o         = Activator.CreateInstance(type);
                    chargeMgr = o as IStatus;
                    if (chargeMgr != null)
                    {
                        chargeMgr.GetChargeStatus(api.Resource_id);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Beispiel #4
0
        public void SyncChargeStatus()
        {
            chargebitEntities db = new chargebitEntities();

            try
            {
                List <Resrouce_interface> apis = (from api in db.Resrouce_interface where string.IsNullOrEmpty(api.CallBackUrl) && !string.IsNullOrEmpty(api.QueryStatusUrl) && api.Resource_id == 10 orderby api.CallBackUrl select api).ToList <Resrouce_interface>();
                foreach (Resrouce_interface api in apis)
                {
                    if (api.Synchronized == false && string.IsNullOrEmpty(api.CallBackUrl))
                    {
                        Logger.Info("Processing order status for resourceId:" + api.Resource_id);
                        IStatus chargeMgr = null;
                        object  o         = null;
                        o         = Assembly.Load(api.Interface_assemblyname).CreateInstance(api.Interface_classname);
                        chargeMgr = (IStatus)o;
                        chargeMgr.GetChargeStatus(api.Resource_id);
                        Logger.Info("Done!");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Beispiel #5
0
        public bool ChargeAgencyAccount(int agencyId, float amount)
        {
            bool ret = false;

            if (!CurrentLoginUser.Permission.UPDATE_USER)
            {
                throw new KMBitException("没有权限更新用户信息");
            }
            chargebitEntities db = null;

            try
            {
                db = new chargebitEntities();
                Users dbUser = (from u in db.Users where u.Id == agencyId && u.Enabled == true select u).FirstOrDefault <Users>();
                if (dbUser == null)
                {
                    throw new KMBitException(string.Format("编号为{0}的代理商不存在", agencyId));
                }

                Payment_history payment = new Payment_history()
                {
                    OperUserId     = CurrentLoginUser.User.Id,
                    Amount         = amount,
                    User_id        = agencyId,
                    Status         = 1,
                    PayType        = 2,
                    Pay_time       = 0,
                    ChargeOrderId  = 0,
                    CreatedTime    = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now),
                    PaymentAccount = "",
                    PaymentTradeId = "",
                    Tranfser_Type  = 0
                };

                db.Payment_history.Add(payment);
                db.SaveChanges();
                ret = true;
            }
            catch (KMBitException kex)
            {
                logger.Error(kex);
                throw kex;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw ex;
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
            return(ret);
        }
Beispiel #6
0
        public List <BActivityOrder> FindMarketingOrders(int agentId, int customerId, int activityId, int activityTaocanId, out int total, bool paging = false, int page = 1, int pagesize = 30)
        {
            total = 0;
            List <BActivityOrder> orders = new List <BActivityOrder>();

            agentId = agentId > 0 ? agentId : CurrentLoginUser.User.Id;
            chargebitEntities db = new chargebitEntities();

            try
            {
                var query = from o in db.Marketing_Orders
                            join t in db.Marketing_Activity_Taocan on o.ActivityTaocanId equals t.Id into lt
                            from llt in lt.DefaultIfEmpty()
                            join a in db.Marketing_Activities on o.ActivityId equals a.Id into lo
                            from llo in lo.DefaultIfEmpty()
                            join tc in db.Resource_taocan on llt.ResourceTaocanId equals tc.Id
                            join tcc in db.Taocan on tc.Taocan_id equals tcc.Id into ltcc
                            from lltcc in ltcc.DefaultIfEmpty()
                            select new BActivityOrder
                {
                    Order        = o,
                    ActivityName = llo != null?llo.Name:"",
                    TaocanName   = lltcc != null?lltcc.Name:""
                };

                if (activityId > 0)
                {
                    query = query.Where(o => o.Order.ActivityId == activityId);
                }
                if (activityTaocanId > 0)
                {
                    query = query.Where(o => o.Order.ActivityTaocanId == activityTaocanId);
                }

                query = query.OrderBy(o => o.Order.ActivityTaocanId);
                total = query.Count();
                if (paging)
                {
                    page     = page > 0 ? page : 1;
                    pagesize = pagesize > 0 ? pagesize : 30;
                    query    = query.Skip((page - 1) * pagesize).Take(pagesize);
                }

                orders = query.ToList <BActivityOrder>();
            }catch (Exception ex)
            {
                logger.Error(ex);
            }finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
            return(orders);
        }
Beispiel #7
0
        public ChargeResult ImportResourceProducts(int resourceId, int operate_user)
        {
            ChargeResult result = new ChargeResult()
            {
                Status = ChargeStatus.SUCCEED
            };
            ICharge           chargeMgr = null;
            chargebitEntities db        = new chargebitEntities();

            try
            {
                KMBit.DAL.Resource resource = (from ri in db.Resource
                                               where ri.Id == resourceId
                                               select ri).FirstOrDefault <Resource>();

                if (resource == null)
                {
                    throw new KMBitException(string.Format("编号为{0}的资源不存在", resourceId));
                }
                if (!resource.Enabled)
                {
                    throw new KMBitException(string.Format("编号为{0}的资源没有启用,请先启用在进行资源产品导入", resourceId));
                }

                KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == resourceId select ri).FirstOrDefault <Resrouce_interface>();
                if (rInterface == null)
                {
                    throw new KMBitException(string.Format("编号为{0}的资源没有配置资源接口,请先配置资源接口,并配置产品导入接口URL,然后进行资源产品导入", resourceId));
                }
                object   o        = null;
                Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                Type     type     = assembly.GetType(rInterface.Interface_classname);
                o = Activator.CreateInstance(type);
                if (o != null)
                {
                    chargeMgr = (ICharge)o;
                    chargeMgr.ImportProducts(resourceId, operate_user);
                }
            }
            catch (Exception ex)
            {
                result.Status  = ChargeStatus.FAILED;
                result.Message = ex.Message;
            }finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }

            return(result);
        }
Beispiel #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);
        }
Beispiel #9
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...");
        }
Beispiel #10
0
        public static void SendBackStatus()
        {
            chargebitEntities db = null;

            try
            {
                db = new chargebitEntities();
                List <Charge_Order> orders = (from o in db.Charge_Order where
                                              o.Received == false && o.PushedTimes < 4 &&
                                              !string.IsNullOrEmpty(o.CallBackUrl)
                                              select o).ToList <Charge_Order>();
                foreach (Charge_Order order in orders)
                {
                    Resource           resource    = (from r in resources where r.Id == order.Resource_id select r).FirstOrDefault <Resource>();
                    Resrouce_interface resourceAPI = null;
                    if (resource != null)
                    {
                        resourceAPI = (from api in resourceAPIs where api.Resource_id == order.Resource_id select api).FirstOrDefault <Resrouce_interface>();
                    }
                    if (resourceAPI == null)
                    {
                        continue;
                    }
                    if (resourceAPI.Synchronized == false && !string.IsNullOrEmpty(resourceAPI.CallBackUrl))
                    {
                        chargeSvr.SendStatusBackToAgentCallback(order);
                    }
                    else
                    {
                        order.Received = true;
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Fatal(ex);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Beispiel #11
0
        public void GetChargeStatus(int resourceId)
        {
            chargebitEntities db = new chargebitEntities();

            try
            {
                List <Charge_Order> orders = (from o in db.Charge_Order where o.Status == 1 select o).ToList <Charge_Order>();
                if (orders.Count <= 0)
                {
                    Logger.Info("No orders need to sync status of resourceId:" + resourceId);
                    return;
                }
                Logger.Info(string.Format("{0} orders need to sync status", orders.Count));
                KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == resourceId select ri).FirstOrDefault <Resrouce_interface>();
                ServerUri = new Uri(rInterface.APIURL);
                List <WebRequestParameters> parmeters = new List <WebRequestParameters>();
                parmeters.Add(new WebRequestParameters("V", version, false));
                parmeters.Add(new WebRequestParameters("Action", "getReports", false));
                SortedDictionary <string, string> paras = new SortedDictionary <string, string>();
                paras["Account"] = rInterface.Username;
                paras["Count"]   = statusCount.ToString();
                string signStr = "";
                foreach (KeyValuePair <string, string> p in paras)
                {
                    if (signStr == string.Empty)
                    {
                        signStr += p.Key.ToLower() + "=" + p.Value;
                    }
                    else
                    {
                        signStr += "&" + p.Key.ToLower() + "=" + p.Value;
                    }
                }
                signStr      += "&key=" + KMAes.DecryptStringAES(rInterface.Userpassword);
                paras["Sign"] = UrlSignUtil.GetMD5(signStr);

                foreach (KeyValuePair <string, string> p in paras)
                {
                    parmeters.Add(new WebRequestParameters(p.Key, p.Value, false));
                }
                bool succeed = false;
                SendRequest(parmeters, false, out succeed);
                if (succeed && !string.IsNullOrEmpty(Response))
                {
                    JObject jsonRes = JObject.Parse(Response);
                    string  code    = jsonRes["Code"] != null ? jsonRes["Code"].ToString() : "";
                    string  message = jsonRes["Message"] != null ? jsonRes["Message"].ToString() : "";
                    Logger.Info(string.Format("Code:{0}, Message:{1}", code, message));
                    if (!string.IsNullOrEmpty(code) && code == "0" && !string.IsNullOrEmpty(message) && message == "OK")
                    {
                        JArray charges = (JArray)jsonRes["Reports"];
                        if (charges != null)
                        {
                            Logger.Info(string.Format("Get {0} reports from resource", charges.Count));
                            for (int i = 0; i < charges.Count; i++)
                            {
                                JObject report  = (JObject)charges[i];
                                string  taskId  = report["TaskID"] != null? report["TaskID"].ToString():"";
                                string  phone   = report["Mobile"] != null? report["Mobile"].ToString():"";
                                string  status  = report["Status"] != null? report["Status"].ToString():"";
                                string  time    = report["ReportTime"] != null?report["ReportTime"].ToString():"";
                                string  rptCode = report["ReportCode"] != null? report["ReportCode"].ToString():"";
                                Logger.Info(string.Format("TaskId:{0}, MobilePhone:{1}, Status:{2}, Time:{3}", taskId, phone, status, time));
                                Charge_Order order = (from o in orders where o.Out_Order_Id == taskId && o.Phone_number == phone select o).FirstOrDefault <Charge_Order>();
                                if (order != null && !string.IsNullOrEmpty(taskId) && !string.IsNullOrEmpty(phone) && !string.IsNullOrEmpty(status))
                                {
                                    DateTime cTime = DateTime.MinValue;
                                    DateTime.TryParse(time, out cTime);
                                    if (cTime != DateTime.MinValue)
                                    {
                                        order.Completed_Time = DateTimeUtil.ConvertDateTimeToInt(cTime);
                                    }
                                    if (status == "4")
                                    {
                                        order.Status  = 2;
                                        order.Message = "充值成功:" + rptCode;
                                        RemoveQRCode(order);
                                    }
                                    else if (status == "5")
                                    {
                                        order.Status  = 3;
                                        order.Message = "充值失败:" + rptCode;
                                        if (order.Agent_Id > 0)
                                        {
                                            if (order.MarketOrderId <= 0)
                                            {
                                                Users agency = (from u in db.Users where u.Id == order.Agent_Id select u).FirstOrDefault <Users>();
                                                if (agency != null)
                                                {
                                                    agency.Remaining_amount += order.Purchase_price;
                                                    order.Refound            = true;
                                                }
                                            }
                                            else
                                            {
                                                order.Message = string.Format("充值失败:{0},二维码可以重复扫码使用直到充值成功", rptCode);
                                                order.Refound = false;
                                                Marketing_Orders mOrder = (from mo in db.Marketing_Orders where mo.Id == order.MarketOrderId select mo).FirstOrDefault <Marketing_Orders>();
                                                if (mOrder != null)
                                                {
                                                    mOrder.Used = false;
                                                }
                                            }

                                            db.SaveChanges();
                                        }
                                    }
                                }

                                //send back status to agent api calling
                                if (!string.IsNullOrEmpty(order.CallBackUrl))
                                {
                                    this.SendStatusBackToAgentCallback(order);
                                }
                            }
                            if (charges != null && charges.Count > 0)
                            {
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }
            catch (KMBitException kex)
            {
                Logger.Warn(kex);
            }catch (Exception ex)
            {
                Logger.Fatal(ex);
            }finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Beispiel #12
0
        public void GetChargeStatus(int resourceId)
        {
            Logger.Info("GetChargeStatus...");
            chargebitEntities db = null;

            try
            {
                List <Charge_Order> orders = null;
                lock (getStatusObj)
                {
                    db     = new chargebitEntities();
                    orders = (from o in db.Charge_Order where o.Status == 1 && o.Resource_id == resourceId && o.Payed && o.Id > lastMaxGetStatusOrderId orderby o.Id ascending select o).ToList <Charge_Order>();
                    if (orders.Count <= 0)
                    {
                        Logger.Info("No orders need to sync status of resourceId:" + resourceId);
                        return;
                    }
                    else
                    {
                        lastMaxGetStatusOrderId = (from o in orders select o.Id).Max();
                        Logger.Info(string.Format("{0} orders need to sync status", orders.Count));
                    }
                }

                KMBit.DAL.Resrouce_interface rInterface = rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == resourceId select ri).FirstOrDefault <Resrouce_interface>();
                if (string.IsNullOrEmpty(rInterface.QueryStatusUrl))
                {
                    Logger.Warn("QueryStatusUrl is empty.");
                    return;
                }
                ServerUri = new Uri(rInterface.QueryStatusUrl);
                if (string.IsNullOrEmpty(token))
                {
                    GetToken(rInterface);
                }
                if (DateTimeUtil.ConvertDateTimeToInt(DateTime.Now) > expiredTime)
                {
                    Logger.Info("Token expired, get it again.");
                    GetToken(rInterface);
                }

                if (string.IsNullOrEmpty(token))
                {
                    Logger.Error("Cannot get token.");
                    return;
                }

                List <WebRequestParameters> parmeters = new List <WebRequestParameters>();
                StringBuilder orderIds = new StringBuilder();
                foreach (Charge_Order o in orders)
                {
                    if (!string.IsNullOrEmpty(o.Out_Order_Id))
                    {
                        orderIds.Append(o.Out_Order_Id + ",");
                    }
                }
                string orderParamStr = orderIds.ToString();
                orderParamStr = orderParamStr.Substring(0, orderParamStr.Length - 1);
                parmeters.Add(new WebRequestParameters()
                {
                    Name = "para", Value = "{\"orderId\":\"" + orderParamStr + "\"}"
                });
                parmeters.Add(new WebRequestParameters()
                {
                    Name = "token", Value = token
                });
                parmeters.Add(new WebRequestParameters()
                {
                    Name = "id", Value = rInterface.Username.Trim()
                });
                bool succeed = false;
                SendRequest(parmeters, false, out succeed, RequestType.POST);
                ChargeResult result = new ChargeResult();
                if (!string.IsNullOrEmpty(Response))
                {
                    try
                    {
                        Newtonsoft.Json.Linq.JObject jsonResult = Newtonsoft.Json.Linq.JObject.Parse(Response);
                        string ret     = jsonResult["result"].ToString();
                        string message = jsonResult["resultMsg"].ToString();
                        Logger.Info(string.Format("Message:{0} returned by {1}" + message != null?message:"", rInterface.QueryStatusUrl));
                        if (!string.IsNullOrEmpty(ret) && ret.Trim() == "0")
                        {
                            if (jsonResult["orderResult"] != null)
                            {
                                Newtonsoft.Json.Linq.JArray backOrders = JArray.Parse(jsonResult["orderResult"].ToString());
                                if (backOrders != null && backOrders.Count > 0)
                                {
                                    foreach (JObject ro in backOrders)
                                    {
                                        string roId      = ro["orderId"] != null? ro["orderId"].ToString():null;
                                        string roPhone   = ro["accNumber"] != null ? ro["accNumber"].ToString() : null;
                                        string roResult  = ro["orderResult"] != null ? ro["orderResult"].ToString() : null;
                                        string roMessage = ro["orderMsg"] != null ? ro["orderMsg"].ToString() : null;
                                        if (string.IsNullOrEmpty(roId) || string.IsNullOrEmpty(roPhone))
                                        {
                                            continue;
                                        }

                                        Charge_Order dbOrder = (from o in orders where o.Out_Order_Id == roId.Trim() && o.Phone_number == roPhone.Trim() select o).FirstOrDefault <Charge_Order>();
                                        if (dbOrder != null)
                                        {
                                            if (!string.IsNullOrEmpty(roResult) && roResult.Trim() == "0")
                                            {
                                                result.Status  = ChargeStatus.SUCCEED;
                                                result.Message = roMessage != null ? roMessage : "充值成功";
                                            }
                                            else
                                            {
                                                result.Status  = ChargeStatus.FAILED;
                                                result.Message = roMessage != null ? roMessage : "充值失败";
                                            }
                                        }
                                        ChargeOrder blOrder = new ChargeOrder()
                                        {
                                            Id = dbOrder.Id, OutOrderId = dbOrder.Out_Order_Id, AgencyId = dbOrder.Agent_Id, Status = dbOrder.Status
                                        };
                                        ChangeOrderStatus(blOrder, result, true);
                                    }
                                }
                            }
                        }
                        else
                        {
                            Logger.Info(string.Format("No order status returned back by {0}", rInterface.QueryStatusUrl));
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Fatal(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception was thrown");
                Logger.Fatal(ex);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }

            Logger.Info("GetChargeStatus done!");
        }
Beispiel #13
0
        public ChargeResult Charge(ChargeOrder order)
        {
            ChargeResult      result    = null;
            ICharge           chargeMgr = null;
            chargebitEntities db        = null;
            Charge_Order      cOrder    = null;

            try
            {
                db     = new chargebitEntities();
                cOrder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault <Charge_Order>();
                List <LaJi> las = (from laji in db.LaJi where laji.PId == 3 select laji).ToList <LaJi>();
                if (las.Count == 0)
                {
                    result = new ChargeResult()
                    {
                        Status = ChargeStatus.FAILED, Message = "系统已经被停用,请联系统管理员"
                    };
                    Logger.Warn(result.Message);
                    return(result);
                }
                if (las.Count > 1)
                {
                    result = new ChargeResult()
                    {
                        Status = ChargeStatus.FAILED, Message = "系统设置有错误,请联系统管理员"
                    };
                    Logger.Warn(result.Message);
                    return(result);
                }
                LaJi la = las[0];
                if (!la.UP)
                {
                    result = new ChargeResult()
                    {
                        Status = ChargeStatus.FAILED, Message = "系统已经被停用,请联系统管理员"
                    };
                    Logger.Warn(result.Message);
                    return(result);
                }
                if (cOrder == null)
                {
                    result = new ChargeResult()
                    {
                        Status = ChargeStatus.FAILED, Message = ChargeConstant.ORDER_NOT_EXIST
                    };
                    return(result);
                }
                Resource_taocan taocan = (from tc in db.Resource_taocan where tc.Id == order.ResourceTaocanId select tc).FirstOrDefault <Resource_taocan>();
                if (!taocan.Enabled)
                {
                    result = new ChargeResult()
                    {
                        Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_TAOCAN_DISABLED
                    };
                    return(result);
                }

                KMBit.DAL.Resource resource = (from ri in db.Resource
                                               join tr in db.Resource_taocan on ri.Id equals tr.Resource_id
                                               where tr.Id == order.ResourceTaocanId
                                               select ri).FirstOrDefault <Resource>();

                if (resource == null)
                {
                    db.Charge_Order.Remove(cOrder);
                    db.SaveChanges();
                    result = new ChargeResult()
                    {
                        Status = ChargeStatus.FAILED, Message = "落地资源部存在,请联系平台管理员"
                    };
                    return(result);
                }
                if (!resource.Enabled)
                {
                    db.Charge_Order.Remove(cOrder);
                    db.SaveChanges();
                    result = new ChargeResult()
                    {
                        Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_DISABLED
                    };
                    return(result);
                }
                if (order.ResourceId == 0)
                {
                    order.ResourceId = resource.Id;
                }
                KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault <Resrouce_interface>();
                if (rInterface == null)
                {
                    db.Charge_Order.Remove(cOrder);
                    db.SaveChanges();
                    result = new ChargeResult()
                    {
                        Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_INTERFACE_NOT_CONFIGURED
                    };
                    return(result);
                }
                object o = Assembly.Load(rInterface.Interface_assemblyname).CreateInstance(rInterface.Interface_classname);
                chargeMgr = (ICharge)o;
                result    = chargeMgr.Charge(order);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                if (cOrder != null)
                {
                    db.Charge_Order.Remove(cOrder);
                    db.SaveChanges();
                }
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }

            return(result);
        }
Beispiel #14
0
        public List <BResource> FindResources(int resourceId, string resourceName, int spId, out int total, int page = 1, int pageSize = 20, bool paging = false)
        {
            total = 0;
            List <BResource> resources = null;
            int skip             = (page - 1) * pageSize;
            chargebitEntities db = new chargebitEntities();

            try
            {
                var tmp = from s in db.Resource
                          join sp in db.Sp on s.SP_Id equals sp.Id into lsp
                          from llsp in lsp.DefaultIfEmpty()
                          join pa in db.Area on s.Province_Id equals pa.Id into lpa
                          from llpa in lpa.DefaultIfEmpty()
                          join ca in db.Area on s.City_Id equals ca.Id into lca
                          from llca in lca.DefaultIfEmpty()
                          join cu in db.Users on s.CreatedBy equals cu.Id into lcu
                          from llcu in lcu.DefaultIfEmpty()
                          join uu in db.Users on s.UpdatedBy equals uu.Id into luu
                          from lluu in luu.DefaultIfEmpty()
                          select new BResource
                {
                    Resource  = s,
                    City      = llca,
                    Province  = llpa,
                    SP        = llsp,
                    CreatedBy = llcu,
                    UpdatedBy = lluu
                };
                if (spId > 0)
                {
                    tmp = tmp.Where(s => s.Resource.SP_Id == spId);
                }
                if (resourceId > 0)
                {
                    tmp = tmp.Where(s => s.Resource.Id == resourceId);
                }
                if (!string.IsNullOrEmpty(resourceName))
                {
                    tmp = tmp.Where(s => s.Resource.Name.Contains(resourceName));
                }

                total = tmp.Count();
                if (paging)
                {
                    tmp = tmp.OrderBy(s => s.Resource.Created_time).Skip(skip).Take(pageSize);
                }

                resources = tmp.ToList <BResource>();
            }catch (Exception ex)
            {
            }finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }

            return(resources);
        }
Beispiel #15
0
        public ChargeResult Charge(ChargeOrder order)
        {
            Logger.Info("Charging...");
            ChargeResult result = new ChargeResult()
            {
                Status = ChargeStatus.FAILED
            };
            chargebitEntities db = null;

            ProceedOrder(order, out result);
            if (result.Status == ChargeStatus.FAILED)
            {
                return(result);
            }

            List <WebRequestParameters> parmeters = new List <WebRequestParameters>();
            bool succeed = false;

            try
            {
                db = new chargebitEntities();
                Charge_Order corder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault <Charge_Order>();
                corder.Process_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
                KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault <Resrouce_interface>();
                Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == order.ResourceTaocanId select t).FirstOrDefault <Resource_taocan>();

                if (string.IsNullOrEmpty(rInterface.APIURL))
                {
                    result.Status  = ChargeStatus.FAILED;
                    result.Message = "资源充值API URL没有配置";
                    Logger.Error("Cannot get token.");
                    ChangeOrderStatus(order, result);
                    return(result);
                }
                ServerUri = new Uri(rInterface.APIURL);
                if (string.IsNullOrEmpty(token))
                {
                    Logger.Info("Token doesn't exist, try to request one.");
                    GetToken(rInterface);
                }
                else
                {
                    Logger.Info("Token is already existed.");
                }
                if (DateTimeUtil.ConvertDateTimeToInt(DateTime.Now) > expiredTime)
                {
                    Logger.Info("Existing token is already expired, try to request a new one.");
                    GetToken(rInterface);
                }

                if (string.IsNullOrEmpty(token))
                {
                    result.Status  = ChargeStatus.FAILED;
                    result.Message = "获取令牌失败";
                    Logger.Error("Failed to request token, please contact gatway administrator. The charge order will be marked as fail, refound the currency to agent.");
                    ChangeOrderStatus(order, result);
                    return(result);
                }
                StringBuilder jsonParam = new StringBuilder();
                corder.Out_Order_Id = rInterface.Username + DateTimeUtil.ConvertDateTimeToInt(DateTime.Now).ToString("0");
                order.OutOrderId    = corder.Out_Order_Id;
                db.SaveChanges();
                jsonParam.Append("[");
                jsonParam.Append("{");
                jsonParam.Append("\"orderId\":");
                jsonParam.Append("\"" + corder.Out_Order_Id.Trim() + "\",");
                jsonParam.Append("\"accNumber\":");
                jsonParam.Append("\"" + corder.Phone_number.Trim() + "\",");
                jsonParam.Append("\"pricePlanCd\":");
                jsonParam.Append("\"" + taocan.Serial.Trim() + "\",");
                jsonParam.Append("\"orderType\":");
                jsonParam.Append("\"0\"");
                jsonParam.Append("}");
                jsonParam.Append("]");
                parmeters.Add(new WebRequestParameters()
                {
                    Name = "para", Value = jsonParam.ToString()
                });
                parmeters.Add(new WebRequestParameters()
                {
                    Name = "token", Value = token
                });
                parmeters.Add(new WebRequestParameters()
                {
                    Name = "id", Value = rInterface.Username.Trim()
                });
                SendRequest(parmeters, false, out succeed, RequestType.POST);

                if (!string.IsNullOrEmpty(Response))
                {
                    try
                    {
                        Newtonsoft.Json.Linq.JObject jsonResult = Newtonsoft.Json.Linq.JObject.Parse(Response);
                        string ret     = jsonResult["result"].ToString();
                        string message = jsonResult["resultMsg"].ToString();
                        if (!string.IsNullOrEmpty(ret) && ret.Trim() == "0")
                        {
                            result.Status = ChargeStatus.ONPROGRESS;
                        }
                        else
                        {
                            result.Status = ChargeStatus.FAILED;
                        }
                        result.Message = message;
                    }
                    catch (Exception ex)
                    {
                        Logger.Fatal(ex);
                        result.Status  = ChargeStatus.FAILED;
                        result.Message = "系统错误,请联系管理员";
                    }

                    if (result.Message != null && result.Message.Length > 5000)
                    {
                        result.Message = result.Message.Substring(0, 5000);
                    }
                    ChangeOrderStatus(order, result);
                }
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
            Logger.Info("Charging done!");
            return(result);
        }
Beispiel #16
0
        public ChargeResult Charge(ChargeOrder order)
        {
            ChargeResult      result    = null;
            ICharge           chargeMgr = null;
            chargebitEntities db        = null;
            Charge_Order      cOrder    = null;

            try
            {
                db     = new chargebitEntities();
                cOrder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault <Charge_Order>();
                if (cOrder == null)
                {
                    result = new ChargeResult()
                    {
                        Status = ChargeStatus.FAILED, Message = ChargeConstant.ORDER_NOT_EXIST
                    };
                    return(result);
                }
                Resource_taocan taocan = (from tc in db.Resource_taocan where tc.Id == order.ResourceTaocanId select tc).FirstOrDefault <Resource_taocan>();
                if (!taocan.Enabled)
                {
                    result = new ChargeResult()
                    {
                        Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_TAOCAN_DISABLED
                    };
                    return(result);
                }

                KMBit.DAL.Resource resource = (from ri in db.Resource
                                               join tr in db.Resource_taocan on ri.Id equals tr.Resource_id
                                               where tr.Id == order.ResourceTaocanId
                                               select ri).FirstOrDefault <Resource>();

                if (resource == null)
                {
                    db.Charge_Order.Remove(cOrder);
                    db.SaveChanges();
                    result = new ChargeResult()
                    {
                        Status = ChargeStatus.FAILED, Message = "落地资源部存在,请联系平台管理员"
                    };
                    return(result);
                }
                if (!resource.Enabled)
                {
                    db.Charge_Order.Remove(cOrder);
                    db.SaveChanges();
                    result = new ChargeResult()
                    {
                        Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_DISABLED
                    };
                    return(result);
                }
                if (order.ResourceId == 0)
                {
                    order.ResourceId = resource.Id;
                }
                KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault <Resrouce_interface>();
                if (rInterface == null)
                {
                    db.Charge_Order.Remove(cOrder);
                    db.SaveChanges();
                    result = new ChargeResult()
                    {
                        Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_INTERFACE_NOT_CONFIGURED
                    };
                    return(result);
                }
                object   o        = null;
                Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                Type     type     = assembly.GetType(rInterface.Interface_classname);
                o         = Activator.CreateInstance(type);
                chargeMgr = (ICharge)o;
                result    = chargeMgr.Charge(order);
            }
            catch (Exception ex)
            {
                if (cOrder != null)
                {
                    db.Charge_Order.Remove(cOrder);
                    db.SaveChanges();
                }
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }

            return(result);
        }
Beispiel #17
0
        protected void SendStatusBackToAgentCallback(Charge_Order order)
        {
            Logger.Info("SendStatusBackToAgentCallback");
            if (order == null || order.Agent_Id <= 0 || string.IsNullOrEmpty(order.CallBackUrl))
            {
                return;
            }
            Logger.Info(string.Format("Order Id {0}", order.Id.ToString()));
            Logger.Info(string.Format("Order Status {0}", order.Status.ToString()));
            Logger.Info(string.Format("Order Message {0}", order.Message != null?order.Message:""));
            chargebitEntities db = new chargebitEntities();

            try
            {
                List <WebRequestParameters>       parmeters = new List <WebRequestParameters>();
                SortedDictionary <string, string> paras     = new SortedDictionary <string, string>();
                string orderId = order.Id.ToString();
                string status  = order.Status.ToString();
                string message = order.Message != null ? order.Message : "";
                Users  agent   = (from u in db.Users where u.Id == order.Agent_Id select u).FirstOrDefault <Users>();
                Logger.Info(string.Format("Agent {0}", agent.Email));
                if (agent == null)
                {
                    status  = "3";
                    message = "代理商账户没有找到";
                }
                string token = agent.SecurityStamp;
                paras["OrderId"] = orderId;
                paras["Status"]  = status;
                paras["Message"] = message;
                string signStr = "";
                foreach (KeyValuePair <string, string> p in paras)
                {
                    if (signStr == string.Empty)
                    {
                        signStr += p.Key.ToLower() + "=" + p.Value;
                    }
                    else
                    {
                        signStr += "&" + p.Key.ToLower() + "=" + p.Value;
                    }
                }
                signStr += "&key=" + token;
                Logger.Info(string.Format("Sign String {0}", signStr));
                Logger.Info(string.Format("Signature {0}", UrlSignUtil.GetMD5(signStr)));
                paras["Signature"] = UrlSignUtil.GetMD5(signStr);
                foreach (KeyValuePair <string, string> p in paras)
                {
                    parmeters.Add(new WebRequestParameters(p.Key, p.Value, false));
                }
                ServerUri = new Uri(order.CallBackUrl);
                bool succeed = false;
                SendRequest(parmeters, false, out succeed);
                if (succeed)
                {
                    Logger.Info("Successfully sent back status to anegt callback API");
                }
                else
                {
                    Logger.Info("Failed sent back status to anegt callback API");
                }
            }
            catch (Exception ex)
            {
            }finally
            {
                if (db != null)
                {
                    db.Dispose();
                }

                Logger.Info("Leaving SendStatusBackToAgentCallback");
            }
        }
Beispiel #18
0
        public static void ProcessAgentAccountChargePayments()
        {
            ILog Logger = log4net.LogManager.GetLogger(typeof(ChargeService));

            lock (o)
            {
                Logger.Info("ProcessAgentAccountChargePayments...");
                chargebitEntities db = null;
                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));
                                Logger.Info("Sync agent remaining amount..");
                                List <Payment_history> handledPays = (from p in db.Payment_history where p.User_id == user.Id && p.ChargeOrderId == 0 && p.PayType != 0 && p.Status == 2 select p).ToList <Payment_history>();
                                int ordersCount = (from o in db.Charge_Order where o.Agent_Id == user.Id && (o.Status == 10 || o.Status == 2) select o.Id).Count();
                                if (handledPays.Count > 0 && ordersCount > 0)
                                {
                                    float totalPaymentsAmount = (from p in handledPays select p.Amount).Sum();
                                    float totalChargeAmount   = (from o in db.Charge_Order where o.Agent_Id == user.Id && (o.Status == 10 || o.Status == 2) select o.Purchase_price).Sum();
                                    Logger.Info("Total handled payments amount:" + totalPaymentsAmount.ToString("0.00"));
                                    Logger.Info("Total used amount:" + totalChargeAmount.ToString("0.00"));
                                    if ((user.Remaining_amount + totalChargeAmount) != totalPaymentsAmount)
                                    {
                                        user.Remaining_amount = totalPaymentsAmount - totalChargeAmount;
                                        db.SaveChanges();
                                        Logger.Info("Agent remaining amount has been successfully synced.");
                                    }
                                    else
                                    {
                                        Logger.Info("No need to sync.");
                                    }
                                }
                                Logger.Info("Payment:" + payment.Amount.ToString() + " has been handled.");
                                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...");
            }
        }
Beispiel #19
0
        public ChargeResult MarketingCharge(BMarketOrderCharge orderCharge)
        {
            logger.Info("MarketingCharge");
            ChargeResult result = new ChargeResult();

            if (orderCharge == null)
            {
                result.Status  = ChargeStatus.FAILED;
                result.Message = "参数不正确";
                return(result);
            }
            if (orderCharge.AgentId == 0 || orderCharge.CustomerId == 0 || orderCharge.ActivityId == 0)
            {
                result.Status  = ChargeStatus.FAILED;
                result.Message = "参数不正确";
                return(result);
            }
            if (string.IsNullOrEmpty(orderCharge.SPName))
            {
                result.Status  = ChargeStatus.FAILED;
                result.Message = "参数不正确";
                return(result);
            }
            if (string.IsNullOrEmpty(orderCharge.Phone))
            {
                result.Status  = ChargeStatus.FAILED;
                result.Message = "参数不正确";
                return(result);
            }
            int sp = 0;

            if (orderCharge.SPName.Contains("联通"))
            {
                sp = 3;
            }
            else if (orderCharge.SPName.Contains("移动"))
            {
                sp = 1;
            }
            else if (orderCharge.SPName.Contains("电信"))
            {
                sp = 2;
            }
            chargebitEntities         db      = new chargebitEntities();
            Marketing_Activity_Taocan mtaocan = null;
            Marketing_Orders          mOrder  = null;

            try
            {
                Marketing_Activities activity = (from a in db.Marketing_Activities where a.Id == orderCharge.ActivityId select a).FirstOrDefault <Marketing_Activities>();
                if (activity == null)
                {
                    result.Status  = ChargeStatus.FAILED;
                    result.Message = "参数不正确";
                    return(result);
                }
                if (activity.CustomerId != orderCharge.CustomerId)
                {
                    result.Status  = ChargeStatus.FAILED;
                    result.Message = "参数不正确";
                    return(result);
                }
                if (activity.AgentId != orderCharge.AgentId)
                {
                    result.Status  = ChargeStatus.FAILED;
                    result.Message = "参数不正确";
                    return(result);
                }
                //非直接扫码活动,必须传入特定的marketing order id
                if (activity.ScanType != 1 && orderCharge.ActivityOrderId == 0)
                {
                    result.Status  = ChargeStatus.FAILED;
                    result.Message = "参数不正确";
                    return(result);
                }
                ChargeOrder order = new ChargeOrder()
                {
                    AgencyId     = orderCharge.AgentId,
                    ChargeType   = 1,
                    City         = orderCharge.City,
                    CreatedTime  = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now),
                    IsMarket     = true,
                    MacAddress   = orderCharge.OpenId,
                    MobileNumber = orderCharge.Phone,
                    MobileSP     = orderCharge.SPName,
                    Payed        = true,
                    Province     = orderCharge.Province,
                };

                //direct scan
                if (activity.ScanType == 1 && orderCharge.ActivityOrderId <= 0)
                {
                    //判断是否还有可用marketing order

                    List <Marketing_Activity_Taocan> rTaocans = (from mt in db.Marketing_Activity_Taocan
                                                                 join t in db.Resource_taocan on mt.ResourceTaocanId equals t.Id
                                                                 where mt.ActivityId == orderCharge.ActivityId && t.Sp_id == sp
                                                                 select mt).ToList <Marketing_Activity_Taocan>();

                    if (rTaocans.Count == 0)
                    {
                        result.Status  = ChargeStatus.FAILED;
                        result.Message = "本次活动" + orderCharge.SPName + "不能扫码充值";
                        return(result);
                    }

                    mtaocan = rTaocans[0];
                    mOrder  = (from o in db.Marketing_Orders where o.ActivityId == orderCharge.ActivityId && o.Sent == false && o.Used == false && o.ActivityTaocanId == mtaocan.Id select o).FirstOrDefault <Marketing_Orders>();
                    if (mOrder == null)
                    {
                        result.Status  = ChargeStatus.FAILED;
                        result.Message = "本次活动的流量充值额度已经全部被扫完,尽请期待下次活动";
                        return(result);
                    }
                    if (mOrder.Used)
                    {
                        result.Status  = ChargeStatus.FAILED;
                        result.Message = "本次活动的流量充值额度已经全部被扫完,尽请期待下次活动";
                        return(result);
                    }
                    mOrder.Used = true;
                    mOrder.Sent = true;
                    //db.SaveChanges();
                    order.MarketOrderId    = mOrder.Id;
                    order.ResourceTaocanId = mtaocan.ResourceTaocanId;
                }//weichat push
                else if (activity.ScanType == 2 && orderCharge.ActivityOrderId > 0)
                {
                    mOrder = (from o in db.Marketing_Orders where o.Id == orderCharge.ActivityOrderId select o).FirstOrDefault <Marketing_Orders>();
                    if (mOrder == null)
                    {
                        result.Status  = ChargeStatus.FAILED;
                        result.Message = "参数有误";
                        return(result);
                    }
                    if (mOrder.Used)
                    {
                        result.Status  = ChargeStatus.FAILED;
                        result.Message = "本次活动的流量充值额度已经全部被扫完,尽请期待下次活动";
                        return(result);
                    }
                    mtaocan = (from mt in db.Marketing_Activity_Taocan where mt.Id == mOrder.ActivityTaocanId select mt).FirstOrDefault <Marketing_Activity_Taocan>();
                    if (mtaocan == null)
                    {
                        result.Status  = ChargeStatus.FAILED;
                        result.Message = "参数有误";
                        return(result);
                    }
                    Resource_taocan rT = (from r in db.Resource_taocan where r.Id == mtaocan.ResourceTaocanId select r).FirstOrDefault <Resource_taocan>();
                    if (rT == null)
                    {
                        result.Status  = ChargeStatus.FAILED;
                        result.Message = "参数有误";
                        return(result);
                    }
                    if (rT.Sp_id != sp)
                    {
                        string tmpSPName = "";
                        if (rT.Sp_id == 1)
                        {
                            tmpSPName = "中国移动";
                        }
                        else if (rT.Sp_id == 2)
                        {
                            tmpSPName = "中国电信";
                        }
                        else if (rT.Sp_id == 3)
                        {
                            tmpSPName = "中国联通";
                        }
                        result.Status  = ChargeStatus.FAILED;
                        result.Message = string.Format("此二维码链接不能充值{0}的手机号码的流量,只能充值{1}的号码的流量", orderCharge.SPName, tmpSPName);
                        return(result);
                    }
                    order.ResourceTaocanId = mtaocan.ResourceTaocanId;
                    order.MarketOrderId    = orderCharge.ActivityOrderId;
                    mOrder.Used            = true;
                    mOrder.Sent            = true;
                }
                else if (activity.ScanType == 1 && orderCharge.ActivityOrderId > 0)
                {
                    result.Status  = ChargeStatus.FAILED;
                    result.Message = "参数有误";
                    return(result);
                }
                else if (activity.ScanType == 2 && orderCharge.ActivityOrderId <= 0)
                {
                    result.Status  = ChargeStatus.FAILED;
                    result.Message = "参数有误";
                    return(result);
                }

                OrderManagement orderMgr = new OrderManagement(CurrentLoginUser);
                order = orderMgr.GenerateOrder(order);
                ChargeBridge chargeBridge = new ChargeBridge();
                if (order.Id > 0)
                {
                    db.SaveChanges();
                    result = chargeBridge.Charge(order);
                    if (result.Status == ChargeStatus.FAILED)
                    {
                        //Rollback, the order cannot be used next time
                        mOrder.UsedTime = 0;
                        mOrder.Used     = false;
                        if (activity.ScanType == 1)
                        {
                            mOrder.Sent = false;
                        }

                        db.SaveChanges();
                    }
                    else
                    {
                        mOrder.UsedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
                    }
                    db.SaveChanges();
                }
            }
            catch (KMBitException kex)
            {
                logger.Warn(kex);
                result.Status  = ChargeStatus.FAILED;
                result.Message = kex.Message;
                if (mOrder != null)
                {
                    mOrder.Used = false;
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                logger.Fatal(ex);
                result.Status  = ChargeStatus.FAILED;
                result.Message = "系统错误,稍后再试";
                if (mOrder != null)
                {
                    mOrder.Used = false;
                    db.SaveChanges();
                }
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
            logger.Info("Finished MarketingCharge");
            return(result);
        }
Beispiel #20
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);
        }
Beispiel #21
0
        public void ImportProducts(int resourceId, int operate_user)
        {
            chargebitEntities db = null;

            try
            {
                bool succeed = false;
                List <WebRequestParameters> parmeters = new List <WebRequestParameters>();
                parmeters.Add(new WebRequestParameters("V", version, false));
                parmeters.Add(new WebRequestParameters("Action", "getPackage", false));
                db = new chargebitEntities();
                db.Configuration.AutoDetectChangesEnabled = false;
                KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == resourceId select ri).FirstOrDefault <Resrouce_interface>();
                ServerUri = new Uri(rInterface.ProductApiUrl);
                SortedDictionary <string, string> paras = new SortedDictionary <string, string>();
                paras["Account"] = rInterface.Username;
                paras["Type"]    = "0";
                string signStr = "";
                foreach (KeyValuePair <string, string> p in paras)
                {
                    if (signStr == string.Empty)
                    {
                        signStr += p.Key.ToLower() + "=" + p.Value;
                    }
                    else
                    {
                        signStr += "&" + p.Key.ToLower() + "=" + p.Value;
                    }
                }
                signStr      += "&key=" + KMAes.DecryptStringAES(rInterface.Userpassword);
                paras["Sign"] = UrlSignUtil.GetMD5(signStr);
                foreach (KeyValuePair <string, string> p in paras)
                {
                    parmeters.Add(new WebRequestParameters(p.Key, p.Value, false));
                }

                SendRequest(parmeters, false, out succeed);
                if (succeed)
                {
                    if (!string.IsNullOrEmpty(Response))
                    {
                        JObject json    = JObject.Parse(Response);
                        string  code    = json["Code"] != null? json["Code"].ToString():"";
                        string  message = json["Message"] != null ? json["Message"].ToString() : "";
                        if (!string.IsNullOrEmpty(code) && code == "0" && !string.IsNullOrEmpty(message) && message == "OK")
                        {
                            JArray packages = (JArray)json["Packages"];
                            if (packages != null)
                            {
                                for (int i = 0; i < packages.Count; i++)
                                {
                                    JObject package = (JObject)packages[i];

                                    if (package != null)
                                    {
                                        Resource_taocan taocan = null;
                                        int             sp     = 0;
                                        int             spId   = 0;
                                        int.TryParse(package["Type"].ToString(), out sp);
                                        int quantity = 0;
                                        int.TryParse(package["Package"].ToString(), out quantity);
                                        float price = 0;
                                        float.TryParse(package["Price"].ToString(), out price);

                                        if (sp == 2)
                                        {
                                            spId = 3;
                                        }
                                        else if (sp == 1)
                                        {
                                            spId = 1;
                                        }
                                        else if (sp == 3)
                                        {
                                            spId = 2;
                                        }

                                        taocan = (from t in db.Resource_taocan where t.Resource_id == rInterface.Resource_id && t.Quantity == quantity && t.Sp_id == spId select t).FirstOrDefault <Resource_taocan>();
                                        if (taocan != null)
                                        {
                                            taocan.Purchase_price = price;
                                            taocan.UpdatedBy      = operate_user;
                                            taocan.Updated_time   = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
                                            db.SaveChanges();
                                        }
                                        else
                                        {
                                            taocan = new Resource_taocan()
                                            {
                                                Area_id           = 0,
                                                CreatedBy         = operate_user,
                                                Created_time      = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now),
                                                Enabled           = false,
                                                EnableDiscount    = true,
                                                Purchase_price    = price,
                                                Quantity          = quantity,
                                                Resource_id       = rInterface.Resource_id,
                                                Sale_price        = price,
                                                Serial            = "",
                                                Sp_id             = spId,
                                                Taocan_id         = 0,
                                                Resource_Discount = 1
                                            };

                                            Taocan ntaocan = (from t in db.Taocan where t.Sp_id == taocan.Sp_id && t.Quantity == taocan.Quantity select t).FirstOrDefault <Taocan>();
                                            Sp     spO     = (from s in db.Sp where s.Id == taocan.Sp_id select s).FirstOrDefault <Sp>();
                                            if (ntaocan == null)
                                            {
                                                string taocanName = spO != null ? spO.Name + " " + taocan.Quantity.ToString() + "M" : "全网 " + taocan.Quantity.ToString() + "M";
                                                ntaocan = new Taocan()
                                                {
                                                    Created_time = taocan.Created_time, Description = taocanName, Name = taocanName, Sp_id = taocan.Sp_id, Quantity = taocan.Quantity, Updated_time = 0
                                                };
                                                db.Taocan.Add(ntaocan);
                                                db.SaveChanges();
                                            }
                                            if (ntaocan.Id > 0)
                                            {
                                                taocan.Taocan_id = ntaocan.Id;
                                                db.Resource_taocan.Add(taocan);
                                            }
                                        }
                                    }
                                }
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Beispiel #22
0
        public void SendStatusBackToAgentCallback(object oorder)
        {
            if (oorder.GetType() != typeof(Charge_Order))
            {
                return;
            }
            Charge_Order order = oorder as Charge_Order;

            Logger.Info("SendStatusBackToAgentCallback...");
            if (order == null || order.Agent_Id <= 0 || string.IsNullOrEmpty(order.CallBackUrl))
            {
                Logger.Info("Not an agent order, no need to proceed anymore.");
                return;
            }
            Logger.Info(string.Format("Order Id {0}", order.Id.ToString()));
            if (!string.IsNullOrEmpty(order.Client_Order_Id))
            {
                Logger.Info(string.Format("Client OrderId {0}", order.Client_Order_Id.ToString()));
            }
            if (!string.IsNullOrEmpty(order.Out_Order_Id))
            {
                Logger.Info(string.Format("Out Order Id {0}", order.Out_Order_Id.ToString()));
            }
            Logger.Info(string.Format("Order Status {0}", order.Status.ToString()));
            Logger.Info(string.Format("Order Message {0}", order.Message != null?order.Message:""));
            chargebitEntities db = null;

            try
            {
                if (string.IsNullOrEmpty(order.CallBackUrl))
                {
                    Logger.Info("Order callback URL is empty, no need to callback.");
                    return;
                }
                db = new chargebitEntities();
                NameValueCollection col = new NameValueCollection();
                SortedDictionary <string, string> paras = new SortedDictionary <string, string>();
                string orderId = order.Id.ToString();
                string status  = order.Status.ToString();
                string message = order.Message != null ? order.Message : "";
                Users  agent   = (from u in db.Users where u.Id == order.Agent_Id select u).FirstOrDefault <Users>();
                Logger.Info(string.Format("Agent {0}", agent.Email));
                if (agent == null)
                {
                    status  = "3";
                    message = "代理商账户没有找到";
                }
                string token = agent.SecurityStamp;
                paras["OrderId"]       = orderId;
                paras["Status"]        = status;
                paras["ClientOrderId"] = order.Client_Order_Id != null? order.Client_Order_Id:"";
                paras["Message"]       = message;
                string signStr = "";
                foreach (KeyValuePair <string, string> p in paras)
                {
                    if (signStr == string.Empty)
                    {
                        signStr += p.Key.ToLower() + "=" + p.Value;
                    }
                    else
                    {
                        signStr += "&" + p.Key.ToLower() + "=" + p.Value;
                    }
                }
                Logger.Info(string.Format("Post data {1} to {0}", order.CallBackUrl, signStr));
                signStr += "&key=" + token;
                Logger.Info(string.Format("String to be signed {0}", signStr));
                Logger.Info(string.Format("Signature is {0}", UrlSignUtil.GetMD5(signStr)));
                paras["Sign"] = UrlSignUtil.GetMD5(signStr);
                foreach (KeyValuePair <string, string> p in paras)
                {
                    col[p.Key] = p.Value;
                }
                Charge_Order dborder = (from o in db.Charge_Order where o.Id == order.Id select o).FirstOrDefault <Charge_Order>();
                string       resStr  = HttpSercice.PostHttpRequest(order.CallBackUrl, col, WeChat.Adapter.Requests.RequestType.POST, null);
                if (resStr == null)
                {
                    dborder.PushedTimes += 1;
                    dborder.Received     = true;
                }
                else if (resStr.ToLower() == "fail")
                {
                    dborder.PushedTimes += 1;
                    dborder.Received     = false;
                }
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }

                Logger.Info("Leaving SendStatusBackToAgentCallback...");
            }
        }
Beispiel #23
0
        public ChargeResult Charge(ChargeOrder order)
        {
            ChargeResult result = new ChargeResult()
            {
                Status = ChargeStatus.FAILED
            };
            chargebitEntities db = null;

            ProceedOrder(order, out result);
            if (result.Status == ChargeStatus.FAILED)
            {
                return(result);
            }
            List <WebRequestParameters> parmeters = new List <WebRequestParameters>();
            bool succeed = false;

            try
            {
                db = new chargebitEntities();
                Charge_Order corder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault <Charge_Order>();
                corder.Process_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
                KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault <Resrouce_interface>();
                Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == order.ResourceTaocanId select t).FirstOrDefault <Resource_taocan>();
                ServerUri = new Uri(rInterface.APIURL);
                parmeters.Add(new WebRequestParameters("V", version, false));
                parmeters.Add(new WebRequestParameters("Action", "charge", false));
                parmeters.Add(new WebRequestParameters("Range", taocan.Area_id > 0 ? "1" : "0", false));
                SortedDictionary <string, string> paras = new SortedDictionary <string, string>();
                paras["Account"] = rInterface.Username;
                paras["Mobile"]  = order.MobileNumber;
                paras["Package"] = taocan.Quantity.ToString();
                string signStr = "";
                foreach (KeyValuePair <string, string> p in paras)
                {
                    if (signStr == string.Empty)
                    {
                        signStr += p.Key.ToLower() + "=" + p.Value;
                    }
                    else
                    {
                        signStr += "&" + p.Key.ToLower() + "=" + p.Value;
                    }
                }
                signStr      += "&key=" + KMAes.DecryptStringAES(rInterface.Userpassword);
                paras["Sign"] = UrlSignUtil.GetMD5(signStr);

                foreach (KeyValuePair <string, string> p in paras)
                {
                    parmeters.Add(new WebRequestParameters(p.Key, p.Value, false));
                }
                SendRequest(parmeters, false, out succeed);
                if (!string.IsNullOrEmpty(Response))
                {
                    JObject jsonResult = JObject.Parse(Response);
                    order.OutOrderId = jsonResult["TaskID"] != null ? jsonResult["TaskID"].ToString() : "";
                    string code    = jsonResult["Code"] != null ? jsonResult["Code"].ToString() : "";
                    string message = jsonResult["Message"] != null ? jsonResult["Message"].ToString() : "";
                    result.Message = message;
                    switch (code)
                    {
                    case "0":
                        result.Message = ChargeConstant.CHARGING;
                        result.Status  = ChargeStatus.ONPROGRESS;
                        break;

                    case "001":
                        result.Status = ChargeStatus.FAILED;
                        break;

                    case "002":
                        result.Status = ChargeStatus.FAILED;
                        break;

                    case "003":
                        result.Status = ChargeStatus.FAILED;
                        break;

                    case "004":
                        result.Status  = ChargeStatus.FAILED;
                        result.Message = ChargeConstant.RESOURCE_NOT_ENOUGH_MONEY;
                        break;

                    case "005":
                        result.Status = ChargeStatus.FAILED;
                        break;

                    case "006":
                        result.Status = ChargeStatus.FAILED;
                        break;

                    case "007":
                        result.Status = ChargeStatus.FAILED;
                        break;

                    case "008":
                        result.Status = ChargeStatus.FAILED;
                        break;

                    case "009":
                        result.Status = ChargeStatus.FAILED;
                        break;

                    case "100":
                        result.Status = ChargeStatus.FAILED;
                        break;

                    case "999":
                        result.Status = ChargeStatus.FAILED;
                        break;

                    default:
                        result.Status = ChargeStatus.FAILED;
                        break;
                    }
                    ChangeOrderStatus(order, result);
                }
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex);
            }finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
            return(result);
        }
Beispiel #24
0
        public static void ProcessOrders()
        {
            logger.Info("Going to process orders...");
            chargebitEntities db = null;

            try
            {
                List <Charge_Order> orders = null;
                db = new chargebitEntities();
                db.Configuration.AutoDetectChangesEnabled = true;
                if (resources == null)
                {
                    resources = (from r in db.Resource where r.Enabled == true select r).ToList <Resource>();
                }
                if (resourceAPIs == null)
                {
                    resourceAPIs = (from r in db.Resrouce_interface select r).ToList <Resrouce_interface>();
                }
                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)
                {
                    Resource           resource    = (from r in resources where r.Id == corder.Resource_id select r).FirstOrDefault <Resource>();
                    Resrouce_interface resourceAPI = null;
                    if (resource != null)
                    {
                        resourceAPI = (from api in resourceAPIs where api.Resource_id == corder.Resource_id select api).FirstOrDefault <Resrouce_interface>();
                    }
                    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);

                    //just for Synchronized resources
                    if (!string.IsNullOrEmpty(corder.CallBackUrl) && corder.Agent_Id > 0 &&
                        agent != null &&
                        resourceAPI != null &&
                        (resourceAPI.Synchronized == true || result.Status == ChargeStatus.FAILED)
                        )
                    {
                        logger.Info("Synchronized resource api or failed resource api submission.");
                        //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);
                        string resStr = HttpSercice.PostHttpRequest(corder.CallBackUrl, col, WeChat.Adapter.Requests.RequestType.POST, null);
                        if (resStr == null)
                        {
                            corder.PushedTimes += 1;
                            corder.Received     = true;
                        }
                        else if (resStr.ToLower() == "fail")
                        {
                            corder.PushedTimes += 1;
                            corder.Received     = false;
                        }
                        db.SaveChanges();
                    }
                    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();
                }
            }
        }
Beispiel #25
0
        public ChargeResult Charge(ChargeOrder order)
        {
            Logger.Info("Charging...");
            ChargeResult result = new ChargeResult()
            {
                Status = ChargeStatus.FAILED
            };
            chargebitEntities db = null;

            ProceedOrder(order, out result);
            if (result.Status == ChargeStatus.FAILED)
            {
                return(result);
            }
            List <WebRequestParameters> parmeters = new List <WebRequestParameters>();
            bool succeed = false;

            try
            {
                db = new chargebitEntities();
                Charge_Order corder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault <Charge_Order>();
                corder.Process_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
                KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault <Resrouce_interface>();
                Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == order.ResourceTaocanId select t).FirstOrDefault <Resource_taocan>();
                ServerUri = new Uri(rInterface.APIURL);

                StringBuilder body = new StringBuilder();
                body.Append("{");
                body.Append("usernumber:\"" + rInterface.Username + "\"");
                body.Append(",gavingnumber:\"" + order.MobileNumber + "\"");
                body.Append(",packagetype:\"1\"");
                body.Append(",packagecode:\"" + taocan.Serial + "\"");
                body.Append(",validtype:\"0\"");
                body.Append("}");
                string appx      = order.Id.ToString();
                string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string method    = "ai.cuc.ll.method.gav";
                string appkey    = rInterface.AppKey;    // "ai.cuc.ll.appkey.test";
                string appSecret = rInterface.AppSecret; // "8888";
                parmeters.Add(new WebRequestParameters("apptx", appx, false));
                parmeters.Add(new WebRequestParameters("timestamp", timestamp, false));
                parmeters.Add(new WebRequestParameters("method", method, false));
                parmeters.Add(new WebRequestParameters("appkey", appkey, false));
                parmeters.Add(new WebRequestParameters("msg", body.ToString(), false));

                SortedDictionary <string, string> paras = new SortedDictionary <string, string>();
                foreach (WebRequestParameters p in parmeters)
                {
                    paras.Add(p.Name, p.Value);
                }

                string urlStr = string.Empty;
                foreach (KeyValuePair <string, string> p in paras)
                {
                    if (urlStr == string.Empty)
                    {
                        urlStr = p.Key + "=" + p.Value;
                    }
                    else
                    {
                        urlStr += "&" + p.Key + "=" + p.Value;
                    }
                }

                urlStr += "&" + UrlSignUtil.GetMD5(appSecret);
                string sign = UrlSignUtil.GetMD5(urlStr);
                parmeters.Add(new WebRequestParameters("sign", sign, false));
                parmeters.Add(new WebRequestParameters("signMethod", "MD5", false));
                SendRequest(parmeters, false, out succeed, RequestType.POST);

                //parse Response
                if (!string.IsNullOrEmpty(Response))
                {
                    result.Message = ChargeConstant.SUCCEED_CHARGE;
                    result.Status  = ChargeStatus.SUCCEED;
                    try
                    {
                        Newtonsoft.Json.Linq.JObject jsonResult = Newtonsoft.Json.Linq.JObject.Parse(Response);
                        string code    = jsonResult["code"].ToString();
                        string message = jsonResult["detail"].ToString();
                        switch (code)
                        {
                        case "0000":
                            result.Status = ChargeStatus.SUCCEED;
                            break;

                        case "9999":
                            result.Status  = ChargeStatus.FAILED;
                            result.Message = message;
                            break;

                        default:
                            result.Message = "未知错误";
                            result.Status  = ChargeStatus.FAILED;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Message = ex.Message;
                        result.Status  = ChargeStatus.FAILED;
                    }
                }
                else
                {
                    result.Message = "未知错误";
                    result.Status  = ChargeStatus.FAILED;
                }
                if (result.Message != null && result.Message.Length > 5000)
                {
                    result.Message = result.Message.Substring(0, 5000);
                }
                ChangeOrderStatus(order, result);
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
            Logger.Info("Charging done!");
            return(result);
        }
Beispiel #26
0
        public ChargeResult Charge(ChargeOrder order)
        {
            ChargeResult result = new ChargeResult();

            ProceedOrder(order, out result);
            if (result.Status == ChargeStatus.FAILED)
            {
                return(result);
            }
            List <WebRequestParameters> parmeters = new List <WebRequestParameters>();
            bool succeed = false;

            result = new ChargeResult();
            chargebitEntities db = null;

            try
            {
                db = new chargebitEntities();
                Charge_Order corder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault <Charge_Order>();
                corder.Process_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
                KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault <Resrouce_interface>();
                Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == order.ResourceTaocanId select t).FirstOrDefault <Resource_taocan>();
                if (string.IsNullOrEmpty(taocan.Serial))
                {
                    result.Message = ChargeConstant.RESOURCE_TAOCAN_NO_PDTID;
                    result.Status  = ChargeStatus.ONPROGRESS;
                    return(result);
                }
                ServerUri = new Uri(rInterface.APIURL);
                parmeters.Add(new WebRequestParameters("appKey", rInterface.Username, false));
                parmeters.Add(new WebRequestParameters("appSecret", KMAes.DecryptStringAES(rInterface.Userpassword), false));
                parmeters.Add(new WebRequestParameters("phoneNo", order.MobileNumber, false));
                parmeters.Add(new WebRequestParameters("prodCode", taocan.Serial, false));
                parmeters.Add(new WebRequestParameters("backUrl", rInterface.CallBackUrl, false));
                parmeters.Add(new WebRequestParameters("transNo", order.Id.ToString(), false));
                SendRequest(parmeters, false, out succeed);
                if (!string.IsNullOrEmpty(Response))
                {
                    JObject jsonResult = JObject.Parse(Response);
                    order.OutId = jsonResult["orderId"] != null? jsonResult["orderId"].ToString():"";
                    string res    = jsonResult["respCode"] != null?jsonResult["respCode"].ToString():"";
                    string resMsg = jsonResult["respMsg"] != null?jsonResult["respMsg"].ToString():"";
                    switch (res.ToLower())
                    {
                    case "jx0000":
                        result.Message = ChargeConstant.CHARGING;
                        result.Status  = ChargeStatus.ONPROGRESS;
                        break;

                    case "0000":
                    case "00000":
                    case "000000":
                        result.Message = ChargeConstant.SUCCEED_CHARGE;
                        result.Status  = ChargeStatus.SUCCEED;
                        break;

                    case "jx0001":
                        result.Message = ChargeConstant.AGENT_WRONG_PASSWORD;
                        result.Status  = ChargeStatus.FAILED;
                        break;

                    case "jx0002":
                        result.Message = ChargeConstant.AGENT_NOT_BIND_IP;
                        result.Status  = ChargeStatus.FAILED;
                        break;

                    case "jx0003":
                        result.Message = ChargeConstant.AGENT_IP_NOT_MATCH;
                        result.Status  = ChargeStatus.FAILED;
                        break;

                    case "jx0004":
                        result.Message = ChargeConstant.RESOURCE_PRODUCT_NOT_EXIST;
                        result.Status  = ChargeStatus.FAILED;
                        break;

                    case "jx0005":
                        result.Message = ChargeConstant.RESOURCE_NOT_ENOUGH_MONEY;
                        result.Status  = ChargeStatus.FAILED;
                        break;

                    default:
                        result.Message = resMsg;
                        result.Status  = ChargeStatus.FAILED;
                        break;
                    }

                    ChangeOrderStatus(order, result);
                }
            }
            catch (Exception ex)
            {
            }finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
            return(result);
        }
Beispiel #27
0
        public bool CreateActivityTaocan(Marketing_Activity_Taocan taocan)
        {
            bool result = false;

            if (taocan == null)
            {
                throw new KMBitException("输入不正确");
            }
            if (taocan.ActivityId <= 0)
            {
                throw new KMBitException("活动信息丢失");
            }
            if (taocan.RouteId <= 0)
            {
                throw new KMBitException("套餐必须选择");
            }
            if (taocan.Quantity <= 0)
            {
                throw new KMBitException("数量不能小于0");
            }
            if (taocan.Price <= 0)
            {
                throw new KMBitException("价格不能小于0");
            }
            chargebitEntities db = new chargebitEntities();

            try
            {
                Marketing_Activities activity = (from a in db.Marketing_Activities where a.Id == taocan.ActivityId select a).FirstOrDefault <Marketing_Activities>();
                if (activity == null)
                {
                    throw new KMBitException(string.Format("编号为{0}的活动不存在", taocan.ActivityId));
                }
                Customer customer = (from c in db.Customer where c.Id == activity.CustomerId select c).FirstOrDefault <Customer>();
                if (customer == null)
                {
                    throw new KMBitException(string.Format("编号为{0}的活动不属于任何客户", taocan.ActivityId));
                }
                if (customer.AgentId != CurrentLoginUser.User.Id)
                {
                    throw new KMBitException(string.Format("编号为{0}的活动不属您的客户", taocan.ActivityId));
                }

                List <BAgentRoute> routes = new List <BAgentRoute>();
                var query = from r in db.Agent_route
                            join u in db.Users on r.CreatedBy equals u.Id
                            join uu in db.Users on r.UpdatedBy equals uu.Id into luu
                            from lluu in luu.DefaultIfEmpty()
                            join re in db.Resource on r.Resource_Id equals re.Id
                            join tc in db.Resource_taocan on r.Resource_taocan_id equals tc.Id
                            join city in db.Area on tc.Area_id equals city.Id into lcity
                            from llcity in lcity.DefaultIfEmpty()
                            join sp in db.Sp on tc.Sp_id equals sp.Id into lsp
                            from llsp in lsp.DefaultIfEmpty()
                            join tcc in db.Taocan on tc.Taocan_id equals tcc.Id into ltc
                            from lltc in ltc.DefaultIfEmpty()
                            where r.Id == taocan.RouteId
                            select new BAgentRoute
                {
                    Route     = r,
                    CreatedBy = u,
                    UpdatedBy = lluu,
                    Taocan    = new BResourceTaocan
                    {
                        Taocan   = tc,
                        Resource = new BResource {
                            Resource = re
                        },
                        Province = llcity,
                        SP       = llsp,
                        Taocan2  = lltc
                    }
                };
                routes = query.ToList <BAgentRoute>();
                if (routes.Count == 0)
                {
                    throw new KMBitException(string.Format("编号为{0}的套餐不存在", taocan.RouteId));
                }
                BAgentRoute route = routes[0];
                if (!route.Route.Enabled)
                {
                    throw new KMBitException(string.Format("编号为{0}的套餐已经被管理员停用", taocan.RouteId));
                }
                if (!route.Taocan.Taocan.Enabled)
                {
                    throw new KMBitException(string.Format("编号为{0}的套餐的落地套餐被管理员停用", taocan.RouteId));
                }
                if (!route.Taocan.Resource.Resource.Enabled)
                {
                    throw new KMBitException(string.Format("编号为{0}的套餐的落地被管理员停用", taocan.RouteId));
                }
                taocan.CreatedTime      = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
                taocan.ResourceId       = route.Taocan.Resource.Resource.Id;
                taocan.ResourceTaocanId = route.Taocan.Taocan.Id;
                taocan.Generated        = true;

                Users agency = (from a in db.Users where activity.AgentId == a.Id select a).FirstOrDefault <Users>();
                if (agency.Remaining_amount < taocan.Quantity * (route.Taocan.Taocan.Sale_price * route.Route.Discount))
                {
                    throw new KMBitException("代理商账户没有足够的余额");
                }
                if (customer.RemainingAmount < taocan.Quantity * taocan.Price)
                {
                    throw new KMBitException("客户账户没有足够的余额");
                }

                Marketing_Activity_Taocan dbmTaocan = (from mt in db.Marketing_Activity_Taocan where mt.ResourceTaocanId == taocan.ResourceTaocanId && mt.ActivityId == taocan.ActivityId select mt).FirstOrDefault <Marketing_Activity_Taocan>();
                if (dbmTaocan == null)
                {
                    db.Marketing_Activity_Taocan.Add(taocan);
                }
                else
                {
                    dbmTaocan.Quantity += taocan.Quantity;
                    taocan.Id           = dbmTaocan.Id;
                }
                db.SaveChanges();
                if (taocan.Id > 0)
                {
                    agency.Remaining_amount  -= taocan.Quantity * (route.Taocan.Taocan.Sale_price * route.Route.Discount);
                    customer.RemainingAmount -= taocan.Quantity * taocan.Price;
                    db.SaveChanges();
                    for (int i = 0; i < taocan.Quantity; i++)
                    {
                        Marketing_Orders order = new Marketing_Orders()
                        {
                            ActivityId            = taocan.ActivityId,
                            ActivityTaocanId      = taocan.Id,
                            AgentPurchasePrice    = 0,
                            AgentSalePrice        = 0,
                            CreatedTime           = taocan.CreatedTime,
                            ExpiredTime           = activity.ExpiredTime,
                            PlatformPurchasePrice = 0,
                            PlatformSalePrice     = route.Taocan.Taocan.Sale_price,
                            Sent      = false,
                            Used      = false,
                            StartTime = activity.StartedTime,
                            UsedTime  = 0
                        };

                        if (route.Taocan.Taocan.EnableDiscount)
                        {
                            order.PlatformPurchasePrice = route.Taocan.Taocan.Purchase_price * route.Taocan.Taocan.Resource_Discount;
                        }

                        order.AgentPurchasePrice = order.PlatformSalePrice * route.Route.Discount;
                        order.AgentSalePrice     = taocan.Price;
                        db.Marketing_Orders.Add(order);
                    }
                    db.SaveChanges();
                    if (activity.ScanType == 2)
                    {
                        GenerateQRCodeForMarketingOrders(taocan.Id);
                    }
                    result = true;
                }
            }catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
            return(result);
        }
Beispiel #28
0
        public void ImportProducts(int resourceId, int operate_user)
        {
            chargebitEntities db = null;

            try
            {
                bool succeed = false;
                List <WebRequestParameters> parmeters = new List <WebRequestParameters>();
                db = new chargebitEntities();
                db.Configuration.AutoDetectChangesEnabled = false;
                KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == resourceId select ri).FirstOrDefault <Resrouce_interface>();
                ServerUri = new Uri(rInterface.ProductApiUrl);
                parmeters.Add(new WebRequestParameters("appKey", rInterface.Username, false));
                parmeters.Add(new WebRequestParameters("appSecret", KMAes.DecryptStringAES(rInterface.Userpassword), false));
                SendRequest(parmeters, false, out succeed);
                if (succeed)
                {
                    if (!string.IsNullOrEmpty(Response))
                    {
                        JArray products = JArray.Parse(Response);
                        if (products != null && products.Count > 0)
                        {
                            for (int i = 0; i < products.Count; i++)
                            {
                                Resource_taocan taocan   = null;
                                string          serial   = products[i]["ccode"].ToString();
                                string          name     = products[i]["cname"].ToString();
                                int             quantity = 0;
                                int             spId     = int.Parse(products[i]["iprotypeid"].ToString());
                                char[]          names    = name.ToCharArray();
                                StringBuilder   qStr     = new StringBuilder();
                                Regex           regex    = new Regex("[^0-9]");
                                for (int j = 0; j < names.Length; j++)
                                {
                                    char tmp = names[j];
                                    if (!regex.IsMatch(tmp.ToString()))
                                    {
                                        qStr.Append(tmp.ToString());
                                    }

                                    if (tmp.ToString().ToLower() == "g")
                                    {
                                        quantity = int.Parse(qStr.ToString()) * 1024;
                                        break;
                                    }
                                }
                                if (quantity == 0 && qStr.ToString() != "")
                                {
                                    quantity = int.Parse(qStr.ToString());
                                }

                                taocan = (from t in db.Resource_taocan where t.Resource_id == resourceId && t.Serial == serial select t).FirstOrDefault <Resource_taocan>();

                                if (taocan == null)
                                {
                                    //create new product taocan
                                    taocan = new Resource_taocan()
                                    {
                                        Area_id        = 0,
                                        CreatedBy      = operate_user,
                                        Serial         = serial,
                                        Purchase_price = float.Parse(products[i]["iprice"].ToString()),
                                        Quantity       = quantity,
                                        Resource_id    = resourceId,
                                        Created_time   = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now),
                                        Sale_price     = 0,
                                        Enabled        = false
                                    };
                                    if (spId == 2)
                                    {
                                        taocan.Sp_id = 1;
                                    }
                                    else if (spId == 3)
                                    {
                                        taocan.Sp_id = 3;
                                    }
                                    else if (spId == 4)
                                    {
                                        taocan.Sp_id = 2;
                                    }

                                    Taocan ntaocan = (from t in db.Taocan where t.Sp_id == taocan.Sp_id && t.Quantity == taocan.Quantity select t).FirstOrDefault <Taocan>();
                                    Sp     sp      = (from s in db.Sp where s.Id == taocan.Sp_id select s).FirstOrDefault <Sp>();
                                    if (ntaocan == null)
                                    {
                                        string taocanName = sp != null ? sp.Name + " " + taocan.Quantity.ToString() + "M" : "全网 " + taocan.Quantity.ToString() + "M";
                                        ntaocan = new Taocan()
                                        {
                                            Created_time = taocan.Created_time, Description = taocanName, Name = taocanName, Sp_id = taocan.Sp_id, Quantity = taocan.Quantity, Updated_time = 0
                                        };
                                        db.Taocan.Add(ntaocan);
                                        db.SaveChanges();
                                    }
                                    if (ntaocan.Id > 0)
                                    {
                                        taocan.Taocan_id = ntaocan.Id;
                                        db.Resource_taocan.Add(taocan);
                                    }
                                }
                                else
                                {
                                    //update product taocan
                                    taocan.Purchase_price = float.Parse(products[i]["iprice"].ToString());
                                    taocan.UpdatedBy      = operate_user;
                                    taocan.Updated_time   = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
                                    db.SaveChanges();
                                }
                            }

                            db.SaveChanges();
                        }
                    }
                }
            }
            catch (KMBitException ex)
            { }
            catch (Exception ex)
            { }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Beispiel #29
0
        public ChargeOrder GenerateOrder(ChargeOrder order)
        {
            if (order == null)
            {
                throw new KMBitException("订单对象不能为NULL");
            }
            if (string.IsNullOrEmpty(order.MobileNumber))
            {
                throw new KMBitException("充值的手机号码不能为空");
            }
            chargebitEntities db = null;

            try
            {
                db = new chargebitEntities();
                Marketing_Orders          mOrder   = null;
                Marketing_Activity_Taocan mTaocan  = null;
                Marketing_Activities      activity = null;
                if (order.IsMarket && order.MarketOrderId > 0)
                {
                    //if (string.IsNullOrEmpty(order.MacAddress))
                    //{
                    //    throw new KMBitException("活动充值时必须获取终端的MAC地址");
                    //}
                    mOrder = (from o in db.Marketing_Orders where o.Id == order.MarketOrderId select o).FirstOrDefault <Marketing_Orders>();
                    if (mOrder == null)
                    {
                        throw new KMBitException(string.Format("编号为{0}的活动充值记录不存在", order.MarketOrderId));
                    }
                    if (mOrder.Used)
                    {
                        throw new KMBitException("此二维码已经只用过,不能重复使用");
                    }
                    mTaocan = (from m in db.Marketing_Activity_Taocan where m.Id == mOrder.ActivityTaocanId select m).FirstOrDefault <Marketing_Activity_Taocan>();
                    if (mTaocan == null)
                    {
                        throw new KMBitException(string.Format("编号为{0}的活动充值记录的套餐信息不存在", order.MarketOrderId));
                    }

                    activity = (from a in db.Marketing_Activities where a.Id == mTaocan.ActivityId select a).FirstOrDefault <Marketing_Activities>();
                    if (activity == null)
                    {
                        throw new KMBitException(string.Format("编号为{0}的活动不存在", mTaocan.ActivityId));
                    }
                    //check if the device or the number is already charged
                    if (activity.ScanType == 1)
                    {
                        int[] acos = (from mo in db.Marketing_Orders where mo.ActivityId == activity.Id select mo.Id).ToArray <int>();
                        if (acos == null || acos.Length <= 0)
                        {
                            throw new KMBitException(string.Format("编号为{0}的活动还没有任何可用的充值套餐", mTaocan.ActivityId));
                        }
                        //验证电话号码是否在某个直扫活动里已经成功充值过
                        int count = (from o in db.Charge_Order where o.Phone_number == order.MobileNumber && o.Status != 3 && acos.Contains(o.MarketOrderId) select o.Id).Count();
                        if (count > 0)
                        {
                            throw new KMBitException("同一次营销活动每个手机每个号码只能扫描一次");
                        }
                    }

                    order.ResourceId       = mTaocan.ResourceId;
                    order.ResourceTaocanId = mTaocan.ResourceTaocanId;
                    order.RouteId          = mTaocan.RouteId;
                    if (order.AgencyId == 0)
                    {
                        order.AgencyId = (from a in db.Marketing_Activities
                                          where a.Id == mTaocan.ActivityId
                                          select a.AgentId
                                          ).FirstOrDefault <int>();
                    }
                }
                Resource_taocan taocan = null;
                if (order.ResourceTaocanId <= 0 && order.RouteId > 0)
                {
                    var query = from ta in db.Agent_route
                                join tc in db.Resource_taocan on ta.Resource_taocan_id equals tc.Id
                                where ta.Id == order.RouteId
                                select tc;
                    taocan = query.FirstOrDefault <Resource_taocan>();
                }
                else if (order.ResourceTaocanId > 0)
                {
                    taocan = (from tc in db.Resource_taocan where tc.Id == order.ResourceTaocanId select tc).FirstOrDefault <Resource_taocan>();
                }
                if (!taocan.Enabled)
                {
                    throw new KMBitException(ChargeConstant.RESOURCE_TAOCAN_DISABLED);
                }
                if (taocan == null)
                {
                    throw new KMBitException("套餐信息不存在,不能充值");
                }
                order.ResourceTaocanId = taocan.Id;
                KMBit.DAL.Resource resource = (from ri in db.Resource
                                               join tr in db.Resource_taocan on ri.Id equals tr.Resource_id
                                               where tr.Id == order.ResourceTaocanId
                                               select ri).FirstOrDefault <Resource>();

                if (resource == null)
                {
                    throw new KMBitException("落地资源不存在");
                }
                if (!resource.Enabled)
                {
                    throw new KMBitException(ChargeConstant.RESOURCE_DISABLED);
                }
                Agent_route route = null;
                if (order.AgencyId > 0 && order.RouteId > 0)
                {
                    route = (from r in db.Agent_route where r.Id == order.RouteId select r).FirstOrDefault <Agent_route>();
                    if (route == null)
                    {
                        throw new KMBitException("代理商路由不存在");
                    }

                    if (route.User_id != order.AgencyId)
                    {
                        throw new KMBitException("当前代理商没有此路由");
                    }

                    if (!route.Enabled)
                    {
                        throw new KMBitException(string.Format("编号为{0}代理商路由已被管理员停用", route.Id));
                    }
                }

                Charge_Order history = new Charge_Order();
                history.Agent_Id            = order.AgencyId;
                history.Completed_Time      = 0;
                history.Created_time        = order.CreatedTime > 0 ? order.CreatedTime : DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
                history.Operate_User        = order.OperateUserId;
                history.Out_Order_Id        = "";
                history.Payed               = order.Payed;
                history.Phone_number        = order.MobileNumber;
                history.MobileSP            = order.MobileSP;
                history.Province            = order.Province;
                history.City                = order.City;
                history.Resource_id         = resource.Id;
                history.Resource_taocan_id  = order.ResourceTaocanId;
                history.RuoteId             = order.RouteId;
                history.Status              = 11;
                history.CallBackUrl         = order.CallbackUrl != null ? order.CallbackUrl : null;
                history.Platform_Sale_Price = taocan.Sale_price;
                if (taocan.EnableDiscount)
                {
                    history.Platform_Cost_Price = taocan.Purchase_price * taocan.Resource_Discount;
                }
                else
                {
                    history.Platform_Cost_Price = taocan.Purchase_price;
                }

                if (order.IsMarket && order.MarketOrderId > 0)
                {
                    //营销充值
                    history.Charge_type    = 1;
                    history.MarketOrderId  = order.MarketOrderId;
                    history.Sale_price     = mTaocan.Price;
                    history.Purchase_price = history.Platform_Sale_Price * route.Discount;
                    history.Payed          = true;
                }
                else
                {
                    if (order.AgencyId > 0)
                    {
                        //代理商充值
                        history.Charge_type    = 1;
                        history.Purchase_price = taocan.Sale_price * route.Discount;
                        history.Sale_price     = route.Sale_price;
                        history.Revenue        = history.Purchase_price - history.Platform_Cost_Price;
                    }
                    else if (order.OperateUserId > 0)
                    {
                        //管理员后台充值
                        history.Charge_type    = 2;
                        history.Purchase_price = taocan.Sale_price;
                        history.Sale_price     = taocan.Sale_price;
                        history.Revenue        = history.Platform_Sale_Price - history.Platform_Cost_Price;
                    }
                    else
                    {
                        //前台用户直冲
                        history.Charge_type    = 0;
                        history.Purchase_price = taocan.Sale_price;
                        history.Sale_price     = taocan.Sale_price;
                        history.Revenue        = history.Platform_Sale_Price - history.Platform_Cost_Price;
                    }
                }

                db.Charge_Order.Add(history);
                db.SaveChanges();
                order.Id = history.Id;

                //Create Payment record for direct charge
                if (history.Charge_type == 0)
                {
                    Payment_history payment = new Payment_history()
                    {
                        PaymentAccount = "", Amount = taocan.Sale_price, ChargeOrderId = history.Id, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now), PayType = 0, Tranfser_Type = 1
                    };
                    db.Payment_history.Add(payment);
                    db.SaveChanges();
                    order.PaymentId = payment.Id;
                }
            }catch (Exception ex)
            {
                throw new KMBitException(ex.Message);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }

            return(order);
        }
Beispiel #30
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();
                }
            }
        }