chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:20:55 +08:00
commit d25d482dc2
13754 changed files with 4996608 additions and 0 deletions
@@ -0,0 +1,650 @@
/**
* Tests for schedule reactivate PUT API route
*
* @vitest-environment node
*/
import {
auditMock,
authMockFns,
databaseMock,
workflowAuthzMockFns,
workflowsUtilsMock,
} from '@sim/testing'
import { NextRequest } from 'next/server'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('@/lib/workflows/utils', () => workflowsUtilsMock)
vi.mock('drizzle-orm', () => ({
and: vi.fn(),
eq: vi.fn(),
isNull: vi.fn(),
}))
vi.mock('@sim/audit', () => auditMock)
import { PUT } from './route'
function createRequest(body: Record<string, unknown>): NextRequest {
return new NextRequest(new URL('http://test/api/schedules/sched-1'), {
method: 'PUT',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
}
function createParams(id: string): { params: Promise<{ id: string }> } {
return { params: Promise.resolve({ id }) }
}
const mockDbSelect = databaseMock.db.select as ReturnType<typeof vi.fn>
const mockDbUpdate = databaseMock.db.update as ReturnType<typeof vi.fn>
function mockDbChain(selectResults: unknown[][]) {
let selectCallIndex = 0
mockDbSelect.mockImplementation(() => ({
from: () => ({
where: () => ({
limit: () => selectResults[selectCallIndex++] || [],
}),
}),
}))
mockDbUpdate.mockImplementation(() => ({
set: () => ({
where: vi.fn().mockResolvedValue({}),
}),
}))
}
describe('Schedule PUT API (Reactivate)', () => {
beforeEach(() => {
vi.clearAllMocks()
authMockFns.mockGetSession.mockResolvedValue({ user: { id: 'user-1' } })
workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({
allowed: true,
status: 200,
workflow: { id: 'wf-1', workspaceId: 'ws-1' },
workspacePermission: 'write',
})
})
afterEach(() => {
vi.clearAllMocks()
})
describe('Authentication', () => {
it('returns 401 when user is not authenticated', async () => {
authMockFns.mockGetSession.mockResolvedValue(null)
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(401)
const data = await res.json()
expect(data.error).toBe('Unauthorized')
})
})
describe('Request Validation', () => {
it('returns 400 when action is not a valid enum value', async () => {
mockDbChain([
[{ id: 'sched-1', workflowId: 'wf-1', status: 'disabled' }],
[{ userId: 'user-1', workspaceId: null }],
])
const res = await PUT(createRequest({ action: 'invalid-action' }), createParams('sched-1'))
expect(res.status).toBe(400)
const data = await res.json()
expect(data.error).toBe('Invalid request body')
})
it('returns 400 when action is missing', async () => {
mockDbChain([
[{ id: 'sched-1', workflowId: 'wf-1', status: 'disabled' }],
[{ userId: 'user-1', workspaceId: null }],
])
const res = await PUT(createRequest({}), createParams('sched-1'))
expect(res.status).toBe(400)
const data = await res.json()
expect(data.error).toBe('Invalid request body')
})
})
describe('Schedule Not Found', () => {
it('returns 404 when schedule does not exist', async () => {
mockDbChain([[]])
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-999'))
expect(res.status).toBe(404)
const data = await res.json()
expect(data.error).toBe('Schedule not found')
})
it('returns 404 when workflow does not exist for schedule', async () => {
workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({
allowed: false,
status: 404,
workflow: null,
workspacePermission: null,
message: 'Workflow not found',
})
mockDbChain([[{ id: 'sched-1', workflowId: 'wf-1', status: 'disabled' }], []])
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(404)
const data = await res.json()
expect(data.error).toBe('Workflow not found')
})
})
describe('Authorization', () => {
it('returns 403 when user is not workflow owner', async () => {
workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({
allowed: false,
status: 403,
workflow: { id: 'wf-1', workspaceId: null },
workspacePermission: null,
message:
'This workflow is not attached to a workspace. Personal workflows are deprecated and cannot be accessed.',
})
mockDbChain([
[{ id: 'sched-1', workflowId: 'wf-1', status: 'disabled' }],
[{ userId: 'other-user', workspaceId: null }],
])
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(403)
const data = await res.json()
expect(data.error).toContain('Personal workflows are deprecated')
})
it('returns 403 for workspace member with only read permission', async () => {
workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({
allowed: false,
status: 403,
workflow: { id: 'wf-1', workspaceId: 'ws-1' },
workspacePermission: 'read',
message: 'Unauthorized: Access denied to write this workflow',
})
mockDbChain([
[{ id: 'sched-1', workflowId: 'wf-1', status: 'disabled' }],
[{ userId: 'other-user', workspaceId: 'ws-1' }],
])
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(403)
})
it('allows workflow owner to reactivate', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '*/5 * * * *',
timezone: 'UTC',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
const data = await res.json()
expect(data.message).toBe('Schedule activated successfully')
})
it('allows workspace member with write permission to reactivate', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '*/5 * * * *',
timezone: 'UTC',
},
],
[{ userId: 'other-user', workspaceId: 'ws-1' }],
])
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
})
it('allows workspace admin to reactivate', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '*/5 * * * *',
timezone: 'UTC',
},
],
[{ userId: 'other-user', workspaceId: 'ws-1' }],
])
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
})
})
describe('Schedule State Handling', () => {
it('returns success message when schedule is already active', async () => {
mockDbChain([
[{ id: 'sched-1', workflowId: 'wf-1', status: 'active' }],
[{ userId: 'user-1', workspaceId: null }],
])
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
const data = await res.json()
expect(data.message).toBe('Schedule is already active')
expect(mockDbUpdate).not.toHaveBeenCalled()
})
it('successfully reactivates disabled schedule', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '*/5 * * * *',
timezone: 'UTC',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
const data = await res.json()
expect(data.message).toBe('Schedule activated successfully')
expect(data.nextRunAt).toBeDefined()
expect(mockDbUpdate).toHaveBeenCalled()
})
it('returns 400 when schedule has no cron expression', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: null,
timezone: 'UTC',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(400)
const data = await res.json()
expect(data.error).toBe('Schedule has no cron expression')
})
it('returns 400 when schedule has invalid cron expression', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: 'invalid-cron',
timezone: 'UTC',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(400)
const data = await res.json()
expect(data.error).toBe('Schedule has invalid cron expression')
})
it('calculates nextRunAt from stored cron expression (every 5 minutes)', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '*/5 * * * *',
timezone: 'UTC',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const beforeCall = Date.now()
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
const afterCall = Date.now()
expect(res.status).toBe(200)
const data = await res.json()
const nextRunAt = new Date(data.nextRunAt).getTime()
// nextRunAt should be within 0-5 minutes in the future
expect(nextRunAt).toBeGreaterThan(beforeCall)
expect(nextRunAt).toBeLessThanOrEqual(afterCall + 5 * 60 * 1000 + 1000)
// Should align with 5-minute intervals (minute divisible by 5)
expect(new Date(nextRunAt).getUTCMinutes() % 5).toBe(0)
})
it('calculates nextRunAt from daily cron expression', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '30 14 * * *', // 2:30 PM daily
timezone: 'UTC',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const beforeCall = Date.now()
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
const data = await res.json()
const nextRunAt = new Date(data.nextRunAt)
// Should be a future date at 14:30 UTC
expect(nextRunAt.getTime()).toBeGreaterThan(beforeCall)
expect(nextRunAt.getUTCHours()).toBe(14)
expect(nextRunAt.getUTCMinutes()).toBe(30)
expect(nextRunAt.getUTCSeconds()).toBe(0)
})
it('calculates nextRunAt from weekly cron expression', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '0 9 * * 1', // Monday at 9:00 AM
timezone: 'UTC',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const beforeCall = Date.now()
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
const data = await res.json()
const nextRunAt = new Date(data.nextRunAt)
// Should be a future date on Monday at 09:00 UTC
expect(nextRunAt.getTime()).toBeGreaterThan(beforeCall)
expect(nextRunAt.getUTCDay()).toBe(1) // Monday
expect(nextRunAt.getUTCHours()).toBe(9)
expect(nextRunAt.getUTCMinutes()).toBe(0)
})
it('calculates nextRunAt from monthly cron expression', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '0 10 15 * *', // 15th of month at 10:00 AM
timezone: 'UTC',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const beforeCall = Date.now()
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
const data = await res.json()
const nextRunAt = new Date(data.nextRunAt)
// Should be a future date on the 15th at 10:00 UTC
expect(nextRunAt.getTime()).toBeGreaterThan(beforeCall)
expect(nextRunAt.getUTCDate()).toBe(15)
expect(nextRunAt.getUTCHours()).toBe(10)
expect(nextRunAt.getUTCMinutes()).toBe(0)
})
})
describe('Timezone Handling in Reactivation', () => {
it('calculates nextRunAt with America/New_York timezone', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '0 9 * * *', // 9:00 AM Eastern
timezone: 'America/New_York',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const beforeCall = Date.now()
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
const data = await res.json()
const nextRunAt = new Date(data.nextRunAt)
// Should be a future date
expect(nextRunAt.getTime()).toBeGreaterThan(beforeCall)
// The exact UTC hour will depend on DST, but it should be 13:00 or 14:00 UTC
const utcHour = nextRunAt.getUTCHours()
expect([13, 14]).toContain(utcHour) // 9 AM ET = 1-2 PM UTC depending on DST
expect(nextRunAt.getUTCMinutes()).toBe(0)
})
it('calculates nextRunAt with Asia/Tokyo timezone', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '30 15 * * *', // 3:30 PM Japan Time
timezone: 'Asia/Tokyo',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const beforeCall = Date.now()
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
const data = await res.json()
const nextRunAt = new Date(data.nextRunAt)
// Should be a future date
expect(nextRunAt.getTime()).toBeGreaterThan(beforeCall)
// 3:30 PM JST (UTC+9) = 6:30 AM UTC
expect(nextRunAt.getUTCHours()).toBe(6)
expect(nextRunAt.getUTCMinutes()).toBe(30)
})
it('calculates nextRunAt with Europe/London timezone', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '0 12 * * 5', // Friday at noon London time
timezone: 'Europe/London',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const beforeCall = Date.now()
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
const data = await res.json()
const nextRunAt = new Date(data.nextRunAt)
// Should be a future date on Friday
expect(nextRunAt.getTime()).toBeGreaterThan(beforeCall)
expect(nextRunAt.getUTCDay()).toBe(5) // Friday
// UTC hour depends on BST/GMT (11:00 or 12:00 UTC)
const utcHour = nextRunAt.getUTCHours()
expect([11, 12]).toContain(utcHour)
expect(nextRunAt.getUTCMinutes()).toBe(0)
})
it('uses UTC as default timezone when timezone is not set', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '0 10 * * *', // 10:00 AM
timezone: null,
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const beforeCall = Date.now()
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
const data = await res.json()
const nextRunAt = new Date(data.nextRunAt)
// Should be a future date at 10:00 UTC
expect(nextRunAt.getTime()).toBeGreaterThan(beforeCall)
expect(nextRunAt.getUTCHours()).toBe(10)
expect(nextRunAt.getUTCMinutes()).toBe(0)
})
it('handles minutely schedules with timezone correctly', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '*/10 * * * *', // Every 10 minutes
timezone: 'America/Los_Angeles',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const beforeCall = Date.now()
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
const data = await res.json()
const nextRunAt = new Date(data.nextRunAt)
// Should be a future date within the next 10 minutes
expect(nextRunAt.getTime()).toBeGreaterThan(beforeCall)
expect(nextRunAt.getTime()).toBeLessThanOrEqual(beforeCall + 10 * 60 * 1000 + 1000)
// Should align with 10-minute intervals
expect(nextRunAt.getUTCMinutes() % 10).toBe(0)
})
it('handles hourly schedules with timezone correctly', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '15 * * * *', // At minute 15 of every hour
timezone: 'America/Chicago',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const beforeCall = Date.now()
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
const data = await res.json()
const nextRunAt = new Date(data.nextRunAt)
// Should be a future date at minute 15
expect(nextRunAt.getTime()).toBeGreaterThan(beforeCall)
expect(nextRunAt.getUTCMinutes()).toBe(15)
expect(nextRunAt.getUTCSeconds()).toBe(0)
})
it('handles custom cron expressions with complex patterns and timezone', async () => {
mockDbChain([
[
{
id: 'sched-1',
workflowId: 'wf-1',
status: 'disabled',
cronExpression: '0 9 * * 1-5', // Weekdays at 9 AM
timezone: 'America/New_York',
},
],
[{ userId: 'user-1', workspaceId: null }],
])
const beforeCall = Date.now()
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(200)
const data = await res.json()
const nextRunAt = new Date(data.nextRunAt)
// Should be a future date on a weekday (1-5)
expect(nextRunAt.getTime()).toBeGreaterThan(beforeCall)
const dayOfWeek = nextRunAt.getUTCDay()
expect([1, 2, 3, 4, 5]).toContain(dayOfWeek)
})
})
describe('Error Handling', () => {
it('returns 500 when database operation fails', async () => {
mockDbSelect.mockImplementation(() => {
throw new Error('Database connection failed')
})
const res = await PUT(createRequest({ action: 'reactivate' }), createParams('sched-1'))
expect(res.status).toBe(500)
const data = await res.json()
expect(data.error).toBe('Failed to update schedule')
})
})
})
+391
View File
@@ -0,0 +1,391 @@
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
import { db } from '@sim/db'
import { workflowSchedule } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import {
assertWorkflowMutable,
authorizeWorkflowByWorkspacePermission,
WorkflowLockedError,
} from '@sim/platform-authz/workflow'
import { and, eq, isNull } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { getScheduleByIdContract, updateScheduleContract } from '@/lib/api/contracts/schedules'
import { parseRequest } from '@/lib/api/server'
import { getSession } from '@/lib/auth'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { captureServerEvent } from '@/lib/posthog/server'
import {
performDeleteJob,
performExcludeOccurrence,
performUpdateJob,
} from '@/lib/workflows/schedules/orchestration'
import { validateCronExpression } from '@/lib/workflows/schedules/utils'
import { verifyWorkspaceMembership } from '@/app/api/workflows/utils'
const logger = createLogger('ScheduleAPI')
export const dynamic = 'force-dynamic'
type ScheduleRow = typeof workflowSchedule.$inferSelect
async function fetchAndAuthorize(
requestId: string,
scheduleId: string,
userId: string,
action: 'read' | 'write'
): Promise<{ schedule: ScheduleRow; workspaceId: string | null } | NextResponse> {
const [schedule] = await db
.select()
.from(workflowSchedule)
.where(and(eq(workflowSchedule.id, scheduleId), isNull(workflowSchedule.archivedAt)))
.limit(1)
if (!schedule) {
logger.warn(`[${requestId}] Schedule not found: ${scheduleId}`)
return NextResponse.json({ error: 'Schedule not found' }, { status: 404 })
}
if (schedule.sourceType === 'job') {
if (!schedule.sourceWorkspaceId) {
return NextResponse.json({ error: 'Job has no workspace' }, { status: 400 })
}
const permission = await verifyWorkspaceMembership(userId, schedule.sourceWorkspaceId)
const canWrite = permission === 'admin' || permission === 'write'
if (!permission || (action === 'write' && !canWrite)) {
return NextResponse.json({ error: 'Not authorized' }, { status: 403 })
}
return { schedule, workspaceId: schedule.sourceWorkspaceId }
}
if (!schedule.workflowId) {
logger.warn(`[${requestId}] Schedule has no workflow: ${scheduleId}`)
return NextResponse.json({ error: 'Schedule has no associated workflow' }, { status: 400 })
}
const authorization = await authorizeWorkflowByWorkspacePermission({
workflowId: schedule.workflowId,
userId,
action,
})
if (!authorization.workflow) {
logger.warn(`[${requestId}] Workflow not found for schedule: ${scheduleId}`)
return NextResponse.json({ error: 'Workflow not found' }, { status: 404 })
}
if (!authorization.allowed) {
logger.warn(`[${requestId}] User not authorized to modify schedule: ${scheduleId}`)
return NextResponse.json(
{ error: authorization.message || 'Not authorized to modify this schedule' },
{ status: authorization.status }
)
}
return { schedule, workspaceId: authorization.workflow.workspaceId ?? null }
}
export const GET = withRouteHandler(
async (request: NextRequest, context: { params: Promise<{ id: string }> }) => {
const requestId = generateRequestId()
try {
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(getScheduleByIdContract, request, context, {
validationErrorResponse: () =>
NextResponse.json({ error: 'Invalid request' }, { status: 400 }),
})
if (!parsed.success) return parsed.response
const { id: scheduleId } = parsed.data.params
// fetchAndAuthorize already loads the full row (and 404s if missing), so
// return it directly — no second query.
const authResult = await fetchAndAuthorize(requestId, scheduleId, session.user.id, 'read')
if (authResult instanceof NextResponse) return authResult
return NextResponse.json({ schedule: authResult.schedule })
} catch (error) {
logger.error(`[${requestId}] Failed to get schedule`, { error })
return NextResponse.json({ error: 'Failed to get schedule' }, { status: 500 })
}
}
)
export const PUT = withRouteHandler(
async (request: NextRequest, context: { params: Promise<{ id: string }> }) => {
const requestId = generateRequestId()
try {
const session = await getSession()
if (!session?.user?.id) {
logger.warn(`[${requestId}] Unauthorized schedule update attempt`)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(updateScheduleContract, request, context, {
validationErrorResponse: () =>
NextResponse.json({ error: 'Invalid request body' }, { status: 400 }),
})
if (!parsed.success) return parsed.response
const { id: scheduleId } = parsed.data.params
const validatedBody = parsed.data.body
const result = await fetchAndAuthorize(requestId, scheduleId, session.user.id, 'write')
if (result instanceof NextResponse) return result
const { schedule, workspaceId } = result
if (schedule.workflowId) {
await assertWorkflowMutable(schedule.workflowId)
}
const { action } = validatedBody
if (action === 'disable') {
if (schedule.status === 'disabled') {
return NextResponse.json({ message: 'Schedule is already disabled' })
}
await db
.update(workflowSchedule)
.set({ status: 'disabled', nextRunAt: null, lastQueuedAt: null, updatedAt: new Date() })
.where(and(eq(workflowSchedule.id, scheduleId), isNull(workflowSchedule.archivedAt)))
logger.info(`[${requestId}] Disabled schedule: ${scheduleId}`)
recordAudit({
workspaceId,
actorId: session.user.id,
actorName: session.user.name,
actorEmail: session.user.email,
action: AuditAction.SCHEDULE_UPDATED,
resourceType: AuditResourceType.SCHEDULE,
resourceId: scheduleId,
resourceName: schedule.jobTitle ?? undefined,
description: `Disabled schedule "${schedule.jobTitle ?? scheduleId}"`,
metadata: {
operation: 'disable',
sourceType: schedule.sourceType,
previousStatus: schedule.status,
},
request,
})
return NextResponse.json({ message: 'Schedule disabled successfully' })
}
if (action === 'update') {
if (schedule.sourceType !== 'job') {
return NextResponse.json(
{ error: 'Only standalone job schedules can be edited' },
{ status: 400 }
)
}
if (!workspaceId) {
return NextResponse.json({ error: 'Job has no workspace' }, { status: 400 })
}
const updateResult = await performUpdateJob({
jobId: scheduleId,
workspaceId,
userId: session.user.id,
actorName: session.user.name,
actorEmail: session.user.email,
title: validatedBody.title,
prompt: validatedBody.prompt,
timezone: validatedBody.timezone,
lifecycle: validatedBody.lifecycle,
maxRuns: validatedBody.maxRuns,
cronExpression: validatedBody.cronExpression,
time: validatedBody.time,
endsAt: validatedBody.endsAt,
contexts: validatedBody.contexts,
request,
})
if (!updateResult.success) {
return NextResponse.json(
{ error: updateResult.error || 'Failed to update schedule' },
{ status: updateResult.errorCode === 'validation' ? 400 : 500 }
)
}
logger.info(`[${requestId}] Updated job schedule: ${scheduleId}`)
return NextResponse.json({ message: 'Schedule updated successfully' })
}
if (action === 'exclude_occurrence') {
if (schedule.sourceType !== 'job') {
return NextResponse.json(
{ error: 'Only standalone job schedules have occurrences' },
{ status: 400 }
)
}
if (!workspaceId) {
return NextResponse.json({ error: 'Job has no workspace' }, { status: 400 })
}
const excludeResult = await performExcludeOccurrence({
jobId: scheduleId,
workspaceId,
userId: session.user.id,
actorName: session.user.name,
actorEmail: session.user.email,
occurrence: validatedBody.occurrence,
request,
})
if (!excludeResult.success) {
return NextResponse.json(
{ error: excludeResult.error || 'Failed to delete occurrence' },
{
status:
excludeResult.errorCode === 'not_found'
? 404
: excludeResult.errorCode === 'validation'
? 400
: 500,
}
)
}
logger.info(`[${requestId}] Excluded occurrence on job schedule: ${scheduleId}`)
return NextResponse.json({ message: 'Occurrence deleted successfully' })
}
// reactivate
if (schedule.status === 'active') {
return NextResponse.json({ message: 'Schedule is already active' })
}
if (!schedule.cronExpression) {
logger.error(`[${requestId}] Schedule has no cron expression: ${scheduleId}`)
return NextResponse.json({ error: 'Schedule has no cron expression' }, { status: 400 })
}
const cronResult = validateCronExpression(schedule.cronExpression, schedule.timezone || 'UTC')
if (!cronResult.isValid || !cronResult.nextRun) {
logger.error(`[${requestId}] Invalid cron expression for schedule: ${scheduleId}`)
return NextResponse.json({ error: 'Schedule has invalid cron expression' }, { status: 400 })
}
const now = new Date()
const nextRunAt = cronResult.nextRun
await db
.update(workflowSchedule)
.set({ status: 'active', failedCount: 0, infraRetryCount: 0, updatedAt: now, nextRunAt })
.where(and(eq(workflowSchedule.id, scheduleId), isNull(workflowSchedule.archivedAt)))
logger.info(`[${requestId}] Reactivated schedule: ${scheduleId}`)
recordAudit({
workspaceId,
actorId: session.user.id,
actorName: session.user.name,
actorEmail: session.user.email,
action: AuditAction.SCHEDULE_UPDATED,
resourceType: AuditResourceType.SCHEDULE,
resourceId: scheduleId,
resourceName: schedule.jobTitle ?? undefined,
description: `Reactivated schedule "${schedule.jobTitle ?? scheduleId}"`,
metadata: {
operation: 'reactivate',
sourceType: schedule.sourceType,
cronExpression: schedule.cronExpression,
timezone: schedule.timezone,
},
request,
})
return NextResponse.json({ message: 'Schedule activated successfully', nextRunAt })
} catch (error) {
if (error instanceof WorkflowLockedError) {
return NextResponse.json({ error: error.message }, { status: error.status })
}
logger.error(`[${requestId}] Error updating schedule`, error)
return NextResponse.json({ error: 'Failed to update schedule' }, { status: 500 })
}
}
)
export const DELETE = withRouteHandler(
async (request: NextRequest, { params }: { params: Promise<{ id: string }> }) => {
const requestId = generateRequestId()
try {
const { id: scheduleId } = await params
const session = await getSession()
if (!session?.user?.id) {
logger.warn(`[${requestId}] Unauthorized schedule delete attempt`)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const result = await fetchAndAuthorize(requestId, scheduleId, session.user.id, 'write')
if (result instanceof NextResponse) return result
const { schedule, workspaceId } = result
if (schedule.sourceType === 'job') {
if (!workspaceId) {
return NextResponse.json({ error: 'Job has no workspace' }, { status: 400 })
}
const deleteResult = await performDeleteJob({
jobId: scheduleId,
workspaceId,
userId: session.user.id,
actorName: session.user.name,
actorEmail: session.user.email,
request,
})
if (!deleteResult.success) {
return NextResponse.json(
{ error: deleteResult.error || 'Failed to delete schedule' },
{ status: deleteResult.errorCode === 'not_found' ? 404 : 500 }
)
}
return NextResponse.json({ message: 'Schedule deleted successfully' })
}
await db.delete(workflowSchedule).where(eq(workflowSchedule.id, scheduleId))
logger.info(`[${requestId}] Deleted schedule: ${scheduleId}`)
recordAudit({
workspaceId,
actorId: session.user.id,
actorName: session.user.name,
actorEmail: session.user.email,
action: AuditAction.SCHEDULE_DELETED,
resourceType: AuditResourceType.SCHEDULE,
resourceId: scheduleId,
resourceName: schedule.jobTitle ?? undefined,
description: `Deleted ${schedule.sourceType === 'job' ? 'job' : 'schedule'} "${schedule.jobTitle ?? scheduleId}"`,
metadata: {
sourceType: schedule.sourceType,
cronExpression: schedule.cronExpression,
timezone: schedule.timezone,
},
request,
})
captureServerEvent(
session.user.id,
'scheduled_task_deleted',
{ workspace_id: workspaceId ?? '' },
workspaceId ? { groups: { workspace: workspaceId } } : undefined
)
return NextResponse.json({ message: 'Schedule deleted successfully' })
} catch (error) {
logger.error(`[${requestId}] Error deleting schedule`, error)
return NextResponse.json({ error: 'Failed to delete schedule' }, { status: 500 })
}
}
)