# Google Chat Space Creation API - Simple Documentation

## Overview

This API provides programmatic access to create Google Chat spaces. It accepts the exact same data structure as the web form interface, making it easy to integrate with existing workflows.

## Endpoint

**URL:** `https://your-domain.com/ai/google-chat/php-tools/onboarding-spaces/api.php`  
**Method:** `POST`  
**Content-Type:** `application/json`  
**Authentication:** None (internal API)

## Request Structure

The API accepts a JSON payload with the following structure:

```json
{
  "clientName": "ACME Corporation",
  "location": "Sydney",
  "jobNumber": "12345",
  "spaces": [
    {
      "prefix": "A",
      "name": "A: ACME Corporation - Sydney (12345)",
      "members": [
        "user1@example.com",
        "user2@example.com",
        "user3@example.com"
      ],
      "managers": [
        "user1@example.com"
      ],
      "welcomeMessage": "Welcome to the ACME Corporation project space!"
    }
  ]
}
```

### Field Descriptions

- **clientName** (required): The name of the client
- **location** (required): The client's location
- **jobNumber** (required): The job/project number
- **spaces** (required): Array of spaces to create
  - **prefix**: The space prefix (e.g., "A", "S", "IT", "V")
  - **name**: Full name of the space (usually includes client, location, and job number)
  - **members**: Array of email addresses for space members
  - **managers**: Array of email addresses for space managers (must also be in members array)
  - **welcomeMessage** (optional): Custom welcome message for this space

## Response Format

The API returns a streaming JSON response with real-time progress updates:

```json
{"status":"info","message":"Initializing Google Chat API...","progress":0}
{"status":"info","message":"Creating 2 spaces...","progress":5}
{"status":"success","message":"Created space: A: ACME Corporation - Sydney (12345)","progress":35}
{"status":"info","message":"Adding members to A: ACME Corporation - Sydney (12345)..."}
{"status":"success","message":"Added 3 members to A: ACME Corporation - Sydney (12345) (1 as managers)","progress":50}
{"status":"info","message":"All operations completed!","progress":100,"completed":true,"summary":{"requested":2,"created":2,"failed":0}}
```

### Response Fields

- **status**: "info", "success", or "error"
- **message**: Human-readable status message
- **progress**: Percentage complete (0-100)
- **completed**: Boolean indicating if all operations are done
- **summary**: Final summary with counts

## Error Handling

### Error Response Format

```json
{
  "success": false,
  "error": "Error message",
  "code": "ERROR_CODE"
}
```

### Common Error Codes

- `METHOD_NOT_ALLOWED`: Request method is not POST
- `INVALID_JSON`: Request body is not valid JSON
- `MISSING_FIELD`: Required field is missing
- `NO_SPACES`: No spaces array provided or it's empty
- `INVALID_SPACE`: Space data is malformed
- `CONFIG_NOT_FOUND`: Server configuration issue
- `CONFIG_INVALID`: Server configuration is invalid

## Example Usage

### cURL

```bash
curl -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "clientName": "ACME Corporation",
    "location": "Sydney",
    "jobNumber": "12345",
    "spaces": [
      {
        "prefix": "A",
        "name": "A: ACME Corporation - Sydney (12345)",
        "members": ["john@company.com", "jane@company.com"],
        "managers": ["john@company.com"]
      },
      {
        "prefix": "S",
        "name": "S: ACME Corporation - Sydney (12345)",
        "members": ["jane@company.com", "bob@company.com"],
        "managers": ["jane@company.com"]
      }
    ]
  }' \
  https://your-domain.com/api.php
```

### JavaScript (Fetch API)

```javascript
async function createSpaces(clientData) {
  const response = await fetch('https://your-domain.com/api.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(clientData)
  });

  // Handle streaming response
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    
    const chunk = decoder.decode(value);
    const lines = chunk.split('\n').filter(line => line.trim());
    
    for (const line of lines) {
      const update = JSON.parse(line);
      console.log(`[${update.status}] ${update.message}`);
      
      if (update.progress !== undefined) {
        console.log(`Progress: ${update.progress}%`);
      }
    }
  }
}

// Example usage
await createSpaces({
  clientName: "ACME Corporation",
  location: "Sydney",
  jobNumber: "12345",
  spaces: [
    {
      prefix: "A",
      name: "A: ACME Corporation - Sydney (12345)",
      members: ["john@company.com", "jane@company.com"],
      managers: ["john@company.com"]
    }
  ]
});
```

### Python

```python
import requests
import json

def create_spaces(client_data):
    response = requests.post(
        'https://your-domain.com/api.php',
        headers={'Content-Type': 'application/json'},
        json=client_data,
        stream=True
    )
    
    for line in response.iter_lines():
        if line:
            update = json.loads(line)
            print(f"[{update['status']}] {update['message']}")
            
            if 'progress' in update:
                print(f"Progress: {update['progress']}%")

# Example usage
create_spaces({
    'clientName': 'ACME Corporation',
    'location': 'Sydney',
    'jobNumber': '12345',
    'spaces': [
        {
            'prefix': 'A',
            'name': 'A: ACME Corporation - Sydney (12345)',
            'members': ['john@company.com', 'jane@company.com'],
            'managers': ['john@company.com']
        }
    ]
})
```

## Common Scenarios

### 1. Single Space with One Manager

```json
{
  "clientName": "Small Corp",
  "location": "Melbourne",
  "jobNumber": "9999",
  "spaces": [
    {
      "prefix": "A",
      "name": "A: Small Corp - Melbourne (9999)",
      "members": ["manager@company.com"],
      "managers": ["manager@company.com"]
    }
  ]
}
```

### 2. Multiple Spaces with Different Teams

```json
{
  "clientName": "Big Enterprise",
  "location": "Brisbane",
  "jobNumber": "5555",
  "spaces": [
    {
      "prefix": "A",
      "name": "A: Big Enterprise - Brisbane (5555)",
      "members": ["admin@company.com", "user1@company.com", "user2@company.com"],
      "managers": ["admin@company.com"]
    },
    {
      "prefix": "IT",
      "name": "IT: Big Enterprise - Brisbane (5555)",
      "members": ["it@company.com", "admin@company.com"],
      "managers": ["it@company.com", "admin@company.com"]
    }
  ]
}
```

### 3. Custom Space Prefix

```json
{
  "clientName": "Special Client",
  "location": "Perth",
  "jobNumber": "7777",
  "spaces": [
    {
      "prefix": "CUSTOM",
      "name": "CUSTOM: Special Client - Perth (7777)",
      "members": ["team@company.com"],
      "managers": ["team@company.com"]
    }
  ]
}
```

## Notes

- Managers must also be listed in the members array
- The space creator (configured in the system) is automatically added as a manager
- Space names should follow the pattern: `{prefix}: {client} - {location} ({jobNumber})`
- All email addresses must be valid Google Workspace users
- The API will continue processing even if some spaces fail to create
- Progress updates are sent in real-time as operations complete

## For AI Assistants

This section is optimized for AI assistants (like Claude Code) to understand and use the TLC Onboarding Spaces API.

### Request Schema (TypeScript)

```typescript
interface SpaceCreationRequest {
  clientName: string;    // Required: Client/company name
  location: string;      // Required: Client location
  jobNumber: string;     // Required: Job/project identifier
  spaces: Space[];       // Required: Array of spaces to create (min 1)
}

interface Space {
  prefix: string;        // Space type identifier (e.g., "A", "S", "IT", "V")
  name: string;          // Full space name (format: "{prefix}: {client} - {location} ({jobNumber})")
  members: string[];     // Email addresses of space members
  managers: string[];    // Email addresses of space managers (subset of members)
  welcomeMessage?: string; // Optional custom welcome message for this space
}
```

### AI-Specific Usage Notes

1. **Space Name Format**: Always follow the pattern "{prefix}: {client} - {location} ({jobNumber})"
2. **Manager Validation**: All managers must also be included in the members array
3. **Error Handling**: Parse streaming JSON responses line by line
4. **Progress Tracking**: Monitor the 'progress' field (0-100) in status updates
5. **Completion**: Check for 'completed': true in the final status update

### Example for AI Code Generation

When generating code to use this API:

```javascript
// Build request matching web form data
const request = {
  clientName: userInput.clientName,
  location: userInput.location,
  jobNumber: userInput.jobNumber,
  spaces: selectedSpaces.map(space => ({
    prefix: space.prefix,
    name: `${space.prefix}: ${userInput.clientName} - ${userInput.location} (${userInput.jobNumber})`,
    members: space.selectedMembers,
    managers: space.selectedMembers.filter(m => space.managers.includes(m))
  }))
};

// Process streaming response
const response = await fetch(apiUrl, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(request)
});

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  
  const lines = decoder.decode(value).split('\n').filter(Boolean);
  for (const line of lines) {
    const status = JSON.parse(line);
    // Handle status update
  }
}
```