API Requirements & Development Coordination
API Requirements & Development Coordination
This document is the single source of truth for coordinating API development between frontend and backend teams. It provides project management, tracking, and prioritization for all API operations.
🎯 Project Coordination Interface
CRITICAL PROCESS: This file manages the complete API development workflow between teams.
Workflow Process:
- Frontend Identifies Need → Create detailed requirement with user story and technical specs
- Backend Team Reviews → Estimates complexity, assigns developer, sets timeline
- Implementation Tracked → Status updated through development lifecycle
- Testing & Integration → End-to-end validation and issue resolution
- Documentation Updated → Move completed operations to reference documentation
Status Legend:
- ❌ Frontend Need - Frontend requires this operation, backend not started
- 🚧 Backend In Progress - Backend team actively implementing
- ✅ Backend Complete - Backend implementation finished, testing needed
- ⚠️ Integration Issues - Problems found during frontend integration
- ✅ Production Ready - Fully implemented and tested end-to-end
🚀 Current Development Sprint
🎯 Sprint Goal: HD Wallet System & Use Case Documentation
Sprint Duration: 2025-07-01 → 2025-07-15 Sprint Focus: Complete HD wallet implementation and comprehensive use case documentation
✅ Major Sprint Accomplishments (Updated: Fri Jul 11 07:35:45 CEST 2025)
- HD Wallet Phase 2 Complete ✅
- Single master key architecture implemented
- Path registry system with collision prevention
- Manufacturer registration and management
- Full GraphQL API integration
- Comprehensive Documentation ✅
- Created detailed identifier overview explaining all design decisions
- Documented real-world use cases for consumers, retail, and personal use
- Clear guidance on when paths and class keys matter
- Complete implementation guide for developers
📊 API Development Tracking
🔴 Critical Priority (Blocking Core Features)
| API Operation | User Story | Status | Developer | Timeline | Frontend Ready | Backend Ready | Issues | ||
|---|---|---|---|---|---|---|---|---|---|
| Organization Management | |||||||||
getMyOrganizations |
“As a user, I want to see my organizations” | ✅ Production Ready | Completed | ✅ 2025-06-26 | ✅ | ✅ | None | ||
createOrganization |
“As a user, I want to create new organizations” | ✅ Production Ready | Completed | ✅ 2025-01-27 | ✅ | ✅ | None | ||
| Object Details | |||||||||
getObjectDetailsComplete |
“As a user, I want complete object information” | ✅ Production Ready | Claude | ✅ 2025-07-03 | ✅ | ✅ | CRITICAL ID MISMATCH FIXED - Resolved Neo4j ID to PostgreSQL ID conversion issues preventing images from being returned. Backend now correctly maps GraphQL inputs to database queries. | ||
getObjectDetailsComplete |
“As a user, I want complete object information” | ✅ Production Ready | Claude | ✅ 2025-07-03 | ✅ | ✅ | CRITICAL ID MISMATCH FIXED - Resolved Neo4j ID to PostgreSQL ID conversion issues preventing images from being returned. Backend now correctly maps GraphQL inputs to database queries. | ||
| Core Object Operations | |||||||||
createObject |
“As a user, I want to create new objects with images, tags, and spatial relationships” | ✅ Production Ready | Claude | ✅ 2025-07-03 | Complete modal built | ✅ Enhanced implementation | CRITICAL ASYNC EVENT LOOP FIX COMPLETE - Resolved “Future attached to a different loop” errors by removing duplicate async Neo4j code and implementing sync Neo4j driver pattern. Architecture now stable for serverless Vercel deployment with PostgreSQL-first image handling. | ||
| Enhanced Create Object Features | |||||||||
startImageProcessing |
“As a user, I want AI to automatically classify my object images and detect duplicates” | ✅ Production Ready | Claude | ✅ 2025-07-07 | UC-300 | ✅ Complete API | Background AI processing with object classification, duplicate detection, quality analysis, and metadata extraction | ||
createObjectWithLocation |
“As a user, I want to store GPS location when creating objects outdoors” | ✅ Production Ready | Claude | ✅ 2025-07-07 | UC-301 | ✅ Complete API | GPS capture, reverse geocoding, “near me” discovery, tool sharing integration | ||
applySquareCropping |
“As a user, I want square-cropped images for consistent visual presentation” | ✅ Production Ready | Claude | ✅ 2025-07-07 | UC-302 | ✅ Complete API | AI-powered subject detection, intelligent cropping suggestions, manual override | ||
generateContainerOverview |
“As a user, I want visual previews of container contents before opening them” | ✅ Production Ready | Claude | ✅ 2025-07-07 | UC-303 | ✅ Complete API | Spatial layout visualization, type diversity selection for large containers, “+N more” indicators | ||
| Tool Sharing Economy | |||||||||
enableToolSharing |
“As a user, I want to share tools with my neighbors and community” | ✅ Production Ready | Claude | ✅ 2025-07-07 | UC-304 | ✅ Complete API | Peer-to-peer borrowing, trust scores, sharing terms, rating system | ||
findToolsNear |
“As a user, I want to find tools available for rent/borrow near my location” | ✅ Production Ready | Claude | ✅ 2025-07-07 | UC-305 | ✅ Complete API | Multi-source discovery (P2P, commercial, libraries), acquisition options, distance-based filtering | ||
joinCommunity |
“As a user, I want to access community tool libraries and maker spaces” | ✅ Production Ready | Claude | ✅ 2025-07-07 | UC-306 | ✅ Complete API | Library membership, tool reservations, educational resources, community access | ||
searchObjects |
“As a user, I want to search for objects” | ❌ Frontend Need | TBD | Sprint Goal | Landing page ready | Not started | Main search broken | ||
moveObject |
“As a user, I want to drag objects between containers” | ⚠️ Integration Issues | GraphQL Schema | ✅ 2025-06-27 | Spatial UI ready | ⚠️ Partial implementation | Missing positional relationship cleanup on container transitions | ||
bulkCreateObjects |
“As a user, I want to create multiple objects at once” | ❌ Frontend Need | TBD | Sprint Goal | Batch UI ready | Not started | CSV import broken | ||
| Set Object Operations | |||||||||
convertToSet |
“As a user, I want to convert objects to sets” | ❌ Frontend Need | TBD | Sprint + 1 | Not built | Not started | Set workflow missing | ||
createSetChild |
“As a user, I want to add items to sets” | ❌ Frontend Need | TBD | Sprint + 1 | Not built | Not started | Set workflow missing | ||
| Spatial & Image Operations | |||||||||
updateObjectBasicInfo |
“As a user, I want to update object information” | ✅ Production Ready | GraphQL Schema | ✅ 2025-06-27 | Edit forms ready | ✅ | None | ||
updateObjectStatuses |
“As a user, I want to update object statuses” | ✅ Production Ready | GraphQL Schema | ✅ 2025-06-27 | Status UI ready | ✅ | None | ||
uploadObjectImages |
“As a user, I want to upload object images” | ✅ Production Ready | Claude | ✅ 2025-07-03 | Upload UI ready | ✅ PostgreSQL-first architecture | ARCHITECTURE ENHANCED - Centralized ID conversion ensures proper Neo4j→PostgreSQL mapping for all image operations. Single source of truth established. | ||
deleteObjectImages |
“As a user, I want to delete object images” | ✅ Production Ready | Claude | ✅ 2025-07-03 | Delete UI ready | ✅ PostgreSQL-first architecture | ARCHITECTURE ENHANCED - All image operations now use centralized helper functions for consistent ID handling and error management. | ||
updateObjectImages |
“As a user, I want to update object images” | ✅ Production Ready | Claude | ✅ 2025-07-03 | Update UI ready | ✅ PostgreSQL-first architecture | ARCHITECTURE ENHANCED - Complete image workflow now supports dual-database architecture with proper fallback mechanisms. | ||
createSpatialRelationship |
“As a user, I want to create spatial relationships” | ✅ Production Ready | GraphQL Schema | ✅ 2025-06-27 | Spatial UI ready | ✅ | None | ||
removeSpatialRelationship |
“As a user, I want to remove spatial relationships” | ✅ Production Ready | GraphQL Schema | ✅ 2025-06-27 | Spatial UI ready | ✅ | None | ||
getSpatialPredicates |
“As a user, I want to see spatial relationship types” | ✅ Production Ready | GraphQL Schema | ✅ 2025-06-27 | Spatial UI ready | ✅ | None | ||
getPotentialContainers |
“As a user, I want to see available containers” | ✅ Production Ready | GraphQL Schema | ✅ 2025-06-27 | Container UI ready | ✅ | None | ||
getSpatialChildren |
“As a user, I want to see objects in containers” | ✅ Production Ready | GraphQL Schema | ✅ 2025-06-27 | Spatial UI ready | ✅ | None | ||
| Enhanced Spatial Predicates System | |||||||||
spatialPredicatesMigration |
“As a system, I want dual NORMAL_/CURRENT_ spatial predicates for better inventory tracking” | ✅ Production Ready | Backend+Frontend | ✅ 2025-07-03 | Dual predicates system | ✅ | Migration enables misplacement detection between designated vs actual locations | ||
| Advanced Object Creation | |||||||||
generateObjectName |
“As a user, I want auto-generated object names” | ❌ Frontend Need | TBD | Sprint Goal | Auto-naming ready | Not started | Manual name entry required | ||
checkNameAvailability |
“As a user, I want unique object names and avoid cross-organization confusion” | ✅ Production Ready | Backend+Frontend | ✅ 2025-07-05 | ✅ Name validation with cross-org warnings | ✅ Enhanced with cross-organization detection | PRODUCTION READY - Real-time name validation with cross-organization warnings. Shows gentle notices when same name exists in other accessible organizations. Includes clickable links to view similar objects and prevents accidental duplicates across family/personal organizations. | ||
searchObjectClasses |
“As a user, I want to search object types” | ❌ Frontend Need | TBD | Sprint Goal | Class selector ready | Not started | Hardcoded dropdown blocking | ||
getRecentObjectTypes |
“As a user, I want quick access to recent types” | ❌ Frontend Need | TBD | Sprint Goal | Quick buttons ready | Not started | No usage tracking | ||
getContainerContext |
“As a user, I want location context for creation” | ❌ Frontend Need | TBD | Sprint Goal | Location picker ready | Not started | Missing spatial context | ||
getSpatialNavigatorState |
“As a user, I want access to current spatial navigator context” | ❌ Frontend Need | TBD | Sprint Goal | Location defaults ready | Not started | No spatial navigator variable access | ||
| Enhanced Location Management | |||||||||
getPotentialContainers |
“As a user, I want to see all available containers for object placement” | ✅ Production Ready | GraphQL Schema | ✅ 2025-06-27 | Location selector ready | ✅ | Ready for integration | ||
getSpatialHierarchyPath |
“As a user, I want to see spatial breadcrumb for current location” | ✅ Backend Complete | Claude | ✅ 2025-07-03 | Breadcrumb UI ready | ✅ Spatial hierarchy path with permissions | Ready for integration testing - includes breadcrumb generation, container capacity, and permission checks | ||
createNormalSpatialRelationship |
“As a user, I want to set expected location for misplacement detection” | ✅ Production Ready | Claude | ✅ 2025-07-03 | Normal location selector ready | ✅ Normal placement system | CRITICAL ID MISMATCH FIXED - Resolved “Object or container not found” errors. Backend now correctly handles Neo4j ID to PostgreSQL ID mapping for validation queries. | ||
createNormalSpatialRelationship |
“As a user, I want to set expected location for misplacement detection” | ✅ Production Ready | Claude | ✅ 2025-07-03 | Normal location selector ready | ✅ Normal placement system | CRITICAL ID MISMATCH FIXED - Resolved “Object or container not found” errors. Backend now correctly handles Neo4j ID to PostgreSQL ID mapping for validation queries. | ||
validateSpatialPlacement |
“As a user, I want validation when placing objects in invalid containers” | ✅ Backend Complete | Claude | ✅ 2025-07-03 | Validation UI ready | ✅ Placement validation system | Ready for integration testing - validates capacity, compatibility, permissions with alternative suggestions | ||
| Enhanced Capacity Management | |||||||||
removeSpatialCapacityLimits |
“As a user, I want unlimited object capacity when no limits are set” | ✅ Backend Complete | Claude | ✅ 2025-07-03 | UI updated for unlimited display | ✅ Unlimited capacity system | Ready for integration testing - removed hard-coded limits, maxObjects=0 indicates unlimited capacity | ||
enhancePotentialContainersHierarchy |
“As a user, I want to see spatial hierarchy in normal location selection” | ✅ Production Ready | Claude | ✅ 2025-07-03 | Location selector ready for hierarchy display | ✅ Enhanced with spatial hierarchy | Frontend integrated successfully - normal location selector now shows spatial hierarchy like “Västervägen 26 → Husvagnen” using backend-provided breadcrumbPath | ||
| Tag Management APIs | |||||||||
resolveTagIdentifier |
“As a user, I want to scan QR/NFC tags and resolve to object data” | ❌ Frontend Need | TBD | Sprint Goal | Tag scanner ready | Not started | QR/NFC scanning integration broken | ||
assignTagToObject |
“As a user, I want to assign scanned tags to new objects during creation” | ❌ Frontend Need | TBD | Sprint Goal | Tag integration ready | Not started | No tag assignment in creation flow | ||
checkTagAvailability |
“As a user, I want to validate tag isn’t already assigned” | ❌ Frontend Need | TBD | Sprint Goal | Tag conflict resolution ready | Not started | No tag conflict detection | ||
| HD Wallet Identifier System - Single Master Key Architecture | |||||||||
createGenericTag |
“As a user, I want to generate new generic Plings tags with cryptographic verification” | ✅ Production Ready | Claude Code | ✅ 2025-07-10 | Tag generation ready | ✅ Phase 1 complete | ARCHITECTURE REVISED - All identifiers derive from single Plings master key with path-based verification | ||
createBatchIdentifiers |
“As a manufacturer, I want to generate identifiers in bulk for printing” | ✅ Production Ready | Claude Code | ✅ 2025-07-10 | Batch UI ready | ✅ Phase 1 complete | Mass identifier creation with CSV export capability | ||
| Path Registry System | |||||||||
allocatePath |
“As an admin, I want to reserve paths for batch generation to prevent collisions” | ✅ Backend Complete | Claude Code | ✅ 2025-07-10 | Path allocation UI ready | ✅ Phase 2 complete | PHASE 2 COMPLETE - Full path allocation system with collision prevention, manufacturer registration, and single master key architecture. PostgreSQL tables, GraphQL mutations, and HDWalletService all updated. | ||
registerManufacturer |
“As an admin, I want to onboard manufacturers with dedicated path ranges” | ✅ Backend Complete | Claude Code | ✅ 2025-07-10 | Manufacturer management UI | ✅ Phase 2 complete | PHASE 2 COMPLETE - Manufacturer registration with automatic index assignment and path prefix allocation. Supports organization linking and status management. | ||
verifyPathAllocation |
“As a user, I want to validate path assignments and avoid conflicts” | ❌ Frontend Need | TBD | Sprint + 1 | Path validation UI | Not started | Path integrity verification (Phase 3) | ||
| Three Core Scenarios Implementation | |||||||||
createTestBatch |
“As a Plings admin, I want to generate test identifiers for system validation” | ❌ Frontend Need | TBD | Sprint + 1 | Test batch UI | Not started | Internal testing workflow (path range 1.2.x) | ||
orderManufacturerBatch |
“As a manufacturer, I want to order identifier batches for printing” | ❌ Frontend Need | TBD | Sprint + 2 | Manufacturer portal | Not started | Batch ordering with CSV export (path range 1.3.x) | ||
generateOrganizationIdentifiers |
“As an organization, I want to self-generate identifiers using delegated keys” | ❌ Frontend Need | TBD | Sprint + 3 | Organization management | Not started | Self-service identifier generation (path range 2.x.x+) | ||
| Cryptographic Verification | |||||||||
verifyIdentifierAuthenticity |
“As anyone, I want to verify identifier authenticity offline against Plings master key” | ❌ Frontend Need | TBD | Sprint + 2 | Verification UI | Not started | Offline cryptographic validation | ||
validatePathDerivation |
“As a system, I want to verify identifiers derive from correct HD wallet paths” | ❌ Frontend Need | TBD | Sprint + 2 | System validation | Not started | BIP32 derivation verification | ||
| Image Upload Enhancement | |||||||||
uploadObjectImagesMultiple |
“As a user, I want to upload multiple images during object creation” | ✅ Production Ready | Frontend Team | ✅ 2025-07-07 | ✅ Multi-image upload implemented | ✅ Complete implementation | PRODUCTION READY - Multiple image upload with camera, drag-drop, file picker, remove, and reorder functionality fully working in CreateObjectModal | ||
generateImageThumbnails |
“As a user, I want automatic thumbnail generation for uploaded images” | ✅ Production Ready | Frontend Team | ✅ 2025-07-07 | ✅ Image grid with thumbnails | ✅ Thumbnail generation working | PRODUCTION READY - Real-time thumbnail generation and preview grid working with progress indicators | ||
compressImages |
“As a user, I want automatic image compression for performance” | ❌ Frontend Need | TBD | Sprint Goal | Upload optimization ready | Not started | No automatic compression system | ||
| Batch Creation APIs | |||||||||
getBatchSession |
“As a user, I want to resume batch sessions” | ❌ Frontend Need | TBD | Sprint + 1 | Session manager ready | Not started | No session persistence | ||
resumeBatchSession |
“As a user, I want to recover interrupted batches” | ❌ Frontend Need | TBD | Sprint + 1 | Recovery UI ready | Not started | No offline support | ||
completeBatchSession |
“As a user, I want to finalize batch creation” | ❌ Frontend Need | TBD | Sprint + 1 | Completion screen ready | Not started | No batch summary | ||
| Object Class System | |||||||||
getObjectClassHierarchy |
“As a user, I want to browse class categories” | ❌ Frontend Need | TBD | Sprint + 2 | Hierarchy UI ready | Not started | No class system | ||
createObjectClass |
“As an admin, I want to define new object types” | ❌ Frontend Need | TBD | Sprint + 3 | Admin UI ready | Not started | No class management | ||
| Advanced Tag Management | |||||||||
resolveTagIdentifier |
“As a user, I want to scan tags” | ❌ Frontend Need | TBD | Sprint + 1 | Camera ready | Not started | Tag scanning broken | ||
assignTagToObject |
“As a user, I want to assign tags to objects” | ❌ Frontend Need | TBD | Sprint + 1 | Tag UI ready | Not started | No tag assignment | ||
getTagHistory |
“As a user, I want to see tag assignment history” | ❌ Frontend Need | TBD | Sprint + 2 | History UI ready | Not started | No audit trail | ||
transferTag |
“As a user, I want to move tags between objects” | ❌ Frontend Need | TBD | Sprint + 2 | Transfer UI ready | Not started | No tag transfer | ||
| Organization Intelligence | |||||||||
getRecommendedOrganization |
“As a user, I want intelligent organization defaults based on spatial context and creation history” | ✅ Backend Complete | Claude | ✅ 2025-07-03 | Organization selector ready | ✅ Intelligent recommendation system | Ready for integration testing - includes spatial analysis, user behavior tracking, and confidence scoring | ||
| Analytics & Tracking | |||||||||
getCreationAnalytics |
“As an admin, I want creation usage metrics” | ❌ Frontend Need | TBD | Sprint + 3 | Analytics UI ready | Not started | No metrics tracking | ||
trackCreationEvent |
“As a system, I want to track user behavior” | ❌ Frontend Need | TBD | Sprint + 2 | Event tracking ready | Not started | No usage analytics |
📋 Detailed Requirements for Backend Team
🔴 Sprint Priority 1: Core Object Operations
createObject mutation - Enhanced for Complete Object Creation Workflow
- Business Impact: Complete object creation workflow with images, tags, and spatial relationships
- Frontend Integration: Complete object creation modal at
src/components/objects/creation/CreateObjectModal.tsx - Current Implementation: Basic creation works, needs enhancement for production features
- Required Enhancements:
- Multi-image Upload: Support multiple image uploads with thumbnail generation
- Tag Assignment: Assign scanned PlingsIdentifier tags during creation
- Spatial Default Location: Auto-assign parent relationship from spatial navigator context
- Set Creation Support: Enable “Create as Set?” workflow after object creation
- Smart Naming: Auto-generate names with organization prefix and tag short codes
- Validation: Duplicate name checking, tag availability, spatial relationship validation
- Required Fields:
- Core: name (optional with auto-generation), description (optional), owner_organization_id
- Spatial: spatialParentId, spatialRelationshipType (IN/ON/CONTAINS inferred from container type)
- Images: imageUploadIds[] (from multi-image upload), mainImageIndex
- Tags: tagInstanceKey (optional), tagData (scanned tag information)
- Set: setComponents (relationship-based), setMetadata (for set creation workflow)
- Business Rules:
- Every object MUST have exactly one spatial parent relationship
- Tag assignment must validate tag availability and conflict resolution
-
Auto-generate names with format: “[Organization] [UserInput] [TagShortCode SequentialNumber]” - Default to current spatial navigator container with appropriate relationship type
- Performance Target: <2s object creation including image upload and spatial assignment
- Testing Criteria:
- Create object with multiple images → images uploaded and thumbnails generated
- Create object with scanned tag → tag assigned and short code included in name
- Create object in spatial container → correct parent relationship auto-assigned
- Create object with auto-generated name → unique name within organization scope
- Create object and convert to set →
PART_OFrelationships created successfully
searchObjects query
- Business Impact: Landing page search non-functional, users cannot find objects
- Frontend Integration: Search components ready at
src/components/search/SearchResults.tsx - Required Fields: Full-text search with filtering, pagination, organization scoping
- Performance Target: <200ms response time for 10k+ objects
- Testing Criteria: Search by name, description, location with proper ranking
moveObject mutation - Enhanced Container Transition Support
- Business Impact: Spatial dashboard drag-and-drop broken for container transitions
- Frontend Integration: Drag-drop handlers in
src/components/spatial/SpatialDashboard.tsx - Current Issue: Missing positional relationship cleanup when moving between containers
- Required Enhancements:
- Delete ALL existing spatial relationships (parent + positional) when moving to new container
- Create new parent relationship to target container
- Cleanup orphaned positional relationships from old container
- Validate container scope for positional relationships (same container only)
- Business Rules:
- Every object MUST have exactly one parent relationship
- Positional relationships only valid within same container
- Moving containers breaks all positional relationships to objects in old container
- Required Fields: objectId, newContainerId, relationshipType (IN/ON/CONTAINS)
- Performance Target: Handle relationship cleanup in single transaction
- Testing Criteria:
- Move object with LEFT_OF relationship to new container → old positional relationship removed
- Create object in container → gets appropriate parent relationship (IN for rooms, ON for surfaces)
- Drag object between containers with real-time UI updates and relationship cleanup
bulkCreateObjects mutation
- Business Impact: Cannot efficiently create multiple objects
- Frontend Integration: CSV import and batch scanning workflows ready
- Required Fields: Array of object inputs with transaction safety
- Performance Target: Handle 100+ objects in single request
- Testing Criteria: Partial success handling, detailed error reporting
searchObjectClasses query
- Business Impact: Dynamic object type selection replaces hardcoded dropdown
- Frontend Integration: ObjectClassSelector component with autocomplete search
- Required Fields: Full-text search, hierarchical navigation, usage analytics
- Performance Target: <300ms response time with fuzzy matching
- Testing Criteria: Search by name, category, manufacturer with relevance ranking
getRecentObjectTypes query
- Business Impact: Quick access to frequently used object types
- Frontend Integration: QuickTypeButtons component for mobile batch creation
- Required Fields: Organization-scoped usage tracking with temporal weighting
- Performance Target: <100ms response time with aggressive caching
- Testing Criteria: Return last 4 types used globally, updated in real-time
Tag Management APIs for Object Creation
resolveTagIdentifier query
- Business Impact: QR/NFC tag scanning integration for object creation workflow
- Frontend Integration: TagScanner component in
src/components/objects/creation/TagScanner.tsx - Required Fields:
- tagKey (scanned QR/NFC identifier), tagType (QR/NFC/BARCODE)
- Return: objectId (if assigned), tagData (instanceKey, classKey, path), availability status
- Business Rules:
- Parse Plings identifier URLs without navigation (security requirement)
- Extract 4-character short code from instanceKey for human identification
- Detect manufacturer vs general tags based on classKey presence
- Validate tag format and cryptographic authenticity
- Performance Target: <500ms tag resolution including database lookup
- Testing Criteria:
- Scan valid Plings tag → return tag data with short code and availability
- Scan assigned tag → return current object assignment with conflict warning
- Scan invalid QR → return clear error message
- Scan manufacturer tag → return rich metadata with class information
assignTagToObject mutation
- Business Impact: Link scanned tags to newly created objects
- Frontend Integration: CreateObjectModal tag assignment during object creation
- Required Fields: objectId, tagInstanceKey, tagMetadata, assignmentContext
- Business Rules:
- Validate tag is not already assigned to another object (unless multiple tags supported)
- Support multiple tag assignment to same object with tag role specification
- Create IDENTIFIES relationship in Neo4j graph with assignment metadata
- Update object name to include tag short code if auto-generated
- Handle tag migration for set objects (move tag from set to child)
- Track tag roles (primary, backup, verification, etc.) for multiple tag scenarios
- Performance Target: <300ms tag assignment including name updates
- Testing Criteria:
- Assign unassigned tag → creates IDENTIFIES relationship successfully
- Assign already-assigned tag → returns conflict error with current assignment
- Assign multiple tags to same object → creates multiple IDENTIFIES relationships with roles
- Assign tag during set creation → handles tag migration correctly
- Specify tag role → stores role metadata in relationship properties
checkTagAvailability query
- Business Impact: Validate tag availability before assignment during creation
- Frontend Integration: Real-time validation in tag scanner workflow
- Required Fields: tagInstanceKey, requestingObjectId (optional for creation)
- Business Rules:
- Return availability status, current assignment if any
- Handle tag conflicts with clear resolution options
- Support tag reservation during creation workflow
- Performance Target: <200ms availability check
- Testing Criteria:
- Check unassigned tag → return available status
- Check assigned tag → return assignment details and conflict options
getObjectTags query - NEW REQUIREMENT
- Business Impact: Display and manage multiple tags assigned to a single object
- Frontend Integration: Object details modal tag management section
- Required Fields: objectId
- Business Rules:
- Return all PlingsIdentifier nodes that IDENTIFIES the specified object
- Include tag metadata (type, status, role, assignment date)
- Sort by assignment order and tag role priority
- Support filtering by tag type (QR, NFC, Barcode)
- Performance Target: <150ms tag list retrieval
- Testing Criteria:
- Object with single tag → return single tag with metadata
- Object with multiple tags → return all tags sorted by role priority
- Object with no tags → return empty array
removeTagFromObject mutation - NEW REQUIREMENT
- Business Impact: Remove specific tags from objects while preserving others
- Frontend Integration: Object details tag management interface
- Required Fields: objectId, tagInstanceKey, removalReason
- Business Rules:
- Validate user has permission to modify object tags
- Remove specific IDENTIFIES relationship while preserving others
- Log tag removal in audit trail
- Prevent removal of last primary tag without replacement
- Performance Target: <200ms tag removal
- Testing Criteria:
- Remove backup tag → removes relationship, preserves primary tag
- Remove primary tag with backup present → promotes backup to primary
- Remove only tag → prompts for confirmation and updates object status
createGenericTag mutation - PHASE 1 IMPLEMENTATION
- Business Impact: Enable basic identifier generation for personal use without HD wallet complexity
- Frontend Integration: Object creation modal tag generation button
- Required Fields: batchSize (optional, default 1), organizationId
- Business Rules:
- Generate cryptographically random instanceKey using secure entropy
- Create 4-character shortCode from first 4 characters of instanceKey
- Store PlingsIdentifier node in Neo4j with isManufacturerTag: false
- Support batch generation up to 100 identifiers per request
- Validate user permissions for organization
- Performance Target: <200ms for single tag, <3s for batch of 100
- Testing Criteria:
- Generate single tag → returns valid instanceKey and shortCode
- Generate batch of tags → returns array of unique identifiers
- Validate uniqueness → no duplicate instanceKeys across system
- Permission validation → only organization members can generate
createBatchIdentifiers mutation - PHASE 1 IMPLEMENTATION
- Business Impact: Mass identifier generation for manufacturing and bulk object creation
- Frontend Integration: Batch creation workflow with progress tracking
- Required Fields: batchSize, organizationId, batchMetadata (optional)
- Business Rules:
- Support batch sizes from 1 to 1000 identifiers
- Generate all identifiers in single database transaction
- Return progress updates for large batches
- Store batch session metadata for resumption capability
- Validate organizational permissions and rate limits
- Performance Target: <5s for 100 identifiers, <30s for 1000 identifiers
- Testing Criteria:
- Small batch (1-10) → completes in single request
- Large batch (100+) → provides progress updates
- Transaction integrity → all-or-none generation on failure
- Rate limiting → prevents abuse by limiting concurrent batches
🔴 Sprint Priority 3: HD Wallet Foundation
generateMasterKey mutation - PHASE 2 IMPLEMENTATION
- Business Impact: Enable HD wallet infrastructure for manufacturer onboarding
- Frontend Integration: Admin panel key management interface
- Required Fields: organizationId, keyMetadata, securityLevel
- Business Rules:
- Generate BIP32 master key with high-entropy seed
- Store public key in database, private key in HSM or secure storage
- Create derivation path template for organization
- Require super-admin permissions for key generation
- Implement key backup and recovery procedures
- Performance Target: <1s for key generation, secure storage confirmation
- Testing Criteria:
- Generate valid BIP32 master key → passes cryptographic validation
- Security compliance → private key never exposed in logs or responses
- Derivation capability → can derive child keys successfully
- Permission enforcement → only authorized admins can generate
deriveAnchorKey mutation - PHASE 2 IMPLEMENTATION
- Business Impact: Create manufacturer object classes with cryptographic authentication
- Frontend Integration: Manufacturer onboarding workflow
- Required Fields: masterKeyId, derivationPath, classMetadata
- Business Rules:
- Derive AnchorKey from organization master key using BIP32
- Create ObjectClass node with anchor_key property
- Validate derivation path follows established format
- Link to manufacturer namespace and permissions
- Store public key for offline verification
- Performance Target: <300ms for key derivation and database storage
- Testing Criteria:
- Derive valid anchor key → verifiable against master key
- ObjectClass creation → properly linked with cryptographic proof
- Path validation → follows standardized derivation format
- Namespace isolation → keys unique within manufacturer scope
deriveInstanceKey mutation - PHASE 2 IMPLEMENTATION
- Business Impact: Generate cryptographically secure object identifiers
- Frontend Integration: Manufacturing workflow with QR generation
- Required Fields: anchorKeyId, instanceIndex, objectMetadata
- Business Rules:
- Derive instance key from AnchorKey using manufacturer-controlled derivation settings
- Generate PlingsIdentifier with full HD wallet metadata
- Create proper URL format with class and instance keys
- Support batch derivation for manufacturing runs
- Maintain cryptographic verifiability chain
- Performance Target: <200ms for single derivation, <5s for batch of 100
- Testing Criteria:
- Authority verification → instance key verified by Plings or manufacturer
- URL generation → produces valid scan.plings.io URLs
- Batch operations → maintains performance for manufacturing scale
- Uniqueness guarantee → no duplicate instance keys possible
validateKeyChain query - PHASE 3 IMPLEMENTATION
- Business Impact: Enable offline verification of identifier authenticity
- Frontend Integration: Mobile scanning app with offline capability
- Required Fields: instanceKey, classKey, derivationPath
- Business Rules:
- Verify instance key derives from provided class key
- Validate derivation path follows manufacturer standards
- Support offline verification without database lookup
- Return verification status and manufacturer information
- Handle both HD wallet and legacy identifier formats
- Performance Target: <100ms for cryptographic verification
- Testing Criteria:
- Valid HD wallet identifier → returns verified status with manufacturer info
- Invalid derivation → returns failed verification with reason
- Legacy identifier → graceful fallback to database lookup
- Offline capability → functions without network connectivity
🟡 Sprint Priority 2: Enhanced Creation Features
getContainerContext query
- Business Impact: Spatial context awareness for object creation
- Frontend Integration: LocationSelector with breadcrumb navigation
- Required Fields: Spatial hierarchy, permissions, recent object types in container
- Business Rules: Validate create permissions, spatial relationship constraints
- Testing Criteria: Return full spatial path with creation permissions
getSpatialNavigatorState query
- Business Impact: Object creation needs default location from current spatial navigator context
- Frontend Integration: CreateObjectModal default location assignment
- Required Fields:
- Current container ID and name
- Container type for relationship inference (Room→IN, Desk→ON)
- Full spatial hierarchy for breadcrumb display
- Organization context and permissions
- Business Rules:
- Must return accessible container variable for object creation
- Infer appropriate relationship type based on container characteristics
- Validate user has create permissions in current container
- Performance Target: <100ms response time, aggressive caching of spatial state
- Testing Criteria:
- Return current spatial navigator object when user opens create modal
- Correctly infer IN relationship for Room containers
- Correctly infer ON relationship for Desk/Table/Shelf containers
- Handle cases where no container is selected (default to user’s primary organization)
Enhanced Location Management APIs
getSpatialHierarchyPath query - NEW REQUIREMENT
- Business Impact: Object creation needs breadcrumb display for current location context
- Frontend Integration: LocationSelector and CreateObjectModal breadcrumb navigation
- Required Fields:
query GetSpatialHierarchyPath($containerId: ID!) { getSpatialHierarchyPath(containerId: $containerId) { pathElements { id name type level permissions { canCreateObjects canManageContents } } currentContainer { id name type description containerType # ROOM|DRAWER|SHELF|DESK|TABLE|BOX spatialCapacity { maxObjects currentObjects percentFull } } breadcrumbPath # "Home > Office > Desk > Drawer 1" } } - Business Rules:
- Return complete spatial hierarchy from root to current container
- Include permission checks for each level in hierarchy
- Provide human-readable breadcrumb path for UI display
- Include container capacity information for placement validation
- Performance Target: <150ms response time with spatial tree caching
- Testing Criteria:
- Query with container ID → return complete hierarchy path with permissions
- Query with nested container → return proper breadcrumb “Room > Desk > Drawer”
- Include capacity info → return current/max object counts for container
createNormalSpatialRelationship mutation - NEW REQUIREMENT
- Business Impact: Enable misplacement detection by setting expected object locations
- Frontend Integration: Normal Location selector in CreateObjectModal
- Required Fields:
mutation CreateNormalSpatialRelationship($input: NormalSpatialRelationshipInput!) { createNormalSpatialRelationship(input: $input) { id objectId normalPlacement { containerId containerName relationshipType # NORMAL_IN, NORMAL_ON, NORMAL_ATTACHED_TO confidence # 0.0-1.0 confidence score setByUser # true if manually set, false if inferred } spatialHierarchy { id name type } } } input NormalSpatialRelationshipInput { objectId: ID! normalContainerId: ID! relationshipType: NormalSpatialRelationshipType! confidence: Float = 1.0 setByUser: Boolean = true reason: String # "User selected during creation", "Inferred from usage pattern" } - Business Rules:
- Create NORMAL_* spatial relationship for expected placement
- Validate container can hold object type (capacity + compatibility)
- Override any existing normal placement relationship
- Store confidence score and assignment method for analytics
- Create relationship in Neo4j for misplacement detection queries
- Performance Target: <200ms relationship creation including validation
- Testing Criteria:
- Create normal placement → NORMAL_IN relationship created in Neo4j
- Override existing normal placement → old relationship deleted, new one created
- Validate container compatibility → reject incompatible placements with clear error
validateSpatialPlacement query - NEW REQUIREMENT
- Business Impact: Prevent invalid object placement with real-time validation
- Frontend Integration: Real-time validation in location selectors
- Required Fields:
query ValidateSpatialPlacement($input: SpatialPlacementValidationInput!) { validateSpatialPlacement(input: $input) { isValid: Boolean! validationResult { capacityValid { hasSpace currentCount maxCapacity } compatibilityValid { compatible containerType supportedObjectTypes[] incompatibilityReason } permissionValid { userCanPlace organizationMatch requiredRole } spatialConstraints { maxObjectSize { width height depth unit } restrictedObjectTypes[] specialRequirements[] } } warnings: [String!] suggestions: [String!] alternativeContainers { id name type availableSpace compatibilityScore } } } input SpatialPlacementValidationInput { objectType: String! objectSize: ObjectDimensionsInput currentContainerId: ID! targetContainerId: ID! organizationId: ID! userId: ID! } - Business Rules:
- Check container capacity (current objects vs max capacity)
- Validate object type compatibility with container type
- Verify user permissions for container access
- Check spatial constraints (size, weight, special requirements)
- Suggest alternative containers when placement invalid
- Return actionable warnings and suggestions
- Performance Target: <100ms validation with aggressive caching
- Testing Criteria:
- Validate valid placement → return isValid=true with capacity info
- Validate over-capacity container → return capacity violation with alternatives
- Validate incompatible object type → return compatibility error with supported types
- Validate insufficient permissions → return permission error with required role
Enhanced Capacity Management - NEW REQUIREMENTS
removeSpatialCapacityLimits system change - NEW REQUIREMENT
- Business Impact: Remove artificial 20-object limits, prepare for flexible capacity constraints
- Frontend Integration: Updated capacity display in LocationSelector and spatial dashboard
- Required Changes:
- Database Migration: Update all containers with
maxObjects: 20tomaxObjects: 0(unlimited) - Default Behavior: New containers default to
maxObjects: 0(unlimited capacity) - Capacity Logic: When
maxObjects = 0, system treats as unlimited (no capacity checks) - UI Updates: Show “(unlimited)” for unlimited containers, hide progress bars
- Future Preparation: Prepare schema for
maxWeight,maxVolumeconstraints
- Database Migration: Update all containers with
- Schema Updates:
type SpatialCapacity { maxObjects: Int # 0 = unlimited, >0 = limited maxWeight: Float # 0 = unlimited (future use) maxVolume: Float # 0 = unlimited (future use) currentObjects: Int currentWeight: Float # future use currentVolume: Float # future use percentFull: Float # Should be 0 when no limits set } - Business Rules:
maxObjects = 0means unlimited capacitypercentFullalways returns 0 for unlimited containers- Capacity validation skipped for unlimited containers
- Future weight/volume constraints use same 0 = unlimited pattern
- Database Migration SQL:
UPDATE object_instances SET spatial_capacity = jsonb_set(spatial_capacity, '{maxObjects}', '0') WHERE spatial_capacity->>'maxObjects' = '20'; ALTER TABLE object_instances ALTER COLUMN spatial_capacity SET DEFAULT '{"maxObjects": 0, "currentObjects": 0, "percentFull": 0}'; - Performance Target: No performance impact, maintains existing query patterns
- Testing Criteria:
- Create new container → defaults to unlimited capacity (maxObjects: 0)
- Query unlimited container → returns “(unlimited)” display, no progress bar
- Place objects in unlimited container → no capacity validation errors
- Legacy containers → migrated to unlimited without data loss
enhancePotentialContainersHierarchy query enhancement - NEW REQUIREMENT
- Business Impact: Normal location selector shows spatial hierarchy like “Västervägen 26 → Husvagnen”
- Frontend Integration: Updated LocationSelector to display container hierarchy paths
- Current Issue:
GET_POTENTIAL_CONTAINERSonly returns basic container info without spatial context - Required Enhancement:
query GetPotentialContainers { potentialContainers { id name description type mainImageUrl imageUrls statuses # ADD THESE FIELDS: spatialHierarchy { id name type } hierarchyPath # "Västervägen 26 → Huset → Vardagsrummet" } } - Business Rules:
- Include complete spatial hierarchy from root to container
- Generate human-readable hierarchy path for UI display
- Maintain existing filtering and status logic
- Performance optimization with hierarchy caching
- Frontend Usage:
- Normal location dropdown shows “Husvagnen” with hierarchy “Västervägen 26 → Husvagnen”
- Eliminates confusion about object locations
- Consistent with current location hierarchy display
- Performance Target: <300ms response with hierarchy resolution
- Testing Criteria:
- Query containers → return hierarchy paths for all containers
- Container in nested location → shows complete path “Root → Parent → Container”
- Root-level container → shows just container name
- UI displays hierarchy consistently with current location format
Image Upload Enhancement APIs
uploadObjectImagesMultiple mutation
- Business Impact: Multi-image upload support for complete object documentation
- Frontend Integration: ImageUploadSection component with drag-drop and camera capture
- Required Fields:
- objectId (optional for creation), imageFiles[], mainImageIndex
-
uploadContext (creation update), compressionLevel, generateThumbnails
- Business Rules:
- Support up to 10 images per object (5MB per image, 50MB total)
- Auto-generate thumbnails for immediate UI feedback
- Compress images for performance (maintain quality <2MB)
- First image auto-marked as “Main” unless specified
- Background upload with progress tracking
- Performance Target: <5s for batch upload of 5 images including compression
- Testing Criteria:
- Upload multiple images → all images processed with thumbnails generated
- Upload during object creation → images linked to object immediately
- Upload with compression → file sizes reduced while maintaining quality
- Upload large batch → progress tracking and parallel processing
generateImageThumbnails mutation
- Business Impact: Immediate thumbnail generation for image grid display
- Frontend Integration: Image preview grid with instant thumbnail display
- Required Fields: imageIds[], thumbnailSizes[] (small, medium, large)
- Business Rules:
- Generate multiple thumbnail sizes for different UI contexts
- Maintain aspect ratio while fitting target dimensions
- Store thumbnails in optimized format (WebP with JPEG fallback)
- Background processing for large batches
- Performance Target: <2s thumbnail generation for batch of 10 images
- Testing Criteria:
- Generate thumbnails → multiple sizes created with correct aspect ratios
- Batch thumbnail generation → processed in parallel efficiently
compressImages service
- Business Impact: Performance optimization for image upload and storage
- Frontend Integration: Automatic compression during upload process
- Required Fields: imageFile, targetQuality, maxDimensions, outputFormat
- Business Rules:
- Compress images before upload to reduce network usage
- Maintain visual quality while reducing file size
- Support multiple output formats (JPEG, WebP, PNG)
- Client-side compression for immediate feedback
- Performance Target: <1s compression per image on client-side
- Testing Criteria:
- Compress large image → significant size reduction with maintained quality
- Batch compression → processed efficiently without blocking UI
Batch Session Management
getBatchSession: Resume interrupted mobile batch creation sessionsresumeBatchSession: Recovery from app crashes or network interruptionscompleteBatchSession: Finalize batch with analytics and summary- Requirements: See Object Creation Backend Requirements Section F
🟡 Sprint Priority 3: Set Object Workflows
Set Object Operations (Relationship-Based Architecture)
convertToSet: CreatePART_OFrelationships to convert object to set containercreateSetChild: Add items to existing sets withPART_OFrelationship creationcompleteSet: Finalize set creation with relationship metadata updates- Architecture Note: Sets determined by Neo4j
PART_OFrelationships, not boolean flags - Requirements: See Object Creation Backend Requirements Section C
🟢 Sprint Priority 4: Advanced Tag Management
Core Tag Operations
resolveTagIdentifier: Process scanned QR/NFC tags with conflict detectionassignTagToObject: Link tags to objects with audit trailgetTagHistory: Complete assignment and scanning historytransferTag: Move tags between objects with validation- Requirements: See Object Creation Backend Requirements Section H
🔵 Sprint Priority 5: Object Class System
Object Class Management
getObjectClassHierarchy: Hierarchical class navigation with propertiescreateObjectClass: Admin interface for defining custom object types- Requirements: See Object Creation Backend Requirements Section G
🔴 Sprint Priority 6: Organization Intelligence System
getRecommendedOrganization query - Intelligent Organization Selection
- Business Impact: Eliminates manual organization selection by intelligently predicting optimal organization based on spatial context and user behavior
- Frontend Integration: CreateObjectModal organization selector with smart defaults and explanations
- Required Fields:
- Input: spatialContextId (current container where object is being created)
- Output: primaryRecommendation, alternatives, spatialAnalysis, userBehaviorAnalysis
- Intelligence Algorithm:
- Priority 1: Organization of last object user created in current spatial hierarchy (up to root)
- Priority 2: Organizations that currently own objects in spatial hierarchy (ranked by presence)
- Priority 3: User’s organizations ordered by recent usage frequency
- Business Rules:
- Analyze spatial hierarchy from current container up to root level
- Track user creation history per spatial hierarchy root
- Calculate organization presence scores based on object count and recency
- Provide confidence scores and clear explanations for recommendations
- Support both home environments (multiple family members) and work environments (multiple companies)
- Performance Target: <300ms recommendation including spatial analysis and user history lookup
- Testing Criteria:
- Home scenario: User creates tool in workshop → defaults to organization of last tool created in house hierarchy
- Work scenario: User creates item in office → defaults to organization of last item created in building hierarchy
- Multi-organization space: Shows primary recommendation with alternatives ranked by relevance
- New space: Falls back to user’s most recently used organization with clear explanation
- Real-World Examples:
- Home: 6 organizations (5 family members + 1 shared) → intelligent default based on last creation in house
- Work: 5 companies sharing office → intelligent default based on last creation in building + company presence
- Required Backend Intelligence:
- Spatial hierarchy analysis service
- User creation history tracking per spatial root
- Organization presence analysis within hierarchies
- Smart ranking algorithm with confidence scoring
- Database Requirements:
- user_creation_history table with spatial_root_id tracking
- organization_hierarchy_presence cache table
- Trigger functions for automatic history and presence updates
- Documentation Reference: See Organization Ownership Intelligence System
🔴 Sprint Priority 7: User Role & Permission Management System
assignUserRole mutation - User Role Management
- Business Impact: Enable proper access control and developer tool restrictions
- Frontend Integration: Admin interface for role assignment, permission validation throughout app
- Required Fields:
mutation AssignUserRole($input: AssignUserRoleInput!) { assignUserRole(input: $input) { success: Boolean! user { id email role abilities organizationId organizationRole } message: String } } input AssignUserRoleInput { userId: ID! role: SystemRole! organizationId: ID organizationRole: OrganizationRole assignedBy: ID! } enum SystemRole { PUBLIC_GUEST ORG_MEMBER ORG_ADMIN MANUFACTURER_ISSUER PLINGS_ADMIN PLINGS_DEVELOPER SYSTEM_OWNER } enum OrganizationRole { MEMBER ADMIN OWNER } - Business Rules:
- Only
system_ownerandplings_admincan assign roles - Use Supabase Admin API to set
app_metadata.role - Include role in JWT claims during authentication
- Validate role hierarchy (can’t assign higher role than assigner has)
- Audit log all role changes with timestamp and assigner
- Only
- Implementation Method: Use Supabase
app_metadatafield for role storage - Performance Target: <500ms role assignment including JWT refresh
- Testing Criteria:
- Assign plings_developer role → user gets DEV_BACKEND_SWITCH ability
- Assign system_owner role → user gets all abilities
- Role assignment by non-admin → returns permission error
getCurrentUserPermissions query - Permission Validation
- Business Impact: Frontend permission system validation and UI state management
- Frontend Integration: useUserPermissions hook validation, component access control
- Required Fields:
query GetCurrentUserPermissions { getCurrentUserPermissions { user { id email role abilities organizationId organizationRole } permissions { canSwitchBackend canAccessDebugPanel canManageClasses canManageUsers canAssignPermissions hasAdminAccess hasDevAccess } } } - Business Rules:
- Extract role from JWT
app_metadata.role - Map role to abilities using role-ability matrix
- Return computed permissions for frontend use
- Cache permissions in user session
- Extract role from JWT
- Performance Target: <200ms permission lookup with JWT caching
- Testing Criteria:
- Query as plings_developer → returns canSwitchBackend: true
- Query as org_member → returns limited permissions
- Query without auth → returns public guest permissions
Initial System Setup - REQUIRED FOR PAUL@GRONTEKNIK.NU
- Business Impact: Establish initial system owner for platform administration
- Required Action: Backend team must run initial setup script
- Setup Script:
// Backend setup script - run once during deployment const { createClient } = require('@supabase/supabase-js') const supabase = createClient( process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_ROLE_KEY, { auth: { persistSession: false } } ) // Set paul@gronteknik.nu as system owner await supabase.auth.admin.updateUserById( 'paul-user-id', // Find user ID for paul@gronteknik.nu { app_metadata: { role: 'system_owner' } } ) - Verification: Paul should be able to access all developer tools and admin functions
- Timeline: Critical - required for proper development environment setup
🔵 Sprint Priority 8: Analytics & Optimization
Usage Analytics
getCreationAnalytics: Organization-level creation metrics and insightstrackCreationEvent: Behavioral analytics for UX optimization- Requirements: See Object Creation Backend Requirements Section I
🚨 URGENT: Frontend Integration Issue - createObject Query Mismatch
Issue Description
Status: ⚠️ Frontend Integration Required - Backend Working, Frontend Query Incorrect
The createObject mutation is working correctly on the backend, but the frontend is using an incorrect GraphQL query structure.
Problem
- Frontend Query: Expects
createObjectto returnObjectInstancedirectly - Backend Implementation: Returns
CreateObjectResultwrapper with additional metadata
Frontend Error
Cannot query field 'id' on type 'CreateObjectResult'
Cannot query field 'name' on type 'CreateObjectResult'
...
❌ Current Frontend Query (INCORRECT)
mutation CreateObject($input: CreateObjectInput!) {
createObject(input: $input) {
id # ❌ Wrong - this field doesn't exist on CreateObjectResult
name # ❌ Wrong - this field doesn't exist on CreateObjectResult
description # ❌ Wrong - this field doesn't exist on CreateObjectResult
owner_organization_id # ❌ Wrong - this field doesn't exist on CreateObjectResult
spatialParent { # ❌ Wrong - this field doesn't exist on CreateObjectResult
id
name
__typename
}
__typename
}
}
✅ Correct Frontend Query (REQUIRED FIX)
mutation CreateObject($input: CreateObjectInput!) {
createObject(input: $input) {
object { # ✅ Correct - object is the wrapper field
id # ✅ Correct - now accessing ObjectInstance fields
name # ✅ Correct - now accessing ObjectInstance fields
description # ✅ Correct - now accessing ObjectInstance fields
owner_organization_id # ✅ Correct - now accessing ObjectInstance fields
spatialParent { # ✅ Correct - now accessing ObjectInstance fields
id
name
__typename
}
__typename
}
warnings # ✅ Additional - helpful validation warnings
generatedName # ✅ Additional - shows auto-generated name
spatialRelationshipCreated # ✅ Additional - confirms spatial setup
imagesUploaded # ✅ Additional - confirms image processing
__typename
}
}
Action Required
Frontend Team: Update the createObject mutation query in CreateObjectModal.tsx to use the correct structure with the object wrapper field.
Testing Status
- ✅ Backend mutation working correctly on Vercel production
- ✅ Database schema updated with required columns
- ✅ Authentication and authorization working
- ⚠️ Frontend needs query structure update
✅ RESOLVED: Backend Bug - spatialChildren mainImageUrl Fixed
Issue Description
Status: ✅ RESOLVED - spatialChildren field resolvers now properly populate mainImageUrl
The GET_SPATIAL_DASHBOARD_DATA query’s spatialChildren field was returning mainImageUrl: null for all child objects, even when those same objects had valid image URLs when queried individually.
Resolution Summary
Fixed on: 2025-07-05 19:21:00
Commit: d315f211 - Fix spatialChildren mainImageUrl null issue - populate images from PostgreSQL
Root Cause Identified
The issue was in three backend resolvers where spatial children were retrieved from Neo4j but their mainImageUrl was never populated from PostgreSQL:
myObjectsresolver (app/resolvers.pyline 114) - Used byGET_SPATIAL_DASHBOARD_DATAobjectresolver (app/object_detail_resolvers.py) - Used by individual object queriesgetObjectDetailsCompleteresolver (app/object_detail_resolvers.py) - Used by detailed object queries
Technical Fix Applied
Added PostgreSQL image lookup for spatial children in all three resolvers:
# CRITICAL FIX: Fetch mainImageUrl for spatial children from PostgreSQL
if spatial_children:
try:
async with pg_engine.begin() as conn:
for child in spatial_children:
child_id = child['id']
child_image_result = await conn.execute(
text("""
SELECT public_url FROM object_images
WHERE object_instance_id = :child_id AND is_main = true
LIMIT 1
"""),
{"child_id": child_id}
)
child_image_record = child_image_result.fetchone()
child['mainImageUrl'] = child_image_record[0] if child_image_record else None
Verification
Before Fix:
"spatialChildren": [
{
"mainImageUrl": null // ❌ Always null
}
]
After Fix:
"spatialChildren": [
{
"mainImageUrl": "https://gjzcqcxoacxkrchrzaen.supabase.co/storage/v1/object/public/object-images/..." // ✅ Correct URL
}
]
Impact Resolved
- ✅ Child preview icons now display correctly in spatial navigator
- ✅ Improved user experience with proper visual cues
- ✅ Performance optimized - no more fallback icon rendering
🚨 URGENT: Frontend Integration Issue - createObject Query Mismatch
Issue Description
Status: ⚠️ Frontend Integration Required - Backend Working, Frontend Query Incorrect
The createObject mutation is working correctly on the backend, but the frontend is using an incorrect GraphQL query structure.
Problem
- Frontend Query: Expects
createObjectto returnObjectInstancedirectly - Backend Implementation: Returns
CreateObjectResultwrapper with additional metadata
Frontend Error
Cannot query field 'id' on type 'CreateObjectResult'
Cannot query field 'name' on type 'CreateObjectResult'
...
❌ Current Frontend Query (INCORRECT)
mutation CreateObject($input: CreateObjectInput!) {
createObject(input: $input) {
id # ❌ Wrong - this field doesn't exist on CreateObjectResult
name # ❌ Wrong - this field doesn't exist on CreateObjectResult
description # ❌ Wrong - this field doesn't exist on CreateObjectResult
owner_organization_id # ❌ Wrong - this field doesn't exist on CreateObjectResult
spatialParent { # ❌ Wrong - this field doesn't exist on CreateObjectResult
id
name
__typename
}
__typename
}
}
✅ Correct Frontend Query (REQUIRED FIX)
mutation CreateObject($input: CreateObjectInput!) {
createObject(input: $input) {
object { # ✅ Correct - object is the wrapper field
id # ✅ Correct - now accessing ObjectInstance fields
name # ✅ Correct - now accessing ObjectInstance fields
description # ✅ Correct - now accessing ObjectInstance fields
owner_organization_id # ✅ Correct - now accessing ObjectInstance fields
spatialParent { # ✅ Correct - now accessing ObjectInstance fields
id
name
__typename
}
__typename
}
warnings # ✅ Additional - helpful validation warnings
generatedName # ✅ Additional - shows auto-generated name
spatialRelationshipCreated # ✅ Additional - confirms spatial setup
imagesUploaded # ✅ Additional - confirms image processing
__typename
}
}
Action Required
Frontend Team: Update the createObject mutation query in CreateObjectModal.tsx to use the correct structure with the object wrapper field.
Testing Status
- ✅ Backend mutation working correctly on Vercel production
- ✅ Database schema updated with required columns
- ✅ Authentication and authorization working
- ⚠️ Frontend needs query structure update
⚙️ Implementation Guidelines for Backend Team
🎯 Technical Standards
- Error Handling: Use structured error codes from
object-creation-backend-requirements.mdSection 8 - Performance: All queries <500ms, mutations <1s, batch operations <5s
- Security: Organization-level RLS, validate all user permissions
- Testing: Unit tests + integration tests for all new resolvers
- Documentation: Update GraphQL schema docs and API examples
🏗️ Architecture Decisions
- Database: PostgreSQL for object data + Neo4j for relationships (existing pattern)
- Set Objects: Determined by Neo4j
PART_OFrelationships, not boolean columns - Search: PostgreSQL full-text search for MVP, Elasticsearch for advanced features
- File Storage: Continue using Supabase Storage with existing bucket structure
- Real-time: GraphQL subscriptions for live updates (Apollo Client ready)
📊 Database Schema Requirements
See complete schema changes in Object Creation Backend Requirements Section 9:
- Add
short_code,batch_id,statuscolumns toobject_instances - Create
tag_assignments,batch_sessionstables - Set Object Architecture: Sets determined by Neo4j
PART_OFrelationships, not database column
Set Object Implementation Details
- No
is_setcolumn: Sets are dynamically determined by relationship queries - Single source of truth: Neo4j
PART_OFrelationships define set membership - GraphQL computed fields:
isSet: Boolean!- Resolver checks if object has components withPART_OFrelationshipssetComponents: [ObjectInstance!]!- Objects withPART_OFrelationship to this objectpartOfSets: [ObjectInstance!]!- Sets this object belongs to
- Benefits: Avoids data duplication, maintains consistency, follows existing patterns
- Performance: Add indices for new lookup patterns (excluding set-related boolean queries)
🔄 Team Coordination Process
🎆 SINGLE SOURCE OF TRUTH WORKFLOW
This file (api-requirements.md) is the authoritative coordination hub. All API development status flows through this tracking table.
🚨 CRITICAL RULE: ALL API COMMUNICATION THROUGH DOCUMENTATION
MANDATORY PROCESS: All technical communication between frontend and backend teams regarding API operations MUST be documented in the official API documentation files. No API integration details should be communicated solely through Slack, email, or verbal discussions.
Required Documentation Flow:
- API Requirements: All new API needs documented in this tracking table
- Integration Details: All technical integration guidance documented in API Endpoints Reference
- Status Updates: All progress updates reflected in this tracking table
- Issue Resolution: All integration problems documented with solutions
Why This Matters:
- Knowledge Preservation: Prevents loss of critical integration details
- Team Alignment: Ensures all team members have access to the same information
- Quality Assurance: Reduces integration errors from miscommunication
- Onboarding Efficiency: New team members can understand API contracts immediately
- Documentation Currency: Keeps API docs accurate and up-to-date
Enforcement:
- ❌ BLOCKED: Any API integration without proper documentation
- ❌ BLOCKED: Code reviews for APIs not documented in api-endpoints.md
- ✅ REQUIRED: All “Backend Complete” status changes must include api-endpoints.md examples
- ✅ REQUIRED: All frontend integration questions answered through documentation updates
📝 How Frontend Teams Request New APIs
Step 1: Add Request to Tracking Table
- Add new row to the tracking table above
- Required Information:
- Clear user story (“As a user, I want to…”)
- Business impact explanation
- Frontend readiness status
- Expected timeline/sprint
- Integration component file paths
- Set initial status to “❌ Frontend Need”
- Tag backend team in #api-coordination Slack channel
Step 2: Frontend Preparation
- Build UI components and integration points
- Update “Frontend Ready” column with component locations
- Create frontend requirement docs in
/docs/frontend/if complex - Link to frontend requirements from tracking table
🔧 How Backend Teams Update Implementation Status
Daily Status Updates (Required):
- Assignment: Update “Developer” column with assigned team member
- Timeline: Provide realistic implementation estimate
- Progress: Update “Status” column through progression:
- ❌ Frontend Need → 🚧 Backend In Progress → ✅ Backend Complete → ✅ Production Ready
- Issues: Document blockers or integration problems
Status Definitions:
- ❌ Frontend Need: Frontend requires this, backend not started
- 🚧 Backend In Progress: Active backend implementation
- ✅ Backend Complete: Implementation done, needs frontend integration testing
- ⚠️ Integration Issues: Problems found during frontend integration
- ✅ Production Ready: Fully implemented and tested end-to-end
Implementation Documentation (MANDATORY):
- During Development: Create detailed specs in
/docs/api/[feature]-backend-requirements.md - Upon Completion:
- ✅ REQUIRED: Add complete working examples to API Endpoints Reference
- ✅ REQUIRED: Include “Integration Notes for Frontend” section with specific implementation guidance
- ✅ REQUIRED: Document all required fields, response structures, and usage patterns
- Integration Ready: Update this tracking table to “Backend Complete” ONLY after api-endpoints.md is updated
- Post-Testing: Update to “Production Ready” after successful frontend integration
❌ BLOCKED ACTIONS:
- Marking status as “Backend Complete” without api-endpoints.md documentation
- Communicating API details outside of official documentation
- Code merging without corresponding documentation updates
✅ QUALITY GATES:
- All API operations must have complete GraphQL examples in api-endpoints.md
- All operations must include frontend integration guidance
- All status changes must be reflected in both files consistently
🔄 How to Maintain Consistency Between Documents
Document Hierarchy and Responsibilities:
- api-requirements.md (This File) - PROJECT MANAGEMENT HUB
- Owner: Project/Product Management
- Purpose: Track development progress, coordinate teams, prioritize work
- Updates: Real-time status updates, team coordination, sprint planning
- Authority: Single source of truth for “what needs to be built” and “current status”
- api-endpoints.md - DEVELOPER REFERENCE
- Owner: Backend Development Team
- Purpose: Complete GraphQL schema, working examples, integration patterns
- Updates: Add operations when they reach “Backend Complete” status
- Authority: Technical implementation details, working code examples
- [feature]-backend-requirements.md - TECHNICAL SPECIFICATIONS
- Owner: Backend Development Team + Product Management
- Purpose: Detailed API specs, database schema, business logic
- Updates: Created during “Backend In Progress”, finalized at “Backend Complete”
- Authority: Implementation requirements, validation rules, error handling
- [feature]-frontend-requirements.md - UX SPECIFICATIONS
- Owner: Frontend Development Team + UX Design
- Purpose: User experience, component specs, integration requirements
- Updates: Created when “Frontend Ready” status is set
- Authority: User interface requirements, component architecture
Consistency Maintenance Process:
- When Backend Reaches “Backend Complete”:
```
Backend Developer Action Items:
- Update this tracking table status → “Backend Complete”
- Add working examples to api-endpoints.md
- Link to technical specs from api-endpoints.md
- Notify frontend team via #api-coordination ```
- When Integration Testing Completes:
```
Frontend Developer Action Items:
- Test integration with real backend
- Update this tracking table status → “Production Ready”
- Update “Issues” column if problems found
- Close related GitHub issues/tickets ```
- When Operations Reach Production:
```
Backend Team Action Items:
- Move detailed examples to api-endpoints.md “Working Operations” section
- Archive development-specific notes from tracking table
- Update schema documentation with final field definitions ```
🔗 Integration Points Between Documents
Cross-Reference Requirements:
- From api-requirements.md: Link to detailed specs and frontend requirements
- From api-endpoints.md: Link back to coordination status and technical specs
- From technical specs: Link to coordination table for current status
- From frontend specs: Link to backend specs and coordination status
Navigation Links (Required in all files):
## 📚 **Related Documentation**
- **[API Requirements & Coordination](/api/api-requirements.html)**: Development tracking and team coordination
- **[API Endpoints Reference](/api/api-endpoints.html)**: Complete GraphQL schema and examples
- **[Object Creation Backend Requirements](/api/object-creation-backend-requirements.html)**: Technical specifications
- **[Frontend Object Creation Requirements](/frontend/object-creation-requirements.html)**: User experience requirements
🚑 Escalation and Communication Workflows
Critical Issues (blocking core features):
- Immediate Action: Update status to “⚠️ Integration Issues”
- Communication: Tag team leads in #api-coordination Slack
- Documentation: Document specific problem in “Issues” column
- Resolution: Schedule sync meeting within 48 hours
- Follow-up: Update tracking table with resolution timeline
Timeline Delays:
- Update Status: Revise “Timeline” column with new realistic estimate
- Impact Assessment: Document dependencies and affected features
- Stakeholder Communication: Notify product management and frontend teams
- Scope Decisions: Consider scope reduction, sprint reallocation, or priority changes
- Documentation: Update tracking table with revised plan
Integration Conflicts:
- Document Issues: Capture specific technical problems in tracking table
- Cross-team Communication: Schedule technical discussion between frontend/backend
- Resolution Tracking: Update progress in tracking table daily
- Version Control: Ensure API changes are synchronized across environments
📊 Communication Channels and Update Frequency
Primary Communication:
- This Tracking Table: Updated daily, single source of truth for all API status
- Slack #api-coordination: Real-time discussions, alerts, and quick questions
- Weekly Sprint Review: Progress assessment, priority adjustments, team sync
- GitHub Issues: Technical implementation details (always link from tracking table)
Update Requirements:
- Backend Developers: Update status daily during active development
- Frontend Developers: Update integration status within 48 hours of backend completion
- Project Management: Review and update priorities weekly
- All Teams: Immediate updates for blockers or critical issues
Documentation Sync Schedule:
- api-endpoints.md: Updated when operations reach “Backend Complete”
- Technical specs: Updated during “Backend In Progress” phase
- Frontend specs: Updated when “Frontend Ready” status is set
- Cross-references: Verified weekly during sprint reviews
📈 Success Metrics and Quality Gates
Development Velocity:
- Sprint Velocity: API operations completed per sprint (target: 4-6 operations)
- Development Cycle Time: Average days from “Frontend Need” to “Backend Complete” (target: <7 days)
- Integration Success Rate: % of operations that work on first frontend integration (target: >80%)
- Time to Production: Average days from “Frontend Need” to “Production Ready” (target: <14 days)
Quality Metrics:
- Documentation Completeness: All operations have complete specs and examples (target: 100%)
- Cross-Reference Accuracy: All document links are current and valid (target: 100%)
- Status Synchronization: Tracking table matches actual implementation status (target: 100%)
- User Story Completion: Business value delivered per sprint (measured by user feature availability)
Team Coordination Metrics:
- Communication Response Time: Average time for backend response to frontend requests (target: <24 hours)
- Issue Resolution Time: Average time to resolve integration issues (target: <48 hours)
- Documentation Currency: Days between implementation and documentation updates (target: <2 days)
- Stakeholder Satisfaction: Team satisfaction with coordination process (target: >4.0/5.0)
📚 Related Documentation
Primary Documentation Navigation
- API Endpoints Reference: Complete GraphQL schema and working examples for implemented operations
- Object Creation Backend Requirements: Detailed technical specifications for object creation workflow
- Frontend Object Creation Requirements: User experience and frontend implementation details
Cross-Reference Index
From This File → Navigate To:
- Detailed technical specs for specific features:
[feature]-backend-requirements.md - Working GraphQL examples and schema:
api-endpoints.md - Frontend component specifications:
../frontend/[feature]-requirements.md - Development progress tracking: GitHub Issues linked in tracking table
To This File ← Navigate From:
- All other API documentation files link back to this coordination hub
- GitHub issues reference this tracking table for current status
- Sprint planning tools reference this file for prioritization
- Team communication channels reference this file for authoritative status
Document Update Responsibilities
| Document | Primary Owner | Update Trigger | Update Frequency |
|---|---|---|---|
| api-requirements.md | Product Management | Status changes | Daily |
| api-endpoints.md | Backend Team | Implementation complete | Upon “Backend Complete” |
| [feature]-backend-requirements.md | Backend Team | Development start | During “Backend In Progress” |
| [feature]-frontend-requirements.md | Frontend Team | UI design complete | When “Frontend Ready” |
Quality Assurance:
- All cross-references verified during weekly sprint reviews
- Broken links flagged as high-priority issues
- Documentation currency tracked as team metric
- Consistency maintained through standardized templates
🔄 Quick Reference: Coordination Workflow
For Frontend Developers:
- Request API → Add row to tracking table + tag backend team
- Prepare Integration → Build UI components, update “Frontend Ready”
- Test Integration → Validate when backend reaches “Backend Complete”
- Confirm Production → Update status to “Production Ready”
For Backend Developers:
- Acknowledge Request → Assign developer, estimate timeline (within 24 hours)
- During Development → Update status daily, create technical specs
- Complete Implementation → Add examples to api-endpoints.md, update status
- Support Integration → Resolve issues, update to “Production Ready”
For Project Management:
- Prioritize Requests → Review tracking table, set sprint goals
- Monitor Progress → Daily status review, weekly team coordination
- Resolve Conflicts → Escalate blockers, adjust timelines
- Maintain Quality → Verify documentation consistency, track metrics
Emergency Contact: For critical issues, immediate Slack #api-coordination + tag team leads
Last Updated: 2025-07-01 - Next Review: Weekly Sprint Planning
🔍 myObjects Query Enhancement - PostgreSQL-First Architecture
Issue Description
Status: ✅ COMPLETED - myObjects query enhanced to show ALL objects including PostgreSQL orphans
Background: The user discovered objects like “Tältet” exist in PostgreSQL but are missing from Neo4j, making them invisible in the debugger and unavailable for deletion tools. The original myObjects query was Neo4j-first, which only showed objects that existed in both databases.
User Request: “can you check myObjects query. We have objects like ‘Tältet’ in postgres but missing in Neo4J. It is used to select objects in the debugger and I was thinking of using it as the selector for hard deleting objects.”
Enhancement Summary
Completed on: 2025-07-05 21:00:00
Commit: Pending - myObjects PostgreSQL-first hybrid query implementation
Technical Implementation
Completely rewrote myObjects resolver in app/resolvers.py to use a PostgreSQL-first hybrid approach:
Architecture Change
- PostgreSQL-First Query: Get ALL objects from PostgreSQL (authoritative source)
- Neo4j Enrichment: Add spatial relationships and metadata where available
- Orphan Detection: Mark objects that exist only in PostgreSQL with
ORPHANED_POSTGRESQL_ONLYstatus - Image Integration: Fetch image data from PostgreSQL for all objects and spatial children
Key Benefits
- 🔍 Debugger Visibility: ALL objects now visible in debugger, including orphaned ones
- 🗑️ Deletion Tool Ready: Can now select any object for hard deletion, including orphans
- ⚡ Performance: Single PostgreSQL query + optional Neo4j enrichment
- 🔧 Maintainable: Clear separation between authoritative data (PG) and relationships (Neo4j)
Enhanced Query Fields
query myObjects {
myObjects {
id # Always from PostgreSQL
name # Always from PostgreSQL
description # Always from PostgreSQL
statuses # Includes "ORPHANED_POSTGRESQL_ONLY" for orphans
spatialParent # Neo4j enrichment (null for orphans)
spatialChildren # Neo4j enrichment (empty for orphans)
positionalRelationships # Neo4j enrichment (empty for orphans)
lastSeen # Neo4j enrichment (null for orphans)
# All image data fetched from PostgreSQL
mainImageUrl
imageUrls
}
}
User Benefits
- Complete Object Visibility: See objects that exist only in PostgreSQL
- Debugging Capability: Identify orphaned objects that need cleanup
🎯 Enhanced Fields Update - 2025-07-06 18:20:00
User Request: Frontend needs comprehensive object data for the GraphQL interface including spatial hierarchy, functional relationships, properties, and object class information.
Implementation Completed: Enhanced myObjects query to include all requested fields:
New Fields Added:
- spatialHierarchy: Breadcrumb path from root container to object
- currentPlacement: Current container reference (same as spatialParent)
- normalPlacement: Where object should normally be (SHOULD_BE_IN relationship)
- tags: Array of string tags from Neo4j
- positionalRelationships: Enhanced with distance, unit, confidence, measuredAt properties
- functionalRelationships: All functional predicates (HAS_FUNCTION, USED_FOR, etc.) with direction
- properties: Key-value pairs with automatic dataType detection
- objectClass: Object class schema with property definitions
Technical Details:
- Extended Neo4j query to fetch spatial hierarchy paths using pattern matching
- Added bidirectional functional relationship queries
- Implemented automatic data type detection for properties
- Enhanced positional relationships with measurement metadata
- All fields properly initialized to prevent null reference errors
Frontend Integration:
The myObjects query now returns comprehensive object data suitable for rich UI interactions:
- Spatial navigation with breadcrumb paths
- Relationship visualization with distance/confidence data
- Property editing with type information
- Object class-based validation and UI generation
Status: ✅ Implementation complete and tested
- Deletion Tool Support: Select any object for hard deletion via debug modal
- Data Integrity: Understand dual-database state for maintenance
Implementation Status
- ✅ PostgreSQL-first query implemented
- ✅ Neo4j enrichment for spatial relationships
- ✅ Orphan object detection and marking
- ✅ Image data integration from PostgreSQL
- ✅ Spatial children image enrichment
- ✅ API documentation updated
- 🚧 Testing with known orphaned objects needed
Testing Criteria
- Query returns PostgreSQL objects missing from Neo4j
- Orphaned objects marked with
ORPHANED_POSTGRESQL_ONLYstatus - Neo4j enrichment works for objects in both databases
- Image data properly fetched for all objects
- Performance acceptable for large object sets
🗑️ deleteObject Mutation - Admin Object Deletion
Issue Description
Status: ✅ Production Ready - Full implementation with audit trail and cascade operations
Implemented: 2025-07-05 11:00:00
Updated Documentation: 2025-07-05 21:20:00
Admin-only object deletion feature supporting both hard delete (permanent removal) and soft delete (recoverable marking). Includes comprehensive cascade deletion of images and relationships with full audit trail.
Implementation Summary
- GraphQL Mutation:
deleteObjectwith admin-only access control - Deletion Modes: HARD_DELETE (permanent) and SOFT_DELETE (recoverable)
- Security: Organization admin/owner role required
- Cascade Operations: Images, storage files, Neo4j relationships
- Audit Trail: Complete deletion history with original object snapshot
- CLI Tool: Python script for server-side operations
Integration with myObjects & Debug Modal
The deletion feature is designed to work seamlessly with the enhanced myObjects query:
- Use myObjects to get ALL objects (including PostgreSQL orphans)
- Show objects in debug modal dropdown with orphan indicators
- Allow admin users to select and delete any object
- Refresh myObjects after deletion to update the list
Key Features
- ✅ Two deletion modes (hard/soft)
- ✅ Admin-only access control
- ✅ Cascade deletion of related data
- ✅ Full audit trail logging
- ✅ Support for orphaned objects
- ✅ Integration with debug modal
- ✅ CLI tool for automation
Testing Status
- ✅ Backend implementation complete
- ✅ Security and permissions validated
- ✅ Cascade operations tested
- ✅ Audit trail verified
- ✅ CLI tool functional
- ✅ API documentation updated
API Requirements Last Updated: Mån 7 Jul 2025 10:35:15 CEST - Updated image upload enhancement tracking to reflect production-ready implementation with multiple images, thumbnails, camera, drag-drop, and reordering functionality