Ejemplo n.º 1
0
        public void Notify(Account account, AccountUser owner, DealLog dealItem)
        {
            try
            {
                var site = _siteService.GetSite();
                if (site != null && !string.IsNullOrWhiteSpace(site.MessageTemplateOfDeal))
                {
                    if (owner != null && owner.IsMobileAvailable)
                    {
                        var text = "";
                        switch (dealItem.DealType)
                        {
                        case DealTypes.Deal:
                            text = site.MessageTemplateOfDeal;
                            break;

                        case DealTypes.Integral:
                            text = site.MessageTemplateOfDeal;
                            break;

                        case DealTypes.Recharging:
                            text = site.MessageTemplateOfRecharge;
                            break;

                        case DealTypes.DonePrePay:
                            text = site.MessageTemplateOfDonePrePay;
                            break;

                        case DealTypes.PrePay:
                            text = site.MessageTemplateOfPrePay;
                            break;

                        default:
                            break;
                        }
                        if (string.IsNullOrWhiteSpace(text))
                        {
                            return;
                        }

                        text = MessageFormator.Format(text, owner);
                        text = MessageFormator.Format(text, dealItem);
                        text = MessageFormator.Format(text, account);
                        text = MessageFormator.Format(text, _site);


                        _smsHelper.Send(owner.Mobile, text);

                        _log.Info("send sms for " + account.Name);
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error("send message failed!", ex);
            }
        }
Ejemplo n.º 2
0
        public int Execute(User @operatorUser)
        {
            _operatorUser    = @operatorUser ?? _operatorUser;
            _account.Amount += Amount;
            AccountService.Update(_account);
            var systemDealLog = new SystemDealLog(SerialNo, _operatorUser)
            {
                Amount     = Amount,
                DealType   = SystemDealLogTypes.Recharge,
                HasReceipt = HasReceipt,
                Addin      = _account.AccountId.ToString(),
                DealWayId  = this.HowToDeal
            };

            SystemDealLogService.Create(systemDealLog);

            DealLog dealLog = CreateDealLog();

            dealLog.Addin = systemDealLog.SystemDealLogId;
            DealLogService.Create(dealLog);
            if (!string.IsNullOrWhiteSpace(CurrentSite.MessageTemplateOfRecharge))
            {
                if (_owner != null && _accountType.IsSmsRecharge && _owner.IsMobileAvailable)
                {
                    string message = MessageFormator.FormatTickForRecharging(CurrentSite.MessageTemplateOfRecharge,
                                                                             CurrentSite, HasReceipt, Amount,
                                                                             _dealWay != null?_dealWay.DisplayName:"", dealLog, _account, AccountType,
                                                                             _owner, _operatorUser);
                    SmsHelper.Send(_owner.Mobile, message);
                }
            }
            return(ResponseCode.Success);
        }
Ejemplo n.º 3
0
        private void SendMessage(SystemDealLog dealLog)
        {
            if (string.IsNullOrWhiteSpace(CurrentSite.MessageTemplateOfOpenReceipt))
            {
                return;
            }

            int     accountId = Convert.ToInt32(dealLog.Addin);
            Account account   = AccountService.GetById(accountId);

            if (account.OwnerId == null || !account.IsMessageOfDeal)
            {
                return;
            }
            var user = MembershipService.GetUserById(account.OwnerId.Value) as AccountUser;

            if (user == null || !user.IsMobileAvailable)
            {
                return;
            }

            string msg = MessageFormator.Format(CurrentSite.MessageTemplateOfOpenReceipt, user);

            msg = MessageFormator.Format(msg, account);
            msg = MessageFormator.Format(msg, CurrentSite);
            SmsHelper.Send(user.Mobile, msg);
        }
Ejemplo n.º 4
0
        public CustomJsonResult SendCarInsureOfferFollow(int userId, string phone, string orderSn)
        {
            string           token  = null;
            CustomJsonResult result = SmsHelper.Send("SMS_49300130", "{\"ordersn\":\"" + orderSn + "\"}", phone, out token);

            return(result);
        }
Ejemplo n.º 5
0
        public CustomJsonResult SendCarInsureOfferComplete(int userId, string phone, string orderSn, string carOwner, string carPlateno)
        {
            string           token  = null;
            CustomJsonResult result = SmsHelper.Send("SMS_49450114", "{\"ordersn\":\"" + orderSn + "\",\"carowner\":\"" + carOwner + "\",\"carplateno\":\"" + carPlateno + "\"}", phone, out token);

            return(result);
        }
Ejemplo n.º 6
0
        public CustomJsonResult SendResetPasswordValidCode(int userId, string phone, out string validcode, out string token)
        {
            validcode = BuildValidCode();
            int seconds             = 120;
            CustomJsonResult result = SmsHelper.Send("SMS_49460093", "{\"code\":\"" + validcode + "\",\"seconds\":\"" + seconds + "\"}", phone, out token, validcode, seconds);

            return(result);
        }
Ejemplo n.º 7
0
        public CustomJsonResult SendCreateAccountCode(int operater, string phone, out string validcode, out string token, out int seconds)
        {
            validcode = BuildValidCode();
            seconds   = 600;
            CustomJsonResult result = SmsHelper.Send("SMS_129747717", "{\"code\":\"" + validcode + "\"}", phone, out token, validcode, seconds);

            return(result);
        }
Ejemplo n.º 8
0
        public CustomJsonResult SendGetForgetPwdCode(int userId, string phone, out string validcode, out string token, out int seconds)
        {
            validcode = BuildValidCode();
            seconds   = 600;
            CustomJsonResult result = SmsHelper.Send("SMS_129757696", "{\"code\":\"" + validcode + "\"}", phone, out token, validcode, seconds);

            return(result);
        }
Ejemplo n.º 9
0
        public CustomJsonResult SendAddChildAccountCode(int operater, string phone, out string validcode, out string token)
        {
            validcode = BuildValidCode();
            int seconds             = 120;
            CustomJsonResult result = SmsHelper.Send("SMS_49340095", "{\"code\":\"" + validcode + "\",\"seconds\":\"" + seconds + "\"}", phone, out token, validcode, seconds);

            return(result);
        }
Ejemplo n.º 10
0
Archivo: VCode.cs Proyecto: junprof/EC
        public BaseResponse Send(string phone, int codetype)
        {
            BaseResponse res = new BaseResponse();

            try {
                if (string.IsNullOrEmpty(phone))
                {
                    res.error = 1;
                    res.data  = "手机号为空";
                    return(res);
                }
                //是否在有效期内发送过
                Model.dt_verifycode code = Cache.DataCache.Get(phone + "_" + codetype) as Model.dt_verifycode;
                bool isnew = false;
                if (code == null)
                {
                    code = new Model.dt_verifycode().GetCode(phone, codetype);
                }
                if (code == null || DateTime.Now.Subtract(code.CREATETIME).Minutes > siteConfig.smscodecache) // 重新生成
                {
                    code            = new Model.dt_verifycode();
                    code.CODE       = Common.Utils.Number(4);
                    code.ID         = Guid.NewGuid().ToString();
                    code.ISVALID    = 1;
                    code.CREATETIME = DateTime.Now;
                    code.PHONE      = phone;
                    code.CODETYPE   = codetype;
                    isnew           = true;
                }
                string result = SmsHelper.Send(phone, siteConfig.smstitle, $"您的验证码:{ code.CODE},短信验证码{siteConfig.smscodecache}分钟之类有效,如非本人操作,请忽略本短信,", "liuliangt", siteConfig.smsusername, siteConfig.smspassword, siteConfig.smsapiurl);
                if (result.Contains("000000"))
                {
                    if (isnew)
                    {
                        code.Insert();
                    }
                    Cache.DataCache.Add(phone + "_" + codetype, code, new DateTimeOffset(DateTime.Now.AddMinutes(siteConfig.smscodecache)));
                    res.error = 0;
                    res.data  = "发送成功";
                }
                else
                {
                    res.error = 1;
                    res.data  = "发送失败";
                }
            }catch (Exception ex)
            {
                res.error = 4;
                res.data  = ex;
            }
            return(res);
        }
Ejemplo n.º 11
0
        public SimpleAjaxResult Save()
        {
            try
            {
                var serialNo = SerialNoHelper.Create();
                TransactionHelper.BeginTransaction();
                var account = AccountService.GetById(Id);
                if (account != null && account.State == AccountStates.Invalid)
                {
                    account.State = AccountStates.Normal;
                    AccountService.Update(account);

                    Logger.LogWithSerialNo(LogTypes.AccountResume, serialNo, Id, account.Name);
                    DataAjaxResult r = new DataAjaxResult();
                    if (!string.IsNullOrWhiteSpace(HostSite.MessageTemplateOfAccountResume))
                    {
                        var owner = account.OwnerId.HasValue ? MembershipService.GetUserById(account.OwnerId.Value) : null;
                        if (owner != null && owner.IsMobileAvailable)
                        {
                            var accountType = AccountTypeService.GetById(account.AccountTypeId);
                            if (accountType != null && accountType.IsSmsResume)
                            {
                                var msg = MessageFormator.Format(HostSite.MessageTemplateOfAccountResume, owner);
                                msg = MessageFormator.Format(msg, account);
                                SmsHelper.Send(owner.Mobile, msg);
                            }
                        }
                    }
                    if (!string.IsNullOrWhiteSpace(HostSite.TicketTemplateOfResumeAccount))
                    {
                        r.Data1 = MessageFormator.FormatTickForResumeAccount(
                            HostSite.TicketTemplateOfResumeAccount,
                            serialNo,
                            HostSite,
                            account,
                            account.OwnerId.HasValue ? MembershipService.GetUserById(account.OwnerId.Value) : null,
                            AccountTypeService.GetById(account.AccountTypeId),
                            SecurityHelper.GetCurrentUser().CurrentUser);
                        PrintTicketService.Create(new PrintTicket(LogTypes.AccountResume, serialNo, r.Data1.ToString(), account));
                    }
                    return(TransactionHelper.CommitAndReturn(r));
                }
                return(new SimpleAjaxResult(Localize("accountNoExisting")));
            }
            catch (System.Exception ex)
            {
                Logger.Error(LogTypes.AccountResume, ex);
                return(new SimpleAjaxResult(ex.Message));
            }
        }
Ejemplo n.º 12
0
        public static void callback(Object o)
        {
            string pc = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            try
            {
                string[]     strData = new string[] { "", "", "", "", "" };
                callbackinfo smsc    = (callbackinfo)o;
                DataSet      ds      = smsc.Ds;
                //string sqlstr = "";
                //string updatesql = "";
                //string ids = "";
                for (int i = smsc.Startindex; i <= smsc.Endindex; i++)
                {
                    //发短信操作
                    string phone = smsc.Ds.Tables[0].Rows[i]["phone"].ToString();
                    string title = smsc.Ds.Tables[0].Rows[i]["title"].ToString();
                    string res   = "";
                    foreach (var item in phone.Split(','))
                    {
                        if (item != "")
                        {
                            res += SmsHelper.Send(item, "流量通科技", title, "liuliangt", "hvu7jcvzo81mvoo8endj4etoqmyhng8g", "d9cb15bb613274662803c4edfe121db12611", "");
                        }
                    }

                    if (res.Contains("000000"))
                    {
                        DTcms.BLL.dt_msg bll = new DTcms.BLL.dt_msg();
                        bll.UpdateState(true, System.Guid.Parse(smsc.Ds.Tables[0].Rows[0]["hid"].ToString()));
                        Console.WriteLine(smsc.Ds.Tables[0].Rows[0]["hid"].ToString() + "发送成功" + "-" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                        Log.Info(smsc.Ds.Tables[0].Rows[0]["hid"].ToString() + "_" + res + "\r\n");
                    }
                    else
                    {
                        Console.WriteLine(smsc.Ds.Tables[0].Rows[0]["hid"].ToString() + "发送失败" + "-" + res + "-" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                        Log.Error(smsc.Ds.Tables[0].Rows[0]["hid"].ToString() + "_" + res + "\r\n");
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                Console.WriteLine(pc + "操作失败");
            }
        }
Ejemplo n.º 13
0
        public void Execute()
        {
            if (string.IsNullOrWhiteSpace(_site.MessageTemplateOfBirthDate))
            {
                return;
            }

            var users = GetAccounts();

            foreach (var user in users)
            {
                if (user is AccountUser && user.IsMobileAvailable)
                {
                    var text = MessageFormator.Format(_site.MessageTemplateOfBirthDate, user);
                    _smsHelper.Send(user.Mobile, text);
                }
            }
        }
Ejemplo n.º 14
0
        public ActionResult SendSmsCode(string number, string userName)
        {
            var msg          = MessageFormator.Format(_site.MessageTemplateOfIdentity ?? "", _site);
            var randomNumber = RandomHelper.GenerateNumber(6);

            CodeHelper.CreateObject("sms", randomNumber, TimeSpan.FromMinutes(5));
            CodeHelper.CreateObject("sms_mobile", number, TimeSpan.FromMinutes(5));
            try
            {
                msg = msg.Replace("#code#", randomNumber);
                msg = msg.Replace("#username#", userName);
                _smsHelper.Send(number, msg);
                return(Json("验证短信发送成功.", JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                Logger.Error(LogTypes.SendSmsCode, ex);
                return(Json("验证短信发送失败: " + ex.Message, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 15
0
        public AccountServiceResponse Save()
        {
            var serialNo = SerialNoHelper.Create();

            TransactionHelper.BeginTransaction();

            var account = AccountService.GetByName(AccountName);

            if (account == null)
            {
                return(new AccountServiceResponse(ResponseCode.NonFoundAccount));
            }
            if (account.State != AccountStates.Normal)
            {
                return(new AccountServiceResponse(ResponseCode.AccountStateInvalid));
            }
            AccountUser owner = null;

            if (account.OwnerId.HasValue)
            {
                owner = MembershipService.GetUserById(account.OwnerId.Value) as AccountUser;
            }
            var  accountType  = AccountTypeService.GetById(account.AccountTypeId);
            bool isRenew      = false;
            int  renewalMonth = 6;

            if (accountType != null)
            {
                isRenew      = accountType.IsRenew;
                renewalMonth = accountType.RenewMonths;
            }
            if (!isRenew)
            {
                return(new AccountServiceResponse(ResponseCode.NonRenewal));
            }
            var now = DateTime.Now;

            account.ExpiredDate = (now > account.ExpiredDate ? now : account.ExpiredDate).AddMonths(renewalMonth);
            AccountService.Update(account);
            Logger.LogWithSerialNo(LogTypes.AccountRenew, serialNo, account.AccountId, AccountName, accountType.RenewMonths);
            if (!string.IsNullOrWhiteSpace(HostSite.MessageTemplateOfAccountRenew))
            {
                if (owner != null && owner.IsMobileAvailable)
                {
                    if (accountType.IsSmsRenew)
                    {
                        var msg = MessageFormator.Format(HostSite.MessageTemplateOfAccountRenew, owner);
                        msg = MessageFormator.Format(msg, account);
                        SmsHelper.Send(owner.Mobile, msg);
                    }
                }
            }
            var response = new AccountServiceResponse(ResponseCode.Success, null, ShopService.GetById(account.ShopId), account, owner);

            if (!string.IsNullOrWhiteSpace(HostSite.TicketTemplateOfRenewAccount))
            {
                var msg = MessageFormator.FormatTickForRenewAccount(HostSite.TicketTemplateOfRenewAccount, serialNo, HostSite, account, owner, accountType,
                                                                    SecurityHelper.GetCurrentUser().CurrentUser);
                response.CodeText = msg;
                PrintTicketService.Create(new PrintTicket(LogTypes.AccountRenew, serialNo, msg, account));
            }
            return(TransactionHelper.CommitAndReturn(response));
        }
Ejemplo n.º 16
0
        public AccountServiceResponse Save()
        {
            var serialNo = SerialNoHelper.Create();

            TransactionHelper.BeginTransaction();
            var newAccount = AccountService.GetByName(AccountName);

            if (newAccount == null || newAccount.State != AccountStates.Ready)
            {
                return(new AccountServiceResponse(ResponseCode.NonFoundAccount));
            }

            var oldAccount = AccountService.GetByName(OldAccountName);

            if (oldAccount == null ||
                (oldAccount.State != AccountStates.Normal && oldAccount.State != AccountStates.Invalid))
            {
                return(new AccountServiceResponse(ResponseCode.NonFoundAccount));
            }
            oldAccount.Remark1      = "Ô­¿¨ºÅ£º" + newAccount.Name;
            oldAccount.Name         = newAccount.Name;
            oldAccount.AccountToken = newAccount.AccountToken;
            oldAccount.Password     = newAccount.Password;
            oldAccount.PasswordSalt = newAccount.PasswordSalt;
            var owner = (AccountUser)(oldAccount.OwnerId.HasValue ? MembershipService.GetUserById(oldAccount.OwnerId.Value) : null);

            Logger.LogWithSerialNo(LogTypes.AccountChangeName, serialNo, oldAccount.AccountId, OldAccountName, AccountName);
            var fee = HostSite.ChangeCardFee;

            if (fee.HasValue)
            {
                SystemDealLogService.Create(new SystemDealLog(serialNo, SecurityHelper.GetCurrentUser().CurrentUser)
                {
                    Addin    = oldAccount.AccountId.ToString(),
                    Amount   = fee.Value,
                    DealType = SystemDealLogTypes.ChangeCard
                });
                oldAccount.ChargingAmount += fee.Value;
                CashDealLogService.Create(new CashDealLog(fee.Value, 0, SecurityHelper.GetCurrentUser().CurrentUser.UserId, CashDealLogTypes.ChangeCard));
            }
            AccountService.Delete(newAccount);

            AccountService.Update(oldAccount);
            var response    = new AccountServiceResponse(ResponseCode.Success, null, ShopService.GetById(oldAccount.ShopId), oldAccount, owner);
            var accountType = AccountTypeService.GetById(oldAccount.AccountTypeId);

            if (!string.IsNullOrWhiteSpace(HostSite.MessageTemplateOfAccountChangeName))
            {
                if (owner != null && owner.IsMobileAvailable)
                {
                    var msg = MessageFormator.Format(HostSite.MessageTemplateOfAccountChangeName, owner);
                    SmsHelper.Send(owner.Mobile, msg);
                }
            }

            if (!string.IsNullOrWhiteSpace(HostSite.TicketTemplateOfChangeAccountName))
            {
                var msg = MessageFormator.FormatTickForChangeAccountName(
                    HostSite.TicketTemplateOfChangeAccountName,
                    HostSite,
                    serialNo,
                    OldAccountName,
                    oldAccount,
                    owner,
                    accountType,
                    SecurityHelper.GetCurrentUser().CurrentUser);
                PrintTicketService.Create(new PrintTicket(LogTypes.AccountChangeName, serialNo, msg, oldAccount));
                response.CodeText = msg;
            }

            return(TransactionHelper.CommitAndReturn(response));
        }
Ejemplo n.º 17
0
        public void ServiceSubmit(MeterRecord record, string imsi = "")
        {
            decimal balance = 0;

            //正在换表不记录数
            if (_readTaskApp.GetLastEntity((int)TaskTypeEnum.SetBaseDosage, record.MeterCode) != null)
            {
                return;
            }
            //获取表信息
            var meter = _meterApp.GetFormByMeterCode(record.MeterCode);

            if (meter == null)
            {
                return;
            }
            //表计倍率处理
            if (meter.F_MeterRate != null)
            {
                record.Value = (double.Parse(record.Value) * (double)meter.F_MeterRate).ToString(CultureInfo.InvariantCulture);
            }
            const int read       = (int)TaskTypeEnum.Read;
            const int task       = (int)TaskTypeEnum.Task;
            var       readTask   = _readTaskApp.GetLastEntity(task, record.MeterCode) ?? _readTaskApp.GetLastEntity(read, record.MeterCode);
            var       lastDosage = decimal.Parse(GetLastReadRecord(meter.F_Id, DateTime.Now));
            //本次用量
            var thisDosage = decimal.Parse(record.Value) - lastDosage;

            //过滤异常数据并加载到异常信息表内
            //if (lastDosage != 0 && (thisDosage > 2000 || thisDosage < -2000))
            if (1 > 1)
            {
                var readUnusualEntity = new ReadUnusualEntity()
                {
                    F_Id              = Common.GuId(),
                    F_CreatorTime     = DateTime.Now,
                    F_ErrorType       = ((int)ReadUnusualEnum.Read).ToString(),
                    F_MeterCode       = meter.F_MeterCode,
                    F_MeterType       = meter.F_MeterType,
                    F_Description     = meter.F_Description,
                    F_CustomerAddress = meter.F_CustomerAddress,
                    F_CustomerName    = meter.F_CustomerName,
                    F_Factor          = meter.F_Factor,
                    F_MobilePhone     = meter.F_MobilePhone,
                    F_OwnerId         = meter.F_OwnerId,
                    F_UserCard        = meter.F_UserCard,
                    F_Value           = thisDosage,
                };
                _readUnusualApp.SubmitForm(readUnusualEntity, "");
                return;
            }
            else
            {
                var readRecordEntity = new ReadRecordEntity
                {
                    F_TaskId      = readTask == null ? "" : readTask.F_Id,
                    F_ReadTime    = record.ReadingTime,
                    F_ArchiveId   = meter.F_Id,
                    F_ReadType    = readTask == null ? "-1" : readTask.F_TaskType.ToString(),
                    F_TotalDosage = decimal.Parse(record.Value),
                    F_CreatorTime = DateTime.Now,
                    F_Id          = Common.GuId(),
                    F_ThisDosage  = thisDosage,
                    F_Details     = record.Data == null ? "" : record.Data.ToJson(),
                    F_Settlement  = record.Settlement == null ? "" : record.Settlement.ToJson(),
                    F_Imsi        = imsi
                };
                ReadTaskEntity     controlTask        = null;
                PayOrderEntity     payOrderEntity     = null;
                ChargeRecordEntity chargeRecordEntity = null;
                MoneyAlarmEntity   moneyAlarmEntity   = null;
                //获取计费信息
                var meterCharging       = _meterChargingApp.GetForm(readRecordEntity.F_ArchiveId);
                var subsistenceCharging = _subsistenceSecurityApp.GetFormByArchiveId(readRecordEntity.F_ArchiveId);
                //0.判断表是否为IC卡预付费表
                //获取当前周期开始时间
                var cycleStartTime = _priceApp.GetCycleStartTime(subsistenceCharging != null && subsistenceCharging.F_PriceId != null ? subsistenceCharging.F_PriceId : meterCharging.F_PriceModel);
                //获取当前周期开始时间前一天最后一条抄表记录
                var cycleDosage = cycleStartTime == DateTime.MinValue
                    ? 0
                    : decimal.Parse(GetLastReadRecord(readRecordEntity.F_ArchiveId, cycleStartTime));
                //单位价格
                var uintPrice = _priceApp.GetPriceValue(subsistenceCharging != null && subsistenceCharging.F_PriceId != null ? subsistenceCharging.F_PriceId : meterCharging.F_PriceModel,
                                                        ((readRecordEntity.F_TotalDosage ?? 0) - cycleDosage).ToString(CultureInfo.InvariantCulture));
                if (meterCharging.F_MeterModel != "3")
                {
                    //扣费后的余额
                    balance = _meterChargingApp.UpdateBalance(readRecordEntity.F_ArchiveId, (readRecordEntity.F_ThisDosage ?? 0) * uintPrice);
                }
                else
                {
                    var count = _payOrderApp.GetPayOrderCount(record.MeterCode);
                    if (record.Data != null && record.Data.Keys.Contains("充值次数") && (count + 1).ToString() == record.Data["充值次数"])
                    {
                        payOrderEntity = _payOrderApp.GetLastPayOrder(record.MeterCode);
                        if (payOrderEntity != null)
                        {
                            payOrderEntity.F_State = "1";
                        }
                    }
                    if (record.Data != null && record.Data.Keys.Contains("余额"))
                    {
                        decimal money;
                        //上传的余额
                        balance = decimal.TryParse(record.Data["余额"], out money) ? _meterChargingApp.SetBalance(readRecordEntity.F_ArchiveId, money) : 0;
                    }
                }
                chargeRecordEntity = new ChargeRecordEntity
                {
                    F_ThisBill    = (readRecordEntity.F_ThisDosage ?? 0) * uintPrice,
                    F_ReadId      = readRecordEntity.F_Id,
                    F_UnitPrice   = uintPrice,
                    F_Description = "",
                    F_Balance     = balance,
                    F_ChargeTime  = DateTime.Now
                };
                //1.设备是否阀控,是否报警
                if (meterCharging.F_EnableClose == true && balance <= meterCharging.F_CloseAmount)
                {
                    //2. 判断设备类型+是否可以阀控
                    if (meter.F_MeterType == MeterTypeEnum.WattMeter.ToString()) //电表关阀命令
                    {
                        controlTask = new ReadTaskEntity
                        {
                            F_MeterCode   = meter.F_MeterCode,
                            F_Factor      = meter.F_Factor,
                            F_MeterType   = meter.F_MeterType,
                            F_State       = (int)TaskStateEnum.Wait,
                            F_Id          = Common.GuId(),
                            F_CreatorTime = DateTime.Now,
                            F_TaskType    = (int)TaskTypeEnum.TripSwitch
                        };
                    }
                    else //水表、燃气表、热表关阀命令
                    {
                        //判断是否应急或关阀状态
                        if (!IsEmergency(readRecordEntity))
                        {
                            controlTask = new ReadTaskEntity
                            {
                                F_MeterCode   = meter.F_MeterCode,
                                F_Factor      = meter.F_Factor,
                                F_MeterType   = meter.F_MeterType,
                                F_State       = (int)TaskStateEnum.Wait,
                                F_Id          = Common.GuId(),
                                F_CreatorTime = DateTime.Now,
                                F_TaskType    = (int)TaskTypeEnum.CloseValve
                            };
                        }
                    }
                }
                if (meterCharging.F_EnableClose == true && balance > meterCharging.F_CloseAmount)
                {
                    if (meter.F_MeterType == MeterTypeEnum.WattMeter.ToString()) //电表开阀命令
                    {
                        //电表充值自动开阀,不启用
                        //controlTask = new ReadTaskEntity
                        //{
                        //    F_MeterCode = meter.F_MeterCode,
                        //    F_Factor = meter.F_Factor,
                        //    F_MeterType = meter.F_MeterType,
                        //    F_State = (int)TaskStateEnum.Wait,
                        //    F_Id = Common.GuId(),
                        //    F_CreatorTime = DateTime.Now,
                        //    F_TaskType = (int)TaskTypeEnum.CloseSwitch
                        //};
                    }
                    else //水表、燃气表、热表开阀命令
                    {
                        //判断是否应急或关阀状态
                        if (IsEmergency(readRecordEntity))
                        {
                            controlTask = new ReadTaskEntity
                            {
                                F_MeterCode   = meter.F_MeterCode,
                                F_Factor      = meter.F_Factor,
                                F_MeterType   = meter.F_MeterType,
                                F_State       = (int)TaskStateEnum.Wait,
                                F_Id          = Common.GuId(),
                                F_CreatorTime = DateTime.Now,
                                F_TaskType    = (int)TaskTypeEnum.OpenValve
                            };
                        }
                    }
                }
                if (meterCharging.F_EnableAlarm == true && balance <= meterCharging.F_AlarmAmount)
                {
                    if (_moneyAlarmApp.IsCanSend(meter.F_Id))//判断是否可报警
                    {
                        var dataItems = (Dictionary <string, object>) new ItemsDetailApp().GetDataItemList();
                        var content   = SmsHelper.UrlEncode("#name#=" + meter.F_CustomerName + "&#time#=" + DateTime.Now.ToString("yyyy年MM月dd日") + "&#meter#=" + meter.F_CustomerAddress + ((Dictionary <string, string>)dataItems["DeviceType"])[meter.F_MeterType] + "&#balance#=" + balance.ToString("#0.00"));
                        var content2  = SmsHelper.UrlEncode("#name#=" + meter.F_CustomerName + "&#time#=" + DateTime.Now.ToString("yyyy年MM月dd日") + "&#meter#=" + ((Dictionary <string, string>)dataItems["DeviceType"])[meter.F_MeterType] + "&#balance#=" + balance.ToString("#0.00"));
                        moneyAlarmEntity = new MoneyAlarmEntity
                        {
                            F_Id          = Common.GuId(),
                            F_ArchiveId   = meter.F_Id,
                            F_AlarmMonry  = balance,
                            F_AlarmState  = (meter.F_OwnerId == "ff92def0-dabe-4878-915b-1b8cd0560ce4" && SmsHelper.Send(meter.F_MobilePhone, "58698", content, "c9eb4d0f54ad274842ef562d79f67e59")) || (meter.F_OwnerId == "bd602a97-eb06-4a5e-9c36-30eb45bc717b" && SmsHelper.Send(meter.F_MobilePhone, "96473", content2, "f73188115023c7e37955b095fefe0bb7")), //发送短信
                            F_SureState   = false,
                            F_CreatorTime = DateTime.Now,
                        };
                    }
                }
                else
                {
                    _moneyAlarmApp.SureAlarm(meter.F_Id);
                }
                //3.插入抄表信息、计费信息、阀控命令/报警命令
                _service.SubmitService(readRecordEntity, chargeRecordEntity, readTask, controlTask, payOrderEntity, moneyAlarmEntity);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 发送短信
        /// </summary>
        public ActionResult SendSMS()
        {
            try
            {
                string mobile     = ZNRequest.GetString("Mobile");
                string sms        = ZNRequest.GetString("SMS");
                string num        = new Random().Next(100000, 999999).ToString();
                var    templateId = System.Web.Configuration.WebConfigurationManager.AppSettings["defaultTemplate"].ToString();
                switch (sms)
                {
                //找回密码验证码
                case "findpwdsms":
                    templateId = System.Web.Configuration.WebConfigurationManager.AppSettings["findpwdsmsTemplate"].ToString();
                    break;

                //用户注册验证码
                case "regsms":
                    templateId = System.Web.Configuration.WebConfigurationManager.AppSettings["regsmsTemplate"].ToString();
                    break;

                //绑定手机号码
                case "bindphone":
                    templateId = System.Web.Configuration.WebConfigurationManager.AppSettings["bindphoneTemplate"].ToString();
                    break;

                default:
                    break;
                }

                var code = "0";
                var msg  = string.Empty;

                //是否启用短信
                var usesms = System.Web.Configuration.WebConfigurationManager.AppSettings["usesms"].ToString();
                if (usesms == "1")
                {
                    //发送模板短信
                    var result = SmsHelper.Send(templateId, mobile, "@1@=" + num, "");
                    if (string.IsNullOrWhiteSpace(result))
                    {
                        return(Json(new { result = false, message = "失败" }, JsonRequestBehavior.AllowGet));
                    }
                    var model = JObject.Parse(result);
                    code = model["code"].ToString();
                    msg  = model["msg"].ToString();
                }

                //发送记录
                SendSMS log = new SendSMS();
                log.Mobile     = mobile;
                log.Remark     = sms + "|" + msg;
                log.Result     = code;
                log.Code       = num;
                log.CreateDate = DateTime.Now;
                log.CreateIP   = Tools.GetClientIP;
                db.Add <SendSMS>(log);

                if (code == "0")
                {
                    CookieHelper.SetCookie("SMS", mobile + sms + num, DateTime.Now.AddMinutes(15));
                    return(Json(new { result = true, usesms = usesms, message = usesms == "1" ? msg : num }, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLoger.Error("SystemController_SendSMS:" + ex.Message);
            }
            return(Json(new { result = false, message = "失败" }, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 19
0
        public IHttpActionResult Post([FromBody] UserModel model)
        {
            if (!Msisdn.IsValid(model.MobileNumber, Country))
            {
                return(this.BadRequestEx(Error.MobileNumberInvalid));
            }

            using (var dbContext = new DataContext())
            {
                var user = new User();
                user.FirstName        = model.FirstName;
                user.LastName         = model.LastName;
                user.Email            = model.Email;
                user.MobileNumber     = model.MobileNumber;
                user.Status           = Data.Enums.Status.Active;
                user.CreatedTimestamp = DateTime.Now;
                user.IsOfficer        = model.IsOfficer ? "1" : "0";
                user.ExternalID       = model.ExternalID;

                dbContext.Users.Add(user);

                if (model.Districts != null)
                {
                    foreach (var districtModel in model.Districts)
                    {
                        var district = dbContext.Districts.Find(districtModel.ID);
                        if (district == null)
                        {
                            continue;
                        }

                        var userDistrict = new UserDistrict();
                        userDistrict.District = district;
                        userDistrict.User     = user;

                        dbContext.UserDistricts.Add(userDistrict);
                    }
                }

                var userName = Kapsch.Core.Cryptography.Random.GenerateConcatenatedString(model.FirstName.Substring(0, 1), model.LastName);
                while (true)
                {
                    if (!dbContext.Credentials.Any(f => f.UserName == userName))
                    {
                        break;
                    }

                    userName = Kapsch.Core.Cryptography.Random.GenerateConcatenatedString(model.FirstName.Substring(0, 1), model.LastName);
                }

                Random random = new Random();

                var credential = new Credential();
                credential.CreatedTimeStamp = DateTime.Now;
                credential.EntityID         = user.ID;
                credential.EntityType       = Data.Enums.EntityType.User;
                credential.ExpiryTimeStamp  = DateTime.Now.AddYears(20);
                credential.Status           = Data.Enums.Status.Active;
                credential.UserName         = userName;

                credential.Password = Membership.GeneratePassword(8, 0);
                credential.Password = Regex.Replace(credential.Password, @"[^a-zA-Z0-9]", m => random.Next(0, 9).ToString());

                dbContext.Credentials.Add(credential);

                if (model.SystemFunctions != null)
                {
                    foreach (var systemFunctionModel in model.SystemFunctions)
                    {
                        var systemFunction = dbContext.SystemFunctions.Find(systemFunctionModel.ID);
                        if (systemFunction == null)
                        {
                            continue;
                        }

                        var userSystemFunction = new CredentialSystemFunction();
                        userSystemFunction.SystemFunction = systemFunction;
                        userSystemFunction.Credential     = credential;
                        userSystemFunction.Status         = Data.Enums.Status.Active;

                        dbContext.CredentialSystemFunctions.Add(userSystemFunction);
                    }
                }

                dbContext.SaveChanges();

                var logo = string.Format("{0}/Images/IMS-logo-180x66-1color.png", UserManagementPortal);

                var personalizations = new Dictionary <string, string>();
                personalizations.Add("website", UserManagementPortal);
                personalizations.Add("logo", logo);
                personalizations.Add("fullName", string.Format("{0} {1}", user.FirstName, user.LastName));
                personalizations.Add("userName", credential.UserName);
                personalizations.Add("password", credential.Password);

                //EmailHelper.Send(
                //    HttpContext.Current.Server.MapPath("~/MailTemplates"),
                //    new[] { model.Email },
                //    "Account Created",
                //    "AccountCreated.txt",
                //    personalizations);
                var company = dbContext.Companies.FirstOrDefault(f => f.Name == "Intelligent Mobility Solutions"); // IMS
                if (company == null)
                {
                    Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Unable to get company, Intelligent Mobility Solutions, from database."));
                }
                else
                {
                    SmsHelper.Send(
                        dbContext,
                        "User Management",
                        "Create User",
                        new Router()
                    {
                        Source = "IMS", Target = new Msisdn(user.MobileNumber, Country).ToString(Msisdn.Format.International)
                    },
                        company,
                        user,
                        HttpContext.Current.Server.MapPath("~/MailTemplates"),
                        "SmsAccountCreated.txt",
                        personalizations);
                }

                model.ID               = user.ID;
                model.UserName         = credential.UserName;
                model.Status           = (Models.Enums.UserStatus)user.Status;
                model.CreatedTimestamp = user.CreatedTimestamp;

                return(Ok(model));
            }
        }