SHOOTERplano · fase 0 aguardando aprovação

#Modelo de dados

Convenções: Postgres 18, Drizzle. Tabelas em snake_case plural; PK id uuid (UUIDv7 gerado na aplicação, ordenável por tempo); created_at, updated_at timestamptz not null default now(); soft delete com deleted_at onde indicado; toda tabela de domínio tem workspace_id desnormalizado para autorização O(1).

#1. Hierarquia

user ─< member >─ workspace ─< project ─< location ─< set ─< shot ─< version
                     │            │           │        │
                     │            ├─< project_cast     └─ scene_doc (planta)   shot ─ scene_doc (plano)
                     │            └─< project_equipment
                     ├─< library_item (custom)  ├─< kit  ├─< audit_log  ├─< api_key (futuro)
erDiagram
  USER ||--o{ MEMBER : has
  WORKSPACE ||--o{ MEMBER : has
  WORKSPACE ||--o{ INVITATION : has
  WORKSPACE ||--o{ PROJECT : owns
  PROJECT ||--o{ PROJECT_CAST : has
  PROJECT ||--o{ PROJECT_EQUIPMENT : has
  PROJECT ||--o{ LOCATION : has
  LOCATION ||--o{ LOCATION_CONTACT : has
  LOCATION ||--o{ LOCATION_ACCESS_WINDOW : has
  LOCATION ||--o{ ATTACHMENT : has
  LOCATION ||--o{ SET : has
  SET ||--o{ SHOT : has
  SET ||--|| SCENE_DOC : plan
  SHOT ||--|| SCENE_DOC : shot
  SHOT ||--o{ VERSION : snapshots
  SHOT ||--o{ COMMENT_THREAD : has
  COMMENT_THREAD ||--o{ COMMENT : has
  SHOT ||--o{ SHARE_LINK : has
  WORKSPACE ||--o{ LIBRARY_ITEM : custom
  WORKSPACE ||--o{ KIT : has
  WORKSPACE ||--o{ AUDIT_LOG : records
  WORKSPACE ||--o{ FILE : stores
  WORKSPACE ||--o{ EXPORT_JOB : runs

#2. Tabelas

#2.1 Autenticação (geradas pelo Better Auth, nomes padrão, usePlural: true)

Tabela Campos relevantes Observações
users id, name, email (unique, citext), email_verified, image, locale, two_factor_enabled
sessions id, user_id, token (unique), expires_at, ip_address, user_agent, active_organization_id cookie httpOnly __Host-shooter.session
accounts id, user_id, provider_id, account_id, password (hash Argon2id) provider_id='credential'
verifications id, identifier, value, expires_at magic link, reset de senha, verificação de e-mail
two_factors id, user_id, secret (cifrado), backup_codes (cifrado)
organizations id, name, slug (unique), logo, metadata = workspace (renomeado na UI)
members id, organization_id, user_id, role, created_at unique(organization_id, user_id)
invitations id, organization_id, email, role, status, expires_at, inviter_id

Papéis (members.role), em ordem crescente de poder: viewer < commenter < editor < admin < owner.

#2.2 Domínio

Tabela Colunas Índices / restrições
projects id, workspace_id, title, client, starts_on date, ends_on date, status enum(active,archived), cover_file_id, settings jsonb (unidades padrão, fps padrão), deleted_at idx(workspace_id, status, updated_at desc); GIN trigram em title, client
project_members project_id, user_id, role override opcional de papel por projeto (só restringe ou eleva até editor) PK(project_id,user_id)
project_cast id, workspace_id, project_id, name, character, photo_file_id, color (hex), role enum(cast,stand_in,extra_group), notes, sort idx(project_id, sort)
project_equipment id, workspace_id, project_id, library_item_ref (text: global:<id> ou ws:<uuid>), quantity int, notes unique(project_id, library_item_ref)
locations id, workspace_id, project_id, name, address text, geo (lat, lng numeric(9,6)), timezone, north_offset_deg, power jsonb, acoustics jsonb, permits jsonb, tags text[], notes_doc_id, deleted_at GIN(tags); idx(project_id); GIN trigram name/address
location_contacts id, location_id, workspace_id, name, role, phone, email, notes
location_access_windows id, location_id, workspace_id, weekday smallint null, date null, start_time, end_time, notes
sets id, workspace_id, location_id, name, units enum(metric,imperial), print_scale int (20, 50, 100…), grid_size_mm int, background jsonb (file_id, calibração), scene_doc_id, thumbnail_file_id, sort, deleted_at idx(location_id, sort)
shots id, workspace_id, set_id, code (ex.: 12A), title, description, duration_ms, fps, scene_doc_id, thumbnail_file_id, sort, status enum(draft,approved), deleted_at idx(set_id, sort); unique(set_id, code) where deleted_at is null
scene_docs id, workspace_id, kind enum(set,shot,notes), ydoc bytea (estado Yjs compactado), snapshot jsonb, schema_version int, snapshot_at, byte_size int idx(workspace_id); TOAST padrão
versions id, workspace_id, shot_id null, set_id null, label, auto bool, snapshot jsonb (gzip em snapshot_gz bytea após 30 dias), schema_version, created_by, created_at idx(shot_id, created_at desc); check(shot_id is not null or set_id is not null)
comment_threads id, workspace_id, shot_id, anchor jsonb ({type:'object', objectId} ou {type:'point', x, y} ou {type:'time', t}), resolved_at, created_by idx(shot_id, resolved_at)
comments id, thread_id, workspace_id, author_id, body (markdown limitado), mentions uuid[], created_at, edited_at, deleted_at idx(thread_id, created_at)
share_links id, workspace_id, shot_id, token_hash (sha256), permission enum(view), expires_at, revoked_at, created_by, last_used_at unique(token_hash)
files id, workspace_id, bucket, key, mime, size_bytes, sha256, kind enum(photo,plan,svg_symbol,attachment,export,thumbnail), status enum(pending,ready,rejected), owner_type, owner_id, created_by idx(workspace_id, kind); idx(owner_type, owner_id)
library_items id, workspace_id null (null = global publicado do banco, raro), manifest jsonb, manifest_version int, symbol_file_id, icon_file_id, status enum(draft,published), created_by, deleted_at GIN(manifest jsonb_path_ops); trigram em manifest->>'name'
kits id, workspace_id, name, description, items jsonb ([{ref, qty, props}]), created_by idx(workspace_id)
favorites user_id, workspace_id, item_ref text PK(user_id, workspace_id, item_ref)
user_preferences user_id PK, theme, keymap jsonb, units, locale, editor jsonb
export_jobs id, workspace_id, shot_id, kind enum(mp4,pdf_plan,pdf_lighting,png,svg,csv,xlsx,json), params jsonb, status enum(queued,running,done,failed), progress smallint, file_id, error, created_by idx(workspace_id, created_at desc)
audit_log id bigserial, workspace_id, actor_id null, actor_type enum(user,api_key,system), action text (ex.: shot.update, member.role_change), target_type, target_id, ip inet, user_agent, metadata jsonb, created_at idx(workspace_id, created_at desc); idx(target_type, target_id); append-only (REVOKE UPDATE/DELETE para o papel da app)
api_keys (futuro) id, workspace_id, name, prefix, hash, scopes text[], last_used_at, expires_at, revoked_at
webhooks (futuro) id, workspace_id, url, secret_enc, events text[], active

Extensões: pg_trgm, citext, pgcrypto.

#3. Permissões

#3.1 Matriz

Ação viewer commenter editor admin owner
Ver projetos/locações/planos ✓ ✓ ✓ ✓ ✓
Comentar / resolver próprio comentário ✓ ✓ ✓ ✓
Editar cena, caderno, projetos, locações ✓ ✓ ✓
Exportar ✓ ✓ ✓ ✓ ✓
Criar link público ✓ ✓ ✓
Itens personalizados de biblioteca / kits ✓ ✓ ✓
Convidar / mudar papéis (até admin) ✓ ✓
Ver auditoria ✓ ✓
Excluir workspace, transferir posse, cobrança ✓

project_members pode restringir um usuário num projeto (ex.: editor do workspace vira viewer num projeto sigiloso) ou elevar até editor. Papel efetivo = override do projeto se existir, senão papel do workspace.

#3.2 Aplicação no servidor

#4. Schema da cena (packages/scene-schema)

Um set e um shot são documentos separados: o shot referencia o set (planRef) e o editor monta a cena com os dois Y.Docs (a planta é editável a partir de qualquer plano, e as mudanças valem para todos os planos).

#4.1 Tipos (resumo normativo — a fonte é o Zod em packages/scene-schema/src/v1/*.ts)

type Id = string;            // nanoid(12)
type Mm = number;            // TODAS as distâncias internas em milímetros (float); unidades só na UI
type Deg = number;           // ângulos em graus; 0 = +X (leste na planta), anti-horário positivo
type Ms = number;            // tempo em milissegundos

interface SetDoc {
  schemaVersion: 1;
  meta: { name: string; units: 'metric' | 'imperial'; gridMm: Mm; printScale: number; northDeg: Deg };
  background?: { fileId: string; page?: number; calib: { p1: Vec2; p2: Vec2; distanceMm: Mm }; opacity: number; locked: boolean };
  layers: Record<LayerId, LayerState>;          // só camadas de arquitetura/arte fixa
  objects: Record<Id, SceneObject>;             // paredes, portas, janelas, pilares, escadas, cômodos, mobiliário fixo
  groups: Record<Id, Group>;
}

interface ShotDoc {
  schemaVersion: 1;
  planRef: { setId: string };
  meta: { code: string; title: string; fps: number; durationMs: Ms; camerasISO: Record<Id, ExposureSettings> };
  layers: Record<LayerId, LayerState>;
  objects: Record<Id, SceneObject>;             // câmeras, luzes, grip, elenco, figuração, anotações, objetos do plano
  groups: Record<Id, Group>;
  tracks: Record<Id, Track>;                    // animação
  markers: Record<Id, { t: Ms; label: string; color?: string }>;
  meters: Record<Id, { pos: Vec2; heightMm: Mm; cameraId?: Id; pinned: boolean }>;
  circuits: Record<Id, { name: string; sourceId?: Id; maxW?: number; voltage: 127 | 220 | 230 | 120 | 240 }>;
  overrides: Record<Id, Partial<SceneObject>>;  // ajustes por plano em objetos da planta (ex.: porta aberta)
}

type LayerId = 'architecture' | 'light' | 'grip' | 'camera' | 'cast' | 'extras' | 'art' | 'annotations' | 'background';
interface LayerState { visible: boolean; locked: boolean; opacity: number }

interface Transform { x: Mm; y: Mm; z: Mm; rotation: Deg; scaleX: number; scaleY: number }

interface SceneObjectBase {
  id: Id;
  itemRef: string;             // 'global:lights/aputure-ls-1200x' | 'ws:<uuid>' | 'builtin:wall'
  name?: string;               // rótulo customizado (default: nome do item)
  layer: LayerId;
  transform: Transform;
  parentId?: Id;               // hierarquia (câmera no car mount, luz no stand)
  groupId?: Id;
  locked: boolean;
  visible: boolean;
  props: Record<string, unknown>;   // validado contra o propsSchema do manifesto (biblioteca)
  label?: { show: boolean; offset: Vec2; template?: string };
  links?: { powerFrom?: Id; circuitId?: Id; trackId?: Id };
}

// Especializações por "kind" (o kind vem dos behaviors do manifesto)
interface WallObject extends SceneObjectBase { kind: 'wall'; path: { a: Vec2; b: Vec2; bulge: number }[]; thicknessMm: Mm; heightMm: Mm; material: 'solid' | 'glass' }
interface OpeningObject extends SceneObjectBase { kind: 'door' | 'window'; wallId: Id; offsetMm: Mm; widthMm: Mm; sillMm?: Mm; headMm: Mm; swing: 'left' | 'right' | 'double' | 'sliding' | 'none'; openDeg: Deg; flip: boolean }
interface RoomObject extends SceneObjectBase { kind: 'room'; polygon: Vec2[]; levelMm: Mm; name: string }  // área derivada
interface CameraObject extends SceneObjectBase { kind: 'camera'; letter: 'A' | 'B' | 'C' | string; bodyRef: string; lensRef: string; props: CameraProps }
interface LightObject extends SceneObjectBase { kind: 'light'; props: LightProps }
interface PathObject extends SceneObjectBase { kind: 'path'; segments: PathSegment[]; closed: boolean }    // trilho, trajeto, cabo
interface PersonObject extends SceneObjectBase { kind: 'person'; castId?: string; props: PersonProps }
interface CrowdObject extends SceneObjectBase { kind: 'crowd'; area: Vec2[]; count: number; seed: number; paths: Id[]; speedRange: [number, number] }
interface MarkObject extends SceneObjectBase { kind: 'mark'; ownerId: Id; index: number }                 // "1", "2"…
interface DimensionObject extends SceneObjectBase { kind: 'dimension'; a: Vec2 | AnchorRef; b: Vec2 | AnchorRef; offsetMm: Mm }
interface AnnotationObject extends SceneObjectBase { kind: 'text' | 'arrow' | 'area'; /* … */ }

interface CameraProps {
  heightMm: Mm; tiltDeg: Deg; rollDeg: Deg;
  focalMm: number;                 // zoom: dentro da faixa da lente
  formatId: string;                // modo de gravação do corpo (ex.: 'alexa35-4.6k-3:2-og')
  aspect: number | null;           // extração (ex.: 2.39) — null = formato nativo
  tStop: number; focusMm: Mm; cocMm?: number;
  iso: number; shutterAngle: number; fps: number; ndStops: number;
  showCone: boolean; coneLengthMm: Mm; showDof: boolean;
  rig: RigState;
}
type RigState =
  | { type: 'tripod' | 'highhat' } 
  | { type: 'dolly'; trackId: Id; s: Mm; armOffsetMm: Mm }
  | { type: 'slider'; trackId: Id; s: Mm }
  | { type: 'jib' | 'technocrane'; baseId: Id; armDeg: Deg; reachMm: Mm }
  | { type: 'steadicam' | 'gimbal' | 'easyrig' | 'handheld' | 'drone' }
  | { type: 'cablecam'; trackId: Id; s: Mm }
  | { type: 'carmount' | 'russianarm'; vehicleId: Id; local: Transform };

interface LightProps {
  on: boolean; dimmer: number;          // 0..1
  cctK: number; tint: number;           // tint em Δuv ×1000 (+ verde / − magenta)
  rgb?: [number, number, number];       // modos RGB das luzes de cor
  modeId: string;                       // refletor/lente da fotometria (ex.: 'hyper-reflector-15deg')
  modifiers: { itemRef: string; props: Record<string, unknown> }[];  // ordem = do aparelho para fora
  gels: { itemRef: string }[];
  heightMm: Mm; tiltDeg: Deg;
  showCone: boolean; showLabel: boolean;
}

interface Track {
  id: Id; objectId: Id;
  property: string;                     // JSON pointer limitado: 'transform.x', 'props.dimmer', 'props.rig.s', 'visible'…
  keys: Record<Id, Keyframe>;           // Y.Map por id — ordenação por t na leitura
  pathId?: Id;                          // animação em caminho (property = 'path.s')
}
interface Keyframe { id: Id; t: Ms; value: number | boolean | string | Vec2; ease: Easing; label?: string }
type Easing = { type: 'linear' | 'hold' } | { type: 'bezier'; x1: number; y1: number; x2: number; y2: number } | { type: 'preset'; name: 'easeIn' | 'easeOut' | 'easeInOut' };

#4.2 Mapeamento em Yjs

JSON Yjs
raiz doc.getMap('root') com chaves meta, layers, objects, groups, tracks, markers, meters, circuits, overrides
objects[id] Y.Map (cada campo é chave; props é Y.Map aninhado; arrays de geometria como valores JSON imutáveis — trocados inteiros)
tracks[id].keys Y.Map<Id, Y.Map>
schemaVersion doc.getMap('root').get('schemaVersion')

packages/scene-schema exporta toJSON(doc), fromJSON(json) → Y.Doc e validate(json). Testes de round-trip.

#4.3 Unidades

Internamente milímetros e graus, sempre. A UI converte com formatLength(mm, units, precision); entrada aceita expressões (3m 20, 10' 6", 2.5m+30cm). Troca de unidades é só preferência de exibição — nunca reescreve a cena. Escala de impressão afeta só exportação/régua.

#5. Versionamento do schema e migrações

#5.1 Cena

#5.2 Banco

#5.3 Biblioteca

manifestVersion no manifesto; itemRef é estável para sempre (renomear = alias). Itens removidos ficam como deprecated para cenas antigas continuarem abrindo.