Skip to content

Messenger and tickets

The messenger is where your users write to your team, with a help bot in front of it if your team set one up. The SDK reads and sends; you draw every screen:

  • The messenger’s home and list, from crm.messenger.
  • A conversation (its thread and composer), from a ConversationSession.
  • Tickets, from crm.tickets.
  • The unread badge, from crm.unread.

These are the places navigate is asked to open (.messenger, .newConversation, .conversation, .tickets, .ticket), from a tapped push, a link or your own menu (Initialise).

The messenger, the help center and in-app messages are switched on for the app on PurrCRM (the Name and features card on Settings › your app › General), and the SDK reads them as it starts. crm.appFeatures is the parts the app has on, as a CrmValue for your own ways in, such as a tab. crm.features is the parts the user signed in has, and crm.has(.messenger) asks for one.

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

crm.messenger.state is a CrmValue<MessengerState>. Load it as the screen opens:

MessengerViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
watching.append(crm.messenger.state.observe { [weak self] state in
self?.draw(state)
})
Task { await crm.messenger.load() }
}
private func draw(_ state: MessengerState) {
spinner.isHidden = !state.loading
if let failure = state.message { showFailure(failure) } // see "Failures"
guard let home = state.home else { return }
greeting.text = home.layout?.greeting
openConversations = home.open // the open ones, first
earlier = state.earlier // the rest, newest first
tableView.reloadData()
}
  • home (a MessengerHome) holds the open conversations (open), the unread count, when your team usually replies (reply), featured articles, the user’s tickets, the help bot’s opening, and layout: the home your team designed on Settings › your app › Messenger (a greeting with the user’s name, an intro, the team’s faces, and cards such as “Send us a message”, their conversations, their tickets, articles, a link or a status, in order). With no published home, layout is nil, and you draw a home of your own.
  • earlier is the conversations that are not open, newest first. When hasMore, await crm.messenger.loadMore() adds the next page as the user scrolls.
  • await crm.messenger.refresh() reads the home again (a pull to refresh). The SDK refreshes it itself when the app comes back and when a reply’s push arrives.
  • loading and message say a load is on its way, or why it failed.

replyLine(home.reply, Date()) answers what to say about a reply: .within(.minutes), .within(.hours), .within(.day), or .backAt(date, today:) while your team is away. teammatesOf(conversations) gives the first names of the teammates the user last heard from.

crm.unread is the messenger’s unread count, kept right by check-ins, pushes and read marks. Put it on whatever opens the messenger:

watching.append(crm.unread.observe { [weak self] unread in
self?.messagesItem.badgeValue = unread > 0 ? "\(unread)" : nil
})

Make a ConversationSession for the screen:

  • crm.conversation(id) for one that exists,
  • crm.newConversation() for a new one (the user’s first message, or an answer to the bot, starts it),
  • crm.ticketConversation(ticketId) for writing on a ticket.

Tell it when it is on screen, and close it when the screen goes:

ConversationViewController.swift
final class ConversationViewController: UIViewController {
private let chat: ConversationSession
private var watching: [CrmCancellable] = []
init(session: ConversationSession) {
chat = session
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) { fatalError() }
override func viewDidLoad() {
super.viewDidLoad()
watching.append(chat.state.observe { [weak self] state in self?.draw(state) })
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Task { await chat.onScreen(true) }
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
Task { await chat.onScreen(false) }
if isMovingFromParent { chat.close() }
}
@objc private func sendTapped() {
let words = composer.text ?? ""
Task { await chat.send(words) }
}
}

While it is on screen and the app is in front, the session reads the conversation, waits for new parts as they come, and marks staff’s parts read as they arrive; a push of a reply to it answers replyOnScreen. Off screen, it waits for nothing. close() stops it for good.

chat.state is a CrmValue<ChatState>:

FieldWhat it is
threadThe parts to draw, oldest first: the help bot’s opening for a new conversation, else parts.
outgoingMessages on their way (status .sending or .failed, with message), drawn after the thread until PurrCRM has them.
status, closedThe conversation’s state. Writing in a closed one opens it again.
assignee, replyWho has it, and when your team usually replies.
loading, loaded, messageReading it, and why that failed. await chat.retry() reads it again.
troubledThe wait for new parts is failing: show a quiet “reconnecting”.
goneIt is not the user’s any more, or the app is switched off.
sending, sendMessage, sentSerialA message on its way, why the last failed, and a count that moves with each message sent: clear your composer when it moves.
noteWhy the composer cannot send as it is: .tooLong, .tooManyPictures, .pictureTooLarge, .pictureWrongType, .waitForPictures.
picturesThe pictures added to what the user is writing.
ratingRequest, rating, ratingMessageA rating to ask for, and where it is.
awaiting, bot, botNote, botMessageThe help bot’s question waiting on an answer, and where the answer is.

Each Part has a kind (.message from the user, .reply from your team, .bot, .state for the conversation closing or opening again, .ratingRequest), an author (kind, name), text or blocks (Content blocks), attachments and createdAt. Your team’s notes and assignments never reach the phone. isBubble(part) says which are drawn as bubbles; the others are lines such as “Conversation closed”. placeParts(parts) says, for each part, whether it starts a run of one author’s bubbles, a new day, and whether it carries the run’s time.

await chat.send(text) sends the words with the pictures added, shows them at once in outgoing, and answers whether they went. The same words sent again after a failure go with the first try’s key, so PurrCRM never keeps them twice; await chat.resend(message.key) does it for a failed message you show a “Try again” on.

Every limit is checked before sending: 4000 characters (code points) a message, 4 pictures, 5 MB each. checkMessage(text, pictures) answers the same check for your composer as the user types.

Your app picks the pictures (PHPickerViewController on iOS 14, UIImagePickerController before), and hands the SDK the bytes:

chat.addPicture(jpegData, name: "photo.jpg")

It is checked (JPEG, PNG, GIF or WebP, at most 5 MB, at most 4) and uploaded at once. Each PendingPicture in state.pictures has a status (.uploading, .ready, .failed) and a progress from 0 to 1; chat.removePicture(picture.key) takes one out. Show your add-picture button only when state.home?.picturesAllowed (from crm.messenger.state) says your team allows pictures.

A picture in a part is an Attachment with a url that works until expiresAt; the pictures the user sent this time are also in state.shown, by attachment id, to draw from the phone.

If your team set up a help bot, it speaks first in a new conversation, before anything is sent: no empty conversation reaches your inbox if the user leaves. chat.state.value.thread is then its opening, and awaiting names the part waiting on an answer.

A bot part has part.bot, a BotPart: its kind (.says, .asks, .collects, .suggests, .handsOff, .resolves), its buttons, the field it collects (.text, .email, .orderRef), suggested articles, and reply when it hands over to your team. Draw the buttons, or a box for what it collects, and answer:

await chat.answerBot(part, button: button.id) // a button
await chat.answerBot(part, value: typed) // what it collects

An answer the bot would refuse is not sent: botNote says why (.notEmail, .notOrderRef, .notText, .refused); part.bot?.orderRef?.hint words an order number’s shape. Call chat.clearBotNote() as the user edits.

When your team asks for a rating, state.ratingRequest is the part to answer. await chat.rate(stars, remark:) sends 1 to 5 stars and an optional remark of at most 500 characters; rating goes .sending, then .sent (or .closed when the request is no longer open).

Tickets are the user’s support requests your team tracks, with a type, fields and a state:

let page = try await crm.tickets.list() // SupportTicketPage: items, newest first
let ticket = try await crm.tickets.get(id) // SupportTicket: fields, description, parts
let part = try await crm.tickets.write(id, text: "It arrived, thanks")

Draw the list (ref, title, state: .submitted, .inProgress, .waitingOnGuest, .resolved) and a ticket (its description blocks, its fields with hasValue, and its parts). To write on a ticket with pictures, use its conversation: crm.ticketConversation(ticket.id), as above. crm.uploadPicture(bytes, name:) uploads one for write(_:text:attachmentIds:) if you write without a session.

The SDK never shows a word to your users: every failure arrives as a CrmFailureMessage, in a state’s message field or from tellCrmFailure(error, attempt:) for a call that throws:

  • detail is PurrCRM‘s own sentence for the user when it gave one; show it when fromService.
  • Otherwise sentence is a CrmSentence to word in your app’s languages: .offline, .unavailable, .rateLimited, .signInAgain, .conversationGone, .ticketGone, .articleGone and the rest (API at a glance).
  • retry, after a rate limit, says when trying again is worth it (soon under a minute).

A call that throws throws a CrmFailure: CrmProblem (PurrCRM said no, with its status, code and detail), CrmAppUnavailable, CrmOffline (no answer; a send is not retried by itself) or CrmContractError.