All files / src/apps/user/pages/organisations NewOrganisation.tsx

38.63% Statements 17/44
37.5% Branches 9/24
36.36% Functions 4/11
43.58% Lines 17/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                                        1x     1x   1x         1x                     1x 1x                                                 1x 1x 1x   1x 1x 1x 1x   1x           1x                                         1x                                                                 5x                                                                                                          
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import SubPage from "@/components/page/SubPage/SubPage";
import { APP_ROUTES } from "@/routes/const";
import { useApiHandler } from "@/services/useApiHandler";
import { Organisation } from "@/objects/Organisation";
import {
  Building2,
  Users,
  AlertCircle,
  Loader2,
  Check,
} from "lucide-react";
import {
  SectionCard,
} from "@/components/detail";
 
// ─── Primitives ───────────────────────────────────────────────────────────────
 
const inputBase =
  "w-full px-3 py-2 text-sm rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-300 dark:focus:ring-gray-500 transition-colors";
 
const errorBase =
  "w-full px-3 py-2 text-sm rounded-lg border border-red-300 dark:border-red-700 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-red-200 dark:focus:ring-red-900 transition-colors";
 
const FieldLabel: React.FC<{
  label: string;
  description?: string;
  required?: boolean;
}> = ({ label, description, required }) => (
  <div className="mb-1.5">
    <div className="text-sm font-medium text-gray-700 dark:text-gray-300">
      {label}
      {required && <span className="ml-0.5 text-red-500">*</span>}
    </div>
    {description && (
      <p className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">{description}</p>
    )}
  </div>
);
 
const CharCount: React.FC<{ value: string; max: number }> = ({ value, max }) => (
  <div
    className={`text-right text-xs mt-1 ${
      value.length > max ? "text-red-500" : "text-gray-400 dark:text-gray-500"
    }`}
  >
    {value.length} / {max}
  </div>
);
 
// ─── Form state ───────────────────────────────────────────────────────────────
 
interface FormData {
  name: string;
}
 
function validate(data: FormData): Partial<Record<keyof FormData, string>> {
  const errors: Partial<Record<keyof FormData, string>> = {};
  if (!data.name.trim()) errors.name = "Name is required.";
  else if (data.name.trim().length < 2) errors.name = "Name must be at least 2 characters.";
  else if (data.name.trim().length > 50) errors.name = "Name must be 50 characters or fewer.";
  return errors;
}
 
// ─── NewOrganisation ──────────────────────────────────────────────────────────
 
const NewOrganisation: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  const navigate = useNavigate();
 
  const [data, setData] = useState<FormData>({ name: "" });
  const [errors, setErrors] = useState<Partial<Record<keyof FormData, string>>>({});
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
 
  const set = <K extends keyof FormData>(key: K, value: string) => {
    setData((prev) => ({ ...prev, [key]: value }));
    setErrors((prev) => ({ ...prev, [key]: undefined }));
    setSubmitError(null);
  };
 
  const handleSubmit = async () => {
    const errs = validate(data);
    if (Object.keys(errs).length > 0) {
      setErrors(errs);
      return;
    }
    setSubmitting(true);
    setSubmitError(null);
    try {
      await getApiHandler().organisation_router.new({
        name: data.name.trim(),
      } as unknown as Organisation);
      navigate(APP_ROUTES.USER.organisations);
    } catch (e: unknown) {
      const err = e as { message?: string };
      setSubmitError(err?.message ?? "Something went wrong. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };
 
  return (
    <SubPage title="New Organisation">
      <div className="max-w-2xl space-y-4">
        {/* Identity */}
        <SectionCard variant="form" icon={Building2} title="Identity">
          <div>
            <FieldLabel
              label="Name"
              description="The name of your organisation as it will appear across the platform."
              required
            />
            <input
              type="text"
              value={data.name}
              onChange={(e) => set("name", e.target.value)}
              placeholder="e.g. ACME Corp"
              className={errors.name ? errorBase : inputBase}
            />
            <CharCount value={data.name} max={50} />
            {errors.name && <p className="text-xs text-red-500 mt-1">{errors.name}</p>}
          </div>
        </SectionCard>
 
        {/* What's included info */}
        <SectionCard variant="form" icon={Users} title="What's in an Organisation">
          <ul className="space-y-2">
            {[
              "Projects — workspaces grouped under the organisation.",
              "Resources — agents, knowledge and rules the organisation owns.",
              "Governance — rules and quotas that apply to everything it owns.",
              "Spend — usage and cost broken down by organisation.",
              "Members — inviting colleagues is on the roadmap.",
            ].map((item) => (
              <li
                key={item}
                className="flex items-start gap-2 text-sm text-gray-600 dark:text-gray-400"
              >
                <span className="mt-2 size-1.5 rounded-full bg-gray-400 dark:bg-gray-500 shrink-0" />
                {item}
              </li>
            ))}
          </ul>
        </SectionCard>
 
        {/* Submit error */}
        {submitError && (
          <div className="flex items-center gap-2 px-4 py-3 rounded-lg bg-red-50 dark:bg-red-950/40 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-300 text-sm">
            <AlertCircle className="size-4 shrink-0" />
            {submitError}
          </div>
        )}
 
        {/* Actions */}
        <div className="flex items-center justify-end gap-3 pt-2">
          <button
            type="button"
            onClick={() => navigate(APP_ROUTES.USER.organisations)}
            className="px-4 py-2 rounded-lg text-sm font-medium text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={handleSubmit}
            disabled={submitting}
            className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-gray-900 dark:bg-white text-white dark:text-gray-900 text-sm font-medium hover:opacity-80 disabled:opacity-50 transition-opacity"
          >
            {submitting ? (
              <>
                <Loader2 className="size-4 animate-spin" />
                Creating…
              </>
            ) : (
              <>
                <Check className="size-4" />
                Create Organisation
              </>
            )}
          </button>
        </div>
      </div>
    </SubPage>
  );
};
 
export default NewOrganisation;