Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .bifrost/workflows.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -336,3 +336,15 @@ workflows:
access_level: role_based
role_names: ["Bifrost Docs Administrator"]
timeout_seconds: 1800

4cd9ecbe-462d-49fc-b785-19bfdf5d433b:
id: 4cd9ecbe-462d-49fc-b785-19bfdf5d433b
name: docs_list_expirations
path: functions/expirations.py
function_name: docs_list_expirations
type: workflow
description: Read one bounded page of explicitly flagged asset expiration dates for an authorized organization.
category: Bifrost Docs
access_level: role_based
role_names: ["Bifrost Docs Reader", "Bifrost Docs Editor", "Bifrost Docs Administrator"]
timeout_seconds: 60
31 changes: 29 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,40 @@ Native documentation works without IT Glue. Installers configure only the roles
the Bifrost platform resources needed for their organization. IT Glue is an optional
one-way migration source for teams that have an existing IT Glue account.

## MTG feature development

This fork develops Skra's operational documentation features on top of the
upstream Bifrost Solution. Its first slice adds expiration tracking. In Settings →
Asset types, enable **Track as an expiration date** on a Date field, then enter a
`YYYY-MM-DD` value on an asset. The dashboard shows overdue and upcoming dates for
the selected organization, with 7, 14, 30, and 90 day windows. Ordinary dates are
excluded unless explicitly flagged. Archived/disabled assets and inactive types
are excluded; the caller's existing table policies still govern restricted rows.

The dashboard scans 100 assets per request. Use **Check next 100 assets** until the
scan is complete; dates are ordered across the assets checked so far, not across
unread pages. Refresh starts a new scan. Invalid nonempty flagged date values are
counted rather than treated as valid dates. Dates use the current UTC calendar day.
This slice does not send reminders or change schedules, secrets, or table policies.
Mapped IT Glue schemas retain their existing source-overwrite behavior; an upstream
schema change can replace locally added expiration flags.

Next slices are deduplicated expiration notifications, attributed SOP checklists,
favorites and saved preferences, and field-level sync conflict review. Keep each
slice independently reviewable and preserve customer/provider isolation.

Production releases should use reviewed release tags in this fork. Connecting an
install to Git changes its source owner; it does not deploy a feature branch.
Advance the configured release ref and sync only after release acceptance. Preserve
the upstream slug and manifest identities so the existing install retains its data.

## Install

Use Bifrost CLI 1.4.2 or later against the intended Bifrost instance:

```bash
git clone https://github.com/gobifrost/docs.git
cd docs
git clone https://github.com/MTG-Thomas/bifrost-docs-solution.git
cd bifrost-docs-solution
bifrost solution deploy . --global
```

Expand Down
8 changes: 8 additions & 0 deletions apps/bifrost-docs/src/components/AssetTypeEditor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@ import { describe, expect, it } from "vitest";
import { normalizeAssetTypeFields, safeAssetTypeFields, serializeAssetTypeFields } from "./AssetTypeEditor";

describe("asset type schema helpers", () => {
it("round-trips expiration flags and clears them when a date becomes text", () => {
const source = [{ attributes: { "name-key": "renewal", kind: "date", name: "Renewal", is_expiration: true } }];
const fields = normalizeAssetTypeFields(source);
expect(fields[0].is_expiration).toBe(true);
expect(serializeAssetTypeFields(fields)).toEqual(source);
expect(serializeAssetTypeFields([{ ...fields[0], type: "text" }])[0]).toEqual({ attributes: expect.objectContaining({ kind: "text", is_expiration: false }) });
expect(serializeAssetTypeFields([{ ...fields[0], is_expiration: false }])[0]).toEqual({ attributes: expect.objectContaining({ is_expiration: false }) });
});
it("round-trips imported protected and unsupported definitions without converting them", () => {
const source = [
{ attributes: { name: "Host Name", kind: "text", required: true, options: null } },
Expand Down
7 changes: 6 additions & 1 deletion apps/bifrost-docs/src/components/AssetTypeEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ import { BfCheckbox } from "@/components/bifrost/BfSelection";
import { BfSelect, BfTextField, BfTextarea } from "@/components/bifrost/BfField";

export type AssetFieldType = "text" | "textbox" | "number" | "date" | "checkbox" | "select" | "header" | "url" | "tag" | "upload" | "password" | "totp" | "unknown";
type SourceState = Pick<AssetTypeField, "key" | "name" | "type" | "required" | "show_in_list" | "default_value" | "options">;
type SourceState = Pick<AssetTypeField, "key" | "name" | "type" | "required" | "show_in_list" | "default_value" | "options" | "is_expiration">;

export type AssetTypeField = {
key: string;
name: string;
type: AssetFieldType;
required: boolean;
show_in_list: boolean;
is_expiration?: boolean;
default_value: string | null;
options: string[] | null;
/** Original source type, retained for diagnostics and exact serialization. */
Expand Down Expand Up @@ -85,6 +86,7 @@ function stateFor(field: AssetTypeField): SourceState {
type: field.type,
required: field.required,
show_in_list: field.show_in_list,
is_expiration: field.is_expiration,
default_value: field.default_value,
options: field.options ? [...field.options] : null,
};
Expand All @@ -108,6 +110,7 @@ function serializedField(field: AssetTypeField): Record<string, unknown> {
setAliased(attrs, ["type", "kind"], field.type, "type");
setAliased(attrs, ["required"], field.required, "required");
setAliased(attrs, ["show_in_list", "show-in-list"], field.show_in_list, "show_in_list");
if (field.is_expiration || "is_expiration" in attrs) attrs.is_expiration = field.type === "date" && field.is_expiration === true;
setAliased(attrs, ["default_value", "default-value"], field.default_value, "default_value");
setAliased(attrs, ["options"], field.type === "select" ? field.options?.filter(Boolean) ?? [] : null, "options");
return source;
Expand All @@ -131,6 +134,7 @@ export function normalizeAssetTypeFields(raw: unknown): AssetTypeField[] {
type: kind.type,
required: Boolean(attrs.required),
show_in_list: Boolean(attrs.show_in_list ?? attrs["show-in-list"]),
is_expiration: attrs.is_expiration === true,
default_value: (attrs.default_value ?? attrs["default-value"]) == null ? null : String(attrs.default_value ?? attrs["default-value"]),
options: optionsFrom(attrs.options),
sourceType: kind.sourceType,
Expand Down Expand Up @@ -215,6 +219,7 @@ export function AssetTypeEditor({ initial, onSave, onCancel, saving = false, sou
{field.type === "select" && <BfTextarea label="Options" hint="One option per line." value={(field.options ?? []).join("\n")} onChange={(event) => updateField(index, { options: event.target.value.split("\n").map((option) => option.trim()).filter(Boolean) })} />}
{field.type !== "header" && field.type !== "upload" && <BfTextField label="Default value" value={field.default_value ?? ""} onChange={(event) => updateField(index, { default_value: event.target.value || null })} />}
{field.type === "upload" && <p className="text-sm text-muted-foreground">Upload references are managed with attachments.</p>}
{field.type === "date" && <BfCheckbox checked={field.is_expiration === true} onChange={(is_expiration) => updateField(index, { is_expiration })}>Track as an expiration date</BfCheckbox>}
<div className="flex flex-wrap gap-3"><BfCheckbox checked={field.required} onChange={(required) => updateField(index, { required })}>Required</BfCheckbox><BfCheckbox checked={field.show_in_list} onChange={(show_in_list) => updateField(index, { show_in_list })}>Show in list</BfCheckbox></div></>}
<div className="flex flex-wrap gap-3"><BfButton type="button" variant="ghost" aria-label={`Move ${field.name || `field ${index + 1}`} up`} disabled={index === 0 || readOnly || isReadOnly(values.fields[index - 1])} icon={<ChevronUp size={15} />} onClick={() => move(index, -1)}>Up</BfButton><BfButton type="button" variant="ghost" aria-label={`Move ${field.name || `field ${index + 1}`} down`} disabled={index === values.fields.length - 1 || readOnly || isReadOnly(values.fields[index + 1])} icon={<ChevronDown size={15} />} onClick={() => move(index, 1)}>Down</BfButton><BfButton type="button" variant="danger" disabled={readOnly} icon={<Trash2 size={15} />} onClick={() => update({ fields: values.fields.filter((_, position) => position !== index) })}>Remove</BfButton></div>
</div>;
Expand Down
68 changes: 68 additions & 0 deletions apps/bifrost-docs/src/components/UpcomingExpirations.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import "@testing-library/jest-dom/vitest";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

const mocks = vi.hoisted(() => ({
scope: { organizationId: "a", viewerId: "user-a", viewerSettled: true, loading: false, error: "" },
mutate: vi.fn(),
}));
vi.mock("bifrost", () => ({ useWorkflowMutation: () => ({ mutate: mocks.mutate }) }));
vi.mock("./layout/useDocsOrganizations", () => ({ useDocsOrganizations: () => mocks.scope }));
import { UpcomingExpirations } from "./UpcomingExpirations";

const item = { asset_id: "asset-a", asset_name: "Firewall", asset_type_id: "type-a", asset_type_name: "License", organization_id: "a", field_key: "renewal", field_name: "Renewal", expires_on: "2026-10-15", days_until: 1 };
const page = { items: [item], scanned: 1, invalid_dates: 0, next_cursor: null, as_of: "2026-10-14", within_days: 30 };
function mount() { return render(<MemoryRouter><UpcomingExpirations /></MemoryRouter>); }
beforeEach(() => {
mocks.scope = { organizationId: "a", viewerId: "user-a", viewerSettled: true, loading: false, error: "" };
mocks.mutate.mockReset().mockResolvedValue(page);
});
afterEach(cleanup);

describe("UpcomingExpirations", () => {
it("loads scoped dates with an actionable asset link and window selection", async () => {
mount();
expect(await screen.findByRole("link", { name: "Firewall" })).toHaveAttribute("href", "/org/a/assets/type-a/asset-a");
expect(screen.getByText("Expires in 1 day")).toBeVisible();
expect(mocks.mutate).toHaveBeenCalledWith({ organization_id: "a", within_days: 30, cursor: "" });
fireEvent.change(screen.getByLabelText("Due within"), { target: { value: "7" } });
await waitFor(() => expect(mocks.mutate).toHaveBeenLastCalledWith({ organization_id: "a", within_days: 7, cursor: "" }));
});
it("does not execute with no selected organization or unsettled identity", () => {
mocks.scope.organizationId = "";
const view = mount();
expect(screen.getByText("Select an organization to view its expiration dates.")).toBeVisible();
expect(mocks.mutate).not.toHaveBeenCalled();
mocks.scope.organizationId = "a";
mocks.scope.viewerSettled = false;
view.rerender(<MemoryRouter><UpcomingExpirations /></MemoryRouter>);
expect(mocks.mutate).not.toHaveBeenCalled();
});
it("does not label an incomplete empty page as no expirations", async () => {
mocks.mutate.mockResolvedValueOnce({ ...page, items: [], scanned: 100, next_cursor: "cursor-a" }).mockResolvedValueOnce(page);
mount();
expect(await screen.findByText("No matching dates in the assets checked so far.")).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Check next 100 assets" }));
expect(await screen.findByRole("link", { name: "Firewall" })).toBeVisible();
expect(screen.getByText(/Checked 101 assets/)).toBeVisible();
expect(mocks.mutate).toHaveBeenLastCalledWith({ organization_id: "a", within_days: 30, cursor: "cursor-a" });
});
it("shows errors with retry and date validation warnings", async () => {
mocks.mutate.mockRejectedValueOnce(new Error("unavailable")).mockResolvedValueOnce({ ...page, invalid_dates: 2 });
mount();
fireEvent.click(await screen.findByRole("button", { name: "Retry" }));
expect(await screen.findByText("Some dates need attention")).toBeVisible();
});
it("hides previous account data immediately and ignores its delayed result", async () => {
let resolve!: (value: typeof page) => void;
mocks.mutate.mockReturnValueOnce(new Promise(result => { resolve = result; }));
const view = mount();
mocks.scope = { ...mocks.scope, organizationId: "b", viewerId: "user-b" };
mocks.mutate.mockResolvedValue({ ...page, items: [] });
view.rerender(<MemoryRouter><UpcomingExpirations /></MemoryRouter>);
await act(async () => { resolve(page); });
expect(screen.queryByRole("link", { name: "Firewall" })).not.toBeInTheDocument();
expect(await screen.findByText(/No matching expiration dates/)).toBeVisible();
});
});
83 changes: 83 additions & 0 deletions apps/bifrost-docs/src/components/UpcomingExpirations.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { useWorkflowMutation } from "bifrost";
import { useDocsOrganizations } from "./layout/useDocsOrganizations";
import { BfAlert } from "./bifrost/BfAlert";
import { BfButton } from "./bifrost/BfButton";
import { BfSelect } from "./bifrost/BfField";

type Expiration = {
asset_id: string; asset_name: string; asset_type_id: string; asset_type_name: string; organization_id: string;
field_key: string; field_name: string; expires_on: string; days_until: number;
};
type Page = { items: Expiration[]; scanned: number; invalid_dates: number; next_cursor: string | null; as_of: string; within_days: number };
type Snapshot = { key: string; page: Page | null; loading: boolean; error: string; failedCursor: string };
const WORKFLOW = "functions/expirations.py::docs_list_expirations";

function timing(days: number) {
return days < 0 ? `Expired ${-days} ${days === -1 ? "day" : "days"} ago` : days === 0 ? "Expires today" : `Expires in ${days} ${days === 1 ? "day" : "days"}`;
}

export function UpcomingExpirations() {
const { organizationId, viewerId, viewerSettled, loading: scopeLoading, error: scopeError } = useDocsOrganizations();
const [withinDays, setWithinDays] = useState(30);
const workflow = useWorkflowMutation<Page>(WORKFLOW);
const mutate = useRef(workflow.mutate);
mutate.current = workflow.mutate;
const key = `${viewerId ?? ""}:${organizationId}:${withinDays}:${viewerSettled}:${scopeLoading}:${scopeError}`;
const activeKey = useRef(key);
activeKey.current = key;
const request = useRef(0);
const [snapshot, setSnapshot] = useState<Snapshot>({ key: "", page: null, loading: false, error: "", failedCursor: "" });
const current = snapshot.key === key ? snapshot : null;
const ready = Boolean(organizationId && viewerId && viewerSettled && !scopeLoading && !scopeError);

const load = useCallback(async (cursor = "") => {
const expectedKey = key;
const attempt = ++request.current;
setSnapshot(previous => ({ key, page: cursor && previous.key === key ? previous.page : null, loading: true, error: "", failedCursor: cursor }));
try {
const page = await mutate.current({ organization_id: organizationId, within_days: withinDays, cursor });
if (activeKey.current !== expectedKey || request.current !== attempt) return;
if (page.next_cursor && page.next_cursor === cursor) throw new Error("The next asset page repeated. Refresh to restart.");
setSnapshot(previous => {
const prior = cursor && previous.key === key ? previous.page : null;
const items = new Map([...(prior?.items ?? []), ...page.items].map(item => [`${item.asset_id}:${item.field_key}`, item]));
return { key, loading: false, error: "", failedCursor: "", page: {
...page, items: [...items.values()].sort((a, b) => a.expires_on.localeCompare(b.expires_on) || a.asset_id.localeCompare(b.asset_id) || a.field_key.localeCompare(b.field_key)),
scanned: (prior?.scanned ?? 0) + page.scanned,
invalid_dates: (prior?.invalid_dates ?? 0) + page.invalid_dates,
} };
});
} catch {
if (activeKey.current === expectedKey && request.current === attempt) {
setSnapshot(previous => ({ ...previous, loading: false, error: "Expiration dates could not load. Try again.", failedCursor: cursor }));
}
}
}, [key, organizationId, withinDays]);

useEffect(() => {
if (ready) void load();
return () => { request.current += 1; };
}, [load, ready]);

return <section aria-label="Upcoming expirations" className="grid gap-3">
<div className="flex flex-wrap items-end justify-between gap-3">
<div><h2 className="text-lg font-semibold">Upcoming expirations</h2><p className="text-sm text-muted-foreground">Expired assets and flagged dates due soon in the selected organization.</p></div>
{ready && <div className="flex items-end gap-2"><BfSelect label="Due within" value={withinDays} options={[7, 14, 30, 90].map(days => ({ value: String(days), label: `${days} days` }))} onChange={event => setWithinDays(Number(event.target.value))} /><BfButton variant="secondary" disabled={current?.loading} onClick={() => void load()}>Refresh</BfButton></div>}
</div>
{!ready ? <p className="text-sm text-muted-foreground">{scopeError ? "Organization scope is unavailable. Retry using the organization selector." : scopeLoading || !viewerSettled ? "Loading organization scope…" : "Select an organization to view its expiration dates."}</p> : <>
{current?.error && <BfAlert tone="danger" title="Could not load expirations">{current.error}<BfButton variant="secondary" onClick={() => void load(current.failedCursor)}>Retry</BfButton></BfAlert>}
{(!current || current.loading) && <p role="status">Loading expiration dates…</p>}
{current?.page && <>
{current.page.items.length > 0 ? <ul className="divide-y divide-[var(--bf-line)]">{current.page.items.map(item => <li key={`${item.asset_id}:${item.field_key}`} className="flex flex-wrap items-center justify-between gap-2 py-3">
<div><Link className="font-medium text-[var(--bf-primary)] underline underline-offset-3" to={`/org/${encodeURIComponent(item.organization_id)}/assets/${encodeURIComponent(item.asset_type_id)}/${encodeURIComponent(item.asset_id)}`}>{item.asset_name}</Link><p className="text-sm text-muted-foreground">{item.asset_type_name} · {item.field_name}</p></div>
<div className="text-sm"><span className={item.days_until < 0 ? "text-destructive" : ""}>{timing(item.days_until)}</span><time className="ml-2 text-muted-foreground" dateTime={item.expires_on}>{item.expires_on}</time></div>
</li>)}</ul> : <p className="text-sm text-muted-foreground">{current.page.next_cursor ? "No matching dates in the assets checked so far." : "No matching expiration dates. In Settings → Asset types, mark a Date field as an expiration date and set its value on an asset."}</p>}
<p className="text-xs text-muted-foreground">Checked {current.page.scanned} assets as of {current.page.as_of} UTC.{current.page.next_cursor ? " Results are incomplete; check the next assets to find additional dates." : " Scan complete."}</p>
{current.page.invalid_dates > 0 && <BfAlert tone="warning" title="Some dates need attention">{current.page.invalid_dates} flagged values are not valid YYYY-MM-DD dates and were excluded.</BfAlert>}
{current.page.next_cursor && !current.error && <BfButton variant="secondary" disabled={current.loading} onClick={() => void load(current.page!.next_cursor!)}>Check next 100 assets</BfButton>}
</>}
</>}
</section>;
}
1 change: 1 addition & 0 deletions apps/bifrost-docs/src/pages/DashboardPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ vi.mock("@/components/layout/useDocsOrganizations", () => ({
useDocsOrganizations: () => ({ organizations: mocks.organizations }),
}));
vi.mock("@/components/layout/recentRecords", () => ({ useRecentRecords: () => mocks.recent }));
vi.mock("@/components/UpcomingExpirations", () => ({ UpcomingExpirations: () => <section aria-label="Upcoming expirations" /> }));

import { DashboardPage } from "./DashboardPage";

Expand Down
Loading
Loading