Files
tilbudgivern/archive/docs/TODO_MIGRATE_TO_GRAPHQL_API.md
2026-08-13 14:29:15 +02:00

14 KiB

TODO: Migrate from v2 API to GraphQL API

Status: 🔴 Not Started
Priority: HIGH
Estimated Effort: 2-3 weeks
Last Updated: October 23, 2025

Overview

Currently, the tilbudsgiveren application uses the v2 REST API for Ordrestyring integration. We need to migrate all API calls to the new GraphQL API at https://graphql.ordrestyring.dk/graphql.

Benefits of Migration

Single endpoint - No more managing multiple REST endpoints
Efficient data fetching - Request only the fields you need
Type safety - GraphQL schema provides strong typing
Better error handling - Structured error responses
Reduced over/under-fetching - Get exactly what you need
Real-time capabilities - GraphQL subscriptions for live updates
Better documentation - Self-documenting API via introspection

Current State

API Scripts Available

Located in /home/w34078/scripts/apitest/:

  • 255 Query Scripts (read-only operations) - Safe to integrate immediately
  • 311 Mutation Scripts (write operations) - ⚠️ Requires careful integration
  • 144 Output Examples - Real API responses for testing
  • 565/566 Endpoints documented (99.8% coverage)

Documentation

  • API_INTEGRATION_GUIDE.md - Complete integration guide
  • BATCH_*_SUMMARY.md - Batch documentation files
  • All scripts have --help documentation

Migration Plan

Phase 1: Setup & Infrastructure (Week 1)

1.1 Backend Setup

  • Install GraphQL client library (graphql-request or apollo-client)
  • Create GraphQL client wrapper in backend/src/graphql/client.js
  • Set up authentication with API key from environment variables
  • Create error handling middleware for GraphQL responses

Example:

// backend/src/graphql/client.js
const { GraphQLClient } = require('graphql-request');

const client = new GraphQLClient('https://graphql.ordrestyring.dk/graphql', {
  headers: {
    authorization: `Bearer ${process.env.ORDRESTYRING_API_KEY}`,
  },
});

module.exports = client;

1.2 Environment Configuration

  • Add ORDRESTYRING_API_KEY to .env file
  • Add GRAPHQL_ENDPOINT to .env file
  • Update deployment scripts to include new env vars
  • Document API key rotation procedure

Files to update:

  • .env
  • .env.example
  • README.md
  • Deployment scripts

Phase 2: Query Migration (Week 1-2)

Migrate all read-only queries first - these are safe to integrate immediately.

2.1 Core Business Queries (High Priority)

Cases API
  • Migrate GET /api/cases → GraphQL cases query
  • Migrate GET /api/cases/:id → GraphQL case(id: $id) query
  • Migrate case activities, statuses, types, templates queries
  • Update React components to use new endpoints

Current: /api/customer-projects/
New: GraphQL queries from curl_cases.sh, curl_case_activities.sh, etc.

Files to update:

  • backend/routes/customerProjects.js
  • frontend/src/api/customerProjectsAPI.js
  • frontend/src/components/ProjectList.jsx
  • frontend/src/components/ProjectDetails.jsx
Customers API
  • Migrate GET /api/customers → GraphQL customers query
  • Migrate GET /api/customers/:id → GraphQL customer(id: $id) query
  • Migrate contact persons, categories queries
  • Update customer selection components

Files to update:

  • backend/routes/customers.js (if exists)
  • frontend/src/api/customersAPI.js
  • Customer selection components
Offers API
  • Migrate offers queries
  • Migrate offer lines, statuses, types queries
  • Update quote/offer components
Products API
  • Migrate products queries
  • Migrate materials, suppliers queries
  • Update material selection components

2.2 Supporting Queries (Medium Priority)

  • Invoices (sales, creditor, drafts)
  • Finance agreements and contracts
  • Services and installations
  • Hours and time tracking
  • Documentation and files

2.3 Configuration Queries (Low Priority)

  • Settings and preferences
  • VAT types, payment terms
  • Discount groups, hour types
  • User and department data

Phase 3: Safe Mutations (Week 2)

Integrate safe mutations that don't modify critical data:

  • markMessageAsRead - Mark notifications as read (idempotent)
  • setNamedPreference - User preferences (safe)
  • sendCaseViaEmail - Send notifications (with confirmation)
  • sendOfferViaEmail - Send offers (with confirmation)
  • approveScheme - Approve schemes (with validation)

Safety measures:

  • All operations are idempotent or have user confirmation
  • No data deletion or modification of critical records
  • Easy rollback if needed

Files to update:

  • Backend mutation services
  • Frontend action handlers
  • Add confirmation dialogs for email sends

Phase 4: Update Mutations (Week 3)

⚠️ REQUIRES TEST ENVIRONMENT FIRST

Integrate update mutations with proper validation:

4.1 Test Environment Setup

  • Create test database snapshot
  • Set up staging environment with test GraphQL endpoint
  • Implement rollback procedures
  • Create audit logging for all mutations

4.2 Core Update Mutations

  • updateCase - Update case details
  • updateCustomer - Update customer information
  • updateOffer - Update offer details
  • updateProduct - Update product information
  • updateInvoice - Update invoice data

Safety requirements:

  • Input validation on backend
  • User authentication/authorization
  • Audit trail of all changes
  • Rollback capability
  • Test in staging before production

Phase 5: Create/Delete Operations (Week 4+)

🔴 HIGH RISK - IMPLEMENT LAST

Critical requirements before implementation:

  1. Test environment mandatory
  2. Rollback procedures documented and tested
  3. User confirmation dialogs for all operations
  4. Audit logging with user tracking
  5. Database backup before execution
  6. Soft delete implementation (mark as deleted, don't remove)

5.1 Create Mutations

  • createCase - Create new cases
  • createCustomer - Create new customers
  • createOffer - Create new offers
  • createProduct - Create new products
  • createInvoice - Create new invoices

5.2 Delete Mutations (LAST)

  • Implement soft delete strategy
  • deleteCasearchiveCase (soft delete)
  • deleteCustomeranonymizeCustomer (GDPR compliant)
  • Add restore functionality
  • Add bulk operations with careful validation

Code Examples

GraphQL Query Integration

Before (REST API):

// frontend/src/api/customerProjectsAPI.js
export const getProjects = async (page = 1, limit = 20) => {
  const response = await fetch(`/api/customer-projects?page=${page}&limit=${limit}`);
  return response.json();
};

After (GraphQL):

// frontend/src/api/customerProjectsAPI.js
import { request } from '../utils/graphqlClient';

export const getProjects = async (page = 1, limit = 20) => {
  const query = `
    query GetCases($pagination: Pagination) {
      cases(pagination: $pagination) {
        items {
          id
          caseNumber
          customer { id name }
          status { id name }
          createdAt
        }
        totalCount
      }
    }
  `;
  
  const data = await request(query, { 
    pagination: { page, limit } 
  });
  
  return data.cases;
};

GraphQL Mutation Integration

Before (REST API):

export const updateProject = async (projectId, projectData) => {
  const response = await fetch(`/api/customer-projects/${projectId}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(projectData)
  });
  return response.json();
};

After (GraphQL):

export const updateProject = async (caseId, caseInput) => {
  const mutation = `
    mutation UpdateCase($id: Int!, $input: CaseInput!) {
      updateCase(id: $id, input: $input) {
        id
        caseNumber
        updatedAt
      }
    }
  `;
  
  const data = await request(mutation, { 
    id: parseInt(caseId), 
    input: caseInput 
  });
  
  return data.updateCase;
};

Files That Need Migration

Backend Files

  • backend/routes/customerProjects.js - All case/project endpoints
  • backend/routes/customers.js - Customer endpoints (if exists)
  • backend/routes/offers.js - Offer endpoints (if exists)
  • backend/routes/products.js - Product endpoints (if exists)
  • backend/services/*Service.js - All service files that call v2 API

Frontend Files

  • frontend/src/api/customerProjectsAPI.js
  • frontend/src/api/customersAPI.js
  • frontend/src/api/offersAPI.js
  • frontend/src/api/productsAPI.js
  • All components that directly call API functions

Configuration Files

  • .env - Add GraphQL endpoint and API key
  • .env.example - Document required env vars
  • README.md - Update API documentation
  • Deployment scripts - Include new env vars

Testing Strategy

1. Query Testing (Safe)

All 255 queries already tested in production
144 output files available as test fixtures
Can integrate immediately

Test approach:

  1. Create test suite using output files as expected results
  2. Run GraphQL queries and compare with v2 API responses
  3. Validate data structure matches frontend expectations
  4. Check pagination, filtering, sorting

2. Mutation Testing (Requires Staging)

Test environment setup:

  1. Clone production database to staging
  2. Point staging app to test GraphQL endpoint
  3. Test all mutations with dummy data
  4. Validate rollback procedures

Test checklist:

  • Test create operations
  • Test update operations
  • Test delete operations (soft delete)
  • Test bulk operations
  • Test error handling
  • Test validation
  • Test rollback procedures

3. Integration Testing

  • Test complete user workflows (create → update → delete)
  • Test concurrent operations
  • Test error scenarios (network failures, timeouts)
  • Test authentication failures
  • Test rate limiting
  • Performance testing (compare with v2 API)

Rollback Plan

If migration fails or introduces bugs:

  1. Immediate Rollback (< 5 minutes)

    • Keep v2 API endpoints active during migration
    • Use feature flags to toggle between v2/GraphQL
    • Can switch back via environment variable
  2. Gradual Migration

    • Migrate one feature at a time
    • Keep both APIs running in parallel
    • Monitor error rates and performance
    • Roll back individual features if needed
  3. Data Rollback

    • Database snapshots before write operations
    • Audit log for all mutations
    • Restore procedures documented and tested

Performance Considerations

Optimization Strategies

  • Use pagination for large datasets (default: 20 items per page)
  • Implement caching for frequently accessed data
  • Use GraphQL field selection (only request needed fields)
  • Batch operations where possible (bulkUpdate* mutations)
  • Monitor API rate limits and implement throttling

Monitoring

  • Track API response times
  • Monitor error rates
  • Alert on rate limit approaches
  • Log slow queries (> 1 second)

Security Checklist

  • API key stored in environment variables (never in code)
  • Backend validates all user input
  • HTTPS only for API communication
  • Implement user authentication/authorization
  • Rate limiting on backend
  • Audit logging for mutations
  • User confirmation for dangerous operations
  • SQL injection prevention (parameterized queries)
  • XSS prevention (input sanitization)

Resources

Documentation

  • Main Guide: apitest/API_INTEGRATION_GUIDE.md
  • Scripts Location: /home/w34078/scripts/apitest/examples/
  • Output Examples: /home/w34078/scripts/apitest/examples/output/
  • GraphQL Endpoint: https://graphql.ordrestyring.dk/graphql
  • API Key: Stored in environment variables

Available Scripts by Category

Safe Queries (255 scripts)

  • curl_cases.sh, curl_customers.sh, curl_offers.sh, curl_products.sh
  • curl_invoices.sh, curl_users.sh, curl_departments.sh
  • See API_INTEGRATION_GUIDE.md for complete list

Safe Mutations (24 scripts)

  • mutation_mark_message_as_read.sh
  • mutation_set_named_preference.sh
  • mutation_send_*_via_email.sh (7 scripts)
  • mutation_approve_scheme.sh

Update Mutations (78 scripts)

  • mutation_update_case.sh
  • mutation_update_customer.sh
  • mutation_update_offer.sh
  • See BATCHES_14_15_SUMMARY.md

Create/Delete Mutations (208 scripts)

  • mutation_create_*.sh (75 scripts)
  • mutation_delete_*.sh (59 scripts)
  • See BATCHES_16_22_SUMMARY.md

Progress Tracking

Week 1

  • Backend GraphQL client setup
  • Environment configuration
  • Core business queries migration (cases, customers)
  • Test query integration

Week 2

  • Remaining query migrations (offers, products, invoices)
  • Configuration queries migration
  • Safe mutations integration
  • Frontend component updates

Week 3

  • Test environment setup
  • Update mutations integration
  • Validation and error handling
  • Audit logging implementation

Week 4+

  • Create mutations (with caution)
  • Soft delete implementation
  • Final testing and validation
  • Production deployment
  • Monitor and optimize

Success Criteria

All query endpoints migrated to GraphQL
Zero data loss during migration
Performance equal or better than v2 API
Error rates < 0.1%
All mutations properly validated
Audit logging in place
Rollback procedures tested
Documentation updated
Team trained on new API

Notes

  • Current API key: <ORDRESTYRING_API_TOKEN> (rotate after migration)
  • GraphQL endpoint: https://graphql.ordrestyring.dk/graphql
  • 565/566 endpoints available (99.8% coverage)
  • All scripts have --help documentation
  • 144 output examples available for testing

Next Steps

  1. Review this TODO with team
  2. Prioritize which endpoints to migrate first
  3. Set up GraphQL client in backend
  4. Start with safe query migrations
  5. Test thoroughly before production
  6. Monitor closely after deployment

Created: October 23, 2025
Last Updated: October 23, 2025
Assigned To: Development Team
Dependencies: API_INTEGRATION_GUIDE.md, apitest scripts
Related: ORDRESTYRING_DATABASE_SYSTEM.md