Create Message (Backend Flow)

Overview

The createMessage endpoint powers all new messages sent through Hububb Chat — across Support Chat, Guest Chat etc. It creates and stores a new message inside a thread, updates thread state and search indexes, and handles outbound sends (e.g., WhatsApp, SMS) when applicable. This is the foundation for real-time communication, attention tracking, and audit consistency across the chat ecosystem.

Purpose

To:

  • Save a new message to Firestore under the correct thread

  • Update the thread’s last message, participants, and attention state

  • Send external messages (WhatsApp, SMS) when relevant

  • Maintain Elasticsearch indexing for search and unread filtering

Endpoint

POST /chat/threads/:id/messages

Authentication & Identity

  • Protected by DefaultAuthGuard – only authenticated users can post messages.

  • The actor (uid) is automatically derived from the authenticated user.

  • Audit data (actorId, ipAddress, userAgent) is passed for traceability.

  • Any existing participant in the thread can send messages.

  • The sender is automatically added to the thread’s participant list if not already present.

Request Body

Validated via CreateMessageDto

Field
Type
Description

body

string (required)

Text content of the message. Can be empty for structured (payment) messages.

source

string (optional)

Origin of the message (e.g., hububb, whatsapp, operations).

externalMessageId

string (optional)

Provider ID for messages received from external systems.

attachments

string[] (optional)

File identifiers or URLs.

messageId

string (optional)

Optional client-provided ID (else generated server-side).

type

string (optional)

Message category: message, whatsapp-message, sms-message, note.

paymentContent

object (optional)

Structured content for payment-related messages.

contentType

string (optional)

text (default), payment, or payment-processed.

Response

Returns the raw stored message document as created in Firestore. Author metadata is not embedded here — it’s resolved in subsequent GET endpoints.

Creation Flow

1

Message Assembly

The backend builds the message object:

  • Assigns or generates messageId

  • Sets threadId, body, authorId, and createdAt

  • Applies defaults: source = hububb, type = message, contentType = text

  • Attaches any externalMessageId, attachments, and paymentContent

2

Load Thread

Fetches the thread document to determine participants, message routing, and side effects.

3

Forwarding (Hububb Guest)

If the thread source is hububb-guest, the message is forwarded to the Hububb Guest platform. Failures here are logged but do not block local persistence.

4

Attention & Unread

Computes attention state:

  • All other participants (except the author) are added to needsAttention

  • A needsAttentionMap (keyed by userId) is updated for efficient filtering

5

Firestore Atomic Batch

Creates the message and updates the thread in one batch:

  • Saves message under threads/{threadId}/messages/{messageId}

  • Updates thread with:

    • lastMessage → new message

    • updatedAt → message timestamp

    • participantIds → includes the author

    • needsAttention and needsAttentionMap updated

    • lastWhatsappMessageSentAt (if message is WhatsApp)

6

ElasticSearch Index Update

Re-maps and syncs the thread document to Elasticsearch:

  • Keeps thread search results, sorting, and unread states consistent

  • Ensures “Recent,” “Unread,” and “Important” views reflect the new message immediately

7

Audit Logging

Records a success audit entry (if audit info exists) with:

  • actorId, IP, and user agent

  • targetType = message

  • metadata: threadId, type, source, and attachment info

If an error occurs, a failure audit entry is logged before the error is re-thrown.

8

Channel-Specific Sends

Depending on message type:

  • WhatsApp outbound:

    • Triggered when type = whatsapp-message and source = hububb

    • Finds reservation → guest phone → sends WhatsApp text

    • Updates message with external provider ID

    • Updates lastWhatsappMessageSentAt on the thread

  • SMS outbound:

    • Triggered when type = sms-message

    • Uses Twilio to send SMS → saves externalMessageId

  • Note:

    • Internal-only; no outbound sends or notifications

9

Return

Responds with the created message object.

Data Updates

Message Document

Stored under threads/{threadId}/messages/{messageId} with:

  • body, authorId, createdAt, attachments, type, source

  • externalMessageId (if outbound)

  • paymentContent (if applicable)

Thread Document

Updated with:

  • lastMessage (latest message object)

  • updatedAt (timestamp)

  • participantIds (merged with author)

  • needsAttention / needsAttentionMap (other users only)

  • lastWhatsappMessageSentAt (if applicable)

Elasticsearch

Thread index updated for:

  • Sorting (updatedAt)

  • Unread/attention filters

  • Full-text message content and metadata

External Side Effects

  • WhatsApp outbound: Sent through Hububb’s integration and saved with external ID.

  • SMS outbound: Sent via Twilio.

  • Hububb Guest forwarding: Message relayed to guest platform (errors non-blocking).

Error Handling

  • Core failures (Firestore batch or thread update): Throw an error and log failure audit.

  • Outbound send failures (WhatsApp/SMS): Logged separately; local save still succeeds.

  • Audit errors: Captured but do not block message persistence.

  • Inbound WhatsApp replies: Webhook creates messages with source = whatsapp and type whatsapp-message.

  • WhatsApp templates: Template sends call createMessage to store outgoing messages with provider IDs.

  • Automations & OTA messages: OTA workflows post messages using externalMessageId from OTA responses.

  • Support Chat (Operations): Uses createMessage internally; may also trigger notification emails.

Operations Notes

  • Messages you send mark the thread as needing attention from others, not yourself.

  • WhatsApp sends only occur for messages marked whatsapp-message and initiated from Hububb.

  • Guest WhatsApp replies automatically create messages with source = whatsapp.

  • SMS sending requires type = sms-message.

  • Support Chat messages follow the same rules — but may also trigger separate email notifications outside createMessage.

Last updated