feat: Add comprehensive sandbox mode, public API system, and platform support

This commit adds major features for sandbox isolation, public API access, and platform support ticketing.

## Sandbox Mode
- Add sandbox mode toggle for businesses to test features without affecting live data
- Implement schema-based isolation for tenant data (appointments, resources, services)
- Add is_sandbox field filtering for shared models (customers, staff, tickets)
- Create sandbox middleware to detect and set sandbox mode from cookies
- Add sandbox context and hooks for React frontend
- Display sandbox banner when in test mode
- Auto-reload page when switching between live/test modes
- Prevent platform support tickets from being created in sandbox mode

## Public API System
- Full REST API for external integrations with businesses
- API token management with sandbox/live token separation
- Test tokens (ss_test_*) show full plaintext for easy testing
- Live tokens (ss_live_*) are hashed and secure
- Security validation prevents live token plaintext storage
- Comprehensive test suite for token security
- Rate limiting and throttling per token
- Webhook support for real-time event notifications
- Scoped permissions system (read/write per resource type)
- API documentation page with interactive examples
- Token revocation with confirmation modal

## Platform Support
- Dedicated support page for businesses to contact SmoothSchedule
- View all platform support tickets in one place
- Create new support tickets with simplified interface
- Reply to existing tickets with conversation history
- Platform tickets have no admin controls (no priority/category/assignee/status)
- Internal notes hidden for platform tickets (business can't see them)
- Quick help section with links to guides and API docs
- Sandbox warning prevents ticket creation in test mode
- Business ticketing retains full admin controls (priority, assignment, internal notes)

## UI/UX Improvements
- Add notification dropdown with real-time updates
- Staff permissions UI for ticket access control
- Help dropdown in sidebar with Platform Guide, Ticketing Help, API Docs, and Support
- Update sidebar "Contact Support" to "Support" with message icon
- Fix navigation links to use React Router instead of anchor tags
- Remove unused language translations (Japanese, Portuguese, Chinese)

## Technical Details
- Sandbox middleware sets request.sandbox_mode from cookies
- ViewSets filter data by is_sandbox field
- API authentication via custom token auth class
- WebSocket support for real-time ticket updates
- Migration for sandbox fields on User, Tenant, and Ticket models
- Comprehensive documentation in SANDBOX_MODE_IMPLEMENTATION.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
poduck
2025-11-28 16:44:06 -05:00
parent 4acea4f876
commit a9719a5fd2
77 changed files with 11407 additions and 2694 deletions

View File

@@ -0,0 +1,150 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import apiClient from '../api/client';
// Types
export interface APIToken {
id: string;
name: string;
key_prefix: string;
scopes: string[];
is_active: boolean;
is_sandbox: boolean;
created_at: string;
last_used_at: string | null;
expires_at: string | null;
created_by: {
id: number;
username: string;
full_name: string;
} | null;
}
export interface TestTokenForDocs {
id: string;
name: string;
key_prefix: string;
created_at: string;
}
export interface APITokenCreateResponse extends APIToken {
key: string; // Full key, only returned on creation
}
export interface CreateTokenData {
name: string;
scopes: string[];
expires_at?: string | null;
is_sandbox?: boolean;
}
export interface APIScope {
value: string;
label: string;
description: string;
}
// Available scopes
export const API_SCOPES: APIScope[] = [
{ value: 'services:read', label: 'Services (Read)', description: 'View services and pricing' },
{ value: 'resources:read', label: 'Resources (Read)', description: 'View resources and staff' },
{ value: 'availability:read', label: 'Availability (Read)', description: 'Check time slot availability' },
{ value: 'bookings:read', label: 'Bookings (Read)', description: 'View appointments' },
{ value: 'bookings:write', label: 'Bookings (Write)', description: 'Create, update, and cancel appointments' },
{ value: 'customers:read', label: 'Customers (Read)', description: 'View customer information' },
{ value: 'customers:write', label: 'Customers (Write)', description: 'Create and update customers' },
{ value: 'business:read', label: 'Business (Read)', description: 'View business information' },
{ value: 'webhooks:manage', label: 'Webhooks (Manage)', description: 'Manage webhook subscriptions' },
];
// Scope presets for common use cases
export const SCOPE_PRESETS = {
booking_widget: {
label: 'Booking Widget',
description: 'Allow customers to book appointments',
scopes: ['services:read', 'resources:read', 'availability:read', 'bookings:write', 'customers:write'],
},
read_only: {
label: 'Read Only',
description: 'View all data without making changes',
scopes: ['services:read', 'resources:read', 'availability:read', 'bookings:read', 'customers:read', 'business:read'],
},
full_access: {
label: 'Full Access',
description: 'Complete access to all API features',
scopes: API_SCOPES.map(s => s.value),
},
};
// API Functions
const fetchApiTokens = async (): Promise<APIToken[]> => {
const response = await apiClient.get('/api/v1/tokens/');
return response.data;
};
const createApiToken = async (data: CreateTokenData): Promise<APITokenCreateResponse> => {
const response = await apiClient.post('/api/v1/tokens/', data);
return response.data;
};
const revokeApiToken = async (tokenId: string): Promise<void> => {
await apiClient.delete(`/api/v1/tokens/${tokenId}/`);
};
const updateApiToken = async ({ tokenId, data }: { tokenId: string; data: Partial<CreateTokenData> & { is_active?: boolean } }): Promise<APIToken> => {
const response = await apiClient.patch(`/api/v1/tokens/${tokenId}/`, data);
return response.data;
};
const fetchTestTokensForDocs = async (): Promise<TestTokenForDocs[]> => {
const response = await apiClient.get('/api/v1/tokens/test-tokens/');
return response.data;
};
// Hooks
export const useApiTokens = () => {
return useQuery({
queryKey: ['apiTokens'],
queryFn: fetchApiTokens,
});
};
export const useCreateApiToken = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: createApiToken,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['apiTokens'] });
},
});
};
export const useRevokeApiToken = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: revokeApiToken,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['apiTokens'] });
},
});
};
export const useUpdateApiToken = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: updateApiToken,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['apiTokens'] });
},
});
};
export const useTestTokensForDocs = () => {
return useQuery({
queryKey: ['testTokensForDocs'],
queryFn: fetchTestTokensForDocs,
staleTime: 1000 * 60 * 5, // Cache for 5 minutes
});
};

View File

@@ -0,0 +1,76 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
getNotifications,
getUnreadCount,
markNotificationRead,
markAllNotificationsRead,
clearAllNotifications,
Notification,
} from '../api/notifications';
/**
* Hook to fetch all notifications
*/
export const useNotifications = (options?: { read?: boolean; limit?: number }) => {
return useQuery<Notification[]>({
queryKey: ['notifications', options],
queryFn: () => getNotifications(options),
staleTime: 30000, // 30 seconds
});
};
/**
* Hook to fetch unread notification count
*/
export const useUnreadNotificationCount = () => {
return useQuery<number>({
queryKey: ['notificationsUnreadCount'],
queryFn: getUnreadCount,
staleTime: 30000, // 30 seconds
refetchInterval: 60000, // Refetch every minute
});
};
/**
* Hook to mark a notification as read
*/
export const useMarkNotificationRead = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: markNotificationRead,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['notifications'] });
queryClient.invalidateQueries({ queryKey: ['notificationsUnreadCount'] });
},
});
};
/**
* Hook to mark all notifications as read
*/
export const useMarkAllNotificationsRead = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: markAllNotificationsRead,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['notifications'] });
queryClient.invalidateQueries({ queryKey: ['notificationsUnreadCount'] });
},
});
};
/**
* Hook to clear all read notifications
*/
export const useClearAllNotifications = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: clearAllNotifications,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['notifications'] });
},
});
};

View File

@@ -0,0 +1,62 @@
/**
* React Query hooks for sandbox mode management
*/
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getSandboxStatus, toggleSandboxMode, resetSandboxData, SandboxStatus } from '../api/sandbox';
/**
* Hook to fetch current sandbox status
*/
export const useSandboxStatus = () => {
return useQuery<SandboxStatus, Error>({
queryKey: ['sandboxStatus'],
queryFn: getSandboxStatus,
staleTime: 30 * 1000, // 30 seconds
refetchOnWindowFocus: true,
});
};
/**
* Hook to toggle sandbox mode
*/
export const useToggleSandbox = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: toggleSandboxMode,
onSuccess: (data) => {
// Update the sandbox status in cache
queryClient.setQueryData(['sandboxStatus'], (old: SandboxStatus | undefined) => ({
...old,
sandbox_mode: data.sandbox_mode,
}));
// Reload the page to ensure all components properly reflect the new mode
// This is necessary because:
// 1. Backend switches database schemas between live/sandbox
// 2. Some UI elements need to reflect the new mode (e.g., warnings, disabled features)
// 3. Prevents stale data from old mode appearing briefly
window.location.reload();
},
});
};
/**
* Hook to reset sandbox data
*/
export const useResetSandbox = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: resetSandboxData,
onSuccess: () => {
// Invalidate all data queries after reset
queryClient.invalidateQueries({ queryKey: ['resources'] });
queryClient.invalidateQueries({ queryKey: ['events'] });
queryClient.invalidateQueries({ queryKey: ['services'] });
queryClient.invalidateQueries({ queryKey: ['customers'] });
queryClient.invalidateQueries({ queryKey: ['payments'] });
},
});
};

View File

@@ -5,16 +5,12 @@ import { User } from '../types';
interface StaffUser {
id: number | string;
email: string;
first_name: string;
last_name: string;
full_name: string;
name: string; // This is the full_name from the serializer
username?: string;
role: string;
role_display: string;
is_active: boolean;
permissions: Record<string, boolean>;
has_resource: boolean;
resource_id?: string;
resource_name?: string;
can_invite_staff?: boolean;
}
/**
@@ -42,9 +38,9 @@ export const useStaffForAssignment = () => {
const response = await apiClient.get('/api/staff/');
return response.data.map((user: StaffUser) => ({
id: String(user.id),
name: user.full_name || `${user.first_name} ${user.last_name}`.trim() || user.email,
name: user.name || user.email, // 'name' field from serializer (full_name)
email: user.email,
role: user.role_display || user.role,
role: user.role,
}));
},
});