Skip to content

About

Topdesk incident widget for Nextcloud dashboard

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

TOPdesk integration for Nextcloud

integration_topdesk — a dashboard widget showing the signed-in user's five most recent TOPdesk tickets, a button to report a new one, and an admin page that connects the server to one TOPdesk SaaS environment.

Version 1.0.0 · Nextcloud 33–35 · PHP 8.1–8.5 · AGPL-3.0-or-later


What it does

Three dashboard widgets, each showing five items, newest first:

Widget Shows Needs Filter
My TOPdesk tickets tickets the user reported person card caller.id
TOPdesk tickets assigned to me tickets assigned to them operator card operator.id
My TOPdesk reservations rooms, assets and services they booked person card requester.id

So the three cases fall out by themselves: a plain employee gets reported tickets and reservations, an agent with no employee card gets assigned tickets only, and somebody with both gets all three. Each widget explains itself when the user's cards make it irrelevant, rather than sitting there inexplicably empty.

"My TOPdesk tickets" also carries a + Ticket button — a modal with a short description, a details field and optional category/subcategory, filing a first-line incident without leaving Nextcloud. Only that widget has it: an incident needs a caller and only a person card can be one.

Three TeamHub capabilities, offered to the TeamHub app when it is installed, so a Nextcloud administrator can switch TOPdesk on for the team templates that want it:

Capability Type Shows Needs
My TOPdesk canvas card tiles counting the viewer's open/closed tickets, what is assigned to them, and their upcoming/past bookings; New ticket and Open TOPdesk in the card's header menu person or operator card
My assets canvas card the assets assigned to the viewer, each with an icon for its kind person card
My TOPdesk team tab latest tickets and reservations with their TOPdesk status, the assets, and a three-dot menu with New ticket, Open TOPdesk and Refresh person or operator card

Everything on these surfaces is the viewer's own TOPdesk data. A Nextcloud Team has no TOPdesk identity — a ticket belongs to a caller, an asset to a person — so what a team workspace adds is each member's own queue in the place they already work. The team id is verified, then never used as a filter.

Both lead to the same ticket modal as the dashboard widget. The tab draws its menu inside its own frame; the card declares its two entries at registration and TeamHub draws them in the card header (TeamHub 4.13.29 and later — an older one simply shows the card without a menu). A declared action is a label, an icon and a URL: TeamHub never speaks to the frame, so "New ticket" is a link to the page holding the form rather than a message asking the card to open it, and that page decides whether this viewer may file one — an incident needs a caller, and only a person card can be one.

The two cards are widget_iframe capabilities (TeamHub 4.13.24): TeamHub keeps the card — its place in the grid, its header, its collapse control, the team's shown/hidden switch — and this app draws the inside. They were row widgets first, and rows is what they looked like.

See docs/teamhub-integration.md for why each surface is shaped the way it is, who gets to switch it on, and the two places where this app has to re-check something TeamHub already checked.

Why three widgets and not one with tabs

Tabs were the obvious first thought and are the wrong shape:

  • Nextcloud's dashboard has no tabbed-widget pattern, so it would be a bespoke control where users do not expect one.
  • A dashboard card is narrow and short. A tab strip costs a row of vertical space that five items already compete for.
  • Decisively: getItemsV2() returns one flat list per widget, and that is what the mobile and desktop clients read. One tabbed widget could expose only one of the three lists to them; three widgets expose all three.

Three widgets are also independently addable, removable and orderable, which is how dashboard widgets already work — a person-only user simply never adds "assigned to me".

Each widget is rendered twice over, deliberately: a Vue component for the browser (which the create modal needs), and getItemsV2() on the PHP side for the clients.

Links follow the audience

An operator opening a ticket assigned to them gets the operator interface, where they can work on it. A person gets the Self-Service Portal. Sending an agent to the SSP gives them a read-only view of their own job; sending a person to the operator section gets them refused.

The API provides no link for an incident or a reservation — there is no link or url field — so these are built from path conventions, and those conventions are not documented either. They cannot be probed from outside: an unauthenticated request answers 401 for a real path and for an invented one alike. So they all live in lib/Service/TopdeskLinks.php, one method per (item type, audience) pair, and occ topdesk:diagnose <user> prints the generated URL under every item so they can be checked with one click. If one is wrong for a given TOPdesk it is a one-line fix in one file.

Admin settings (Administration settings → TOPdesk) — the environment URL, the credentials, the matching rule, and a "Save and test connection" button that makes a real authenticated call and explains the failure when there is one.

Personal settings (Personal settings → TOPdesk) — shows the user which TOPdesk person they are matched to and why, and lets them pick one by hand when the automatic match cannot settle it.


Setting up TOPdesk

Two authentication modes; pick whichever the customer's TOPdesk supports.

Application token (works on every TOPdesk 7.11.005 and later)

  1. Modules → Supporting Files → Permission Groups → new group, with read on API access > REST API and write on API access > Use application tokens. The account also needs read on first/second-line incidents, read on Persons, and create permission on first-line incidents.
  2. Link the group to the operator or API account the integration will use.
  3. Create the token: on the operator's own card via My Settings, or on an API account card under Application tokens. Creating one on an API account card additionally needs write on Supporting Files > Login data, and read on Supporting Files > Operator to see API accounts at all.
  4. Copy the token immediately — it is shown once — and note the expiry date. The default is one year out, and nothing warns you when it passes.
  5. In Nextcloud, enter the URL, the login name and the token, then Save and test connection.

OAuth connected application

  1. Modules → Supporting Files → System integrations overview → Connected applications → new application integration (the client-credentials kind; the user-delegated kind is a different flow this version does not use). Managing these needs the Manage connected applications > Manage integration clients permission.
  2. Copy the client id and the one-time secret. A lost secret cannot be retrieved — delete the client and make a new one.
  3. In Nextcloud, switch the auth mode to OAuth, enter both, then Save and test connection.

Access tokens are short-lived (900 s) and minted on demand; there is no refresh token in this grant and nothing to rotate by hand.

What the API account can see

The operator's category, branch and operator filters apply to everything this app reads. If the account is filtered to one branch, users outside it will show no tickets even when the person match is correct — which looks like a matching bug and is not one. Give the API account unfiltered read access to incidents, or expect that asymmetry.


How a Nextcloud user becomes a TOPdesk person

The problem

TOPdesk's incident API has two endpoint families. GET /incidents is operator-only and can read every ticket in the environment; GET /requester/incidents returns only the caller's own tickets but requires the person's own credentials, which a server-to-server integration does not have.

So this app authenticates as an operator and filters. Which means the filter is the only thing standing between a user and everybody else's ticket history — and the filter is only as good as the identity behind it.

Two kinds of card

TOPdesk keeps a person card and an operator card for a human, and the same address can sit on either or both. They are not interchangeable — they answer different questions, so they give different ticket lists:

Matched as Tickets shown Filter Can report a ticket?
person the ones they reported caller.id yes, as themselves
operator the ones assigned to them operator.id only via a linked person card

Both lookups run on every resolution, and both ids are stored independently. There is deliberately no "primary" card: with a widget per list, each one uses the id it needs. Asking only about persons is what made an operator-only account look permanently unmatchable, which is the state whoever sets the integration up is usually in — they are an operator, that is how they got an application token, and they may have no person card at all.

Where an operator card carries TOPdesk's own linked person pointer, that person is used for reservations and as the caller for new tickets — so an agent sees their own bookings and can still report a ticket as themselves. Without one, the assigned tickets still list and the other two widgets say why they cannot.

The design

The app stores a pair per user: the identifier it matched on, and the TOPdesk card UUID that identifier resolved to. Tickets are then always read with caller.id==<uuid> or operator.id==<uuid> — never by email address.

That matters because addresses get reused. When somebody leaves and j.doek@acme.nl is handed to their replacement, matching on the address alone shows the newcomer the leaver's entire history. It is not an edge case; it happens on every departure where the address is recycled.

So the pair is re-verified on every login, and whenever it goes stale (one hour by default):

The identifier now resolves to… What happens
the same UUID nothing — carry on
a different UUID the identifier changed hands. The stored UUID is replaced and only the new person's tickets are shown. Logged at warning level
nobody the link is dropped. The widget shows "no TOPdesk person found", not somebody's tickets
several people the link is dropped. The app never guesses between person cards
TOPdesk unreachable the link is kept and marked unverified. A network blip is not evidence of an identity change

That last row is why TopdeskException carries a transient flag: dropping links on a timeout would blank every user's widget during a maintenance window and then re-resolve them all at once afterwards.

A user (or an admin on their behalf) can pin a person by hand for the cases matching cannot settle — shared functional mailboxes, contractors, two cards with one address. A pinned link is an explicit decision and the resolver does not overwrite it, but it is shown in personal settings so it is never invisible.

⚠ Matching on email assumes users cannot change their email

On a stock Nextcloud, a user can change their own email address in personal settings. With email matching, an address they set is an address they get the tickets of — so a user who types a colleague's address into their own account, logs out and back in, sees that colleague's tickets.

Nothing in this app can prevent that, because from its side the change is indistinguishable from a legitimate correction. Choose one of:

  • users provisioned from LDAP / Entra ID / SAML, where the address is not theirs to edit (the common case for a customer running TOPdesk, and the reason email is the default);
  • prevent email changes on the instance;
  • match on the Nextcloud username instead — it is not user-settable. Pair it with the TOPdesk person field that carries the same value, usually networkLoginName when both systems are fed from the same directory.

The admin page says this on screen when email matching is selected.

Troubleshooting a match

occ topdesk:diagnose                 # connection check and the configured match rule
occ topdesk:diagnose <user>          # full trace for one user
occ topdesk:diagnose <user> --raw    # …plus the first row of each list, exactly as sent
occ topdesk:diagnose --as="a@b.nl"  # would this value match, and as what?
occ topdesk:diagnose --all           # one line per user, plus a state summary

Read-only by default — looking at why a user does not match should not quietly change what they are matched to. Pass --repair to write the result.

A trace for one user prints the Nextcloud field and the exact value taken from the account (quoted, with its length, and with leading or trailing whitespace called out by name — a stray space is the most common cause that is invisible in a log), the FIQL query actually sent, every candidate TOPdesk returned, and the decision made.

When nothing matched it then answers why, in the order these are usually the cause:

  1. An archived person card has the value. Archived cards are ignored on purpose — that is the whole reused-address defence — so this means un-archive the card if the person is still around.
  2. Operator cards carry the value but none could be used — usually more than one of them, so the matcher refused to guess.
  3. Active people whose value merely starts the same way, which catches a typo, a .com where the directory says .nl, or a second account.

On a successful match it instead prints all three lists as the widgets would render them, each item with the URL it will link to. That is the one link in the chain the trace cannot prove: a link can resolve perfectly and a list still be empty, because of the API account's filters or because there genuinely is nothing. Which of the three have content is also the question "is this user a person, an operator, or both?" answered in the terms they will actually see.

--raw adds the first row of each list exactly as TOPdesk sent it, for when the question is "what did the API actually return" — which is how the blank-status bug below was found.

--all summarises every user, with a CARDS column: P- is a plain employee, -O an agent with no employee card, PO both.

If a match succeeds but the person card does not have the Caller role ticked, the trace says so. That combination is easy to misread as a broken match: the identity is correct, but the person can never be a caller on an incident, so the widget stays empty and creating a ticket fails.

Also remember that the API operator's branch, category and operator filters apply to everything this app reads — a correctly matched user in a filtered-out branch shows no tickets.

The admin page has a Log matching details switch for the passive version: every resolution, for every user, written to the Nextcloud log as one multi-line entry. Search the log for TOPdesk match trace. It is off by default and should go back off afterwards, because the trace contains the addresses being matched. Entries are written at warning level deliberately — Nextcloud's default loglevel is 2, so an info entry never reaches the file and the switch would appear to do nothing.

Case does not matter

JDoek@Acme.nl, jdoek@acme.nl and JDOEK@ACME.NL all match the same card, and a user whose directory starts sending a differently-capitalised address does not become somebody else.

Two things make that true:

  • TOPdesk's own FIQL == folds case. Verified against a live instance, where all three spellings above returned the same operator card. That is a property of the backend's collation rather than something the API documents, so the app does not rely on it alone: a lookup that finds nothing with a mixed-case value retries with a case-folded one, and the trace says when that retry is what matched.
  • Every comparison on this side goes through MatchValue. The freshness check in particular: comparing the stored value exactly would re-resolve every user whose address changed capitalisation, and — worse — a case-only difference would read as "the identifier changed" in the one part of the app whose job is noticing when an identifier really has changed hands.

Leading and trailing whitespace is also ignored. Whitespace inside a value is not: that is a data-entry mistake rather than a spelling variant, so the trace calls it out (HAS LEADING/TRAILING WHITESPACE, and the character count) instead of the app quietly matching through it.

MatchValue has no Nextcloud dependencies and the rules are covered by tests/matchvalue-test.php.

Match fields

Nextcloud side TOPdesk person card
Email address (default) Email address (default)
Username Network login name · Employee number · TOPdesk login name

Reading tasLoginName (TOPdesk login name) needs the Settings > Login Settings permission on the API operator; without it every match comes back empty.


Build

npm install
npm run build

A production build takes about 7 seconds. Two things had to be worked around to get there, both recorded in the config so they are not rediscovered:

  • TypeScript must stay on 6.x (pinned in devDependencies). TypeScript 7 removed an API that vite-plugin-dts still calls through @volar/typescript, and the vite config then fails to load with Cannot read properties of undefined (reading 'useCaseSensitiveFileNames').

  • extractLicenseInformation: false in vite.config.mjs. With createAppConfig's default REUSE license scanning on, the build never finishes here: it hangs in "rendering chunks" and eventually dies with "Ineffective mark-compacts near heap limit" — at an 8 GB heap limit, for three small entries. It is not the module graph. An entry containing nothing but console.log('probe') behaved identically, and the same entry with the plugin off built in 78 ms. It also survived pinning vite, rollup, TypeScript and @nextcloud/vue to the exact versions that build fine in the TeamHub app next door, so it is the plugin and not the dependency tree. The cost is the generated .license sidecar files; the app's own licence is declared in appinfo/info.xml and composer.json. Worth retrying on a future @nextcloud/vite-config.

Components are imported by subpath (@nextcloud/vue/components/NcButton) rather than from the package root. The root is a barrel that re-exports all ~150 components; going through it pulled 1793 modules into the graph where the subpaths pull 1272.

Vite's warning that build.outDir is the project root is expected — createAppConfig defaults it there, and emptyOutDir: false keeps a build from wiping the app directory.

CSS is extracted per entry into css/vite-*.chunk.css, and the PHP side loads it by reading each entry's css/<entry>.css manifest stub rather than naming chunks by hand — Rollup renames shared chunks whenever an import graph changes, and the symptom of a stale hand-written name is an unstyled page with no error. See lib/Service/ViteStyles.php and the comment block in vite.config.mjs.

Deploying to the AIO test instance

npm run deploy:aio

Builds, then mirrors the shipped paths into the nextcloud-aio-nextcloud container's custom_apps/integration_topdesk, chowns them to www-data, runs occ upgrade and reloads php-fpm. Modelled on TeamHub's script of the same name.

Flag Effect
--dry-run print every docker command, change nothing
--enable also run occ app:enable — needed once, on a first deploy
--restart restart the container instead of reloading php-fpm
--skip-preflight deploy a bundle the checks reject

Overridable with TOPDESK_AIO_CONTAINER and TOPDESK_AIO_APP_DIR.

Pre-flight refuses to deploy when appinfo/info.xml and package.json disagree on the version, when src/ is newer than js/, when an entry's JS is missing, or when a CSS manifest stub is missing or points at a chunk that is not there. That last one is specific to this app: ViteStyles.php discovers stylesheets by reading css/<entry>.css, so a missing stub renders the page completely unstyled with nothing in any log to explain it. Don't reach for --skip-preflight to make a red deploy green — an afternoon testing a stale bundle is an afternoon of conclusions about code that is not running.

Two things worth knowing about the instance:

  • PHP changes land within ~60 s (opcache.validate_timestamps=On, revalidate_freq=60). If a change looks like it did not land, wait a minute before debugging it. Frontend changes are immediate, because Nextcloud cache-busts js/css URLs on the app version.
  • A changed routes.php deployed under the same version number needs the php-fpm reload the script does at the end. Since NC 30 the router caches the compiled route table in APCu for an hour, keyed on the enabled apps' versions — a version bump invalidates it, a same-version redeploy does not, and the new route answers 404 until then while php -r inside the container matches it perfectly.

Publishing to the release repo

npm run publish:release

Mirrors the working folder into C:\Temp\github\Nextcloud-Topdesk — the separate git repo that holds the .git and gets pushed to JustinDoek/Nextcloud-Topdesk. Source is edited here, never there; the script is the only thing that writes to it, and it then prints the git commands to commit, tag and push.

Flag Effect
--dry-run print what would move, change nothing
--skip-preflight publish a version the checks reject

Overridable with TOPDESK_RELEASE_DIR. The script refuses a destination that does not exist or has no .git, because it deletes directories there and only does that where git can undo it.

Every mirrored directory is wiped and re-copied, not copied over. A plain copy is additive, so a renamed component or a deleted service stays in the repo forever — which is how the repo came to carry v0.1's single TicketsWidget while the app had four widgets. Nothing outside the mirrored entries is touched: .git/, node_modules/ and the build output are left alone.

The list of what gets mirrored lives in scripts/lib/app-files.js, next to the PUBLISHABLE list deploy:aio walks. They are two lists on purpose: a deploy needs the compiled bundle, and the release repo does not carry one — its .gitignore excludes js/ and every generated css/, so what it holds is the source of the app and css/icon.css is the one stylesheet in it. Pre-flight here checks only that appinfo/info.xml and package.json agree on the version, since a stale js/ cannot reach this destination.

Tests

npm test                              # all of them
node scripts/run-tests.js --container # force the container's PHP

Plain PHP, no Nextcloud, no PHPUnit:

  • tests/fiql-test.php — FIQL quoting, which is the one place a crafted email address could otherwise append conditions to the persons query and widen which card an account resolves to.
  • tests/matchvalue-test.php — the case and whitespace rules that decide whether two identifiers are the same person.

matchvalue-test.php needs mbstring, since MatchValue folds case with mb_strtolower (byte-wise strtolower would leave ÅKESSON alone, so it would not compare equal to its own lower-cased self). Nextcloud requires mbstring so the app always has it, but a bare Windows PHP CLI often does not — the test then reports SKIPPED with exit code 2 and the runner re-runs it inside the AIO container, which has mbstring because Nextcloud would not start otherwise. The runner copies tests/ in for the run and removes it afterwards; it is not part of a deployed install.

Note the diagnose command can also answer "would this value match?" without touching any account, which is how the case behaviour above was established:

occ topdesk:diagnose --as="JDOEK@ACME.NL"

Layout

appinfo/info.xml              manifest (validated against the App Store schema)
appinfo/routes.php
lib/Service/
  ConnectionConfig.php        admin connection; secrets via ICrypto
  TopdeskClient.php           HTTP; absorbs TOPdesk's 204-means-empty and 206-means-more
  Fiql.php                    query building and escaping
  MatchValue.php              the case/whitespace rules, dependency-free and tested
  PersonResolver.php          the matching rules above
  PersonLink.php              one user's (match value, person id, operator id)
  IncidentService.php         reported + assigned lists, and create
  ReservationService.php      bookings; sorts locally, since the endpoint cannot
  AssetService.php            assets assigned to a person; Asset Management API
  SummaryService.php          the open/closed counts, and what "closed" means
  PersonalOverviewService.php what the TeamHub surfaces show; isolates each section
  ServiceCatalogueService.php published services (registered capability withdrawn)
  TeamMembership.php          is this user in this Team — ITeamManager, fails closed
  TopdeskLinks.php            every deep link, one method per item type and audience
  Auth/                       application token · OAuth client credentials
  ViteStyles.php              loads built CSS from the Vite manifest
lib/Dashboard/
  AbstractTopdeskWidget.php   shared widget boilerplate; why three and not tabs
  ReportedTicketsWidget.php   needs a person card
  AssignedTicketsWidget.php   needs an operator card
  ReservationsWidget.php      needs a person card
lib/Command/Diagnose.php      occ topdesk:diagnose
lib/Controller/               admin · personal · incident · team
lib/Listener/                 re-verify at login · forget on account deletion
templates/team-page.php       the shell for every page TeamHub embeds (RENDER_AS_BASE)
src/components/
  TopdeskWidget.vue           one component, mounted three times with a `kind` prop
  CreateTicketModal.vue       the report form
  AdminSettings.vue           connection and matching
  PersonalSettings.vue        which cards the user matched, and pinning
  TopdeskSummaryCard.vue      the counts card — tiles
  TopdeskAssetsCard.vue       the assets card — tiles
  TopdeskOverview.vue         the team tab — tickets, reservations, assets
  TeamServiceCatalogue.vue    the catalogue page (capability withdrawn, page kept)
src/topdeskPresentation.js    asset icons, status tone and label, date formatting
src/embed.css                 page rules for the embedded documents: opaque
                              background, body pinned to the frame

docs/topdesk-api-notes.md     API research: spec URLs, endpoint permissions, quirks
docs/teamhub-integration.md   what is registered with TeamHub, and the two re-checks

Since every TeamHub capability is an iframe, no class of this app's is named in the registration, and the only reference to a TeamHub class anywhere is inside the guarded block in Application::boot(). There is no longer a directory of classes implementing interfaces from an app that may not be installed.

docs/topdesk-api-notes.md is worth reading before extending this — it records which endpoints an operator may call versus a person, the exact callerLookup semantics, the FIQL operator table, and the download URLs for TOPdesk's OpenAPI specs (the developer portal's HTML explorer is JS-rendered and cannot be fetched, but the specs behind it can).


Not in this version

  • Per-user OAuth (TOPdesk's user-delegated integration, authorization-code grant). Each user would connect their own TOPdesk account once and the app would read /requester/incidents with their token — TOPdesk enforces "own tickets" server-side, so no operator credential could over-read and the matching problem above disappears entirely. Costs the OAuth dance, per-user token storage, and a reconnect whenever the 60-day refresh token lapses. IncidentService is the only class that would need a second implementation.
  • Ticket detail inside Nextcloud, replies, attachments.
  • Changes, problems and operational activities — separate TOPdesk APIs.
  • Deep links to an asset. The Asset Management API returns no URL and no path convention for an asset card has been confirmed against a real TOPdesk, so an asset is text and an icon rather than a link to a guessed path. A confirmed path is a one-line addition to TopdeskLinks. Tickets and reservations do have deep links, and use them everywhere.
  • Team-wide TOPdesk figures. Every TeamHub widget shows the viewer's own items, because a Nextcloud Team has no TOPdesk identity to filter on. Mapping a team onto a TOPdesk operator group or branch would be the way in, and it needs a per-team setting that nothing in this app has yet.
  • An admin overview of who is matched to whom. Links live in oc_preferences (integration_topdesk / person_id, match_value, state, …); a listing page would want them promoted to a table of their own.

About

Topdesk incident widget for Nextcloud dashboard

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages