Course menuForge Cloud

Level 2 · Lesson 4

Write the repair report

Goal of this lesson

After the repair tasks, write one Confluence page that lists them, and comment its link on each repair task, once.

About 30 min6 steps

Behind, or starting here? Download the code as it should be before this lesson, or in the course workspace run course-catch-up level-2/after-03-split-the-notes in the folder above your app. It offers to bring your own app folder to this point and keeps its app id (the id: line in manifest.yml, which links the code to your app on the site), so it stays the same app. Your old files are kept in a copy next to it.

Repair tasks say what to do. The workshop also needs one place that says what came in with the car and where each repair task is. That is the repair report, a Confluence page the consumer writes after the repair tasks.

Step 1: Permissions for Confluence

Writing a page takes two Confluence scopes: one to look up the space, one to create pages in it. Add them now; the code that needs them comes next.

Editmanifest.yml

Read spaces and write pages in Confluence.

- read:jira-work
- write:jira-work
- storage:app
Added: - read:space:confluence

Permission to look up a Confluence space.

Added: - write:page:confluence

Permission to create Confluence pages.

Why: Scope · Confluence page

Stuck?One common problem, and its fix
  • I added a scope or an outside host

    A permission change makes a new major version. Approve it, then move each installation onto it:

    RunTerminal
    forge deploy --approve MAJOR_VERSION_RULE
    forge install --upgrade

    If the app is installed on Jira and Confluence, run the upgrade for each; it asks which installation.

    Open in the FAQ

Step 2: Write the repair report

Atlassian’s own products

Confluence pagein the workshop: the repair report

The repair report is one Confluence page per check-in, written by the app. It names the car, lists every repair task as a live Jira card, then the original notes. Because the consumer records the page in its checkpoint, a retry never writes a second one.

In the workshop What came in with the car and where each repair task is, in one place.

See this on the Level 2 chart, in the step that writes the repair report.

This step adds the longest file so far. You copy it in whole; what it does fits in three lines:

  • It finds the Confluence space for repair reports.
  • It builds the page: the car, a list of the repair tasks, and the original notes, with every piece of text made safe to show.
  • It creates the page and hands back its address, which the next steps link from each repair task.

The details, if you want them: a new file finds the space’s id from its key, then creates the page through Confluence’s REST API. The body is written in Confluence’s storage format, page markup like HTML (tags in angle brackets). If a note contained < or a tag, Confluence would treat it as markup and could break the page, so every piece of text goes through escapeHtml first, which turns such characters into harmless text. That includes the repair descriptions that came from Forge LLM.

New filesrc/repairs/repairReport.js

A new file: find the space, then create one page listing every repair task.

Added: import api, { route } from '@forge/api';
Added: import { escapeHtml } from '../lib/html';
Added:
Added: /** Looks up a Confluence space's id from its key. Pass api.asApp() or api.asUser(). */
Added: export async function findSpaceId(client, spaceKey) {

Confluence’s page API wants the space’s number, not its key: this looks it up.

Added: const response = await client.requestConfluence(route`/wiki/api/v2/spaces?keys=${spaceKey}&limit=1`);
Added: if (!response.ok) throw new Error(`Confluence answered ${response.status} looking for space ${spaceKey}.`);
Added: const data = await response.json();
Added: const id = String(data.results?.[0]?.id ?? '');
Added: if (!/^\d+$/.test(id)) throw new Error(`No Confluence space with key ${spaceKey}.`);
Added: return id;
Added: }
Added:
Added: // Storage format is XHTML. The jira macro shows each repair task live.
Added: function render(checkIn, cards) {

Build the page’s content, in the HTML-like format Confluence stores pages in.

Added: const repairs = cards
Added: .map((c) => `<li><ac:structured-macro ac:name="jira"><ac:parameter ac:name="key">${escapeHtml(c.key)}</ac:parameter></ac:structured-macro> ${escapeHtml(c.summary)}</li>`)

One line per repair task, with Confluence’s Jira macro, the same one you add from the editor.

Added: .join('');
Added: const reported = checkIn.reportedBy ? `<p>Reported by: ${escapeHtml(checkIn.reportedBy)}</p>` : '';
Added: const notes = escapeHtml(checkIn.notes).replace(/\n/g, '<br/>');

escapeHtml makes sure anything typed in the notes shows as text, never as page code.

Added: return `<p>Car: ${escapeHtml(checkIn.car)}</p>${reported}<h2>Repair tasks</h2><ul>${repairs}</ul><h2>Notes</h2><p>${notes}</p>`;
Added: }
Added:
Added: /** The repair report: one page per check-in, in the space from settings, on the workshop's own account. */
Added: export async function createRepairReport({ spaceKey, checkInId, checkIn, cards }) {

Create the repair report page, as the app.

Added: const spaceId = await findSpaceId(api.asApp(), spaceKey);
Added: const response = await api.asApp().requestConfluence(route`/wiki/api/v2/pages`, {
Added: method: 'POST',
Added: headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
Added: body: JSON.stringify({
Added: spaceId,
Added: status: 'current',
Added: title: `Repair report: ${checkIn.car} (${checkInId.slice(0, 8)})`,

The page title: the car, and the first eight characters of the receipt number to tell reports apart.

Added: body: { representation: 'storage', value: render(checkIn, cards) },
Added: }),
Added: });
Added: if (!response.ok) throw new Error(`Confluence answered ${response.status}: ${await response.text()}`);
Added: const page = await response.json();
Added: return { id: String(page.id), title: page.title, url: `${page._links?.base ?? ''}${page._links?.webui ?? ''}` };

Give back the page’s id, title and web address.

Added: }

Why: Confluence page · Product REST APIs

Stuck?One common problem, and its fix
  • The repair tasks appear, but no repair report

    Set the space key and make sure the app is installed on Confluence:

    RunTerminal
    forge variables set REPORTS_SPACE_KEY RR
    forge deploy
    forge install --product confluence
    Open in the FAQ

Step 3: A way to leave a comment on a repair task

A small helper adds a comment to a work item as the app:

New filesrc/repairs/comment.js

A new file: comment on a work item on the workshop’s account.

Added: import api, { route } from '@forge/api';
Added:
Added: /** Adds a comment (an ADF document) to a work item on the workshop's own account. */
Added: export async function comment(issueKey, body) {

Add a comment to a work item, as the app.

Added: const response = await api.asApp().requestJira(route`/rest/api/3/issue/${issueKey}/comment`, {
Added: method: 'POST',
Added: headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
Added: body: JSON.stringify({ body }),
Added: });
Added: if (!response.ok) throw new Error(`Jira answered ${response.status} commenting on ${issueKey}.`);
Added: }

Why: asApp()

Step 4: Publish once, then link every repair task

After the repair tasks, the consumer writes the repair report, if a space is set, and then comments the link on each repair task. Both steps are checkpointed:

Editsrc/worker.jsChange 1 of 2

Bring in the page, the comment and the settings.

import { getCheckIn, saveCheckIn } from './checkins';
import { createRepairTask } from './repairs/createRepairTask';
import { splitNotes } from './repairs/splitNotes';
Added: import { createRepairReport } from './repairs/repairReport';
Added: import { comment } from './repairs/comment';
Added: import { withLink } from './lib/adf';
Added: import { settings } from './lib/config';
// Forge runs this once per check-in number in the checkin-queue, after
// submitCheckIn has already returned. A message can arrive more than once, so
Editsrc/worker.jsChange 2 of 2

After the repair tasks: write the page once, then comment on each repair task once.

}
cards.push({ key: checkpoint.created[index], summary });
}
Removed: await save('done', { cards });
Added: const { spaceKey } = settings();
Added: if (spaceKey && !checkpoint.page) {

Only if a reports space is set, and only once.

Added: await save('publishing', { cards });
Added: checkpoint.page = await createRepairReport({ spaceKey, checkInId, checkIn, cards });

Create the repair report and note it.

Added: await save('publishing', { cards });
Added: }
Added: checkpoint.commented = checkpoint.commented ?? {};
Added: for (const card of checkpoint.page ? cards : []) {

If there is a report, go through the repair tasks one by one.

Added: if (checkpoint.commented[card.key]) continue;

Skip a task that already has its comment. continue jumps to the next one.

Added: await comment(card.key, withLink('In the repair report:', checkpoint.page.url));

Comment on the task with a link to the report.

Added: checkpoint.commented[card.key] = true;
Added: await save('publishing', { cards });
Added: }
Added: await save('done', { cards, page: checkpoint.page ?? null });
} catch (error) {
console.error(`Worker: check-in ${checkInId} failed:`, error);
await save('failed', { error: error.message });

Why: Confluence page · Checkpoint

WS-24 grinding noiseWS-25 oil serviceWS-26 battery lighta comment with the link, once each12Repair report:BMW 3 Series• grinding noise• oil service• battery lightone page in Confluence
Stuck?2 common problems, and their fixes
  • The repair tasks appear, but no repair report

    Set the space key and make sure the app is installed on Confluence:

    RunTerminal
    forge variables set REPORTS_SPACE_KEY RR
    forge deploy
    forge install --product confluence
    Open in the FAQ
  • My check-in stays “waiting” or ends “failed”

    The consumer ran into a problem. Read its log, which names the step that failed:

    RunTerminal
    forge logs --since 15m

    The usual causes are a missing WORKSHOP_PROJECT_KEY, a Jira space you cannot create work items in, or Forge LLM not being available on the site yet.

    Open in the FAQ

Step 5: Sign the new approval, and install on Confluence

New scopes mean a major version. And the app has only been installed on Jira so far; to write pages, it needs an installation on Confluence on the same site, once:

RunTerminal
npm run build:ui
forge deploy --approve MAJOR_VERSION_RULE
forge install --upgrade
forge install

For the last command, choose Confluence and your developer site. From now on, a major version needs forge install --upgrade for both installations; the CLI asks which one to upgrade.

Stuck?2 common problems, and their fixes
  • The app now writes to Confluence (Level 2)

    Deploy and upgrade as for any permission change, then install the app on Confluence on the same site, once:

    RunTerminal
    forge deploy --approve MAJOR_VERSION_RULE
    forge install --upgrade
    forge install

    In the last command, choose Confluence and the same developer site. After that, each major version needs forge install --upgrade for both installations.

    Open in the FAQ
  • Deploy stops after a permission change

    That is expected, not an error. A new scope or outside host makes a new major version, which you approve. Then move each installation onto it. On your own developer site you are the admin, so you accept it yourself:

    RunTerminal
    forge deploy --approve MAJOR_VERSION_RULE
    forge install --upgrade
    Open in the FAQ

Step 6: Check a car in and read the repair report

Check a car in from the desk. When it is done, the desk offers to open the repair report in Confluence. It names the car and lists every new repair task as a live card, with the notes below. Open any of those repair tasks: its comments include a link back to the repair report.

Stuck?One common problem, and its fix
  • The repair tasks appear, but no repair report

    Set the space key and make sure the app is installed on Confluence:

    RunTerminal
    forge variables set REPORTS_SPACE_KEY RR
    forge deploy
    forge install --product confluence
    Open in the FAQ

Compare with yours: download the code after this lesson.

Type at least two letters.