Files
chatwoot/enterprise/app/services/onboarding/help_center_creation_service.rb
Shivam MishraandGitHub 3d20a7b049 feat: generate Help Center for Onboarding (#14370)
## Manually triggering help center generation

Open a Rails console (`bundle exec rails console`):

```ruby
account = Account.find(<ACCOUNT_ID>)
user    = account.users.first

# Optional: refresh brand info from the customer's website
domain = 'example.com'
result = WebsiteBrandingService.new("noreply@#{domain}").perform
account.update!(
  name: result[:title].presence || account.name,
  custom_attributes: account.custom_attributes.merge('website' => domain, 'brand_info' => result)
)

# Optional: wipe existing portals so a fresh one is created
account.portals.destroy_all

Onboarding::HelpCenterCreationService.new(account, user).perform
```

Sidekiq must be running — articles are written by
`Onboarding::HelpCenterArticleGenerationJob`. Avoid running on
production; generation calls the LLM provider.


### Generation flow (Happy Path) 

```mermaid
sequenceDiagram
    autonumber

    participant Kickoff as HelpCenterCreationService
    participant DB as DB
    participant GenJob as HelpCenterArticleGenerationJob
    participant Curator as HelpCenterCurator
    participant Firecrawl as Firecrawl
    participant CuratorLLM as Curation LLM
    participant Redis as Redis Progress
    participant WriterJob as HelpCenterArticleWriterJob
    participant Builder as HelpCenterArticleBuilder
    participant WriterLLM as Writer LLM
    participant Cable as ActionCable

    Kickoff->>DB: Create portal for account<br/>homepage_link=https://chatwoot.com
    Kickoff->>DB: Attach brand logo if available
    Kickoff->>GenJob: Enqueue generation job<br/>account_id, portal_id, user_id, generation_id

    GenJob->>Curator: Curate help center plan
    Curator->>Firecrawl: map https://chatwoot.com<br/>search: docs help support faq
    Firecrawl-->>Curator: Return discovered links
    Curator->>CuratorLLM: Select categories + article plans<br/>from discovered links only
    CuratorLLM-->>Curator: Return categories, articles, allowed_urls

    GenJob->>DB: Create portal categories
    GenJob->>GenJob: Stamp articles with category_id
    GenJob->>GenJob: Filter article URLs against allowed_urls
    GenJob->>GenJob: Drop articles with no category<br/>or no approved source URLs

    GenJob->>Redis: Start progress<br/>status=generating, total=N, finished=0

    loop For each approved article
      GenJob->>WriterJob: Enqueue writer job<br/>title, category_id, approved URLs
    end

    par Writer jobs run independently
      WriterJob->>Builder: Build article from approved URLs
      Builder->>Firecrawl: batch_scrape approved URLs
      Firecrawl-->>Builder: Return Markdown source pages
      Builder->>WriterLLM: Rewrite sources into one article
      WriterLLM-->>Builder: Return title, description, Markdown content
      Builder->>DB: Create draft portal article<br/>meta.source_urls
      WriterJob->>Redis: Increment finished count
      WriterJob->>Cable: Broadcast help_center.article_generated
    end

    WriterJob->>Redis: If finished >= total<br/>mark status=completed
    WriterJob->>Cable: Broadcast help_center.generation_completed
```

### Redis State Management

```mermaid
 stateDiagram-v2
    [*] --> active_pointer_set
    active_pointer_set --> generating: generation job creates valid plan
    active_pointer_set --> skipped: curation skipped/failed

    generating --> generating: each writer job increments finished
    generating --> completed: finished == total
    generating --> ignored_completion: generation_id superseded

    skipped --> [*]
    completed --> [*]
    ignored_completion --> [*]
```
2026-05-21 16:25:01 +05:30

130 lines
3.4 KiB
Ruby

class Onboarding::HelpCenterCreationService
DEFAULT_PORTAL_COLOR = '#1f93ff'.freeze
LOGO_MAX_DOWNLOAD_SIZE = 5.megabytes
def initialize(account, user)
@account = account
@user = user
end
def perform
existing = existing_portal
return reuse_existing_portal(existing) if existing
@account.portals.create!(portal_attributes).tap do |portal|
attach_brand_logo(portal)
enqueue_article_generation(portal)
end
end
private
def existing_portal
@account.portals.first
end
def reuse_existing_portal(portal)
Rails.logger.info "[HelpCenterCreation] Reusing existing portal #{portal.id} for account #{@account.id}"
portal
end
def portal_attributes
{
name: portal_name,
slug: generate_slug,
color: portal_color,
page_title: portal_name,
header_text: header_text,
homepage_link: homepage_link,
channel_web_widget_id: web_widget_channel_id,
config: { default_locale: locale, allowed_locales: [locale] }
}.compact
end
def brand_info
@brand_info ||= (@account.custom_attributes['brand_info'] || {}).deep_symbolize_keys
end
def portal_name
brand_info[:title].presence || @account.name
end
def portal_color
hex = brand_info[:colors]&.first&.dig(:hex)
hex.to_s.match?(/\A#\h{6}\z/) ? hex : DEFAULT_PORTAL_COLOR
end
def header_text
brand_info[:slogan].presence || brand_info[:description].presence
end
def homepage_link
with_scheme(custom_attributes_website.presence || brand_info[:domain].presence)
end
def with_scheme(raw)
return raw if raw.blank?
raw.match?(%r{\Ahttps?://}i) ? raw : "https://#{raw}"
end
def custom_attributes_website
@account.custom_attributes['website']
end
def enqueue_article_generation(portal)
return if homepage_link.blank?
generation_id = SecureRandom.uuid
Onboarding::HelpCenterArticleGenerationJob.perform_later(@account.id, portal.id, @user.id, generation_id)
rescue StandardError => e
Rails.logger.error "[HelpCenterCreation] Failed to enqueue article generation for account #{@account.id}: #{e.class} - #{e.message}"
end
def attach_brand_logo(portal)
logo_url = brand_logo_url
return if logo_url.blank?
SafeFetch.fetch(logo_url, max_bytes: LOGO_MAX_DOWNLOAD_SIZE, allowed_content_type_prefixes: ['image/']) do |logo_file|
portal.logo.attach(
io: logo_file.tempfile,
filename: logo_file.original_filename,
content_type: logo_file.content_type
)
end
rescue StandardError => e
Rails.logger.error "[HelpCenterCreation] Logo attachment failed for account #{@account.id}: #{e.class} - #{e.message}"
end
def brand_logo_url
Array(brand_info[:logos]).filter_map do |logo|
logo.is_a?(Hash) ? logo[:url] : logo
end.find(&:present?)
end
def web_widget_channel_id
@account.inboxes.find_by(channel_type: 'Channel::WebWidget')&.channel_id
end
def locale
@account.locale.presence || 'en'
end
def generate_slug
slug_candidates.find { |slug| !Portal.exists?(slug: slug) } || fallback_slug
end
def slug_candidates
base = @account.name.to_s.parameterize.presence
return [] if base.blank?
first_token = base.split('-').first
[base, first_token, "#{first_token}-docs", "#{first_token}-help"].uniq
end
def fallback_slug
base = @account.name.to_s.parameterize.presence || 'portal'
"#{base}-#{SecureRandom.hex(4)}"
end
end