Exemplo n.º 1
0
        public void NotificationUsersWhoHaveOpenTask()
        {
            var openTasks = _taskRepository.GetAll().AsNoTracking().Where(t => t.State == TaskState.Open);

            foreach (var openTask in openTasks)
            {
                if (!openTask.AssignedPersonId.HasValue)
                {
                    continue;
                }

                var sendNotificationArgs = new SendNotificationJobArgs()
                {
                    NotificationTitle    = "You have an open task",
                    NotificationSeverity = NotificationSeverity.Info,
                    NotificationData     = new MessageNotificationData(openTask.Title),
                    TargetUserId         = openTask.AssignedPersonId.Value
                };

                _backgroundJobManager.Enqueue <SendNotificationJob, SendNotificationJobArgs>(sendNotificationArgs);
            }
        }
Exemplo n.º 2
0
        public virtual void HandleEvent(EntityCreatedEventData <ProcessTaskReport> eventData)
        {
            //获取所有的被提醒人
            var remindInfos = _tacticManager.GetRemindPersonsByReport(eventData.Entity.Id).Result;

            foreach (var remindInfo in remindInfos)
            {
                var timespan     = remindInfo.GetAvailableRemindTimeSpan();
                var remindPerson = remindInfo.Person;
                var openid       = remindPerson.GetPropertyValue <string>("OpenId");
                //先产生一条提醒记录
                var remindLog = new RemindLog()
                {
                    RemindType = "报工提醒",
                    Name       = remindPerson.Name,
                    TenantId   = eventData.Entity.TenantId,
                    Message    = eventData.Entity.ReportType.ToString(),
                };
                if (timespan.TotalMinutes > 0)
                {
                    remindLog.SetPropertyValue("errMsg", $"延迟{timespan.TotalMinutes.ToString("0")}分钟后运行");
                }
                var remindLogId = RemindLogManager.InsertAndGetIdAsync(remindLog).Result;

                var arg = new SendWeiXinMessageJobArgs()
                {
                    OpenId      = openid,
                    DataId      = eventData.Entity.Id,
                    RemindLogId = remindLogId,
                };


                _backgroundJobManager.Enqueue <SendReportWeiXinMessageJob, SendWeiXinMessageJobArgs>(arg, BackgroundJobPriority.Normal, timespan);
                //_backgroundJobManager.Enqueue<SendReportWeiXinMessageJob, SendWeiXinMessageJobArgs>(arg);
                //WeiXin.WeiXinHelper.SendTemplateMessage(openid, templateId, url, message);
            }
            //_backgroundJobManager.Enqueue<SendReportWeiXinMessageJob, int>(eventData.Entity.Id);
        }
        private void Publish(int?tenantId, string webhookName, object data, List <WebhookSubscription> webhookSubscriptions)
        {
            if (webhookSubscriptions.IsNullOrEmpty())
            {
                return;
            }

            var webhookInfo = SaveAndGetWebhook(tenantId, webhookName, data);

            foreach (var webhookSubscription in webhookSubscriptions)
            {
                _backgroundJobManager.Enqueue <WebhookSenderJob, WebhookSenderArgs>(new WebhookSenderArgs
                {
                    TenantId              = webhookSubscription.TenantId,
                    WebhookEventId        = webhookInfo.Id,
                    Data                  = webhookInfo.Data,
                    WebhookName           = webhookInfo.WebhookName,
                    WebhookSubscriptionId = webhookSubscription.Id,
                    Headers               = webhookSubscription.Headers,
                    Secret                = webhookSubscription.Secret,
                    WebhookUri            = webhookSubscription.WebhookUri
                });
            }
        }
        public virtual void Publish(
            string notificationName,
            NotificationData data             = null,
            EntityIdentifier entityIdentifier = null,
            NotificationSeverity severity     = NotificationSeverity.Info,
            UserIdentifier[] userIds          = null,
            UserIdentifier[] excludedUserIds  = null,
            int?[] tenantIds = null)
        {
            if (notificationName.IsNullOrEmpty())
            {
                throw new ArgumentException("NotificationName can not be null or whitespace!", nameof(notificationName));
            }

            if (!tenantIds.IsNullOrEmpty() && !userIds.IsNullOrEmpty())
            {
                throw new ArgumentException("tenantIds can be set only if userIds is not set!", nameof(tenantIds));
            }

            if (tenantIds.IsNullOrEmpty() && userIds.IsNullOrEmpty())
            {
                tenantIds = new[] { AbpSession.TenantId };
            }

            var notificationInfo = new NotificationInfo(_guidGenerator.Create())
            {
                NotificationName = notificationName,
                EntityTypeName   = entityIdentifier?.Type.FullName,
                EntityTypeAssemblyQualifiedName = entityIdentifier?.Type.AssemblyQualifiedName,
                EntityId        = entityIdentifier?.Id.ToJsonString(),
                Severity        = severity,
                UserIds         = userIds.IsNullOrEmpty() ? null : userIds.Select(uid => uid.ToUserIdentifierString()).JoinAsString(","),
                ExcludedUserIds = excludedUserIds.IsNullOrEmpty() ? null : excludedUserIds.Select(uid => uid.ToUserIdentifierString()).JoinAsString(","),
                TenantIds       = GetTenantIdsAsStr(tenantIds),
                Data            = data?.ToJsonString(),
                DataTypeName    = data?.GetType().AssemblyQualifiedName
            };

            _store.InsertNotification(notificationInfo);

            CurrentUnitOfWork.SaveChanges(); //To get Id of the notification

            if (userIds != null && userIds.Length <= MaxUserCountToDirectlyDistributeANotification)
            {
                //We can directly distribute the notification since there are not much receivers
                foreach (var notificationDistributorType in _notificationConfiguration.Distributers)
                {
                    using (var notificationDistributer = _iocResolver.ResolveAsDisposable <INotificationDistributer>(notificationDistributorType))
                    {
                        notificationDistributer.Object.Distribute(notificationInfo.Id);
                    }
                }
            }
            else
            {
                //We enqueue a background job since distributing may get a long time
                _backgroundJobManager.Enqueue <NotificationDistributionJob, NotificationDistributionJobArgs>(
                    new NotificationDistributionJobArgs(
                        notificationInfo.Id
                        )
                    );
            }
        }
Exemplo n.º 5
0
        public async void Run()
        {
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                var ex = (Exception)e.ExceptionObject;
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Environment.Exit(1);
            };

            Logger.Info("The worker is running...");

            //allowed to be running within the days of the week configured in app.config
            var runningDays = ConfigurationManager.AppSettings["RunningDays"];

            if (!string.IsNullOrEmpty(runningDays))
            {
                var days         = runningDays.Split(',');
                var dayOfTheWeek = Convert.ToInt32(DateTime.Now.DayOfWeek);
                if (!days.Any(x => x == dayOfTheWeek.ToString()))
                {
                    Environment.Exit(0);
                }
            }
            //get the full path for the data source file
            string sourceFileFullPath  = string.Empty;
            string sourceFileDirectory = string.Empty;

            var dataSourceFileDirectory = ConfigurationManager.AppSettings["DataSourceFileDirectory"];

            if (!string.IsNullOrEmpty(dataSourceFileDirectory))
            {
                sourceFileDirectory = dataSourceFileDirectory;
            }
            else
            {
                sourceFileDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "In");
            }

            DirectoryInfo directory = new DirectoryInfo(sourceFileDirectory);
            var           files     = directory.GetFiles().Where(x => x.Extension.Contains("xls") || x.Extension.Contains("xlsx"));

            if (!files.Any())
            {
                var    subject         = ConfigurationManager.AppSettings["Subject"];
                var    from            = ConfigurationManager.AppSettings["From"];
                var    recipients      = ConfigurationManager.AppSettings["Recipients"];
                var    tempateFullPath = string.Format(@"{0}\Template\{1}", AppDomain.CurrentDomain.BaseDirectory, "Template.html");
                string body            = await _fileService.ReadAllText(tempateFullPath);

                var splittedRecipients = recipients.Split(';');
                _emailService.SendEmail(from, splittedRecipients, subject, body, new string[] { });
                Environment.Exit(0);
            }

            var sourceFile = files.ToList().FirstOrDefault();

            sourceFileFullPath = sourceFile.FullName;

            _backgroundJobManager.Enqueue <LoadDataJob, LoadDataJobParameter>(new LoadDataJobParameter {
                FilePath = sourceFileFullPath
            });
            Logger.Info("The worker finished its task, background job is running...");
        }
Exemplo n.º 6
0
 /// <summary>
 /// Sends the mail.
 /// </summary>
 /// <param name="mail">Mail.</param>
 public void SendMail(EmailTask mail)
 {
     backgroundJobManager.Enqueue <EmailSenderJob, EmailTask>(mail);
 }
Exemplo n.º 7
0
        public async Task SendMessage(int id)
        {
            var data = await _mpMessageAppService.GetById(id);

            _backgroundJobManager.Enqueue <SendMessageImmediatelyJob, MpMessageDto>(data);
        }
Exemplo n.º 8
0
 public void HandleEvent(EntityCreatedEventData <Request> eventData)
 {
     _backgroundJobManager.Enqueue <RequestExecuteJob, int>(eventData.Entity.Id);
 }
Exemplo n.º 9
0
 /// <summary>
 /// 当入队(Enqueue)时,我们将42作为参数传递。IBackgroundJobManager将会实例化并使用42作为参数执行TestJob
 /// </summary>
 public void Test()
 {
     _backgroundJobManager.Enqueue <TestJob, int>(42);
 }
 public void EnqueueSharepointSyncJob()
 {
     _backgroundJobManager.Enqueue <SharePointSyncJob, int>(1);
 }
        public async Task <IResponseMessageBase> InCustomer(int mpid, IRequestMessageBase request)
        {
            Logger.Info($"开始接入客服 {request.FromUserName}");

            if (await IsAsking(mpid, request.FromUserName))
            {
                Logger.Info($"接入客服 正在会话中无需接入 {request.FromUserName}");
                return(request.CreateResponseMessage <ResponseMessageNoResponse>());
            }
            var text = await _customerServiceResponseTextAppService.GetCustomerDefaultResponseString(mpid);

            await SendCustomerText(mpid, request.FromUserName, text);

            //推送接入问候语
            if (await _customerServiceResponseTextAppService.CheckIsWorkingTime(mpid))
            {
                Logger.Info($"开始接入客服 工作时间 {request.FromUserName}");
                FansMessageDto msgDto = new FansMessageDto {
                    MpID = mpid, OpenID = request.FromUserName
                };

                _backgroundJobManager.Enqueue <CustomerQuestionJoin, FansMessageDto>(msgDto);//接入机制

                #region 原代码
                //                var faninfo = await GetFan(mpid, request.FromUserName);
                //                if (faninfo != null)
                //                {
                //                    Logger.Info($"开始调用客服接入机制");
                //#warning 此处需要增加自动接入客服的机制,目前全部丢人待接入列表

                //                    var customer = await _customerServiceOnlineAppService.GetAutoJoinCustomer(mpid);
                //                    if (customer == null)//微客服坐席已满,进入等待队列
                //                    {
                //                        Logger.Info($"进入等待队列,开始创建等待会话");
                //                        var conversation = await _customerServiceConversationAppService.Create(new CustomerServiceConversationDto()
                //                        {
                //                            FanOpenId = request.FromUserName,
                //                            FanId = faninfo.Id,
                //                            MpID = mpid,
                //                            State = (int)CustomerServiceConversationState.Wait,
                //                            HeadImgUrl = faninfo.HeadImgUrl,
                //                            NickName = faninfo.NickName
                //                        });
                //                        Logger.Info($"进入等待队列,创建等待会话成功,开始记录缓存");
                //                        await _cacheManager.GetCache(AppConsts.Cache_FanOpenId2Conversation).SetAsync(request.FromUserName, conversation);
                //                        await _cacheManager.GetCache(AppConsts.Cache_Kf_FanOpenId2Conversation).RemoveAsync(request.FromUserName);

                //                        #region 推送消息给客服???
                //                        Logger.Info($"进入等待队列,创建等待会话成功,记录缓存成功,推送等待人数");
                //                        WebClient wc = new WebClient();
                //                        await wc.UploadValuesTaskAsync(_signalrCustomerService.SetUnConnectNoticeUrl, null);
                //                        #endregion
                //                    }
                //                    else
                //                    {
                //                        Logger.Info($"分配到自动接入客服:{JsonConvert.SerializeObject(customer)}");
                //                        #region 创建客服会话
                //                        var conversation = await _customerServiceConversationAppService.Create(new CustomerServiceConversationDto()
                //                        {
                //                            FanOpenId = request.FromUserName,
                //                            FanId = faninfo.Id,
                //                            MpID = mpid,
                //                            State = (int)CustomerServiceConversationState.Asking,
                //                            HeadImgUrl = faninfo.HeadImgUrl,
                //                            NickName = faninfo.NickName,
                //                            CustomerId = customer.Id,
                //                            CustomerOpenId = customer.OpenID,
                //                            StartTalkTime = DateTime.Now,
                //                            LastModificationTime = DateTime.Now
                //                        });
                //                        await _cacheManager.GetCache(AppConsts.Cache_FanOpenId2Conversation).SetAsync(request.FromUserName, conversation);
                //                        await _cacheManager.GetCache(AppConsts.Cache_Kf_FanOpenId2Conversation).RemoveAsync(request.FromUserName);
                //                        #endregion
                //                    }
                //                }
                #endregion

                return(request.CreateResponseMessage <ResponseMessageNoResponse>());
            }
            else
            {
                Logger.Info($"开始接入客服 休息时间 {request.FromUserName}");
                return(request.CreateResponseMessage <ResponseMessageNoResponse>());
            }
        }
Exemplo n.º 12
0
        public async Task <ApiResult> Handle(CreateCompany request, CancellationToken cancellationToken)
        {
            var userUid = request.UserUid ?? throw new ArgumentNullException(nameof(request.UserUid));
            var company = request.Item ?? throw new ArgumentNullException(nameof(request.Item));

            var now = _dateTimeProvider.GetUtcNow();

            var companyUid  = Guid.NewGuid();
            var documentUid = Guid.NewGuid();

            var documentTypeRepository = _classifierRepositoryFactory.GetNamedOrDefaultService(Docs.ClassifierTypeCode.DocumentType);
            var documentType           = await documentTypeRepository.Get(Docs.ClassifierTypeCode.DocumentType, DocumentTypes.CompanyRegistrationRequest, cancellationToken);

            // todo: validate fields
            var metadata = await _fieldMetadataRepository.Search(new MetadataSearchRequest
            {
                EntityTypeCode = DocumentType.EntityTypeCode,
                EntityUid      = documentType.Uid.Value,
                // todo: check flags
                // IsSystem = false,
                IsActive   = true,
                SkipPaging = true
            }, cancellationToken);

            var manageFieldDataRequest = new ManageFieldDataRequest
            {
                EntityTypeCode = Document.TypeCode,
                EntityUid      = documentUid,
                Metadata       = metadata.Rows,
                Item           = company
            };

            // todo: move to Validator (?)
            var result = await _fieldDataRepository.Validate(manageFieldDataRequest, cancellationToken);

            if (result.Success == false)
            {
                return(result);
            }

            using (var scope = _unitOfWorkFactory.Create())
            {
                using (var db = _dbContextFactory.Create())
                {
                    // todo: валидация и ограничения

                    // company + todo: creation date
                    await db.GetTable <DbCompany>()
                    .Value(x => x.Uid, companyUid)
                    .Value(x => x.ConfigCode, company.ConfigCode ?? CompanyConfigCode.Company)
                    .Value(x => x.StatusCode, CompanyStatusCode.Draft)
                    .Value(x => x.Name, company.Name)
                    .InsertAsync(cancellationToken);

                    // user in company
                    await db.GetTable <DbCompanyUser>()
                    .Value(x => x.CompanyUid, companyUid)
                    .Value(x => x.UserUid, userUid)
                    .InsertAsync(cancellationToken);
                }

                // insert fields
                // todo: exclude db fields and sections
                await _fieldDataRepository.Insert(manageFieldDataRequest, cancellationToken);

                // todo: user roles

                // company registration request + todo: creation date
                var document = new Document
                {
                    Uid             = documentUid,
                    DocumentTypeUid = documentType.Uid.Value,
                    CompanyUid      = companyUid,
                    StatusCode      = DocumentStatusCode.Published,
                    Direction       = DocumentDirection.Outgoing,
                    DocumentDate    = now,
                    // Name = $"Company {company.Name} registration request"
                };

                await _documentRepository.Create(document, cancellationToken);

                // todo: audit log for company and for document
                await _auditLogService.Save(new AuditEvent
                {
                    EntityTypeCode = Company.EntityTypeCode,
                    EntityUid      = companyUid,
                    CompanyUid     = companyUid,
                    UserUid        = userUid,
                    CreatedAtUtc   = now,
                    MessageCode    = ExpressionHelper.GetFullName <CreateCompany.Resources>(x => x.CompanyCreated)
                }, cancellationToken);

                // todo: auto-approve request, notifications
                _jobManager.Enqueue <ISender>(x => x.Send(new RunAutomations
                {
                    EntityTypeCode = DocumentType.EntityTypeCode,
                    EntityTypeUid  = documentType.Uid.Value,
                    EntityUid      = documentUid
                }, cancellationToken));

                scope.Commit();

                return(new ApiResult {
                    Uid = companyUid
                });
            }
        }
Exemplo n.º 13
0
 public void HandleEvent(EntityChangedEventData <Entities.Column> eventData)
 {
     //清理该栏目
     _jobManager.Enqueue <CleanStaticFileJob, int?>(eventData.Entity.Id);
 }
Exemplo n.º 14
0
 /// <summary>
 /// 入队
 /// </summary>
 /// <param name="input"></param>
 /// <returns></returns>
 public void Enqueue(TaskActionJobArgs args)
 {
     _backgroundJobManager.Enqueue <TaskActionJob, TaskActionJobArgs>(args);
 }