Use Case: User Creates a New Object

Overview

This document describes the complete workflow when a user creates a new physical object in the Plings system, from frontend interaction through backend processing to data storage across multiple databases. The backend now provides comprehensive GraphQL APIs for both object creation and image management.

User Story

As a user, I want to create a digital record of my physical objects so that I can track, organize, and manage my items across different organizations.

Workflow Steps

Step 1: User Initiates Object Creation

  • Location: Objects Dashboard (/objects) or Dashboard (/dashboard)
  • Action: User clicks “Create Object” button
  • UI Response: Modal opens with creation form
  • Action: User clicks image upload area or drags files
  • Frontend Processing:
    • Validates file types (image/jpeg, image/png, image/webp)
    • Validates file sizes (max 5MB per file)
    • Shows image previews with thumbnails
    • Marks first image as “Main” automatically
    • Allows image removal and reordering
  • Technical: Images stored in browser memory until submission

Step 3: User Fills Object Details

  • Required Fields:
    • Object Name: User-friendly identifier (e.g., “My ski helmet”)
  • Optional Fields:
    • Description: Additional context or notes
  • Auto-filled:
    • Statuses: Defaults to [“active”] (multiple statuses supported via status system)
    • Owner: Current user’s organization context

Step 4: User Selects Organization (Save As)

  • Frontend: Displays buttons for each organization user belongs to
  • Options: “Save as [Organization Name]” for each accessible org
  • Validation: User must be member of selected organization

Step 5: Form Submission and Processing

The system uses a single GraphQL mutation to create new objects. If images are included, they are handled as part of the same operation using the GraphQL multipart request specification.

Frontend Processing

The frontend client constructs a createObject mutation. If files are present, they are mapped to variables in the GraphQL operation.

import { useMutation, gql } from '@apollo/client';

const CREATE_OBJECT = gql`
  mutation createObject($name: String!, $description: String, $ownerOrgId: ID!, $statuses: [String!], $photos: [Upload!]) {
    createObject(name: $name, description: $description, ownerOrgId: $ownerOrgId, statuses: $statuses, photos: $photos) {
      id
      name
      description
      statuses
      imageUrls
      mainImageUrl
      owner
    }
  }
`;

const [createObject] = useMutation(CREATE_OBJECT, {
  onCompleted: (data) => {
    console.log('Object created:', data.createObject);
    // Navigate to object detail page or update local state
  },
  onError: (error) => {
    console.error('Creation failed:', error);
    // Show error message to user
  }
});

// When the user submits the form:
const handleSubmit = async () => {
  try {
    await createObject({
  variables: {
    name: objectName,
    description,
    ownerOrgId: selectedOrgId,
        statuses: ['active'], // Default status
    photos: files, // Array<File>
  },
});
  } catch (error) {
    // Error handling already done in onError callback
  }
};

Backend Processing Flow

  1. Receive GraphQL Request – Multipart request arrives with mutation + files.
  2. AuthN / AuthZ – Validate session & org membership from JWT context.
  3. Process Mutation – Execute createObject resolver.
  4. Image Upload – Stream files to Supabase Storage (object-images bucket).
  5. Neo4j – Create :ObjectInstance node with properties.
  6. Supabase – Insert rows in object_instances & object_images tables.
  7. Consistency – Ensure both databases are synchronized.
  8. Response – Return new object with imageUrls and mainImageUrl in GraphQL payload.

Data Flow Architecture

Frontend → Backend

  • HTTP POST multipart/form-data (GraphQL multipart spec).
  • Authorization: Bearer <JWT> header for auth.
  • Payload includes mutation string, variables JSON, and file streams.

Backend → Supabase Storage

  • Bucket: object-images
  • Path: objects/ObjectInstance/{objectId}/{uniqueFilename}
  • Naming: UUID-based unique filenames prevent conflicts

Backend → Neo4j

  • Create node :ObjectInstance { id, name, description, statuses, owner }
  • Optional relation to class if specified.

Backend → Supabase DB

  • Insert into object_instances table with metadata and main_image_url
  • Insert into object_images table for each uploaded image
  • Maintain referential integrity and RLS policies

Enhanced Features Available

Status Management Integration

The backend now provides comprehensive status management:

// Load available statuses for UI
const GET_STATUS_DEFINITIONS = gql`
  query GetStatusDefinitions {
    statusDefinitions {
      key
      name
      description
      color
      category
      conflictsWith
    }
  }
`;

// Validate status combinations
const VALIDATE_STATUSES = gql`
  query ValidateStatuses($statusKeys: [String!]!) {
    validateStatusCombination(statusKeys: $statusKeys) {
      valid
      errors
      warnings
    }
  }
`;

Image Management Post-Creation

After object creation, users can manage images with dedicated mutations:

// Add more images
const UPLOAD_IMAGES = gql`
  mutation uploadObjectImages($objectId: ID!, $images: [Upload!]!) {
    uploadObjectImages(objectId: $objectId, images: $images) {
      id
      imageUrls
      mainImageUrl
    }
  }
`;

// Delete specific images
const DELETE_IMAGES = gql`
  mutation deleteObjectImages($objectId: ID!, $imageUrls: [String!]!) {
    deleteObjectImages(objectId: $objectId, imageUrls: $imageUrls) {
      id
      imageUrls
      mainImageUrl
    }
  }
`;

// Atomic update (add new + delete old)
const UPDATE_IMAGES = gql`
  mutation updateObjectImages($objectId: ID!, $newImages: [Upload!], $deleteImageUrls: [String!]) {
    updateObjectImages(objectId: $objectId, newImages: $newImages, deleteImageUrls: $deleteImageUrls) {
      id
      imageUrls
      mainImageUrl
    }
  }
`;

Security & Access Control

  • RLS Policies: Ensure user must belong to ownerOrgId.
  • File Validation: Backend validates file types and sizes.
  • Storage Security: Images inherit object access via bucket policies.
  • Ownership Validation: All operations verify user permissions.

Error Handling

  • Validation Errors: Missing name, invalid org, file type/size violations.
  • Partial Failures: Atomic transactions with rollback on database errors.
  • Storage Failures: Graceful degradation if image upload fails.
  • Network Issues: Retry logic and offline capability.

Real-time Updates

  • GraphQL Subscriptions: Other users see new objects immediately.
  • Optimistic Updates: UI updates instantly while backend processes.
  • Live Collaboration: Multiple users can work simultaneously.

Performance Optimizations

  • Lazy Loading: Images loaded progressively.
  • Caching: Apollo Client caches object data.
  • Virtual Scrolling: Efficient rendering of large object lists.
  • Background Sync: Image uploads continue in background.

Future Enhancements & Metrics

  • AI Classification: Automatic object categorization from images.
  • Identifier Minting: Generate QR/NFC identifiers during creation.
  • Batch Creation: Create multiple objects from camera workflow.
  • Template System: Pre-fill forms based on object classes.
  • Analytics: Track creation patterns and user engagement.

Complete Object Creation Workflow (Full Scope)

Dual Creation Modes Implementation

Single Object Mode (Desktop/Detailed)

  1. Enhanced Modal Interface
    • Multi-image upload with drag-drop
    • Dynamic ObjectClass search and selection
    • Tag scanning integration (QR/NFC)
    • Set creation workflow with “Create as Set?” decision
    • Spatial hierarchy navigation
    • Dynamic property fields based on selected class

Batch Creation Mode (Mobile/Rapid)

  1. Mobile Camera Interface
    • Camera-first rapid capture workflow
    • Real-time tag scanning during photo capture
    • Quick type selection with recent/popular types
    • Session management with offline queuing
    • Progress tracking and error handling
    • Batch completion summary and analytics

Advanced Features Implementation

Tag System Integration

  • Dual Purpose Scanning: QR/NFC detection serves tag assignment AND spatial context
  • Smart Dialog Flow: Context-aware responses for known vs unknown tags
  • Spatial Integration: Container tag scanning establishes immediate location relationships
  • Conflict Resolution: Handle already-assigned tags with comprehensive resolution options
  • Security: Cryptographic validation for manufacturer-issued tags with audit trail

Set Object Workflows

  • Conversion Decision: “Create as Set?” prompt after object creation
  • Set Mode Interface: Specialized UI for creating child objects
  • Smart Naming: AI-assisted suggestions for set child names
  • Tag Migration Logic: Seamless tag movement during set creation
  • Set Completion: Finalization with metadata and analytics

Object Class System

  • Dynamic Classes: Replace hardcoded types with searchable class hierarchy
  • Property Fields: Dynamic form fields based on selected ObjectClass
  • Hierarchical Navigation: Browse classes by category and manufacturer
  • Usage Analytics: Track and suggest popular object types
  • Admin Management: Create and manage custom object classes

Analytics & Optimization

  • Creation Metrics: Track user behavior and creation patterns
  • Performance Monitoring: Monitor creation duration and success rates
  • Usage Insights: Analyze popular object types and workflows
  • Mobile Optimization: Battery usage, network efficiency, offline support

Implementation Status (Accurate)

Currently Implemented

  • Complete CREATE_OBJECT mutation: Single object creation with all features
  • CreateObjectModal: Advanced desktop modal with comprehensive functionality
  • Image Upload System: Complete multi-image upload implementation
    • Camera Integration: Live camera capture with photo review and retake
    • Drag & Drop: Visual drop zone with real-time file validation
    • Multiple Images: Support for up to 10 images per object
    • Image Management: Remove, reorder, and designate main image
    • Background Upload: Non-blocking uploads with progress indicators
    • Thumbnail Generation: Instant preview grid with status indicators
  • Organization Context: Objects assigned to user organizations
  • Spatial Integration: Objects can be created within containers
  • Advanced Validation: Client-side form validation with comprehensive error handling
  • Scan Button Infrastructure: Modal header supports prominent scan button placement

⚠️ Partially Implemented

  • Entry Points: QuickActions component exists but only placeholder actions
  • Object Types: Hardcoded dropdown instead of dynamic class system
  • Tag Scanning Foundation: Camera libraries available but scan button not yet implemented

Not Yet Implemented (Priority Order)

  1. 🔴 Critical Priority: Dual tag scanning functionality (assignment + spatial context)
  2. 🟡 High Priority: Dynamic object classes, spatial relationship dialog flows
  3. 🟢 Medium Priority: Mobile batch creation, advanced conflict resolution
  4. 🔵 Low Priority: Set workflows, object class admin, AI enhancements

Technical Architecture (Complete)

Frontend Components (See: Frontend Requirements)

  • Single Mode: CreateObjectModal with enhanced sections
  • Batch Mode: Mobile camera interface with session management
  • Shared: Tag scanner, class selector, image processor, validation helpers

Backend APIs (See: Backend Requirements)

  • Core: CREATE_OBJECT, BATCH_CREATE_OBJECTS, set mutations
  • Advanced: Tag resolution, class management, analytics tracking
  • Infrastructure: Real-time subscriptions, batch sessions, audit trails

Database Schema (See: Backend Requirements)

  • Enhanced Tables: object_classes, tag_scan_events, creation_events
  • Performance: Comprehensive indices for search and analytics
  • Audit: Complete tracking of tag assignments and creation patterns

Development Roadmap

Phase 1: Enhanced Single Creation (Sprint 1)

  • Implement dual purpose tag scanning (scan button + camera interface)
  • Add tag resolution dialogs for known/unknown tags
  • Enable spatial relationship assignment via container tag scanning
  • Connect QuickActions entry points with scan functionality

Phase 2: Complete Single Mode (Sprint 2)

  • Set creation workflow and decision points
  • Advanced tag conflict resolution
  • Dynamic property fields based on class
  • Spatial context integration

Phase 3: Mobile Batch Creation (Sprint 3-4)

  • Camera-first mobile interface
  • Batch session management with recovery
  • Real-time progress and error handling
  • Offline queuing and sync

Phase 4: Advanced Features (Sprint 5-6)

  • Complete set workflows with tag migration
  • Object class admin and management
  • Analytics and usage optimization
  • AI-assisted naming and classification

Success Metrics (Full Scope)

User Experience Targets

  • Single Creation: <2 minutes from open modal to created object
  • Batch Creation: >10 objects per minute on mobile
  • Tag Scanning: <3 seconds from scan to object creation
  • Error Recovery: >95% success rate for interrupted batch sessions

Technical Performance Targets

  • API Response: <1s for single creation, <5s for 100-object batch
  • Mobile Performance: <500ms camera capture, offline queue 100+ objects
  • Search Performance: <300ms ObjectClass search with fuzzy matching
  • Real-time Updates: <2s propagation for creation events across devices

Use Case Last Updated: 2025-07-09 at 9:17 - Added dual tag scanning functionality documentation and updated implementation priorities