Beispiel #1
0
        public void RetrySMS(SendMessageHistory sendMessageHistory)
        {
            DateTime utcNow = DateTime.UtcNow;

            // 扣點
            decimal point          = sendMessageHistory.MessageCost;
            var     userRepository = this.unitOfWork.Repository <ApplicationUser>();
            var     user           = userRepository.Get(p => p.FullName == "Admin");

            user.SmsBalance -= point;
            userRepository.Update(user);

            // 寫入交易明細
            var tradeDetailRepository = this.unitOfWork.Repository <TradeDetail>();
            var tradeDetail           = new TradeDetail
            {
                TradeTime = utcNow,
                TradeType = TradeType.RetrySMS,
                Point     = -1 * point,
                OwnerId   = user.Id,
                TargetId  = sendMessageHistory.Id.ToString(),
                Remark    = string.Format("簡訊發送結果歷史紀錄編號:{0},第{1}次重送,發送至門號:{2}({3}),扣除{4}點",
                                          sendMessageHistory.Id,
                                          sendMessageHistory.RetryTotalTimes + 1,
                                          sendMessageHistory.DestinationAddress,
                                          sendMessageHistory.Region,
                                          point)
            };

            tradeDetailRepository.Insert(tradeDetail);

            // 自動補點與點數預警
            CheckCredit(user);
        }
Beispiel #2
0
        /// <summary>
        /// 處理取回派回結果後,根據派送成功或者失敗,決定是否回補點數。
        /// </summary>
        private void HandleSendMessageHistory(
            SendMessageRule sendMessageRule,
            SendMessageQueue sendMessageQueue,
            SendMessageHistory sendMessageHistory)
        {
            if (sendMessageHistory.Delivered)
            {
                return;
            }
            if (sendMessageHistory.Price != 0)
            {
                return;                                // 如果簡訊商就算傳送失敗,但有收取簡訊費用,就不回補點數
            }
            if (sendMessageHistory.ProviderName == SmsProviderType.Every8d.ToString())
            {
                return;                                                                        // Every8d 會重送,不需要回補點數
            }
            DateTime utcNow = DateTime.UtcNow;

            // 補點
            decimal point          = sendMessageHistory.MessageCost;
            var     userRepository = this.unitOfWork.Repository <ApplicationUser>();
            var     user           = sendMessageRule.CreatedUser;

            user.SmsBalance += point;
            userRepository.Update(user);

            // 寫入交易明細
            var tradeDetailRepository = this.unitOfWork.Repository <TradeDetail>();
            var tradeDetail           = new TradeDetail
            {
                TradeTime = utcNow,
                TradeType = TradeType.CoverOfSendMessage,
                Point     = point,
                OwnerId   = user.Id,
                TargetId  = sendMessageHistory.Id.ToString(),
                Remark    = string.Format("{0}(簡訊編號:{1},序列編號:{2}),收訊門號{3}發送失敗({4}),回補點數{5}點",
                                          AttributeHelper.GetColumnDescription(sendMessageRule.SendTimeType),
                                          sendMessageRule.Id,
                                          sendMessageQueue.Id,
                                          sendMessageHistory.DestinationAddress,
                                          //AttributeHelper.GetColumnDescription(sendMessageHistory.DeliveryStatus),
                                          sendMessageHistory.DeliveryStatusString,
                                          point)
            };

            tradeDetailRepository.Insert(tradeDetail);

            // 自動補點與點數預警 // 回補點數,不用自動補點與點數預警
            //CheckCredit(user);
        }
Beispiel #3
0
        private void UpdateDb(SendMessageHistory sendMessageHistory, SEND_SMS_RESULT sendMessageResult)
        {
            // 寫入對應的 SendMessageResult
            var every8d_SendMessageResult = new Every8d_SendMessageResult();

            every8d_SendMessageResult.SourceTable   = SourceTable.SendMessageHistory;
            every8d_SendMessageResult.SourceTableId = sendMessageHistory.Id;

            every8d_SendMessageResult.SendTime    = sendMessageHistory.SendTime;
            every8d_SendMessageResult.Subject     = sendMessageHistory.SendTitle;
            every8d_SendMessageResult.Content     = sendMessageHistory.SendBody;
            every8d_SendMessageResult.CreatedTime = DateTime.UtcNow;

            every8d_SendMessageResult.CREDIT   = sendMessageResult.CREDIT;
            every8d_SendMessageResult.SENDED   = sendMessageResult.SENDED;
            every8d_SendMessageResult.COST     = sendMessageResult.COST;
            every8d_SendMessageResult.UNSEND   = sendMessageResult.UNSEND;
            every8d_SendMessageResult.BATCH_ID = sendMessageResult.BATCH_ID;

            every8d_SendMessageResult = this.unitOfWork.Repository <Every8d_SendMessageResult>().Insert(every8d_SendMessageResult);

            // Every8d 在此階段無法取得寫入 SendMessageHistory,無對應資料結構
            // CreateSendMessageHistory(sendMessageQueue.Id);

            // 在 Thread 中等待 30 秒,再寫入 DeliveryReportQueue
            var delayMilliseconds = (int)30 * 1000;

            FaFTaskFactory.StartNew(delayMilliseconds, () =>
            {
                using (var context = new ApplicationDbContext())
                {
                    var _unitOfWork = new UnitOfWork(context);
                    var _repository = _unitOfWork.Repository <DeliveryReportQueue>();

                    // 寫入簡訊派送結果等待取回序列
                    var deliveryReportQueue           = new DeliveryReportQueue();
                    deliveryReportQueue.SourceTableId = sendMessageHistory.Id;
                    deliveryReportQueue.SourceTable   = SourceTable.SendMessageHistory;
                    deliveryReportQueue.RequestId     = every8d_SendMessageResult.BATCH_ID;
                    deliveryReportQueue.ProviderName  = this.Name;
                    deliveryReportQueue.CreatedTime   = DateTime.UtcNow;
                    deliveryReportQueue.SendMessageResultItemCount = every8d_SendMessageResult.SENDED.HasValue ? every8d_SendMessageResult.SENDED.Value : 0;
                    deliveryReportQueue.DeliveryReportCount        = 0;
                    deliveryReportQueue = _repository.Insert(deliveryReportQueue);
                }
            });
        }
Beispiel #4
0
        /// <summary>
        /// 在 GetDeliveryReport 之後,更新大表 SendMessageHistory
        /// </summary>
        public void UpdateSendMessageHistory(int sendMessageQueueId)
        {
            var sendMessageRuleRepository    = this.unitOfWork.Repository <SendMessageRule>();
            var sendMessageQueueRepository   = this.unitOfWork.Repository <SendMessageQueue>();
            var sendMessageHistoryRepository = this.unitOfWork.Repository <SendMessageHistory>();

            SendMessageQueue sendMessageQueue = sendMessageQueueRepository.GetById(sendMessageQueueId);

            SendMessageRule sendMessageRule = sendMessageRuleRepository.GetById(sendMessageQueue.SendMessageRuleId);

            var clientTimezoneOffset = sendMessageRule.ClientTimezoneOffset;

            var messageReceivers = this.unitOfWork.Repository <MessageReceiver>().GetMany(p =>
                                                                                          p.SendMessageRuleId == sendMessageQueue.SendMessageRuleId &&
                                                                                          p.SendBody == sendMessageQueue.SendBody).ToList();

            Every8d_SendMessageResult sendMessageResult = this.unitOfWork.Repository <Every8d_SendMessageResult>().Get(p => p.SourceTable == SourceTable.SendMessageQueue && p.SourceTableId == sendMessageQueueId);
            // if (SendMessageResult == null) return; 不應該為 null

            int?DepartmentId = null;

            if (sendMessageRule.CreatedUser.Department != null)
            {
                DepartmentId = sendMessageRule.CreatedUser.Department.Id;
            }
            string          CreatedUserId     = sendMessageRule.CreatedUser.Id;
            int             SendMessageRuleId = sendMessageQueue.SendMessageRuleId;
            SendMessageType SendMessageType   = sendMessageQueue.SendMessageType;

            DateTime     SendTime     = sendMessageQueue.SendTime;
            string       SendTitle    = sendMessageQueue.SendTitle;
            string       SendBody     = sendMessageQueue.SendBody;
            SendCustType SendCustType = sendMessageQueue.SendCustType;
            string       RequestId    = sendMessageResult.BATCH_ID;

            string ProviderName = this.Name;

            DateTime SendMessageResultCreatedTime = sendMessageResult.CreatedTime;

            List <Every8d_DeliveryReport> DeliveryReports = sendMessageResult.DeliveryReports.ToList();

            //foreach (var DeliveryReport in DeliveryReports)
            for (var i = 0; i < DeliveryReports.Count; i++)
            {
                var DeliveryReport  = DeliveryReports[i];
                var messageReceiver = (0 <= i && i < messageReceivers.Count) ? messageReceivers[i] : null;

                string DestinationName = DeliveryReport.NAME;

                var entity = new SendMessageHistory();

                ////////////////////////////////////////
                // 01 ~ 05

                entity.DepartmentId       = DepartmentId;
                entity.CreatedUserId      = CreatedUserId;
                entity.SendMessageRuleId  = SendMessageRuleId;
                entity.SendMessageQueueId = sendMessageQueueId;
                entity.SendMessageType    = SendMessageType;

                ////////////////////////////////////////
                // 06 ~ 10

                entity.SendTime     = SendTime;
                entity.SendTitle    = SendTitle;
                entity.SendBody     = SendBody;
                entity.SendCustType = SendCustType;
                entity.RequestId    = RequestId;

                ////////////////////////////////////////
                // 11 ~ 15

                entity.ProviderName        = ProviderName;
                entity.MessageId           = null;
                entity.MessageStatus       = MessageStatus.Unknown;
                entity.MessageStatusString = entity.MessageStatus.ToString();
                entity.SenderAddress       = sendMessageRule.SenderAddress;

                ////////////////////////////////////////
                // 16 ~ 20

                // 20151106 Norman, Infobip 給的手機門號是 E164格式,但是沒有加上 "+",使用 【MobileUtil.GetE164PhoneNumber】會導致誤判
                var destinationAddress = DeliveryReport.MOBILE;
                if (!destinationAddress.StartsWith("+", StringComparison.OrdinalIgnoreCase))
                {
                    destinationAddress = "+" + destinationAddress;
                }

                entity.DestinationAddress           = MobileUtil.GetE164PhoneNumber(destinationAddress);
                entity.SendMessageResultCreatedTime = SendMessageResultCreatedTime;

                // TODO: 驗證 Every8d 回傳發送時間轉成 UTC 時間是否正確
                //entity.SentDate = Converter.ToDateTime(DeliveryReport.SENT_TIME, Converter.Every8d_SentTime).Value; // 2010/03/23 12:05:29
                //entity.DoneDate = Converter.ToDateTime(DeliveryReport.SENT_TIME, Converter.Every8d_SentTime).Value; // 2010/03/23 12:05:29,簡訊供應商沒有提供此資訊,因此設定與SentDate一致
                entity.SentDate = Converter.ToDateTime(DeliveryReport.SENT_TIME, Converter.Every8d_SentTime).Value.ToUniversalTime(); // 2010/03/23 12:05:29
                entity.DoneDate = Converter.ToDateTime(DeliveryReport.SENT_TIME, Converter.Every8d_SentTime).Value.ToUniversalTime(); // 2010/03/23 12:05:29,簡訊供應商沒有提供此資訊,因此設定與SentDate一致

                entity.DeliveryStatus = (DeliveryReportStatus)Convert.ToInt32(DeliveryReport.STATUS);

                ////////////////////////////////////////
                // 21 ~ 25

                entity.DeliveryStatusString = entity.DeliveryStatus.ToString();
                entity.Price = Convert.ToDecimal(DeliveryReport.COST);
                entity.DeliveryReportCreatedTime = DeliveryReport.CreatedTime;
                entity.MessageCost = (new MessageCostInfo(entity.SendBody, entity.DestinationAddress).MessageCost);
                entity.Delivered   = IsDelivered(entity.DeliveryStatus);

                ////////////////////////////////////////
                // 26
                entity.DestinationName           = DestinationName;
                entity.Region                    = MobileUtil.GetRegionName(entity.DestinationAddress);
                entity.CreatedTime               = DateTime.UtcNow;
                entity.RetryMaxTimes             = systemParameters.RetryMaxTimes;
                entity.RetryTotalTimes           = 0;
                entity.SendMessageRetryHistoryId = null;
                entity.Email = messageReceiver != null ? messageReceiver.Email : string.Empty;

                entity = sendMessageHistoryRepository.Insert(entity);

                // 如果發送失敗,就回補點數
                // 20151123 Norman, Eric 要求發送失敗不回補點數
                //this.tradeService.HandleSendMessageHistory(sendMessageRule, sendMessageQueue, entity);
            }

            // (6) 出統計表
            this.sendMessageStatisticService.AddOrUpdateSendMessageStatistic(sendMessageQueueId);
        }
        private void CreateSendMessageRetryHistory(SendMessageHistory sendMessageHistory)
        {
            int sendMessageHistoryId = sendMessageHistory.Id;

            var sendMessageRetryHistoryRepository = this.unitOfWork.Repository <SendMessageRetryHistory>();
            var sendMessageHistoryRepository      = this.unitOfWork.Repository <SendMessageHistory>();

            Infobip_SendMessageResult sendMessageResult = this.unitOfWork.Repository <Infobip_SendMessageResult>().Get(p => p.SourceTable == SourceTable.SendMessageHistory && p.SourceTableId == sendMessageHistoryId);

            if (sendMessageResult == null)
            {
                throw new Exception(string.Format("InfobipSmsProvider(smsProviderType = {0}),無法取得 Infobip_SendMessageResult(SendMessageHistoryId:{1})", smsProviderType.ToString(), sendMessageHistoryId));
            }

            string RequestId = sendMessageResult.ClientCorrelator;

            string ProviderName = this.Name;

            DateTime SendMessageResultCreatedTime = sendMessageResult.CreatedTime;

            List <Infobip_SendMessageResultItem> SendMessageResults = sendMessageResult.SendMessageResults.ToList();

            SendMessageRetryHistory entity = null;

            foreach (var SendMessageResult in SendMessageResults)
            {
                string DestinationName = SendMessageResult.DestinationName;

                entity = new SendMessageRetryHistory();

                ////////////////////////////////////////
                // 01 ~ 05

                entity.SendMessageHistoryId = sendMessageHistoryId;
                entity.RequestId            = RequestId;

                ////////////////////////////////////////
                // 11 ~ 15

                entity.ProviderName        = ProviderName;
                entity.MessageId           = SendMessageResult.MessageId;
                entity.MessageStatus       = (EFunTech.Sms.Schema.MessageStatus)((int)SendMessageResult.MessageStatus);
                entity.MessageStatusString = entity.MessageStatus.ToString();
                entity.SenderAddress       = SendMessageResult.SenderAddress;

                ////////////////////////////////////////
                // 16 ~ 20

                // 20151106 Norman, Infobip 給的手機門號是 E164格式,但是沒有加上 "+",使用 【MobileUtil.GetE164PhoneNumber】會導致誤判
                var destinationAddress = SendMessageResult.DestinationAddress;
                if (!destinationAddress.StartsWith("+", StringComparison.OrdinalIgnoreCase))
                {
                    destinationAddress = "+" + destinationAddress;
                }

                entity.DestinationAddress           = MobileUtil.GetE164PhoneNumber(destinationAddress);
                entity.SendMessageResultCreatedTime = SendMessageResultCreatedTime;
                entity.SentDate       = null;
                entity.DoneDate       = null;
                entity.DeliveryStatus = DeliveryReportStatus.MessageAccepted;

                ////////////////////////////////////////
                // 21 ~ 25

                entity.DeliveryStatusString = entity.DeliveryStatus.ToString();
                entity.Price = (decimal)0.0; // 尚未傳送完成
                entity.DeliveryReportCreatedTime = null;
                entity.Delivered = IsDelivered(entity.DeliveryStatus);

                ////////////////////////////////////////
                // 26
                entity.CreatedTime = DateTime.UtcNow;

                entity.Email = sendMessageHistory.Email;

                entity = sendMessageRetryHistoryRepository.Insert(entity);
            }

            // (6) 更新 SendMessageHistory
            if (entity != null)
            {
                sendMessageHistory.RetryTotalTimes        += 1;
                sendMessageHistory.SendMessageRetryHistory = entity;
                sendMessageHistoryRepository.Update(sendMessageHistory);
            }
        }
        private void UpdateDb_RetrySMS(SendMessageHistory sendMessageHistory, SendMessageResult sendMessageResult)
        {
            // 寫入對應的 SendMessageResult

            var infobip_SendMessageResult = new Infobip_SendMessageResult();

            infobip_SendMessageResult.SourceTable      = SourceTable.SendMessageHistory;
            infobip_SendMessageResult.SourceTableId    = sendMessageHistory.Id;
            infobip_SendMessageResult.ClientCorrelator = sendMessageResult.ClientCorrelator;
            infobip_SendMessageResult.CreatedTime      = DateTime.UtcNow; // 接收發送命令回傳值的時間
            infobip_SendMessageResult.Balance          = this.Balance;
            infobip_SendMessageResult = this.unitOfWork.Repository <Infobip_SendMessageResult>().Insert(infobip_SendMessageResult);

            var sendMessageResultItemRepository = this.unitOfWork.Repository <Infobip_SendMessageResultItem>();

            for (var i = 0; i < sendMessageResult.SendMessageResults.Length; i++)
            {
                // 一個 messageReceiver 對應一個 sendMessageResult
                //  尚未驗證,是否我傳送的 destinations 順序與 SendMessageResults 順序一致
                //  【目前假設是一致的】
                var sendMessageResultItem = sendMessageResult.SendMessageResults[i];

                // 20160715 Norman, 改成以下方式,用以解決以下問題
                // The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Infobip_DeliveryReport_dbo.Infobip_SendMessageResultItem_MessageId". The conflict occurred in database "EFunTechSms", table "dbo.Infobip_SendMessageResultItem", column 'MessageId'.

                var infobip_SendMessageResultItem = sendMessageResultItemRepository.Get(p => p.MessageId == sendMessageResultItem.MessageId);

                if (infobip_SendMessageResultItem == null)
                {
                    // insert

                    infobip_SendMessageResultItem = new Infobip_SendMessageResultItem();

                    infobip_SendMessageResultItem.MessageId           = sendMessageResultItem.MessageId;
                    infobip_SendMessageResultItem.MessageStatusString = sendMessageResultItem.MessageStatus;

                    EFunTech.Sms.Schema.MessageStatus MessageStatus = EFunTech.Sms.Schema.MessageStatus.Unknown;
                    Enum.TryParse <EFunTech.Sms.Schema.MessageStatus>(sendMessageResultItem.MessageStatus, out MessageStatus);
                    infobip_SendMessageResultItem.MessageStatus = MessageStatus;

                    infobip_SendMessageResultItem.SenderAddress      = sendMessageResultItem.SenderAddress;
                    infobip_SendMessageResultItem.DestinationAddress = sendMessageResultItem.DestinationAddress;
                    infobip_SendMessageResultItem.SendMessageResult  = infobip_SendMessageResult;
                    infobip_SendMessageResultItem.DestinationName    = sendMessageHistory.DestinationName;
                    infobip_SendMessageResultItem.Email = sendMessageHistory.Email;

                    infobip_SendMessageResultItem = sendMessageResultItemRepository.Insert(infobip_SendMessageResultItem);
                }
                else
                {
                    // update

                    //infobip_SendMessageResultItem.MessageId = sendMessageResultItem.MessageId; // update 不需要這個欄位
                    infobip_SendMessageResultItem.MessageStatusString = sendMessageResultItem.MessageStatus;

                    EFunTech.Sms.Schema.MessageStatus MessageStatus = EFunTech.Sms.Schema.MessageStatus.Unknown;
                    Enum.TryParse <EFunTech.Sms.Schema.MessageStatus>(sendMessageResultItem.MessageStatus, out MessageStatus);
                    infobip_SendMessageResultItem.MessageStatus = MessageStatus;

                    infobip_SendMessageResultItem.SenderAddress      = sendMessageResultItem.SenderAddress;
                    infobip_SendMessageResultItem.DestinationAddress = sendMessageResultItem.DestinationAddress;
                    infobip_SendMessageResultItem.SendMessageResult  = infobip_SendMessageResult;
                    infobip_SendMessageResultItem.DestinationName    = sendMessageHistory.DestinationName;
                    infobip_SendMessageResultItem.Email = sendMessageHistory.Email;

                    sendMessageResultItemRepository.Update(infobip_SendMessageResultItem);
                }
            }

            var infobip_ResourceReference = new Infobip_ResourceReference();

            infobip_ResourceReference.SendMessageResultId = infobip_SendMessageResult.Id;
            infobip_ResourceReference.ResourceURL         = sendMessageResult.ResourceRef.ResourceURL;
            infobip_ResourceReference = this.unitOfWork.Repository <Infobip_ResourceReference>().Insert(infobip_ResourceReference);

            CreateSendMessageRetryHistory(sendMessageHistory);

            // 在 Thread 中等待 30 秒,再寫入 DeliveryReportQueue
            var delayMilliseconds = (int)30 * 1000;

            FaFTaskFactory.StartNew(delayMilliseconds, () =>
            {
                using (var context = new ApplicationDbContext())
                {
                    var _unitOfWork = new UnitOfWork(context);
                    var _repository = _unitOfWork.Repository <DeliveryReportQueue>();

                    // 寫入簡訊派送結果等待取回序列
                    var deliveryReportQueue           = new DeliveryReportQueue();
                    deliveryReportQueue.SourceTableId = sendMessageHistory.Id;
                    deliveryReportQueue.SourceTable   = SourceTable.SendMessageHistory;
                    deliveryReportQueue.RequestId     = infobip_SendMessageResult.ClientCorrelator;
                    deliveryReportQueue.ProviderName  = this.Name;
                    deliveryReportQueue.CreatedTime   = DateTime.UtcNow;
                    deliveryReportQueue.SendMessageResultItemCount = infobip_SendMessageResult.SendMessageResults.Count;
                    deliveryReportQueue.DeliveryReportCount        = 0;
                    deliveryReportQueue = _repository.Insert(deliveryReportQueue);
                }
            });
        }
        /// <summary>
        /// 在 GetDeliveryReport 之後,更新大表 SendMessageHistory
        /// </summary>
        public void UpdateSendMessageHistory(int sendMessageQueueId)
        {
            var sendMessageRuleRepository    = this.unitOfWork.Repository <SendMessageRule>();
            var sendMessageQueueRepository   = this.unitOfWork.Repository <SendMessageQueue>();
            var sendMessageHistoryRepository = this.unitOfWork.Repository <SendMessageHistory>();

            SendMessageQueue sendMessageQueue = sendMessageQueueRepository.GetById(sendMessageQueueId);

            SendMessageRule sendMessageRule = sendMessageRuleRepository.GetById(sendMessageQueue.SendMessageRuleId);

            Infobip_SendMessageResult sendMessageResult = this.unitOfWork.Repository <Infobip_SendMessageResult>().Get(p => p.SourceTable == SourceTable.SendMessageQueue && p.SourceTableId == sendMessageQueueId);

            if (sendMessageResult == null)
            {
                throw new Exception(string.Format("InfobipSmsProvider(smsProviderType = {0}),無法取得 Infobip_SendMessageResult(SendMessageQueueId:{1})", smsProviderType.ToString(), sendMessageQueueId));
            }

            int?DepartmentId = null;

            if (sendMessageRule.CreatedUser.Department != null)
            {
                DepartmentId = sendMessageRule.CreatedUser.Department.Id;
            }
            string          CreatedUserId     = sendMessageRule.CreatedUser.Id;
            int             SendMessageRuleId = sendMessageQueue.SendMessageRuleId;
            SendMessageType SendMessageType   = sendMessageQueue.SendMessageType;

            DateTime     SendTime     = sendMessageQueue.SendTime;
            string       SendTitle    = sendMessageQueue.SendTitle;
            string       SendBody     = sendMessageQueue.SendBody;
            SendCustType SendCustType = sendMessageQueue.SendCustType;
            string       RequestId    = sendMessageResult.ClientCorrelator;

            string ProviderName = this.Name;

            DateTime SendMessageResultCreatedTime = sendMessageResult.CreatedTime;

            List <Infobip_SendMessageResultItem> SendMessageResults = sendMessageResult.SendMessageResults.ToList();

            foreach (var SendMessageResult in SendMessageResults)
            {
                Infobip_DeliveryReport DeliveryReport = SendMessageResult.DeliveryReport;
                if (DeliveryReport == null)
                {
                    continue;                         // 如果尚未取得派送報表,就忽略
                }
                SendMessageHistory entity = this.unitOfWork.Repository <SendMessageHistory>().Get(p => p.MessageId == SendMessageResult.MessageId);
                if (entity == null)
                {
                    continue;                 // 如果找不到對應 MessageId,就忽略
                }
                string DestinationName = SendMessageResult.DestinationName;

                ////////////////////////////////////////
                // 01 ~ 05

                entity.DepartmentId       = DepartmentId;
                entity.CreatedUserId      = CreatedUserId;
                entity.SendMessageRuleId  = SendMessageRuleId;
                entity.SendMessageQueueId = sendMessageQueueId;
                entity.SendMessageType    = SendMessageType;

                ////////////////////////////////////////
                // 06 ~ 10

                entity.SendTime     = SendTime;
                entity.SendTitle    = SendTitle;
                entity.SendBody     = SendBody;
                entity.SendCustType = SendCustType;
                entity.RequestId    = RequestId;

                ////////////////////////////////////////
                // 11 ~ 15

                entity.ProviderName        = ProviderName;
                entity.MessageId           = SendMessageResult.MessageId;
                entity.MessageStatus       = (EFunTech.Sms.Schema.MessageStatus)((int)SendMessageResult.MessageStatus);
                entity.MessageStatusString = entity.MessageStatus.ToString();
                entity.SenderAddress       = SendMessageResult.SenderAddress;

                ////////////////////////////////////////
                // 16 ~ 20

                // 20151106 Norman, Infobip 給的手機門號是 E164格式,但是沒有加上 "+",使用 【MobileUtil.GetE164PhoneNumber】會導致誤判
                var destinationAddress = SendMessageResult.DestinationAddress;
                if (!destinationAddress.StartsWith("+", StringComparison.OrdinalIgnoreCase))
                {
                    destinationAddress = "+" + destinationAddress;
                }

                entity.DestinationAddress           = MobileUtil.GetE164PhoneNumber(destinationAddress);
                entity.SendMessageResultCreatedTime = SendMessageResultCreatedTime;
                entity.SentDate       = DeliveryReport.SentDate;
                entity.DoneDate       = DeliveryReport.DoneDate;
                entity.DeliveryStatus = DeliveryReport.Status;

                ////////////////////////////////////////
                // 21 ~ 25

                entity.DeliveryStatusString = entity.DeliveryStatus.ToString();
                entity.Price = DeliveryReport.Price ?? (decimal)0.0;
                entity.DeliveryReportCreatedTime = DeliveryReport.CreatedTime;
                entity.MessageCost = (new MessageCostInfo(entity.SendBody, entity.DestinationAddress).MessageCost);
                entity.Delivered   = IsDelivered(entity.DeliveryStatus);

                ////////////////////////////////////////
                // 26
                entity.DestinationName = DestinationName;

                entity.Region = MobileUtil.GetRegionName(entity.DestinationAddress);

                sendMessageHistoryRepository.Update(entity);

                // 如果發送失敗,就回補點數
                // 20151123 Norman, Eric 要求發送失敗不回補點數
                //this.tradeService.HandleSendMessageHistory(sendMessageRule, sendMessageQueue, entity);
            }

            // (6) 出統計表
            this.sendMessageStatisticService.AddOrUpdateSendMessageStatistic(sendMessageQueueId);
        }
        /// <summary>
        /// 在 SendSMS 之後,建立大表 SendMessageHistory
        /// </summary>
        public void CreateSendMessageHistory(SendMessageQueue sendMessageQueue)
        {
            int sendMessageQueueId = sendMessageQueue.Id;

            var sendMessageRuleRepository    = this.unitOfWork.Repository <SendMessageRule>();
            var sendMessageQueueRepository   = this.unitOfWork.Repository <SendMessageQueue>();
            var sendMessageHistoryRepository = this.unitOfWork.Repository <SendMessageHistory>();

            SendMessageRule sendMessageRule = sendMessageRuleRepository.GetById(sendMessageQueue.SendMessageRuleId);

            Infobip_SendMessageResult sendMessageResult = this.unitOfWork.Repository <Infobip_SendMessageResult>().Get(p => p.SourceTable == SourceTable.SendMessageQueue && p.SourceTableId == sendMessageQueueId);

            if (sendMessageResult == null)
            {
                throw new Exception(string.Format("InfobipSmsProvider(smsProviderType = {0}),無法取得 Infobip_SendMessageResult(SendMessageQueueId:{1})", smsProviderType.ToString(), sendMessageQueueId));
            }

            int?DepartmentId = null;

            if (sendMessageRule.CreatedUser.Department != null)
            {
                DepartmentId = sendMessageRule.CreatedUser.Department.Id;
            }
            string          CreatedUserId     = sendMessageRule.CreatedUser.Id;
            int             SendMessageRuleId = sendMessageQueue.SendMessageRuleId;
            SendMessageType SendMessageType   = sendMessageQueue.SendMessageType;

            DateTime     SendTime     = sendMessageQueue.SendTime;
            string       SendTitle    = sendMessageQueue.SendTitle;
            string       SendBody     = sendMessageQueue.SendBody;
            SendCustType SendCustType = sendMessageQueue.SendCustType;
            string       RequestId    = sendMessageResult.ClientCorrelator;

            string ProviderName = this.Name;

            DateTime SendMessageResultCreatedTime = sendMessageResult.CreatedTime;

            List <Infobip_SendMessageResultItem> SendMessageResults = sendMessageResult.SendMessageResults.ToList();

            foreach (var SendMessageResult in SendMessageResults)
            {
                string DestinationName = SendMessageResult.DestinationName;

                var entity = new SendMessageHistory();

                ////////////////////////////////////////
                // 01 ~ 05

                entity.DepartmentId       = DepartmentId;
                entity.CreatedUserId      = CreatedUserId;
                entity.SendMessageRuleId  = SendMessageRuleId;
                entity.SendMessageQueueId = sendMessageQueueId;
                entity.SendMessageType    = SendMessageType;

                ////////////////////////////////////////
                // 06 ~ 10

                entity.SendTime     = SendTime;
                entity.SendTitle    = SendTitle;
                entity.SendBody     = SendBody;
                entity.SendCustType = SendCustType;
                entity.RequestId    = RequestId;

                ////////////////////////////////////////
                // 11 ~ 15

                entity.ProviderName        = ProviderName;
                entity.MessageId           = SendMessageResult.MessageId;
                entity.MessageStatus       = (EFunTech.Sms.Schema.MessageStatus)((int)SendMessageResult.MessageStatus);
                entity.MessageStatusString = entity.MessageStatus.ToString();
                entity.SenderAddress       = SendMessageResult.SenderAddress;

                ////////////////////////////////////////
                // 16 ~ 20

                // 20151106 Norman, Infobip 給的手機門號是 E164格式,但是沒有加上 "+",使用 【MobileUtil.GetE164PhoneNumber】會導致誤判
                var destinationAddress = SendMessageResult.DestinationAddress;
                if (!destinationAddress.StartsWith("+", StringComparison.OrdinalIgnoreCase))
                {
                    destinationAddress = "+" + destinationAddress;
                }

                entity.DestinationAddress           = MobileUtil.GetE164PhoneNumber(destinationAddress);
                entity.SendMessageResultCreatedTime = SendMessageResultCreatedTime;
                entity.SentDate       = null;
                entity.DoneDate       = null;
                entity.DeliveryStatus = DeliveryReportStatus.MessageAccepted;

                ////////////////////////////////////////
                // 21 ~ 25

                entity.DeliveryStatusString = entity.DeliveryStatus.ToString();
                entity.Price = (decimal)0.0; // 尚未傳送完成
                entity.DeliveryReportCreatedTime = null;
                entity.MessageCost = (new MessageCostInfo(entity.SendBody, entity.DestinationAddress).MessageCost);
                entity.Delivered   = IsDelivered(entity.DeliveryStatus);

                ////////////////////////////////////////
                // 26
                entity.DestinationName           = DestinationName;
                entity.Region                    = MobileUtil.GetRegionName(entity.DestinationAddress);
                entity.CreatedTime               = DateTime.UtcNow;
                entity.RetryMaxTimes             = systemParameters.RetryMaxTimes;
                entity.RetryTotalTimes           = 0;
                entity.SendMessageRetryHistoryId = null;
                entity.Email = SendMessageResult.Email;

                entity = sendMessageHistoryRepository.Insert(entity);
            }

            // (6) 出統計表
            this.sendMessageStatisticService.AddOrUpdateSendMessageStatistic(sendMessageQueueId);
        }