Skip to Content
Baseera Docs

Quickstart

Add immersive mode to an invoice screen: declare fields, a blocking check and a warning, bind the inputs, show the finish bar and verify the finish on your server.

You will take an invoice screen from a plain form to a guarded one in five steps. It uses Next.js (App Router) and assumes the chat setup from the SDK quickstart is done: a BaseeraProvider wraps your app and a BaseeraSurface is rendered inside it.

The packages are not on npm yet. See Installation for how to add them from the Baseera workspace until the first release.

You need an agent with its publishable key, secret key, agent id and runtime URL, and your app's domain in the agent's allowed domains. Checks, drafts and finishes need no model. Only chat turns and AI checks do.

Set the server environment

.env.local
# Server only: never prefix with NEXT_PUBLIC_.
BASEERA_AGENT_ID=your-agent-uuid
BASEERA_SECRET_KEY=sk_your_secret_key
BASEERA_RUNTIME_URL=https://runtime.example.com

Declare the record

Call useBaseeraImmersive in the component that owns the form. It starts immersive mode when the component mounts and ends it when it unmounts.

app/invoices/[id]/invoice-screen.tsx
"use client";
import { useBaseeraImmersive } from "@baseera/react";
import { BaseeraField } from "@baseera/ui/connected";
import { useState } from "react";

const ok = { ok: true } as const;

interface Invoice {
  id: string;
  number: string;
  status: "draft" | "sent";
  customer: string;
  taxId: string;
  dueDate: string;
  total: number;
}

export function InvoiceScreen({ invoice, customerTaxId }: { invoice: Invoice; customerTaxId: string | null }) {
  const [taxId, setTaxId] = useState(invoice.taxId);
  const [dueDate, setDueDate] = useState(invoice.dueDate);
  const [total, setTotal] = useState(String(invoice.total));

  useBaseeraImmersive({
    entity: { type: "invoice", ref: invoice.id, title: `Invoice ${invoice.number}` },
    fields: [
      { name: "customer", label: { ar: "العميل", en: "Customer" }, kind: "text", get: () => invoice.customer },
      { name: "taxId", label: { ar: "الرقم الضريبي", en: "Tax ID" }, kind: "text", get: () => taxId },
      { name: "dueDate", label: { ar: "تاريخ الاستحقاق", en: "Due date" }, kind: "date", get: () => dueDate },
      { name: "total", label: { ar: "الإجمالي", en: "Total" }, kind: "number", get: () => total },
    ],
    checks: [
      {
        id: "tax-id-missing",
        severity: "blocking",
        fields: ["taxId"],
        run: (r) =>
          r.taxId
            ? ok
            : {
                ok: false,
                message: "The tax ID is missing.",
                // A draft the person can approve in the field.
                ...(customerTaxId ? { fix: { field: "taxId", value: customerTaxId, reason: "From the customer record." } } : {}),
              },
      },
      {
        id: "due-date-past",
        severity: "warning",
        fields: ["dueDate"],
        run: (r) => (String(r.dueDate) >= new Date().toISOString().slice(0, 10) ? ok : { ok: false, message: "The due date is in the past." }),
      },
    ],
    finish: {
      label: { ar: "إرسال الفاتورة", en: "Send invoice" },
      closed: invoice.status === "sent", // no finish button on a closed record
      action: async ({ receipt, override }) => {
        const res = await fetch(`/api/invoices/${invoice.id}/send`, {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ receipt, override }),
        });
        if (!res.ok) throw new Error(`send_failed_${res.status}`);
      },
    },
  });

  return (
    <form>
      <BaseeraField name="taxId" value={taxId} onChange={(v) => setTaxId(String(v))}>
        <input value={taxId} onChange={(e) => setTaxId(e.target.value)} />
      </BaseeraField>

      <BaseeraField name="dueDate" value={dueDate} onChange={(v) => setDueDate(String(v))}>
        <input type="date" value={dueDate} onChange={(e) => setDueDate(e.target.value)} />
      </BaseeraField>

      <BaseeraField name="total" value={total} onChange={(v) => setTotal(String(v))}>
        <input inputMode="decimal" value={total} onChange={(e) => setTotal(e.target.value)} />
      </BaseeraField>
    </form>
  );
}

The record your checks receive is { [name]: get() }, read when they run. A blocking check holds the Finish button. A warning does not, unless you set blockOnWarnings.

Bind the inputs

You already did: each BaseeraField wraps one input and names the field it belongs to. The input is rendered unchanged. When a check lists the field in fields, the field gets a ring and a badge with the message. When a draft is proposed for it, it appears right after the input.

onChange is how an approved draft reaches your form. Pass your own state setter, or field.onChange from React Hook Form. See Drafts and fixes.

Show the finish bar

BaseeraSurface already draws one. In immersive mode its review panel lists the open checks and ends with a Send invoice button, the reason it is disabled, and a Finish anyway button while blocking checks are open.

If you draw your own, read the same state:

components/finish-bar.tsx
"use client";
import { useBaseeraImmersiveState } from "@baseera/react";

export function FinishBar() {
  const { openChecks, canFinish, canOverride, finishLabel, finish, acknowledge } = useBaseeraImmersiveState();
  const label = typeof finishLabel === "string" ? finishLabel : finishLabel?.en;

  return (
    <footer>
      {openChecks.warning.map((c) => (
        <p key={c.id}>
          {c.message} <button onClick={() => acknowledge(c.id)}>Dismiss</button>
        </p>
      ))}
      <button disabled={!canFinish} onClick={() => void finish()}>
        {label}
      </button>
      {canOverride && <p>Blocking issues are open. Finish with a written reason instead.</p>}
    </footer>
  );
}

finish() records the finish with Baseera first and only then runs your finish.action({ receipt, override }). If recording fails, your action does not run.

Verify the finish on your server

The receipt is only worth something if your server checks it. Recompute your blocking checks from your own data, never from the browser, and pass them in.

app/api/invoices/[id]/send/route.ts
import { verifyFinish } from "@baseera/node";

export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const { receipt } = (await request.json()) as { receipt?: string };
  if (!receipt) return Response.json({ error: "receipt_required" }, { status: 400 });

  const invoice = await db.invoice.findUnique({ where: { id } });
  if (!invoice || invoice.status === "sent") return Response.json({ error: "closed" }, { status: 409 });

  // Your own blocking checks, from your own data.
  const blocking: string[] = [];
  if (!invoice.taxId) blocking.push("tax-id-missing");

  const result = await verifyFinish({
    receipt,
    entity: { type: "invoice", ref: id },
    openBlocking: blocking, // the override must cover these
    agentId: process.env.BASEERA_AGENT_ID!,
    secretKey: process.env.BASEERA_SECRET_KEY!,
    baseUrl: process.env.BASEERA_RUNTIME_URL!,
  });
  if (!result.ok) return Response.json({ error: result.code }, { status: result.code === "unavailable" ? 503 : 409 });

  await db.invoice.update({
    where: { id },
    data: { status: "sent", sentBy: result.finish.userId, overrideReason: result.finish.override?.reason ?? null },
  });
  return Response.json({ ok: true });
}

db stands for your own data layer. verifyFinish never throws and fails closed: treat unavailable as a refusal and let the person try again. A successful call uses the receipt up.

Try it

Open an invoice with an empty tax ID. The field gets a ring and the Finish button is disabled. Type a tax ID and the flag clears within a fraction of a second. Clear it again and use Finish anyway: write a reason of at least 10 characters. Your route receives the override, and result.finish.override.reason holds the text.

Open the agent's Immersive mode page in the dashboard. The record appears under Records, and its timeline shows each step.

Next steps

On this page