Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | 3x 3x 7x 7x 7x 3x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 3x 3x 3x 3x 3x 3x 17x 3x 3x 6x 51x 1x 1x 4x 1x | import {
ErrorNote,
Field,
inputCls,
} from "@/apps/user/pages/evaluation/components";
import { Modal, ModalActions } from "@/components/detail";
import {
RuleAction,
RuleCatalogue,
RuleCreate,
RuleScopeTargets,
vocabularyEntries,
} from "@/objects/Rule";
import { APP_ROUTES } from "@/routes/const";
import type { WorkspaceKind } from "@/routes/workspace";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { errorDetail } from "@/util/apiError";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Wallet } from "lucide-react";
import React, { useState } from "react";
import { Link } from "react-router-dom";
/**
* Add a budget without the rule builder: an amount, a calendar period, who
* it covers and what happens when it is reached. It is written as an
* ordinary `cost_cap` rule — the builder can do everything else
* ("Open in rule builder").
*
* In an organisation a budget covers the organisation and every project in
* it (an organisation rule, Required in every project), or is an allocation
* to one project (an organisation rule pinned to it). Elsewhere it covers
* the workspace.
*/
/** The calendar periods a budget can count over, if the catalogue has not
* loaded yet. The catalogue's own labels win when it has. */
const FALLBACK_PERIODS = [
{ key: "month", label: "Each calendar month (UTC)" },
{ key: "week", label: "Each week (UTC, from Monday)" },
{ key: "day", label: "Each day (UTC)" },
];
const NAMES: Record<string, string> = {
month: "Monthly budget",
week: "Weekly budget",
day: "Daily budget",
};
type Reach = "workspace" | "project";
/** The rule a budget form describes. Exported for its test. */
export function budgetRule(form: {
amount: number;
period: string;
reach: Reach;
projectId?: string;
perMember: boolean;
warn: boolean;
name: string;
organisation: boolean;
}): RuleCreate {
const action: RuleAction = {
type: "cost_cap",
max_usd: form.amount,
period: form.period,
share: form.perMember ? "per_member" : "shared",
on_reach: form.warn ? "warn" : "block",
};
const project = form.reach === "project" && !!form.projectId;
return {
name: form.name,
description: "Added from Governance → Spend.",
layer: "access",
scope_type: project ? "project" : "global",
...(project ? { scope_id: form.projectId } : {}),
conditions: [],
actions: [action],
is_active: true,
priority: 0,
// An organisation's whole-workspace budget is one budget for it and
// every project in it; an allocation applies where it is pinned.
...(form.organisation && !project ? { required_for_projects: true } : {}),
};
}
const AddBudgetModal: React.FC<{
workspaceKind: WorkspaceKind;
targets: RuleScopeTargets | null | undefined;
catalogue: RuleCatalogue | null | undefined;
onClose: () => void;
}> = ({ workspaceKind, targets, catalogue, onClose }) => {
const { getApiHandler } = useApiHandler();
const queryClient = useQueryClient();
const organisation = workspaceKind === "organisation";
const projects = targets?.targets?.project ?? [];
const calendar = vocabularyEntries(catalogue, "quota_periods").filter(
(p) => p.calendar,
);
const periods = calendar.length ? calendar : FALLBACK_PERIODS;
const [amount, setAmount] = useState("");
const [period, setPeriod] = useState("month");
const [reach, setReach] = useState<Reach>("workspace");
const [projectId, setProjectId] = useState("");
const [perMember, setPerMember] = useState(false);
const [warn, setWarn] = useState(false);
const [name, setName] = useState("");
const [error, setError] = useState<string | null>(null);
const projectName = projects.find((p) => p.id === projectId)?.label;
const defaultName =
(NAMES[period] ?? "Budget") +
(reach === "project" && projectName ? ` — ${projectName}` : "");
const value = Number(amount);
const valid =
Number.isFinite(value) &&
value > 0 &&
(reach === "workspace" || !!projectId);
const create = useMutation({
mutationFn: async () => {
const created = await getApiHandler().rule_router.create(
budgetRule({
amount: value,
period,
reach,
projectId,
perMember,
warn,
name: name.trim() || defaultName,
organisation,
}),
);
Iif (!created) throw new Error("Could not add the budget.");
return created;
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.BUDGETS] });
void queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.RULES] });
onClose();
},
onError: (e) => setError(errorDetail(e, "Could not add the budget.")),
});
return (
<Modal
title="Add a budget"
icon={Wallet}
busy={create.isPending}
onClose={onClose}
description="A cap on what this workspace spends in a calendar period. When it is reached, the work it covers is refused until the period starts again — or, if you choose, let through and recorded."
footer={
<div className="flex w-full flex-wrap items-center justify-between gap-2">
<Link
to={APP_ROUTES.USER.GOVERNANCE.RULES.new}
className="text-xs text-gray-500 dark:text-gray-400 hover:underline"
>
Open in rule builder
</Link>
<ModalActions
onCancel={onClose}
onConfirm={() => {
setError(null);
create.mutate();
}}
confirmLabel="Add budget"
loadingLabel="Adding…"
loading={create.isPending}
disabled={!valid || create.isPending}
/>
</div>
}
>
<div className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Amount (USD)">
<input
autoFocus
aria-label="Amount (USD)"
type="number"
min="0"
step="0.01"
inputMode="decimal"
className={inputCls}
placeholder="100"
value={amount}
onChange={(e) => setAmount(e.target.value)}
/>
</Field>
<Field label="Period">
<select
aria-label="Period"
className={inputCls}
value={period}
onChange={(e) => setPeriod(e.target.value)}
>
{periods.map((p) => (
<option key={p.key} value={p.key}>
{p.label}
</option>
))}
</select>
</Field>
</div>
{organisation && (
<fieldset className="space-y-1.5">
<legend className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
Covers
</legend>
<label className="flex items-center gap-2 text-sm">
<input
type="radio"
name="reach"
checked={reach === "workspace"}
onChange={() => setReach("workspace")}
/>
The organisation and every project in it
</label>
<label className="flex items-center gap-2 text-sm">
<input
type="radio"
name="reach"
checked={reach === "project"}
onChange={() => setReach("project")}
disabled={projects.length === 0}
/>
One project — an allocation from the organisation
</label>
{reach === "project" && (
<select
aria-label="Project"
className={inputCls}
value={projectId}
onChange={(e) => setProjectId(e.target.value)}
>
<option value="">Choose a project…</option>
{projects.map((p) => (
<option key={p.id} value={p.id}>
{p.label}
</option>
))}
</select>
)}
</fieldset>
)}
{workspaceKind !== "personal" && (
<label className="flex items-start gap-2 text-sm">
<input
type="checkbox"
className="mt-1"
checked={perMember}
onChange={(e) => setPerMember(e.target.checked)}
/>
<span>
Give each member this amount
<span className="block text-xs text-gray-500 dark:text-gray-400">
Each member counts only their own spend, instead of sharing one
amount.
</span>
</span>
</label>
)}
<label className="flex items-start gap-2 text-sm">
<input
type="checkbox"
className="mt-1"
checked={warn}
onChange={(e) => setWarn(e.target.checked)}
/>
<span>
Warn instead of stopping
<span className="block text-xs text-gray-500 dark:text-gray-400">
Work goes on once it is reached, and each turn past it is
recorded in Activity.
</span>
</span>
</label>
<Field label="Name" hint="optional">
<input
aria-label="Name"
className={inputCls}
placeholder={defaultName}
value={name}
onChange={(e) => setName(e.target.value)}
/>
</Field>
{error && <ErrorNote message={error} />}
</div>
</Modal>
);
};
export default AddBudgetModal;
|