Messenger and tickets
The messenger is switched on for the app on PurrCRM (Messenger, in the Name and features card on Settings › your app › General), and the user must be signed in. Your team designs its home on Settings › your app › Messenger (Set up the inbox and help center).
What you draw: every screen of it. The messenger’s home, a conversation with its composer, the help bot’s buttons and boxes, the rating request, the picture and file pickers, the list of tickets, a ticket and a new ticket’s form, and the badge on whatever opens the messenger. The built-in screens draw all of these for you. The SDK reads and writes the conversations, waits for replies, keeps the unread count and tells you what to say when something fails.
The home
Section titled “The home”crm.messenger.state is a StateFlow<MessengerState>:
home(MessengerHome, null until read): the user’sopenconversations,tickets, featuredarticles, the team’sreplytime, thelayoutyour team published (greeting, intro, team faces, cards, whether new conversations may start, whether pictures are allowed), and the help bot’sopening;earlier: the conversations not on the home (the closed ones, and open ones older than the home’s three), newest first;hasMoreandcrm.messenger.loadMore()for the next page;unread,loading,loadingMore, andmessagewhen it could not be read.
Call crm.messenger.load() as your messenger screen opens: it reads the home and the first page of conversations. The SDK reads the home again by itself when a user signs in, when the app comes back to the front, and when a reply’s push arrives; crm.messenger.refresh() does it now.
replyLine(home.reply, now) answers what “We usually reply in…” says: ReplyWithin(within) (minutes, hours, a day) while your team is at work, or ReplyBackAt(at, today) while it is away. teammatesOf(conversations) names the teammates who wrote last, for the faces on your home.
Until your team publishes a home, layout is null: draw a home of your own, with a Send us a message button and the open conversations.
The badge
Section titled “The badge”crm.unread is a StateFlow<Int>: the replies from your team the user has not read, in every conversation. Put it on whatever opens the messenger:
val unread by crm.unread.collectAsState()BadgedBox(badge = { if (unread > 0) Badge { Text("$unread") } }) { IconButton(onClick = { if (crm.mayOpen(CrmDestination.messenger)) openMessenger() }) { Icon(Icons.Outlined.ChatBubbleOutline, contentDescription = "Messages") }}CrmHost.onUnreadChanged(before, after) hears every change too, on the main thread.
A conversation
Section titled “A conversation”crm.conversation(id) answers a ConversationSession for your conversation screen; crm.conversation() (an empty id) is a new one, which the user’s first message starts. Tell it when your screen shows and goes, and close it when you are done with it: it reads the conversation and waits for replies (a long poll) only while it is on screen and the app is in front.
@Composablefun ConversationScreen(crm: Crm, id: String) { val session = remember(id) { crm.conversation(id) } DisposableEffect(session) { session.onScreen(true) onDispose { session.onScreen(false) session.close() } } val state by session.state.collectAsState() val scope = rememberCoroutineScope() var draft by remember { mutableStateOf("") }
Column { LazyColumn(Modifier.weight(1f)) { items(state.thread.filter(::shownToGuest), key = { it.id }) { part -> PartBubble(part) } items(state.outgoing, key = { "out-${it.key}" }) { out -> OutgoingBubble(out, onRetry = { scope.launch { session.resend(out.key) } }) } } Composer( text = draft, onText = { draft = it }, sending = state.sending, onSend = { scope.launch { if (session.send(draft)) draft = "" } }, ) }}ConversationSessionState holds what the screen draws:
thread: the parts to draw, oldest first (for a new conversation, the help bot’s opening). EachParthas itskind(PartKind.Messagefrom the user,Replyfrom your team,Bot,Assignment,State,RatingRequest…), itsauthor(kind,name),textorblocks,attachmentsandcreatedAt.shownToGuest(part)says whether a part is one the user sees, andplaceParts(...)where to group bubbles and put day lines.outgoing: messages sent from this phone that PurrCRM does not have yet, eachSendingorFailed(with amessagesaying why). Draw them as the bubbles they will be.reply(the team’s reply time),assignee,statusandclosed.loading,loaded,gone(not there, not the user’s, or the messenger is off),messagewhen it could not be read, andtroubledwhile the wait for replies is failing and being asked again.session.retry()reads it again.sending,sendMessageandnotefor the composer.typing: the teammate writing a reply now (anAuthor), or null.seenSeq: the newest part your team has seen, which only goes up.
Calls, each a suspend function unless noted:
send(text): sends the words and the pictures uploaded; answers whether it went. A message that cannot go at all setsnote(ComposerNote.TooLong,TooManyPictures,WaitForPictures…) and is not sent. Messages are at most 4000 characters (counted as Unicode code points, as PurrCRM counts them).resend(key): sends a failed message again. PurrCRM keeps it once, even if the first try did land.markRead(): what is shown is marked read by itself while on screen; this does it now. Marking read movescrm.unread.onScreen(shown),close()andappForeground(front)are plain calls; the SDK callsappForegrounditself.
A reply’s push for a conversation on screen is already there and read: handlePushArrival says so with replyOnScreen (Push).
The help bot
Section titled “The help bot”If your team set up a help bot, it speaks first when the user starts a new conversation, before anything is sent: no empty conversation reaches your inbox if they leave. A new conversation’s opening holds what it says, and thread shows it at once.
A bot part has part.bot (BotPart): its kind (Says, Asks, Collects, Suggests, HandsOff, Resolves), its buttons, the field it collects (CollectField.Text, Email or OrderRef, with orderRef describing your order references), and suggested articles. The bot waits on the part whose id is state.awaiting. Draw its buttons, or a box for what it collects, and answer:
session.answerBot(part, button = button.id) // a buttonsession.answerBot(part, value = typedEmail) // what it collectsanswerBot answers whether it went. A value the bot cannot take sets botNote (NotEmail, NotOrderRef, NotText, Refused), which you show beside the box (part.bot?.orderRef?.hint says what an order reference looks like); clearBotNote() takes it back once the user types again. bot is BotPhase.Sending while an answer is on its way. In a new conversation, answering the opening’s question starts the conversation.
Pictures
Section titled “Pictures”The user picks pictures with your picker; the SDK checks and uploads them. With Android’s photo picker:
val pick = rememberLauncherForActivityResult( ActivityResultContracts.PickMultipleVisualMedia(maxItems = 4),) { uris -> scope.launch { for (uri in uris) { val bytes = withContext(Dispatchers.IO) { context.contentResolver.openInputStream(uri)?.use { it.readBytes() } } ?: continue val type = context.contentResolver.getType(uri).orEmpty() session.addPicture(bytes, name = uri.lastPathSegment ?: "picture", type = type) } }}addPicture uploads at once; state.pictures shows each PendingPicture with its status (Uploading, Ready, Failed) and its upload for progress, and removePicture(key) takes one out. The next send carries those that are ready. Pictures are JPEG, PNG, GIF or WebP, at most 5 MiB each and four to a message; one that breaks a rule sets note (PictureTooLarge, PictureWrongType, TooManyPictures). state.shown keeps the bytes of pictures sent from this phone, so you can draw them without downloading. Hide your add-picture button when crm.messenger.state.value.home?.picturesAllowed is false: your team turned pictures off.
For a message you send yourself (a ticket’s reply, say), crm.uploadPicture(bytes, contentType, name) answers a CrmUpload: its state (progress, attachmentId, problem, failure), cancel(), and await() for the attachment id.
Where your team turns files on (Let contacts send files), crm.messenger.state.value.home?.filesAllowed is true. Show an add-file button only then, and pick with the system’s document picker, asking for the types PurrCRM takes (FILE_TYPES):
val pickFiles = rememberLauncherForActivityResult( ActivityResultContracts.OpenMultipleDocuments(),) { uris -> scope.launch { for (uri in uris) { val bytes = withContext(Dispatchers.IO) { context.contentResolver.openInputStream(uri)?.use { it.readBytes() } } ?: continue val name = context.contentResolver .query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null) ?.use { if (it.moveToFirst()) it.getString(0) else null } ?: uri.lastPathSegment ?: "file" session.addFile(bytes, name = name, type = context.contentResolver.getType(uri).orEmpty()) } }}
// On your add-file button:pickFiles.launch(FILE_TYPES.toTypedArray())addFile 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, with its name. Pictures and files are four to a message together. A file waits in state.pictures like a picture, with isFile true. One that can’t go sets note: FileWrongType, FileTooLarge, FileBadName or TooManyFiles. A pending file whose refused is true is one PurrCRM would not take: say so, and the message waits until the user removes it. One whose upload failed for the connection can be removed and tried again.
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: open it in the phone’s browser or downloader (Intent.ACTION_VIEW), never in a web view.
Typing and Seen
Section titled “Typing and Seen”While state.typing is not null, draw the teammate’s face and three dots as the conversation’s last entry. It is held for at most 8 seconds after they last typed, and cleared when their reply arrives or the app goes to the background. It is not a new message: don’t move the user’s place or count it as unread.
seenUnder(parts, state.seenSeq) answers the id of the user’s message to show Seen under, or null. It is only ever the last message, and only while it is the user’s own.
From a PurrCRM that doesn’t send them, nobody types and nothing is seen.
Ratings
Section titled “Ratings”When your team closes a conversation and asks for a rating, state.ratingRequest is the part to draw it under. Answer once:
session.rate(stars = 5, remark = "Quick and kind") // remark optional, at most 500 charactersstate.rating goes Open, Sending, Sent; Closed when PurrCRM no longer takes one, and the prompt goes. ratingMessage says why one failed.
Tickets
Section titled “Tickets”crm.tickets is the user’s tickets:
crm.tickets.load()reads the list, andcrm.tickets.list.state(Fetched<SupportTicketPage>:value,loading,message) holds it. PurrCRM sends the list whole; there is no next page. Read it again when the user comes back from a ticket.crm.tickets.ticket(id)is aFetcher<SupportTicket>toload()and observe;crm.tickets.get(id)reads one now, and throws theCrmFailureit ends with. ASupportTickethas itsref,title,type,state(Submitted,InProgress,WaitingOnGuest,Resolved),description(blocks),fields, and its conversation’sparts.crm.tickets.write(id, text, attachmentIds)replies on it, and answersTicketWrite.Sent(the part),TicketWrite.Refused(it breaks a rule, checked before sending) orTicketWrite.Failed(with theidempotencyKeyto send it again with, so it is kept once).
New tickets
Section titled “New tickets”Where your team lets users open tickets of a type themselves (Let contacts open tickets themselves), crm.tickets.forms is a Fetcher<TicketForms> of the forms they can fill in. Show a New ticket button while its items is not empty. crm.tickets.newTicket(forms) answers a NewTicket for your form’s screen:
val newTicket = crm.tickets.newTicket(forms.items)newTicket.choose(form) // when there are severalnewTicket.title("The parcel hasn't arrived")newTicket.text("It was due on Monday.")newTicket.setValue("order_number", TicketFieldValue(text = "NW-123456"))scope.launch { newTicket.send() }Its state (NewTicketState) has the forms, the chosen form, the draft, and problems by field (title, text, fields.<key>), shown once the user has tried to send. The draft is checked against PurrCRM‘s own limits before anything is sent, and 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 (CrmSentence.TicketFormGone). Call close() when the screen goes.
To show a ticket’s conversation as a live conversation, crm.messenger.conversation(ticketId = id, parts = ticket.parts) answers a ConversationSession written on through the ticket.
When something fails
Section titled “When something fails”Each state that can fail carries a CrmMessage instead of an exception: detail is PurrCRM‘s own sentence for the user, which wins when it is there (fromService), and sentence (CrmSentence.Offline, RateLimited, ConversationGone, SignInAgain…) is the kind of thing to say in your own words when it is not. retry says when trying again is worth it, after a rate limit. Your strings stay yours, in your languages.
Routes
Section titled “Routes”The links PurrCRM writes, in a reply, a push or an article, name these pages, which reach your navigate hook as a CrmDestination (Initialise):
| Path | CrmPlace |
|---|---|
/messages | Messenger |
/messages/new | NewConversation |
/messages/<id> | Conversation |
/messages/tickets, /messages/tickets/<id> | Tickets, Ticket |
/help, /help/collections/<slug>, /help/<slug> | HelpCenter, Collection, Article |
/messages/preferences | Preferences |
/messages/show/<id> | Message: an in-app message, shown through crm.inApp.next |
Keep your own paths clear of them. CrmLinks.parse(link) reads one into a CrmDestination.
A test phone
Section titled “A test phone”crm.testPhone says whether PurrCRM treats this phone as one of the app’s test phones, which get test messages at once. Show such a user a “Check for tests now” row that calls crm.checkNow().