Reuse documents and post attachments
Reuse an existing file by passing its source document ID. No download or re-upload is needed. The source must belong to the same company and be accessible to the current user.
These examples use an authenticated sdk from Getting started and IDs selected by your app. Kotlin calls run in a coroutine; React hooks run inside the configured providers.
1. Find a document in Solibo Home
Search the company library and let the user select a file:
val page = sdk.api.documents.listDocument(
companyId = companyId,
search = "House rules",
count = 20,
).body()
val files = page.items.filter { it.isDirectory != true }
files.forEach { println("${it.id}: ${it.fileName}") }
const page = await sdk.api.documents.listDocument({
companyId,
search: 'House rules',
count: 20,
})
const files = (page.items ?? []).filter(file => !file.isDirectory)
files.forEach(file => console.log(file.id, file.fileName))
With a search string, the results are ranked: matches in the file name come first, then folder and content matches. Each result’s searchMatch lists where the words were found (TITLE, FOLDER, CONTENT, strongest first) and, when the content matched, up to two passages as snippet. Render each passage’s parts in order and emphasise the ones with highlighted: true.
Use the selected file’s id as sourceDocumentId. If it is already a reference, use sourceDocumentId from its metadata instead.
2. Or select an attachment from a post
Read the post’s documents collection. Its cover image is separate (pictureDocument / pictureDocumentId). Here attachmentId is the attachment selected by the user.
val post = sdk.api.homepage.getHomepageFeedPost(
companyId = companyId,
postId = sourcePostId,
).body()
val attachment = post.documents.orEmpty().firstOrNull { it.id == attachmentId }
?: error("Selected attachment is not available")
val sourceDocumentId = attachment.sourceDocumentId ?: attachment.id
const post = await sdk.api.homepage.getHomepageFeedPost({
companyId,
postId: sourcePostId,
})
const attachment = (post.documents ?? []).find(file => file.id === attachmentId)
if (!attachment) throw new Error('Selected attachment is not available')
const sourceDocumentId = attachment.sourceDocumentId ?? attachment.id
Use attachment.id to manage this attachment and sourceDocumentId to reuse the file elsewhere.
3. Attach it to an existing post
Create a reference with type = POST and the destination post ID as belongsToId:
import no.solibo.oss.sdk.api.gen.models.CreateDocumentReferenceCommand
import no.solibo.oss.sdk.api.gen.models.DocumentType
val reference = sdk.api.documents.createDocumentReference(
companyId = companyId,
documentId = sourceDocumentId,
createDocumentReferenceCommand = CreateDocumentReferenceCommand(
type = DocumentType.POST,
belongsToId = targetPostId,
),
).body()
println("New attachment: ${reference.id}")
const reference = await sdk.api.documents.createDocumentReference({
companyId,
documentId: sourceDocumentId,
input: { type: 'POST', belongsToId: targetPostId },
})
console.log('New attachment:', reference.id)
In React, use useCreateDocumentReference() and refresh any additional destination views you cache. Direct SDK calls do not refresh query caches.
For a conversation, set visibility: 'INTERNAL' to keep the attachment in the internal (board-only) thread. Uploads to a conversation take the same option.
4. Create a post with an attachment and an inline link
Create the post and its document references together. The rules slot connects the inline link to inlineDocuments.rules; attachments adds the file to the attachment list.
import no.solibo.oss.sdk.api.DocumentInput
import no.solibo.oss.sdk.api.inlineDocumentLinkSlot
import no.solibo.oss.sdk.api.gen.models.CreatePostCommand
val result = sdk.api.integratedDocuments.createHomepagePost(
companyId = companyId,
command = CreatePostCommand(
title = "House rules",
content = "<p>Please read " + inlineDocumentLinkSlot("rules", "the house rules") + "</p>",
),
attachments = listOf(DocumentInput.Existing(sourceDocumentId)),
inlineDocuments = mapOf("rules" to DocumentInput.Existing(sourceDocumentId)),
)
println("Created post ${result.resource.id}")
import { inlineDocumentLinkSlot, type Id } from '@solibo/solibo-sdk'
import { useCreateHomepagePostWithDocuments } from '@solibo/solibo-react'
// Call this hook from a React component, then call publish() from its submit handler.
function usePublishHouseRules(companyId: Id, sourceDocumentId: Id) {
const createPost = useCreateHomepagePostWithDocuments()
return () => createPost.mutateAsync({
companyId,
command: {
title: 'House rules',
content: '<p>Please read ' + inlineDocumentLinkSlot('rules', 'the house rules') + '</p>',
},
attachments: [{ sourceDocumentId }],
inlineDocuments: { rules: { sourceDocumentId } },
})
}
For an inline image, use inlineDocumentImageSlot("entrance", "Building entrance") and supply an image under the same entrance key. For a cover image, pass image separately. Mix reused files with new uploads using DocumentInput.Upload("minutes.pdf", bytes, "application/pdf") in Kotlin, or { file } / { fileName: "minutes.pdf", bytes, contentType: "application/pdf" } in TypeScript.
The pasted images that the solibo-ui Editor reports in onInlineImagesChange can be passed as inlineDocuments as they are: a list of { slot, file } holds exactly the slots in the body. On an update, the server removes the inline images the new body no longer shows; list only removed attachments in removeDocumentIds.
When a save fails because the connection dropped, Solibo Home may have saved it. integratedRetryKey(error) from @solibo/solibo-query gives the idempotency key to send the same request again with, so it is not saved twice. In React, useIntegratedRetry() keeps that key for the very same request: run({ request, files, context }, (idempotencyKey) => mutateAsync({ ..., idempotencyKey })), with request from integratedRequestFingerprint(...) and the files compared by identity. A changed field, another file or a successful save forgets the key.
Outside React, use createHomepagePostWithDocumentsMutationOptions(sdk, queryClient) from @solibo/solibo-query. See Usage examples for standalone uploads.
Conversation messages work the same way: createConversationMessage(...) / useCreateConversationMessageWithDocuments() for a message the participants see, and createConversationInternalMessage(...) / useCreateConversationInternalMessageWithDocuments() (command is a CreateInternalMessageCommand) for an internal message, whose attachments and inline images are internal: only the internal chat shows them.
On a public conversation’s open page, where the writer is not signed in, upload each pasted image with usePublicUploadDocumentToConversation() (it resolves to { documentId }) and embed it as <img data-solibo-document-id="{documentId}">, or let useCreatePublicConversationMessageWithInlineImages() do both from inlineDocumentImageSlot markers and inlineImages: { [slot]: File }. See Documents in the API reference.
5. Download an image at the size you need
Request transformations when resolving the signed URL. This example preserves the full image at a maximum width of 1002 pixels and requests WebP output.
val imageUrl = sdk.api.documents.showDocument(
companyId = companyId,
documentId = sourceDocumentId,
redirect = false,
size = "1002xauto",
format = "webp",
quality = "85",
).body().url
const { url: imageUrl } = await sdk.api.documents.showDocument({
companyId,
documentId: sourceDocumentId,
redirect: false,
size: '1002xauto',
format: 'webp',
quality: '85',
})
For a cached URL, pass the same options to useGetDocumentURL(params) or getDocumentURLQueryOptions(sdk, params). Public pages use usePublicDocumentURL(params) or publicGetDocumentURLQueryOptions(sdk, params). Public conversations use usePublicConversationDocumentURL(params) or publicConversationDocumentURLQueryOptions(sdk, params) with companySlug, conversationId, and documentId. Signed URLs currently expire after an hour, so keep the query’s staleTime well below that.
The private and public URL hooks send the lookups a screen makes together as one request per company and rendition, so render one hook per picture. To sign a list you already hold, use useDocumentURLs(params) or usePublicDocumentURLs(params) (documentURLsQueryOptions and publicDocumentURLsQueryOptions) with up to 100 documentIds and autoPaginate: true.
Omit transformation options to get the original file. All option values are strings.
Image options
| Option | Use |
|---|---|
size | 1002x488, 1002xauto, or autox488. Dimensions: 1–8192; at most 32 million pixels. auto requires fit: 'inside'. |
fit | inside (default), cover (crop), contain (pad), fill (stretch), or outside. All except inside require two numeric dimensions. |
position | center (default), an edge such as top, or a corner such as top-left. Non-center positions require cover or contain. |
format | auto (default), jpeg, png, webp, or avif. |
quality | '1'–'100', default '82'; applies to JPEG, WebP, and AVIF. |
upscale | 'false' (default) or 'true'. Some fits fail if enlargement is required and disabled. |
background | Six or eight hex digits; default 'ffffff'. Use '00000000' for transparent padding. |
disposition | INLINE or ATTACHMENT (DownloadDisposition): whether the signed URL shows the file or downloads it under its file name. Every read that signs a file URL takes it, not only images. |
For a crop, use size: '1002x488', fit: 'cover'. For a transparent square, use size: '640x640', fit: 'contain', background: '00000000', format: 'png'.
Request a new signed URL when changing options. Invalid options return HTTP 400; image-dependent failures can return HTTP 422 at download time, even if resolving the URL succeeded. For non-images, size alone is ignored; other image options are rejected.
6. Rotate or crop an image
A document’s transform says how clients show an image without changing the uploaded original: rotation is a clockwise quarter turn (0, 90, 180 or 270) after the image’s EXIF orientation, and the optional crop selects a region of the rotated image as fractions from 0 to 1. Only image documents take one, and a document reference has its own, independent of its source. Clients apply it when they show document.transform.
import no.solibo.oss.sdk.api.gen.models.DocumentCrop
import no.solibo.oss.sdk.api.gen.models.DocumentTransform
import no.solibo.oss.sdk.api.gen.models.UpdateDocumentCommand
val transform = DocumentTransform(
rotation = 90,
crop = DocumentCrop(x = 0.1, y = 0.0, width = 0.8, height = 1.0),
)
// On an existing document; DocumentTransform(rotation = 0) clears it.
sdk.api.documents.updateDocument(companyId, documentId, UpdateDocumentCommand(transform))
// On upload: the SDK sends it as the upload's base64url `transform` parameter.
sdk.api.documents.uploadDocument(
UploadDocumentRequest(
companyId = companyId,
documentType = DocumentType.POST,
fileName = "entrance.jpg",
bytes = bytes,
transform = transform,
),
)
// In an integrated mutation, on an upload or a reference.
DocumentInput.Upload("entrance.jpg", bytes, "image/jpeg", transform = transform)
DocumentInput.Existing(sourceDocumentId, transform = transform)
import { useUpdateDocument, useUploadDocument } from '@solibo/solibo-react'
const transform = { rotation: 90, crop: { x: 0.1, y: 0, width: 0.8, height: 1 } }
// On an existing document; { rotation: 0 } clears it.
useUpdateDocument().mutate({ companyId, documentId, transform })
// On upload, with useUploadDocument or useUploadDocumentBelongsTo.
useUploadDocument().mutate({ companyId, documentType, file, transform })
// In integrated mutations and document references.
const attachments = [{ file, transform }, { sourceDocumentId, transform }]
The SDK encodes the transform of a body-less upload for you. Calling createDocumentOperation or createDocumentBelongsToOperation yourself, pass encodeDocumentTransform(transform) from @solibo/solibo-sdk/documents/operations as transform. In solibo-query, toDocumentTransform turns the plain object into the SDK model.
Store document IDs, display resolved URLs
Save and edit content, which keeps document markers. Display renderedContent, which resolves those markers into URLs. Do not save signed URLs as document references or replace editable content with rendered HTML.
@solibo/solibo-query reads and cleans that markup without a DOM:
| Helper | Does |
|---|---|
inlineImageSources(renderedContent) | A Map from each saved inline image’s document id to its signed src, so an editor that keeps content can show the images. |
withoutPendingInlineImages(html) | The body without the slots still waiting for an upload (data-solibo-document-slot, an image or a link with its text), such as those in a restored draft whose files are gone. |
hasPendingInlineImages(html) | Whether a body still holds such slots. |
Show a document
useDocumentURL({ companyId, documentId, source, visible, ...imageOptions }) from @solibo/solibo-react signs the URL from the endpoint that fits source:
source | Endpoint |
|---|---|
{ kind: 'company' } (default) | A signed-in reader’s company document, batched with the lookups made together. |
{ kind: 'public' } | A document the company publishes, read without signing in. |
{ kind: 'homepagePost', postId } | A file of a homepage post or practical information on the open homepage. |
{ kind: 'publicConversation', companySlug, conversationId } | A file of a public conversation. |
The URL is used for 45 minutes (DOCUMENT_URL_STALE_TIME), below its hour-long lifetime. Pass visible (whether the document is on screen): a URL that went stale while hidden is signed again when it is shown. A 403 or 404 is not retried.
A file the SDK returns as bytes (Base64ByteArray, such as an invoice PDF) becomes a Blob with byteArrayToBlob(bytes, contentType) from @solibo/solibo-query, or an object URL that is revoked for you with useByteArrayUrl(bytes, contentType) from @solibo/solibo-react.
The backend reports no upload size limit in its contract, so the SDK has no constant for one.
Resources that own documents
Every resource that owns documents takes them through its own create, update and delete command, which calls the backend’s integrated (atomic) route for it. Callers never make nested document calls; the document commands are for documents themselves.
The integrated resource mutations work this way: posts, practical information, comments, newsletters, neighborhood posts and groups, conversations with their initial message, conversation messages and internal messages (see integrated resource mutations). These owners take documents in their own *WithDocuments command, which calls the owner’s integrated route:
| Owner | Document type | Query factory | React hook | Result |
|---|---|---|---|---|
| Settlement | SETTLEMENT | createSettlementWithDocumentsMutationOptions, updateSettlementWithDocumentsMutationOptions | useCreateSettlementWithDocuments, useUpdateSettlementWithDocuments | IntegratedSettlementMutationResult |
| Settlement custom cost | SETTLEMENT_CUSTOM_COST | createSettlementCustomCostWithDocumentsMutationOptions, updateSettlementCustomCostWithDocumentsMutationOptions | useCreateSettlementCustomCostWithDocuments, useUpdateSettlementCustomCostWithDocuments | IntegratedSettlementCustomCostMutationResult |
| Expense (no update) | EXPENSE | createExpenseWithDocumentsMutationOptions | useCreateExpenseWithDocuments | IntegratedExpenseMutationResult |
| Insurance | INSURANCE | createInsuranceWithDocumentsMutationOptions, updateInsuranceDocumentsMutationOptions | useCreateInsuranceWithDocuments, useUpdateInsuranceDocuments | IntegratedInsuranceMutationResult |
| Loan | LOAN | createLoanWithDocumentsMutationOptions, updateLoanWithDocumentsMutationOptions | useCreateLoanWithDocuments, useUpdateLoanWithDocuments | IntegratedLoanMutationResult |
| Issue | ISSUE | createIssueWithDocumentsMutationOptions, updateIssueWithDocumentsMutationOptions | useCreateIssueWithDocuments, useUpdateIssueWithDocuments | IntegratedIssueMutationResult |
| Meeting | MEETING | createMeetingWithDocumentsMutationOptions, updateMeetingWithDocumentsMutationOptions | useCreateMeetingWithDocuments, useUpdateMeetingWithDocuments | IntegratedMeetingMutationResult |
| Routine | ROUTINE | createRoutineWithDocumentsMutationOptions, updateRoutineWithDocumentsMutationOptions | useCreateRoutineWithDocuments, useUpdateRoutineWithDocuments | IntegratedRoutineMutationResult |
| Supplier for company | SUPPLIER_FOR_COMPANY | createSupplierForCompanyWithDocumentsMutationOptions, updateSupplierForCompanyWithDocumentsMutationOptions | useCreateSupplierForCompanyWithDocuments, useUpdateSupplierForCompanyWithDocuments | IntegratedSupplierForCompanyMutationResult |
| Inquiry, signed in | CONVERSATION | createInquiryWithDocumentsMutationOptions | useCreateInquiryWithDocuments | IntegratedConversationMutationResult |
| Invoice plan | INVOICE | createInvoicePlanWithDocumentsMutationOptions, updateInvoicePlanWithDocumentsMutationOptions | useCreateInvoicePlanWithDocuments, useUpdateInvoicePlanWithDocuments | the plain command’s result |
| Ad hoc invoice group | ADHOC | createAdHocLinesWithDocumentsMutationOptions (the group the lines create), updateAdHocGroupWithDocumentsMutationOptions | useCreateAdHocLinesWithDocuments, useUpdateAdHocGroupWithDocuments | the plain command’s result |
In Kotlin the same commands are on sdk.api.integratedDocuments: createSettlement, updateSettlement, createSettlementCustomCost, updateSettlementCustomCost, createExpense, createInsurance, updateInsuranceDocuments, createLoan, updateLoan, createIssue, updateIssue, createMeeting, updateMeeting, createRoutine, updateRoutine, createCompanySupplier, updateCompanySupplier and createInquiry.
Invoice plans and ad hoc invoice groups have no integrated route: their own commands carry PDF attachments as base64 and remove them by id, in the same transaction. Their *WithDocuments commands take the same documents, but only files ({ file } or { fileName, bytes }), not documents to reuse: the SDK encodes the files into the command’s attachments and sends removeDocumentIds as removeAttachments. Without documents the command goes out unchanged. An invoice plan takes attachments on OTHER plans only. The ad hoc create is the lines command; its attachments go on cmd.group, which it then needs. These commands have no idempotency key and resolve what the plain command resolves.
Not covered yet: the open (anonymous) inquiry keeps createInquiryOpen and the public upload. The plain commands stay as they were.
The shape
await createSettlementCustomCost({
companyId,
settlementId,
cmd: { settlementType: 'ELECTRICITY', amount: 1200, units: 1 },
documents: {
attachments: [{ file }, { sourceDocumentId }],
idempotencyKey, // optional; send the key from a failed call again to retry it
onUploadProgress, // optional
},
})
await updateSettlementCustomCost({
companyId,
settlementId,
customCostId,
cmd: { amount: 1300 },
documents: {
attachments: [{ file }], // files to add
removeDocumentIds: [oldDocumentId],
},
})
Here createSettlementCustomCost is useCreateSettlementCustomCostWithDocuments().mutateAsync, or the mutationFn of its query factory. Every owner command takes the plain command’s parameters (cmd and the ids) and documents:
attachmentstakes whatIntegratedDocumentSourcetakes:{ file },{ fileName, bytes, contentType }or{ sourceDocumentId }, each with an optionaltransform. The documents of these owners are attachments.removeDocumentIds, on an update, lists the owner’s own documents to remove; another document is refused and nothing is written.- An insurance and a loan also take
agreement, the document that becomesagreementDocumentId. The insurance update (updateInsuranceDocuments) has no other fields: it replaces the agreement and changes the documents. A loan update that setsagreementalso needs the loan agreement grant. The current agreement can only be listed inremoveDocumentIdstogether with its replacement. - An issue’s description and an inquiry’s message take images by slot in
inlineDocuments, as posts do; an issue update that takes an image out of the description removes it. - The loan update sends the loan’s details (
correctLoanDetails’sUpdateLoanCommand). A routine’s type goes incmd.type; the plain create’sroutineTypeparameter has no counterpart.
A call resolves { resource, documents }: the resource as its own read returns it, and documents, the integrated result with the owner’s documents and the idempotency key (for a supplier, resourceId is the supplier and parentId the company’s link to it, which owns the documents). It never leaves half a change behind. When it fails, it rejects with the integrated mutation error:
- the backend refused it (a definitive 4xx): nothing was saved, the uploads were deleted again, and
rollbackFailuresnames any that could not be; - the outcome is unknown (the answer was lost):
integratedRetryKey(error)gives the key to send again with the same request and files, and the backend returns the saved result if the first attempt committed.useIntegratedRetrywithintegratedRequestFingerprintdoes that for a form.
The call refreshes what the plain command refreshes, the owner’s document list and the company’s document lists.
Deleting an owner
Delete stays one call without documents. The backend soft-deletes a settlement’s, custom cost’s, expense’s, insurance’s, loan’s, issue’s, meeting’s, routine’s and ad hoc invoice group’s documents with it, so their delete commands drop the owner’s document list from the cache and refresh the company’s document lists. They take an optional documentIds (a custom cost’s documentIds, for example) to drop the cached signed URLs of those documents too. Removing a supplier from the company keeps its documents hidden and restorable; that delete only refreshes the document lists.
A settlement’s type
The backend keeps a settlement’s type on each of its invoices and custom costs and changes neither for the other. changeSettlementTypeMutationOptions / useChangeSettlementType() changes them together in one call: { companyId, settlementId, settlementType, cmd? }, where cmd holds other settlement changes to send in the same update. It reads the settlement, updates it with every invoice set to the type, then updates each custom cost of another type. That is several requests, so:
- a failed settlement update rejects, and nothing changed;
- a failed custom cost update resolves
{ status: 'partial', updatedCustomCostIds, failedCustomCosts }: the settlement and the other costs have the new type. The change converges, so calling again with the same type finishes it; - otherwise it resolves
{ status: 'changed', updatedCustomCostIds }.
For upload failures and safe retries, see integrated resource mutations.
Without the documents API
A client from @solibo/solibo-sdk/core has no documents or integratedDocuments member on its raw API, and loading the whole documents API for one upload costs a page every document operation. The upload flows also come as functions that take the raw API:
import { createSoliboClient } from '@solibo/solibo-sdk/core'
import {
completeSignedUpload,
createDocumentBelongsToOperation,
downloadDocument,
DownloadDocumentRequest,
UploadBinaryRequest,
uploadClientFor,
uploadDocument,
} from '@solibo/solibo-sdk/documents/operations'
import { integratedDocumentsOf } from '@solibo/solibo-sdk/interop'
const client = createSoliboClient({ auth: { kind: 'browser', userPoolId, clientId } })
const api = client.raw.api
// The same as sdk.api.documents.uploadDocument and downloadDocument.
await uploadDocument(api, uploadRequest, (progress) => console.log(progress.fraction))
await downloadDocument(api, new DownloadDocumentRequest({ companyId, id: documentId, size: '320x240' }))
// An operation that answers with a signed upload: run it on uploadClientFor, which carries the
// upload's headers for its next request, then send the bytes.
const request = new UploadBinaryRequest({ fileName: file.name, bytes, contentType: file.type })
const response = await createDocumentBelongsToOperation(uploadClientFor(api, request), companyId, 'POST', postId)
await completeSignedUpload(api, response, request)
// The same coordinator as sdk.api.integratedDocuments, created once per client.
await integratedDocumentsOf(api).createHomepagePost(companyId, command, null, attachments)
uploadClientFor keeps the upload’s headers on a client of its own, so a query that runs at the same time never sends them. @solibo/solibo-query runs its uploads this way.