All files / src/apps/workspace/pages/settings General.tsx

92.68% Statements 38/41
87.27% Branches 48/55
75% Functions 9/12
92.3% Lines 36/39

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                      2x       24x                   2x   2x 6x                               2x         2x         26x 26x 26x 8x                   3x 3x                       18x                         14x             3x 3x 1x                                                     2x 12x 12x 12x 12x 12x 12x       12x 3x 3x         2x 3x     12x   8x             12x 12x 12x   12x                                                                                                                                                                    
import React, { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertCircle, Building2, FolderKanban } from "lucide-react";
import MainPage from "@/components/page/MainPage/MainPage";
import { SectionCard, Skeleton } from "@/components/detail";
import { useWorkspace } from "@/context/WorkspaceContext";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { parseServerDate } from "@/util/time";
import WorkspaceSettingsTabs from "./WorkspaceSettingsTabs";
 
const FieldRow: React.FC<{ label: string; value: React.ReactNode }> = ({
  label,
  value,
}) => (
  <div className="flex items-center justify-between gap-6 px-5 py-3.5">
    <div className="text-sm font-medium text-gray-700 dark:text-gray-300">
      {label}
    </div>
    <div className="text-sm text-right text-gray-500 dark:text-gray-400 min-w-0 break-words">
      {value}
    </div>
  </div>
);
 
const none = <span className="italic text-gray-400 dark:text-gray-500">None</span>;
 
const longDate = (value?: string | null) =>
  value
    ? parseServerDate(value).toLocaleDateString(undefined, {
        year: "numeric",
        month: "long",
        day: "numeric",
      })
    : "—";
 
interface WorkspaceRecord {
  name?: string | null;
  description?: string | null;
  cost_centre?: string | null;
  created_at?: string | null;
}
 
/** The longest code svc-core keeps (`COST_CENTRE_MAX`). */
const COST_CENTRE_MAX = 64;
 
/** The code finance files the workspace's spend under — on every row of its
 *  finance export, and frozen into each statement (svc-core migration 100).
 *  An admin may set it; everyone else reads it. */
const CostCentreRow: React.FC<{
  value?: string | null;
  editable: boolean;
  onSave: (code: string) => Promise<boolean>;
}> = ({ value, editable, onSave }) => {
  const [draft, setDraft] = useState<string | null>(null);
  const [failed, setFailed] = useState(false);
  if (!editable || draft === null) {
    return (
      <FieldRow
        label="Cost centre"
        value={
          <span className="inline-flex items-center gap-2">
            {value ? <span className="font-mono">{value}</span> : none}
            {editable && (
              <button
                type="button"
                onClick={() => {
                  setDraft(value ?? "");
                  setFailed(false);
                }}
                className="text-xs font-medium text-violet-600 dark:text-violet-400 hover:underline"
              >
                {value ? "Change" : "Set"}
              </button>
            )}
          </span>
        }
      />
    );
  }
  return (
    <div className="flex flex-wrap items-center justify-between gap-3 px-5 py-3.5">
      <label
        htmlFor="cost-centre"
        className="text-sm font-medium text-gray-700 dark:text-gray-300"
      >
        Cost centre
      </label>
      <span className="flex items-center gap-2">
        <input
          id="cost-centre"
          value={draft}
          maxLength={COST_CENTRE_MAX}
          onChange={(e) => setDraft(e.target.value)}
          placeholder="e.g. CC-104"
          className="w-40 rounded-md border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 px-2 py-1 text-sm font-mono"
        />
        <button
          type="button"
          onClick={async () => {
            const saved = await onSave(draft.trim());
            if (saved) setDraft(null);
            else setFailed(true);
          }}
          className="rounded-md bg-violet-600 px-2.5 py-1 text-xs font-medium text-white hover:bg-violet-700"
        >
          Save
        </button>
        <button
          type="button"
          onClick={() => setDraft(null)}
          className="text-xs text-gray-500 hover:underline"
        >
          Cancel
        </button>
      </span>
      {failed && (
        <p role="alert" className="w-full text-xs text-red-600 dark:text-red-400">
          The cost centre could not be saved.
        </p>
      )}
    </div>
  );
};
 
/**
 * An organisation's or project's General settings tab: what it is called,
 * when it was made and — for a project — whose it is.
 */
const WorkspaceGeneralSettings: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const ws = useWorkspace();
  const project = ws.kind === "project";
  const id = ws.id ?? "";
  const queryKey = [
    project ? QUERY_KEYS.GET.PROJECT_BY_ID : QUERY_KEYS.GET.ORGANISATION_BY_ID,
    id,
  ];
  const saveCostCentre = async (code: string): Promise<boolean> => {
    const body = { cost_centre: code || null };
    const saved = project
      ? await getApiHandler().project_router.update(id, body).catch(() => null)
      : await getApiHandler()
          .organisation_router.update(id, body)
          .catch(() => null);
    Eif (saved) await queryClient.invalidateQueries({ queryKey });
    return Boolean(saved);
  };
 
  const { data, isLoading, error } = useQuery<WorkspaceRecord | null>({
    queryKey,
    queryFn: async () =>
      (project
        ? await getApiHandler().project_router.id(id)
        : await getApiHandler().organisation_router.id(id)) ?? null,
    enabled: !!id,
  });
  // Typed here: TypeScript 5.0 reads useQuery's data as `any`.
  const record: WorkspaceRecord | null = data ?? null;
  const noun = project ? "project" : "organisation";
  const parent = ws.info?.parent;
 
  return (
    <MainPage
      title="General"
      description={`What this ${noun} is called and where it sits.`}
      links={[<WorkspaceSettingsTabs key="tabs" active="general" />]}
    >
      <div className="max-w-2xl space-y-4">
        {error && (
          <p role="alert" className="text-sm text-red-600 dark:text-red-400">
            Couldn&apos;t load this {noun}.
          </p>
        )}
        <SectionCard
          variant="settings"
          icon={project ? FolderKanban : Building2}
          title={project ? "Project" : "Organisation"}
          description={`The ${noun}'s identity.`}
        >
          {isLoading ? (
            <div className="px-5 py-4 space-y-3">
              <Skeleton className="h-4 w-full" />
              <Skeleton className="h-4 w-3/4" />
              <Skeleton className="h-4 w-1/2" />
            </div>
          ) : (
            <>
              <FieldRow label="Name" value={record?.name ?? ws.info?.name ?? "—"} />
              {project && (
                <>
                  <FieldRow label="Description" value={record?.description || none} />
                  <FieldRow
                    label="Part of"
                    value={
                      parent?.kind === "organisation"
                        ? (parent.name ?? "An organisation")
                        : "Your personal workspace"
                    }
                  />
                </>
              )}
              <CostCentreRow
                value={record?.cost_centre}
                editable={ws.info?.role === "admin"}
                onSave={saveCostCentre}
              />
              <FieldRow label="Created" value={longDate(record?.created_at)} />
            </>
          )}
        </SectionCard>
 
        <div className="rounded-xl border border-red-200 dark:border-red-900 bg-white dark:bg-gray-800 shadow-sm overflow-hidden">
          <div className="flex items-center gap-2 px-5 py-3.5 border-b border-red-100 dark:border-red-900/50">
            <AlertCircle className="size-4 text-red-500 dark:text-red-400 shrink-0" />
            <h3 className="text-sm font-semibold text-red-600 dark:text-red-400">
              Danger Zone
            </h3>
          </div>
          <div className="px-5 py-4 flex items-center justify-between">
            <div>
              <div className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Delete {noun}
              </div>
              <div className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">
                Permanently delete this {noun} and everything it owns. This
                cannot be undone.
              </div>
            </div>
            <button
              type="button"
              disabled
              className="ml-6 shrink-0 px-3 py-2 rounded-lg border border-red-200 dark:border-red-800 text-red-600 dark:text-red-400 text-sm font-medium opacity-40 cursor-not-allowed"
            >
              Delete
            </button>
          </div>
        </div>
      </div>
    </MainPage>
  );
};
 
export default WorkspaceGeneralSettings;