Skip to content

Messenger, tickets and unread

The messenger is where your users write to your team, and your team answers. The SDK keeps its state, sends what the user writes, and waits for replies while a conversation is open; your app draws every screen: the home, the list of conversations, a conversation with its composer, the tickets, and the badge.

Your screenIts state
The badge on whatever opens the messengercrm.unread
The messenger’s homecrm.messenger.state (MessengerState)
A conversationcrm.conversation(id).state, crm.newConversation().state (ChatState)
The tickets, a ticketcrm.tickets().state, crm.ticket(id).state

Mount them where navigate sends PurrCRM‘s pages (Initialise): /messages, /messages/new, /messages/<id>, /messages/tickets and /messages/tickets/<id>.

crm.unread is the count of your team’s replies the user has not read, across every conversation. The SDK reads it as a user with the messenger signs in, as the page comes back to the front, when a reply’s push arrives, and at each check-in; it moves as the user reads.

crm.unread.subscribe((n) => {
badge.textContent = n > 0 ? String(n) : "";
badge.hidden = n === 0;
});
src/messenger/home.ts
import { hasMoreConversations, replyLine, teammatesOf } from "crm-sdk";
const stop = crm.messenger.state.subscribe((s) => {
if (s.loading && s.home === null) return drawSpinner();
if (s.message !== null) return drawFailure(s.message); // see "Failures" below
const home = s.home!;
drawGreeting(home.layout); // your team's greeting, cards and faces; null until they publish one
drawReplyTime(replyLine(home.reply, new Date())); // "usually replies in minutes", or "back at 9:00"
drawConversations(home.open, s.earlier); // ConversationSummary: preview, previewAuthor, unread, state
drawTickets(home.tickets);
drawArticles(home.articles); // featured
moreButton.hidden = !hasMoreConversations(s);
});
await crm.messenger.load(); // the home and the first page of conversations
moreButton.onclick = () => crm.messenger.loadMore(); // earlier conversations

MessengerState holds home (the home PurrCRM answered), earlier (conversations not on the home, newest first), unread, loading, loadingMore and message. crm.messenger.refresh() reads the home again, keeping what was known if PurrCRM cannot be reached; the SDK calls it itself at the moments the badge is read.

Your team designs the home on Settings › your app › Messenger (Set up the inbox and help center). home.layout carries it: greeting and intro (with the user’s name), the team’s faces and team, replyText and awayText, the cards in order (send, search_help, articles, conversations, tickets, link, status), whether a new conversation may be started (newConversation: always, when_none_open, never), whether pictures may be sent (attachments) and whether the help center shows (helpCenter). Draw a card of a kind you do not know as nothing. Until your team publishes a home, layout is null and the home is yours to design. teammatesOf(conversations) gives the first names of the teammates who wrote last, for a line such as “Ana and Tom are here”.

src/messenger/conversation.ts
import { placeParts, threadOf } from "crm-sdk";
const chat = crm.conversation(id); // or crm.newConversation()
const stop = chat.state.subscribe((s) => {
if (s.gone) return showNotFound(); // not there, not theirs, or the messenger is off
const parts = threadOf(s); // the help bot's opening for a new one, else the parts
const places = placeParts(parts); // where to put names, day lines and times
drawParts(parts, places);
drawOutgoing(s.outgoing); // sent, not yet in the conversation: "sending" or "failed"
drawComposer(s.pictures, s.note, s.sending);
connectionLine.hidden = !s.troubled; // the wait for replies is failing, and retrying
if (s.sentSerial !== lastSerial) { lastSerial = s.sentSerial; composer.value = ""; }
});
await chat.open();
// When the screen goes:
stop();
chat.close();

open() reads the conversation, then waits on PurrCRM for anything newer while the conversation is open and the page is in front: each wait lasts up to 25 seconds, and a failing one is tried again after 1, 2, 4… up to 30 seconds, with troubled set meanwhile. Hiding the page stops the wait; coming back reads the conversation again before it goes on. What your team wrote is marked read as it arrives, which moves the badge. close() stops it all. retry() reads it again after it could not be read (message says why).

parts are what the user is shown, oldest first: each a Part with kind (message, reply, bot, state, rating_request…), author (kind and name), text or blocks, attachments, and createdAt. A part of a kind you do not know is drawn as nothing. assignee is the teammate on it, and reply when to expect an answer.

const sent = await chat.send(composer.value); // whether PurrCRM has it

The message shows at once in outgoing with status sending. One that did not go stays there as failed, with a message saying why, and chat.resend(key) sends it again; when the first try went unanswered, it goes with the same Idempotency-Key, so PurrCRM keeps it once. sentSerial moves on each message PurrCRM took: clear your composer then.

A message is at most 4 000 characters, and four pictures. note says what the composer should tell the user: tooLong, tooManyPictures, pictureTooLarge, pictureWrongType, or waitForPictures (a picture is still uploading). sendMessage is why the last send failed.

A new conversation (crm.newConversation()) has no id until its first message, or the first answer to the help bot, starts it. isNewChat(state) says whether it is still new.

const input = document.querySelector<HTMLInputElement>("#picture")!;
input.onchange = () => {
for (const file of input.files ?? []) {
const upload = chat.addPicture(file, file.name);
upload?.progress.subscribe(({ sent, total }) => drawProgress(sent / total));
}
};

addPicture(file, name?, type?) takes any Blob, such as a File from an <input type="file"> or a paste, and uploads it at once: JPEG, PNG, GIF or WebP, at most 5 MB. It answers a CrmUpload (with progress, done and cancel()), or null when the picture cannot go (note says why). The pictures waiting are state.pictures, each with status (uploading, ready, failed), sent and total; draw one from its file with URL.createObjectURL. removePicture(key) takes one out, cancelling its upload. send sends the text with the pictures uploaded.

Pictures in the conversation are part.attachments, each with a url that expires (expiresAt); a picture the user sent from this page is in state.shown, by attachment id, to draw without fetching it back. Your team can turn pictures off for everyone (home.layout.attachments).

crm.uploadPicture(file) uploads one picture on its own, for a message you send some other way.

Where your team turns files on (Let contacts send files), home.layout.files is true. Offer files only then:

const input = document.querySelector<HTMLInputElement>("#file")!;
input.accept = ".pdf,.txt,.csv,.zip,.docx,.xlsx,.pptx";
input.multiple = true;
input.onchange = () => {
for (const file of input.files ?? []) chat.addFile(file, file.name);
};

addFile(file, name, type?) takes the type from the browser, else from the name. It checks the file as PurrCRM does (PDF, text, CSV, ZIP, Word, Excel or PowerPoint, up to 20 MB, a name of 1 to 200 characters) and uploads it at once. Pictures and files are four to a message together. A file waits in state.pictures beside the pictures, with isFile set. One that can’t go sets note: fileWrongType, fileTooLarge, fileBadName or tooManyFiles. A file whose refused is set is one PurrCRM would not take: say so, and the message waits until the user removes it with removePicture(key). One whose upload failed for the connection is left out of the message.

In the conversation, a part’s files are part.files, each an Attachment with its name, bytes and url. fileKindOf(contentType) and fileSizeOf(bytes) help you draw its icon and size. The url is a download: link to it with download, never show it in a frame.

state.typing is the teammate writing a reply now (an Author with their first name), or null. Draw their face and three dots as the conversation’s last entry while it is set. It is held for at most 8 seconds after they last typed, and cleared when their reply arrives or the page is hidden. It is not a new message: don’t scroll the reader or count it as unread.

state.seenSeq is the newest part your team has seen, and only goes up. seenUnder(parts, state.seenSeq) answers the id of the reader’s message to show Seen under, or null: only ever the last message, and only while it is the reader’s own.

There is nothing to set up: each wait for replies also asks for typing and seen. From a PurrCRM that doesn’t send them, nobody types and nothing is seen.

If your team set up a help bot, it speaks first in a new conversation, before anything is sent: state.opening holds what it says, and threadOf(state) draws it. No empty conversation reaches your team’s inbox if the user leaves.

A bot’s part (part.bot) may offer buttons, ask the user to type something it collects (text, email, or an order reference in your app’s format, orderRef), or suggest articles. state.awaiting is the id of the part it waits on; answer only that one:

await chat.answerBot(part, { button: button.id }); // a button
await chat.answerBot(part, { value: input.value }); // what it collects

What it collects is checked first: state.botNote says why an answer was not taken (notEmail, notOrderRef, notText, refused), and chat.clearBotNote() takes it back once the user types again. botSending and botMessage are the answer on its way and why it failed.

When your team asks the user to rate the conversation, ratingRequestOf(state) answers the request, or null. chat.rate(stars, remark) answers it once, with 1 to 5 stars and an optional remark of up to 500 characters; state.rating goes open, sending, sent, or closed when PurrCRM will not take one.

const list = crm.tickets(); // a CrmFetch: state, load(), close()
list.state.subscribe(({ value, loading, message }) => drawTickets(value?.items ?? [], loading, message));
await list.load();
const one = crm.ticket(id);
await one.load();
const ticket = one.state.value.value; // ref, title, state, fields, description, parts

Where your team lets users open tickets of a type themselves (Let contacts open tickets themselves), crm.ticketForms() answers the forms (TicketForms, with items). Show a New ticket button while there is at least one. NewTicketSession keeps a new ticket’s state for your form:

import { NewTicketSession } from "crm-sdk";
const draft = new NewTicketSession(crm, { forms: forms.items });
draft.state.subscribe((s) => drawForm(s)); // forms, form, draft, problems, sending, message, ticket
await draft.load(); // reads the forms, unless you passed them
draft.choose(form); // when there are several
draft.title("The parcel hasn't arrived");
draft.text("It was due on Monday.");
draft.setValue("order_number", { text: "NW-123456", boolean: null, date: "" });
await draft.send();

The draft is checked against PurrCRM‘s own limits before anything is sent: problems holds what is wrong by field (title, text, fields.<key>), shown once the user has tried to send. PurrCRM‘s refusal of one field is put under that field. When the ticket is made, ticket holds it: open it. message says why it wasn’t sent otherwise, such as a form that has since been taken away (ticketFormGone). close() when the screen goes.

To draw it all yourself, crm.openTicket(body, idempotencyKey?) sends a NewTicketBody.

A ticket’s conversation is written on through it: crm.ticketConversation(ticket) answers a conversation like any other, with the ticket’s parts already in it. A ticket’s state is submitted, in_progress, waiting_on_guest or resolved.

Where your team lets website visitors write before they sign in (Let people write before they sign in), call await crm.needReader() as your messenger opens with nobody signed in. It makes a visitor the first time, and answers whether there is now someone to write as. Never call it as the page loads. crm.reader says who the messenger reads as: a user, a visitor, or none. When a user signs in, the visitor is merged into them. crm.endVisitor() forgets the visitor, for example on a shared computer.

The messenger, the help center and in-app messages are switched on for the app in the Name and features card on Settings › your app › General, and the SDK reads them as it starts. crm.appFeatures is a Value of the parts the app has on, for your own ways in, such as a tab. crm.features is the parts the user signed in has, crm.has("messenger") asks for one, and crm.mayOpen(destination) whether a page may be opened.

To hold a part back from some users (behind a feature flag of your own), name the parts they may have in CrmSession.features: they get the parts the app has on and you name. Naming a part never switches on one the app has off.

A failure reaches your screen as a CrmMessage: sentence is the kind of sentence to say (offline, rateLimited, signInAgain, conversationGone, ticketGone, attachmentInvalid, botMovedOn…; crmSentences lists them all), detail is PurrCRM‘s own words, which you may show under yours, and retry says when to try again after too many requests. The words are yours, in your app’s languages.

const words: Record<CrmSentence, string> = {
offline: "You're offline. We'll keep trying.",
signInAgain: "Please sign in again.",
conversationGone: "This conversation is no longer available.",
// ...one for each
};

crm.inApp.testPhone is true for a user your team made a test phone. Show them a “Check for tests now” button in your settings that calls crm.checkNow(), and nothing to anyone else.