openapi: 3.0.3
info:
  title: VenuesAPI
  version: 0.2.0
  description: >-
    Venue directory + outreach-list backend for Kickoff HQ. Bearer API-key auth
    (sha256-hashed keys, scopes read/write/admin). All routes under /v1.
servers:
  - url: http://localhost:3014
    description: Local dev
  - url: https://venuesapi.jimfolio.space
    description: Production (Phase 3)
security:
  - bearerAuth: []
paths:
  /v1/health:
    get:
      summary: Liveness check
      security: []
      responses:
        '200':
          description: Service is up
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:
                    type: boolean
                    example: true
  /v1/public/venues:
    get:
      summary: List/search venues (public, no API key)
      description: >-
        Keyless public venue search. Same query params as GET /v1/venues, but
        `limit` is capped at 50 and `q` matches name, city and ext_id only
        (email excluded). Response rows are identical to the private list minus
        `email`, `altEmails`, `emailConfidence`, `emailSource`,
        `emailSourceUrl`, `notes`, `fieldSources`, `importBatch` and
        `groupInbox` — emails are private outreach data and the rest are
        internal fields, none of which appear on the public surface. Each row
        instead carries the derived `coordsSource` (provenance of its
        coordinates) and `publicDisplay` (whether the venue is safe for public
        display with attribution). Phone, website and socials are public
        business contact info and are included. Only live venues
        (deleted=false) are ever returned. Rate-limited to 120 requests/min
        per IP.
      security: []
      tags: [public]
      parameters:
        - name: q
          in: query
          schema: { type: string }
          description: Substring match on name, city, ext_id (email excluded)
        - name: city
          in: query
          schema: { type: string }
          description: City (ilike)
        - name: country
          in: query
          schema: { type: string }
          description: Country name, 2-letter ISO code, or common alias (uk/united kingdom/england → GB, usa/united states → US, …)
        - name: hasEmail
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues with an email on file (existence filter — the address itself is never exposed)
        - name: hasPhone
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues with a phone number
        - name: hasWebsite
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues with a website
        - name: hasFacebook
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues with a facebook link
        - name: hasInstagram
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues with an instagram link
        - name: hasSport
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues flagged as showing live sport (shows_live_sport yes/likely)
        - name: hasCoords
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues with both lat and lng set
        - name: publicDisplay
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues safe for public display (open/licensed source or owner-supplied fields)
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 50, default: 50 }
        - name: offset
          in: query
          schema: { type: integer, minimum: 0, default: 0 }
      responses:
        '200':
          description: >-
            Array of venues (may be empty). Email-family and internal fields
            are stripped from every row; `coordsSource` and `publicDisplay`
            derived fields are attached.
          content:
            application/json:
              schema:
                type: array
                items: { $ref: '#/components/schemas/Venue' }
        '429':
          description: Rate limit exceeded (120 req/min per IP)
          content:
            application/json:
              schema:
                type: object
                properties:
                  error: { type: string, example: rate_limited }
                  retry_after: { type: integer, description: Seconds until the bucket refills }
  /v1/public/venues.csv:
    get:
      summary: CSV export of the public venue search (no API key)
      description: >-
        Same filters as GET /v1/public/venues (q, city, country, has*), but
        returns the first 5,000 matches as a CSV download. Email columns and
        internal fields (notes, fieldSources, importBatch, groupInbox) are
        never included; `coordsSource` and `publicDisplay` columns are
        included. Cells are formula-escaped for spreadsheet safety.
        Rate-limited to 120 requests/min per IP.
      security: []
      tags: [public]
      parameters:
        - name: q
          in: query
          schema: { type: string }
        - name: city
          in: query
          schema: { type: string }
        - name: country
          in: query
          schema: { type: string }
        - name: hasEmail
          in: query
          schema: { type: string, enum: ['1', 'true'] }
        - name: hasPhone
          in: query
          schema: { type: string, enum: ['1', 'true'] }
        - name: hasWebsite
          in: query
          schema: { type: string, enum: ['1', 'true'] }
        - name: hasFacebook
          in: query
          schema: { type: string, enum: ['1', 'true'] }
        - name: hasInstagram
          in: query
          schema: { type: string, enum: ['1', 'true'] }
        - name: hasSport
          in: query
          schema: { type: string, enum: ['1', 'true'] }
      responses:
        '200':
          description: CSV file (max 5,000 rows; x-row-count and x-export-cap headers)
          content:
            text/csv:
              schema: { type: string, format: binary }
        '429':
          description: Rate limit exceeded (120 req/min per IP)
  /v1/public/countries:
    get:
      summary: Distinct countries with venue counts (public, no API key)
      description: >-
        One entry per country_code present in the dataset: the code, the most
        common country name for that code, and the venue count. Ordered by
        count descending. Rate-limited to 120 requests/min per IP.
      security: []
      tags: [public]
      responses:
        '200':
          description: Array of { countryCode, country, count }
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    countryCode: { type: string, example: GB }
                    country: { type: string, example: United Kingdom }
                    count: { type: integer, example: 45791 }
        '429':
          description: Rate limit exceeded (120 req/min per IP)
  /v1/venues:
    get:
      summary: List/search venues
      description: >-
        Returns venues ordered by ext_id then id (or by updated_at, id when
        `updatedSince` is given). `q` matches name, email, city or ext_id
        (case-insensitive substring). `country` accepts a 2-letter code
        (exact match on country_code) or a country name (ilike). Soft-deleted
        rows are excluded unless `updatedSince` (which then also returns
        tombstones for incremental sync) or `includeDeleted=1` is passed.
      tags: [venues]
      parameters:
        - name: q
          in: query
          schema: { type: string }
          description: Substring match on name, email, city, ext_id
        - name: city
          in: query
          schema: { type: string }
          description: City (ilike)
        - name: country
          in: query
          schema: { type: string }
          description: Country name, 2-letter ISO code, or common alias (uk/united kingdom/england → GB, usa/united states → US, …)
        - name: importBatch
          in: query
          schema: { type: string }
          description: Exact match on import_batch
        - name: venueType
          in: query
          schema: { type: string }
          description: Comma-separated venue types (exact match per value)
        - name: hasEmail
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues with a non-empty email
        - name: hasPhone
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues with a non-empty phone
        - name: hasWebsite
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues with a non-empty website
        - name: hasFacebook
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues with a facebook social
        - name: hasInstagram
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues with an instagram social
        - name: hasSport
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues flagged as showing live sport (shows_live_sport yes/likely)
        - name: hasCoords
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues with both lat and lng set
        - name: publicDisplay
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Only venues safe for public display (open/licensed source or owner-supplied fields)
        - name: updatedSince
          in: query
          schema: { type: string, format: date-time }
          description: >-
            ISO timestamp. Returns rows updated at/after this point — including
            soft-deleted tombstones (deleted=true) — ordered by updated_at, id.
            Invalid timestamps are rejected with 400 invalid_updated_since.
        - name: includeDeleted
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: Include soft-deleted rows (ignored when updatedSince is set)
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 500, default: 50 }
        - name: offset
          in: query
          schema: { type: integer, minimum: 0, default: 0 }
      responses:
        '200':
          description: Array of venues (may be empty)
          content:
            application/json:
              schema:
                type: array
                items: { $ref: '#/components/schemas/Venue' }
        '401': { $ref: '#/components/responses/Unauthorized' }
    delete:
      summary: Delete all venues in an import batch (soft delete)
      description: >-
        Soft-deletes every venue whose import_batch matches the importBatch
        query param (deleted=true tombstone; rows remain visible via
        updatedSince and /v1/venues/deleted).
      tags: [venues]
      parameters:
        - name: importBatch
          in: query
          required: true
          schema: { type: string }
          description: import_batch value identifying the batch to delete
      responses:
        '200':
          description: Batch deletion summary
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean, example: true }
                  importBatch: { type: string, example: nordy-xlsx-2026-10 }
                  deleted: { type: integer, example: 120 }
        '400':
          description: importBatch missing
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example: { error: import_batch_required }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
    post:
      summary: Create a venue
      tags: [venues]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/VenueInput' }
      responses:
        '201':
          description: Created venue
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Venue' }
        '400': { $ref: '#/components/responses/ValidationFailed' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
  /v1/venues/deleted:
    get:
      summary: List soft-deleted venue tombstones
      description: >-
        Returns soft-deleted rows (deleted=true) as
        [{ id, extId, deleted: true, updatedAt }], ordered by updated_at then
        id. Pass `since` (ISO timestamp) to only get tombstones updated at/after
        that point — the mirror of the `updatedSince` tombstone stream on
        GET /v1/venues.
      tags: [venues]
      parameters:
        - name: since
          in: query
          schema: { type: string, format: date-time }
          description: Only tombstones updated at/after this ISO timestamp
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 500, default: 50 }
        - name: offset
          in: query
          schema: { type: integer, minimum: 0, default: 0 }
      responses:
        '200':
          description: Array of tombstones (may be empty)
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    id: { type: string, format: uuid }
                    extId: { type: string, nullable: true }
                    deleted: { type: boolean, example: true }
                    updatedAt: { type: string, format: date-time }
        '400':
          description: Invalid since timestamp
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example: { error: invalid_since }
        '401': { $ref: '#/components/responses/Unauthorized' }
  /v1/venues/{id}:
    get:
      summary: Get a single venue
      description: Accepts either the venue uuid `id` or the stable `extId` (e.g. AU-00001).
      tags: [venues]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
          description: Venue uuid or extId
      responses:
        '200':
          description: The venue
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Venue' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }
    patch:
      summary: Partial update of a venue
      description: >-
        Accepts either the venue uuid `id` or the stable `extId` (e.g.
        AU-00001). Requires the 'patch' scope (or higher: write/admin).
        fieldSources are merged over the existing map. A caller holding only
        'patch' (or passing ?source=owner) claims ownership of every field it
        touches — those fields are recorded as source 'owner' in fieldSources,
        which then protects them from being overwritten by later imports.
        Deleted rows return 404.
      tags: [venues]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
          description: Venue uuid or extId
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/VenueInput' }
            description: Any subset of VenueInput fields
      responses:
        '200':
          description: Updated venue
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Venue' }
        '400': { $ref: '#/components/responses/ValidationFailed' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
        '404': { $ref: '#/components/responses/NotFound' }
    delete:
      summary: Delete a venue (soft delete)
      description: >-
        Soft-deletes the venue (deleted=true tombstone; the row remains visible
        via updatedSince and /v1/venues/deleted). Accepts either the venue uuid
        `id` or the stable `extId` (e.g. AU-00001).
      tags: [venues]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
          description: Venue uuid or extId
      responses:
        '200':
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean, example: true }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/import:
    post:
      summary: Import venues from a CSV or .xlsx file
      description: >-
        Multipart upload. Parses the first sheet (or `sheet`), maps columns to
        venue fields via `map` (JSON object merged over the default seed mapping).
        Rows are upserted in this order: (1) rows with an extId matching an
        existing ext_id are fully updated; (2) remaining rows with an email are
        keyed on lower(email) and merged via name/city similarity; (3) the rest
        are inserted keyed on ext_id (conflicts skipped). Sheets using either an
        `ext_id` or `venue_id` column map to extId out of the box. Pass
        `dryRun=1` to count inserts/updates without writing anything. See the
        importing-data guide.
      tags: [import]
      parameters:
        - name: map
          in: query
          schema: { type: string }
          description: >-
            JSON object of {venueField: columnName}, merged over the default
            mapping (ext_id, name, venue_type, country, country_code, state,
            city, postcode, address, latitude, longitude, phone, website,
            email, email_confidence, email_source, email_source_url,
            alt_emails, group_inbox, facebook, instagram, shows_live_sport,
            operator_group, sources, osm_id, closed, notes).
        - name: sheet
          in: query
          schema: { type: string }
          description: Sheet name (default first sheet)
        - name: batch
          in: query
          schema: { type: string }
          description: Value stored in import_batch on imported rows
        - name: dryRun
          in: query
          schema: { type: string, enum: ['1', 'true'] }
          description: 'Report what would be inserted/updated without writing to the DB; response includes dry_run=true'
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file:
                  type: string
                  format: binary
                  description: CSV or .xlsx file
      responses:
        '200':
          description: Import summary
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ImportResult' }
        '400':
          description: Bad request (file_required, invalid_map, unparseable_file)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                file_required:
                  value: { error: file_required }
                invalid_map:
                  value: { error: invalid_map }
                unparseable_file:
                  value: { error: unparseable_file }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
        '404':
          description: Sheet not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example: { error: sheet_not_found }
  /v1/import/{batch}:
    delete:
      summary: Roll back an import batch (soft delete)
      description: >-
        Soft-deletes every venue whose import_batch matches the path batch
        (deleted=true tombstone; rows remain visible via updatedSince and
        /v1/venues/deleted).
      tags: [import]
      parameters:
        - name: batch
          in: path
          required: true
          schema: { type: string }
          description: import_batch value identifying the batch to delete
      responses:
        '200':
          description: Batch deletion summary
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean, example: true }
                  importBatch: { type: string, example: nordy-xlsx-2026-10 }
                  deleted: { type: integer, example: 120 }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
  /v1/admin/keys:
    get:
      summary: List API keys
      description: Lists all keys. Never returns key hashes or raw keys.
      tags: [admin]
      responses:
        '200':
          description: Array of keys
          content:
            application/json:
              schema:
                type: array
                items: { $ref: '#/components/schemas/ApiKey' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
    post:
      summary: Mint a new API key
      description: The raw key (`apiKey`) is returned ONCE and shown nowhere else. Store it immediately.
      tags: [admin]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [label, scopes]
              properties:
                label:
                  type: string
                  example: nordy
                scopes:
                  type: array
                  items:
                    type: string
                    enum: [read, patch, write, admin]
                  minItems: 1
                  example: [read, patch]
      responses:
        '201':
          description: Minted key (raw key included once)
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  keyPrefix: { type: string, example: va_Ab12Cd34 }
                  label: { type: string }
                  scopes:
                    type: array
                    items: { type: string, enum: [read, patch, write, admin] }
                  apiKey: { type: string, description: Raw key, shown once }
        '400': { $ref: '#/components/responses/ValidationFailed' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
  /v1/admin/keys/{id}/revoke:
    post:
      summary: Revoke an API key
      tags: [admin]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Key revoked
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  revokedAt: { type: string, format: date-time }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/InsufficientScope' }
        '404': { $ref: '#/components/responses/NotFound' }
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: 'API key (va_...)'
      description: >-
        `Authorization: Bearer va_...`. Keys are minted via POST /v1/admin/keys;
        only the sha256 hash is stored server-side. Scopes form a hierarchy:
        'admin' grants everything; 'write' grants write/patch/read; 'patch'
        grants patch/read; 'read' is read-only.
  schemas:
    Venue:
      type: object
      properties:
        id: { type: string, format: uuid }
        extId: { type: string, nullable: true, example: AU-00001 }
        name: { type: string, example: Badger & Co }
        venueType: { type: string, nullable: true }
        country: { type: string, example: Australia }
        countryCode: { type: string, nullable: true, example: AU }
        state: { type: string, nullable: true }
        city: { type: string, nullable: true, example: Canberra }
        postcode: { type: string, nullable: true }
        addressLine: { type: string, nullable: true }
        lat: { type: string, nullable: true, description: Numeric stored as text }
        lng: { type: string, nullable: true }
        phone: { type: string, nullable: true }
        website: { type: string, nullable: true }
        email: { type: string, nullable: true }
        emailConfidence: { type: string, nullable: true }
        emailSource: { type: string, nullable: true }
        emailSourceUrl: { type: string, nullable: true }
        altEmails: { type: array, items: { type: string }, nullable: true }
        groupInbox: { type: boolean, nullable: true }
        socials:
          type: object
          nullable: true
          properties:
            facebook: { type: string }
            instagram: { type: string }
        fieldSources:
          type: object
          nullable: true
          additionalProperties: { type: string }
          description: Per-field provenance, e.g. {"email":"venue-website","lat":"fsq-os-places"}. Tracks which source supplied each enriched field (ODbL separation).
        showsLiveSport: { type: string, nullable: true, description: "'likely' / 'unknown' — free text, not boolean" }
        operatorGroup: { type: string, nullable: true }
        sources: { type: array, items: { type: string }, nullable: true }
        osmId: { type: string, nullable: true }
        closed: { type: boolean, nullable: true, description: Permanently closed — venue fact, not outreach state }
        notes: { type: string, nullable: true }
        importBatch: { type: string, nullable: true }
        deleted: { type: boolean, description: Soft-delete tombstone flag; deleted rows are excluded from public/live queries and returned only via updatedSince / /v1/venues/deleted }
        coordsSource: { type: string, nullable: true, description: "Derived: provenance of the venue's coordinates (fieldSources.lat, else 'osm' when osmId is set, else 'seed'); null when coordinates are missing" }
        publicDisplay: { type: boolean, description: 'Derived: true when the venue has an open/licensed source (osm, OpenStreetMap, fsq-os-places, overture, owner) or any owner-supplied field' }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
    VenueInput:
      type: object
      required: [name, country]
      properties:
        extId: { type: string }
        name: { type: string, minLength: 1 }
        venueType: { type: string }
        country: { type: string, minLength: 1 }
        countryCode: { type: string, minLength: 2, maxLength: 2 }
        state: { type: string }
        city: { type: string }
        postcode: { type: string }
        addressLine: { type: string }
        lat: { type: string }
        lng: { type: string }
        phone: { type: string }
        website: { type: string }
        email: { type: string, format: email }
        emailConfidence: { type: string }
        emailSource: { type: string }
        emailSourceUrl: { type: string }
        altEmails: { type: array, items: { type: string } }
        groupInbox: { type: boolean }
        socials:
          type: object
          properties:
            facebook: { type: string }
            instagram: { type: string }
        fieldSources:
          type: object
          additionalProperties: { type: string }
          description: Per-field provenance map (field name → source label)
        showsLiveSport: { type: string }
        operatorGroup: { type: string }
        sources: { type: array, items: { type: string } }
        osmId: { type: string }
        closed: { type: boolean }
        notes: { type: string }
        importBatch: { type: string }
    ApiKey:
      type: object
      properties:
        id: { type: string, format: uuid }
        keyPrefix: { type: string, example: va_Ab12Cd34 }
        label: { type: string }
        scopes:
          type: array
          items: { type: string, enum: [read, patch, write, admin] }
        createdAt: { type: string, format: date-time }
        revokedAt: { type: string, format: date-time, nullable: true }
        lastUsedAt: { type: string, format: date-time, nullable: true }
    ImportResult:
      type: object
      properties:
        inserted: { type: integer }
        updated: { type: integer }
        skipped: { type: integer }
        total_rows: { type: integer }
        skipped_reasons:
          type: object
          additionalProperties: { type: integer }
          example: { missing_name: 3, missing_country: 1 }
    Error:
      type: object
      properties:
        error: { type: string, example: not_found }
  responses:
    Unauthorized:
      description: Missing or unknown API key
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example: { error: invalid_api_key }
    InsufficientScope:
      description: Key lacks the required scope
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example: { error: insufficient_scope }
    NotFound:
      description: Resource not found
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example: { error: not_found }
    ValidationFailed:
      description: Request body failed zod validation
      content:
        application/json:
          schema:
            allOf:
              - { $ref: '#/components/schemas/Error' }
              - type: object
                properties:
                  issues: { type: array, items: { type: object } }
          example:
            error: validation_failed
            issues: [{ path: [name], message: Required }]
