All files / pages/collections CollectionNewPage.tsx

58.18% Statements 32/55
58.62% Branches 17/29
50% Functions 4/8
58.18% Lines 32/55

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                                                                  15x 15x 15x 15x       15x           15x   15x   15x 15x 15x 15x 15x     15x   15x 8x 4x       15x 4x     11x 3x 3x 3x 3x 3x   3x 3x       3x 3x         3x                       11x       11x                                                                                             11x                                                                                                                                                                                                                                                                          
/**
 * /admin/collections/new — full-page create collection flow (Phase 2 + templates).
 */
 
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router';
import { AlertTriangle, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ToastAction } from '@/components/ui/toast';
import SchemaColumnTable from '@/components/collections/SchemaColumnTable';
import SystemFieldsPanel from '@/components/collections/SystemFieldsPanel';
import CollectionTemplatePicker from '@/components/collections/CollectionTemplatePicker';
import {
  prepareSchemaPayload,
  validateSchemaFields,
  type SchemaFieldErrors,
} from '@/components/collections/schemaValidation';
import {
  createCollection,
  type FieldDefinition,
} from '@/services/collections.service';
import {
  applyTemplate,
  BLANK_TEMPLATE_ID,
  getTemplateById,
} from '@/lib/collectionTemplates';
import { handleApiError } from '@/lib/api';
import { useToast } from '@/hooks/use-toast';
import { useCollectionsWorkspace } from './CollectionsWorkspaceContext';
 
export default function CollectionNewPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { toast } = useToast();
  const { collectionNames, refreshCollections, isSuperadmin } =
    useCollectionsWorkspace();
 
  const initialTemplateId =
    searchParams.get('template') &&
    (searchParams.get('template') === BLANK_TEMPLATE_ID ||
      getTemplateById(searchParams.get('template')!))
      ? searchParams.get('template')!
      : BLANK_TEMPLATE_ID;
 
  const initialApply = applyTemplate(initialTemplateId);
 
  const [selectedTemplateId, setSelectedTemplateId] =
    useState(initialTemplateId);
  const [name, setName] = useState(initialApply.suggestedName);
  const [fields, setFields] = useState<FieldDefinition[]>(initialApply.fields);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<SchemaFieldErrors>({});
 
  /** Last template-suggested name so we only overwrite name when user has not customized it. */
  const lastSuggestedNameRef = useRef(initialApply.suggestedName);
 
  useEffect(() => {
    if (!isSuperadmin) {
      navigate('/admin/collections', { replace: true });
    }
  }, [isSuperadmin, navigate]);
 
  if (!isSuperadmin) {
    return null;
  }
 
  const handleSelectTemplate = (templateId: string) => {
    const applied = applyTemplate(templateId);
    setSelectedTemplateId(applied.templateId);
    setFields(applied.fields);
    setFieldErrors({});
    setError(null);
 
    setName((current) => {
      Eif (
        !current.trim() ||
        current === lastSuggestedNameRef.current
      ) {
        lastSuggestedNameRef.current = applied.suggestedName;
        return applied.suggestedName;
      }
      return current;
    });
 
    toast({
      title:
        applied.templateId === BLANK_TEMPLATE_ID
          ? 'Blank template'
          : 'Template applied',
      description:
        applied.templateId === BLANK_TEMPLATE_ID
          ? 'Schema cleared. Add your own columns.'
          : `Loaded ${applied.fields.length} fields. Edit before creating.`,
    });
  };
 
  const handleCancel = () => {
    navigate('/admin/collections');
  };
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setFieldErrors({});
 
    if (!name.trim()) {
      setError('Collection name is required');
      return;
    }
 
    const result = validateSchemaFields(fields);
    if (!result.valid) {
      setFieldErrors(result.fieldErrors);
      setError(result.formError ?? 'Schema validation failed');
      return;
    }
 
    setIsSubmitting(true);
    try {
      const created = await createCollection({
        name: name.trim(),
        schema: prepareSchemaPayload(fields),
      });
      await refreshCollections();
      toast({
        title: 'Collection created',
        description:
          'Default access rules are locked. Configure Rules so clients can list or create records.',
        action: (
          <ToastAction
            altText="Configure rules"
            onClick={() =>
              navigate(`/admin/collections/${created.name}/rules`)
            }
          >
            Configure rules
          </ToastAction>
        ),
      });
      navigate(`/admin/collections/${created.name}/schema`, { replace: true });
    } catch (err) {
      setError(handleApiError(err));
    } finally {
      setIsSubmitting(false);
    }
  };
 
  return (
    <div
      className="mx-auto flex max-w-5xl flex-col gap-6 p-6 pb-28"
      data-testid="collection-new-page"
    >
      <div>
        <h1 className="text-2xl font-bold">Create collection</h1>
        <p className="text-sm text-muted-foreground">
          Define a global multi-tenant table with custom columns. System fields
          are added automatically.
        </p>
      </div>
 
      {isSubmitting ? (
        <div className="flex flex-col items-center justify-center space-y-4 py-16">
          <Loader2 className="h-12 w-12 animate-spin text-primary" />
          <div className="text-center">
            <p className="font-medium">
              Creating collection and applying migrations…
            </p>
            <p className="mt-1 text-sm text-muted-foreground">
              Please wait while the database table is being created.
            </p>
          </div>
        </div>
      ) : (
        <form onSubmit={handleSubmit} className="space-y-6" id="create-collection-form">
          <div className="space-y-2">
            <Label>Starter template</Label>
            <CollectionTemplatePicker
              selectedId={selectedTemplateId}
              onSelect={handleSelectTemplate}
              disabled={isSubmitting}
            />
            <p className="text-xs text-muted-foreground">
              Templates pre-fill columns; everything remains editable before create.
            </p>
          </div>
 
          <div className="space-y-2">
            <Label htmlFor="collection-name">Collection name *</Label>
            <Input
              id="collection-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="customers"
              disabled={isSubmitting}
              autoFocus
            />
            <p className="text-xs text-muted-foreground">
              3–64 characters, alphanumeric and underscores only
            </p>
          </div>
 
          <div
            className="rounded-lg border border-blue-200 bg-blue-50 p-4 dark:border-blue-900 dark:bg-blue-950/20"
            data-testid="create-access-callout"
          >
            <p className="text-sm font-medium text-blue-900 dark:text-blue-100">
              Access model
            </p>
            <ul className="mt-2 list-disc space-y-1.5 pl-5 text-sm text-blue-900/90 dark:text-blue-100/90">
              <li>
                Every collection is a <strong>global table</strong>. Row isolation
                is always on via{' '}
                <code className="font-mono text-xs">account_id</code>.
              </li>
              <li>
                Access rules control API visibility per operation (list / view /
                create / update / delete) — not a Postgres RLS toggle.
              </li>
              <li>
                Defaults are <strong>locked</strong>: non-superadmin clients get
                HTTP 403 until you open or customize rules on the Rules tab.
              </li>
              <li>
                An empty-string rule is <strong>public</strong> (unauthenticated
                allowed for that operation). Custom expressions require auth and
                may return empty lists when no rows match.
              </li>
            </ul>
          </div>
 
          <div className="flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 p-4 dark:border-amber-900 dark:bg-amber-950/20">
            <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-700 dark:text-amber-300" />
            <p className="text-sm text-amber-900 dark:text-amber-200">
              This creates a global database table shared across accounts (data
              isolated by <code className="font-mono text-xs">account_id</code>).
              Migrations run immediately on create.
            </p>
          </div>
 
          <SystemFieldsPanel />
 
          <SchemaColumnTable
            fields={fields}
            onChange={setFields}
            collections={collectionNames}
            fieldErrors={fieldErrors}
          />
 
          {error && (
            <div className="rounded-lg border border-destructive/20 bg-destructive/10 p-4">
              <p className="text-sm text-destructive">{error}</p>
            </div>
          )}
        </form>
      )}
 
      {!isSubmitting && (
        <div className="fixed bottom-0 left-0 right-0 z-10 border-t bg-background/95 px-6 py-3 backdrop-blur supports-[backdrop-filter]:bg-background/80 md:left-[var(--sidebar-width,0px)]">
          <div className="mx-auto flex max-w-5xl justify-end gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={handleCancel}
              disabled={isSubmitting}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              form="create-collection-form"
              disabled={isSubmitting}
            >
              Create collection
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}