fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* Tests for /api/deadlines/[id] — validated PUT and count-checked DELETE.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
import { PUT, DELETE } from '../route'
|
||||
|
||||
const idParams = { params: Promise.resolve({ id: 'deadline-1' }) }
|
||||
|
||||
function createCapturingSupabase(
|
||||
results: { data?: unknown; error?: unknown; count?: number | null }[]
|
||||
) {
|
||||
let idx = 0
|
||||
const makeBuilder = () => {
|
||||
const result = results[idx++] ?? { data: null, error: null, count: null }
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const b: any = {}
|
||||
for (const m of ['select', 'eq', 'update', 'delete', 'single', 'maybeSingle']) {
|
||||
b[m] = () => b
|
||||
}
|
||||
b.then = (resolve: (v: unknown) => void) =>
|
||||
resolve({ data: result.data ?? null, error: result.error ?? null, count: result.count ?? null })
|
||||
return b
|
||||
}
|
||||
return { from: () => makeBuilder() }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
function auth(supabase: unknown) {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
}
|
||||
|
||||
describe('PUT /api/deadlines/[id]', () => {
|
||||
it('rejects a malformed body (bad due_date) with 400', async () => {
|
||||
auth(createCapturingSupabase([]))
|
||||
const req = createMockRequest('/api/deadlines/deadline-1', {
|
||||
method: 'PUT',
|
||||
body: { due_date: 'banana' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await PUT(req, idParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects an empty body with 400', async () => {
|
||||
auth(createCapturingSupabase([]))
|
||||
const req = createMockRequest('/api/deadlines/deadline-1', { method: 'PUT', body: {} })
|
||||
const { status } = await parseJsonResponse(await PUT(req, idParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('maps zero-rows to 404', async () => {
|
||||
auth(createCapturingSupabase([{ error: { code: 'PGRST116', message: 'no rows' } }]))
|
||||
const req = createMockRequest('/api/deadlines/deadline-1', {
|
||||
method: 'PUT',
|
||||
body: { title: 'Momsdeklaration Q3' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await PUT(req, idParams))
|
||||
expect(status).toBe(404)
|
||||
})
|
||||
|
||||
it('updates the deadline', async () => {
|
||||
auth(createCapturingSupabase([{ data: { id: 'deadline-1', title: 'Momsdeklaration Q3' } }]))
|
||||
const req = createMockRequest('/api/deadlines/deadline-1', {
|
||||
method: 'PUT',
|
||||
body: { title: 'Momsdeklaration Q3' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { title: string } }>(
|
||||
await PUT(req, idParams)
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.title).toBe('Momsdeklaration Q3')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/deadlines/[id]', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: {},
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await DELETE(createMockRequest('/x', { method: 'DELETE' }), idParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 instead of phantom success when no row matches', async () => {
|
||||
// First result: the source lookup finds nothing.
|
||||
auth(createCapturingSupabase([{ data: null }]))
|
||||
const { status } = await parseJsonResponse(
|
||||
await DELETE(createMockRequest('/x', { method: 'DELETE' }), idParams)
|
||||
)
|
||||
expect(status).toBe(404)
|
||||
})
|
||||
|
||||
it('hard-deletes a user-created deadline', async () => {
|
||||
auth(createCapturingSupabase([
|
||||
{ data: { id: 'deadline-1', source: 'user' } },
|
||||
{ count: 1 },
|
||||
]))
|
||||
const { status, body } = await parseJsonResponse<{ success: boolean; dismissed?: boolean }>(
|
||||
await DELETE(createMockRequest('/x', { method: 'DELETE' }), idParams)
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.success).toBe(true)
|
||||
expect(body.dismissed).toBeUndefined()
|
||||
})
|
||||
|
||||
it('dismisses a system deadline instead of deleting it', async () => {
|
||||
// A hard-deleted system row is recreated by the nightly backfill cron;
|
||||
// the route must soft-dismiss so the opt-out is durable.
|
||||
auth(createCapturingSupabase([
|
||||
{ data: { id: 'deadline-1', source: 'system' } },
|
||||
{ data: [{ id: 'deadline-1' }] },
|
||||
]))
|
||||
const { status, body } = await parseJsonResponse<{ success: boolean; dismissed?: boolean }>(
|
||||
await DELETE(createMockRequest('/x', { method: 'DELETE' }), idParams)
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.success).toBe(true)
|
||||
expect(body.dismissed).toBe(true)
|
||||
})
|
||||
|
||||
it('returns 404 when the system row vanished before the dismissal landed', async () => {
|
||||
// Concurrent regeneration can delete the row between lookup and update;
|
||||
// a phantom "dismissed" success would persist nothing.
|
||||
auth(createCapturingSupabase([
|
||||
{ data: { id: 'deadline-1', source: 'system' } },
|
||||
{ data: [] },
|
||||
]))
|
||||
const { status } = await parseJsonResponse(
|
||||
await DELETE(createMockRequest('/x', { method: 'DELETE' }), idParams)
|
||||
)
|
||||
expect(status).toBe(404)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* Tests for POST /api/deadlines/[id]/complete.
|
||||
*
|
||||
* The load-bearing case is the explicit-state one: the page's "Ångra" button
|
||||
* posts `{ is_completed: false }`, and a route that toggles instead of setting
|
||||
* turns a second undo click (or an undo of a row already un-ticked elsewhere)
|
||||
* into a re-completed Skatteverket deadline.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const idParams = { params: Promise.resolve({ id: 'deadline-1' }) }
|
||||
|
||||
interface Captured {
|
||||
update?: Record<string, unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
* Sequential query results plus the payload handed to `.update()`, which is the
|
||||
* only place the persisted state is observable.
|
||||
*/
|
||||
function createCapturingSupabase(
|
||||
results: { data?: unknown; error?: unknown }[],
|
||||
captured: Captured,
|
||||
) {
|
||||
let idx = 0
|
||||
const makeBuilder = () => {
|
||||
const result = results[idx++] ?? { data: null, error: null }
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const b: any = {}
|
||||
for (const m of ['select', 'eq', 'single', 'maybeSingle']) {
|
||||
b[m] = () => b
|
||||
}
|
||||
b.update = (payload: Record<string, unknown>) => {
|
||||
captured.update = payload
|
||||
return b
|
||||
}
|
||||
b.then = (resolve: (v: unknown) => void) =>
|
||||
resolve({ data: result.data ?? null, error: result.error ?? null })
|
||||
return b
|
||||
}
|
||||
return { from: () => makeBuilder() }
|
||||
}
|
||||
|
||||
function auth(supabase: unknown) {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('POST /api/deadlines/[id]/complete', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: {},
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST' }), idParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 for a viewer', async () => {
|
||||
auth(createCapturingSupabase([], {}))
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
})
|
||||
const res = await POST(
|
||||
createMockRequest('/x', { method: 'POST', body: { is_completed: false } }),
|
||||
idParams,
|
||||
)
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('maps zero-rows to 404 with a Swedish message', async () => {
|
||||
auth(createCapturingSupabase([{ error: { code: 'PGRST116', message: 'no rows' } }], {}))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(
|
||||
await POST(
|
||||
createMockRequest('/x', { method: 'POST', body: { is_completed: false } }),
|
||||
idParams,
|
||||
),
|
||||
)
|
||||
expect(status).toBe(404)
|
||||
expect(body.error).toBe('Deadline hittades inte')
|
||||
})
|
||||
|
||||
it('marks a pending deadline done and stamps completed_at', async () => {
|
||||
const captured: Captured = {}
|
||||
auth(
|
||||
createCapturingSupabase(
|
||||
[{ data: { is_completed: false } }, { data: { id: 'deadline-1', is_completed: true } }],
|
||||
captured,
|
||||
),
|
||||
)
|
||||
const { status } = await parseJsonResponse(
|
||||
await POST(
|
||||
createMockRequest('/x', { method: 'POST', body: { is_completed: true } }),
|
||||
idParams,
|
||||
),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(captured.update?.is_completed).toBe(true)
|
||||
expect(captured.update?.completed_at).toBeTruthy()
|
||||
})
|
||||
|
||||
it('undoes a completed deadline and clears completed_at', async () => {
|
||||
const captured: Captured = {}
|
||||
auth(
|
||||
createCapturingSupabase(
|
||||
[{ data: { is_completed: true } }, { data: { id: 'deadline-1', is_completed: false } }],
|
||||
captured,
|
||||
),
|
||||
)
|
||||
const { status } = await parseJsonResponse(
|
||||
await POST(
|
||||
createMockRequest('/x', { method: 'POST', body: { is_completed: false } }),
|
||||
idParams,
|
||||
),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(captured.update?.is_completed).toBe(false)
|
||||
expect(captured.update?.completed_at).toBeNull()
|
||||
})
|
||||
|
||||
it('is idempotent: undoing an already-pending deadline leaves it pending', async () => {
|
||||
// The "Ångra" click can land after the row was already un-ticked in another
|
||||
// tab or by an MCP agent. A route that toggled here would re-complete the
|
||||
// deadline, and the caller would still report it as put back on the list.
|
||||
const captured: Captured = {}
|
||||
auth(
|
||||
createCapturingSupabase(
|
||||
[{ data: { is_completed: false } }, { data: { id: 'deadline-1', is_completed: false } }],
|
||||
captured,
|
||||
),
|
||||
)
|
||||
const { status } = await parseJsonResponse(
|
||||
await POST(
|
||||
createMockRequest('/x', { method: 'POST', body: { is_completed: false } }),
|
||||
idParams,
|
||||
),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(captured.update?.is_completed).toBe(false)
|
||||
expect(captured.update?.completed_at).toBeNull()
|
||||
})
|
||||
|
||||
it('is idempotent: re-completing an already-done deadline keeps it done', async () => {
|
||||
const captured: Captured = {}
|
||||
auth(
|
||||
createCapturingSupabase(
|
||||
[{ data: { is_completed: true } }, { data: { id: 'deadline-1', is_completed: true } }],
|
||||
captured,
|
||||
),
|
||||
)
|
||||
await POST(
|
||||
createMockRequest('/x', { method: 'POST', body: { is_completed: true } }),
|
||||
idParams,
|
||||
)
|
||||
expect(captured.update?.is_completed).toBe(true)
|
||||
expect(captured.update?.completed_at).toBeTruthy()
|
||||
})
|
||||
|
||||
it('falls back to toggling when the body carries no state', async () => {
|
||||
// Backwards compatibility: a body-less POST keeps the original toggle.
|
||||
const captured: Captured = {}
|
||||
auth(
|
||||
createCapturingSupabase(
|
||||
[{ data: { is_completed: false } }, { data: { id: 'deadline-1', is_completed: true } }],
|
||||
captured,
|
||||
),
|
||||
)
|
||||
await POST(createMockRequest('/x', { method: 'POST' }), idParams)
|
||||
expect(captured.update?.is_completed).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a non-boolean is_completed with 400 instead of guessing', async () => {
|
||||
// { is_completed: "false" } is the load-bearing case: a string is truthy,
|
||||
// and the old hand-rolled parser silently degraded it to a toggle, so an
|
||||
// "undo" carrying the string could re-complete the deadline. A wrong type
|
||||
// must fail loudly and persist nothing.
|
||||
const captured: Captured = {}
|
||||
auth(createCapturingSupabase([], captured))
|
||||
const { status } = await parseJsonResponse(
|
||||
await POST(
|
||||
createMockRequest('/x', { method: 'POST', body: { is_completed: 'false' } }),
|
||||
idParams,
|
||||
),
|
||||
)
|
||||
expect(status).toBe(400)
|
||||
expect(captured.update).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects other wrong types for is_completed with 400', async () => {
|
||||
const captured: Captured = {}
|
||||
auth(createCapturingSupabase([], captured))
|
||||
for (const bad of [1, 'nope', null, [true]]) {
|
||||
const { status } = await parseJsonResponse(
|
||||
await POST(
|
||||
createMockRequest('/x', { method: 'POST', body: { is_completed: bad } }),
|
||||
idParams,
|
||||
),
|
||||
)
|
||||
expect(status, `is_completed=${JSON.stringify(bad)} must be a 400`).toBe(400)
|
||||
}
|
||||
expect(captured.update).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects unknown body keys with 400 (strict schema)', async () => {
|
||||
const captured: Captured = {}
|
||||
auth(createCapturingSupabase([], captured))
|
||||
const { status } = await parseJsonResponse(
|
||||
await POST(
|
||||
createMockRequest('/x', { method: 'POST', body: { is_completed: true, extra: 1 } }),
|
||||
idParams,
|
||||
),
|
||||
)
|
||||
expect(status).toBe(400)
|
||||
expect(captured.update).toBeUndefined()
|
||||
})
|
||||
|
||||
it('treats an explicit empty object as a toggle', async () => {
|
||||
const captured: Captured = {}
|
||||
auth(
|
||||
createCapturingSupabase(
|
||||
[{ data: { is_completed: false } }, { data: { id: 'deadline-1', is_completed: true } }],
|
||||
captured,
|
||||
),
|
||||
)
|
||||
const { status } = await parseJsonResponse(
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: {} }), idParams),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(captured.update?.is_completed).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,96 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
// Strict: `is_completed` must be a genuine boolean or absent. The hand-rolled
|
||||
// parser this replaces silently degraded { is_completed: "false" } (a string)
|
||||
// to a toggle: the exact hazard the explicit-state contract was built to
|
||||
// remove, since a truthy-string undo could re-complete the row it meant to
|
||||
// un-tick. Wrong types are a 400 now, never a guess.
|
||||
const CompleteDeadlineSchema = z
|
||||
.object({
|
||||
is_completed: z.boolean().optional(),
|
||||
})
|
||||
.strict()
|
||||
|
||||
/**
|
||||
* POST /api/deadlines/[id]/complete
|
||||
* Set the completion status of a deadline.
|
||||
*
|
||||
* The body is optional. When it carries a boolean `is_completed` the route sets
|
||||
* exactly that state; a caller that sends no body (or `{}`) keeps the original
|
||||
* toggle behaviour. A body that IS present but malformed (wrong type, unknown
|
||||
* keys, broken JSON) is rejected with 400 instead of being reinterpreted.
|
||||
*
|
||||
* Honouring an explicit state is what makes the "Ångra" affordance an undo
|
||||
* rather than a second toggle: the click has to be idempotent, because the row
|
||||
* can already have been un-ticked in another tab or by an MCP agent between the
|
||||
* toast appearing and the click landing, and a blind toggle would then
|
||||
* re-complete a Skatteverket deadline the user was trying to put back on the
|
||||
* list. It also makes the caller's own confirmation truthful: the client picks
|
||||
* its toast from the state it asked for, so the server must not silently
|
||||
* persist the opposite.
|
||||
*/
|
||||
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'deadline.toggle_complete',
|
||||
async (request, ctx, { params }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId } = ctx
|
||||
|
||||
// Absent/empty body = toggle (the pre-explicit-state ergonomics); anything
|
||||
// else must validate. The raw text is read first because validateBody
|
||||
// treats an empty body as invalid JSON, which would 400 the plain toggle.
|
||||
const raw = (await request.text()).trim()
|
||||
let requestedState: boolean | null = null
|
||||
if (raw !== '') {
|
||||
const validation = await validateBody(
|
||||
new Request(request.url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: raw,
|
||||
}),
|
||||
CompleteDeadlineSchema,
|
||||
)
|
||||
if (!validation.success) return validation.response
|
||||
requestedState = validation.data.is_completed ?? null
|
||||
}
|
||||
|
||||
// First, get current deadline state
|
||||
const { data: existing, error: fetchError } = await supabase
|
||||
.from('deadlines')
|
||||
.select('is_completed')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (fetchError) {
|
||||
if (fetchError.code === 'PGRST116') {
|
||||
// "Deadline" is the term the Swedish UI uses too (messages/sv.json).
|
||||
return NextResponse.json({ error: 'Deadline hittades inte' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json({ error: getUserErrorMessage(fetchError) }, { status: 500 })
|
||||
}
|
||||
|
||||
// Explicit state when the caller supplied one, otherwise toggle.
|
||||
const newCompletedState = requestedState ?? !existing.is_completed
|
||||
const { data, error } = await supabase
|
||||
.from('deadlines')
|
||||
.update({
|
||||
is_completed: newCompletedState,
|
||||
completed_at: newCompletedState ? new Date().toISOString() : null,
|
||||
})
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.select('*, customer:customers(id, name)')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,160 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateDeadlineSchema } from '@/lib/api/schemas'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
// Sparse update: every Create field, optional. Validated — the previous
|
||||
// implementation type-asserted the raw JSON, so malformed values reached
|
||||
// Postgres and malformed JSON crashed the handler.
|
||||
const UpdateDeadlineSchema = CreateDeadlineSchema.partial()
|
||||
|
||||
/**
|
||||
* GET /api/deadlines/[id]
|
||||
* Get a single deadline by ID
|
||||
*/
|
||||
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'deadline.get',
|
||||
async (_request, ctx, { params }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId } = ctx
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('deadlines')
|
||||
.select('*, customer:customers(id, name)')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
if (error.code === 'PGRST116') {
|
||||
return NextResponse.json({ error: 'Deadline not found' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* PUT /api/deadlines/[id]
|
||||
* Update a deadline
|
||||
*/
|
||||
export const PUT = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'deadline.update',
|
||||
async (request, ctx, { params }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId, log } = ctx
|
||||
|
||||
const validation = await validateBody(request, UpdateDeadlineSchema, {
|
||||
log,
|
||||
operation: 'deadline.update',
|
||||
})
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
// Build update object
|
||||
const updateData: Record<string, unknown> = {}
|
||||
if (body.title !== undefined) updateData.title = body.title
|
||||
if (body.due_date !== undefined) updateData.due_date = body.due_date
|
||||
if (body.due_time !== undefined) updateData.due_time = body.due_time
|
||||
if (body.deadline_type !== undefined) updateData.deadline_type = body.deadline_type
|
||||
if (body.priority !== undefined) updateData.priority = body.priority
|
||||
if (body.customer_id !== undefined) updateData.customer_id = body.customer_id || null
|
||||
if (body.notes !== undefined) updateData.notes = body.notes
|
||||
|
||||
if (Object.keys(updateData).length === 0) {
|
||||
return NextResponse.json({ error: 'Nothing to update' }, { status: 400 })
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('deadlines')
|
||||
.update(updateData)
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.select('*, customer:customers(id, name)')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
// PGRST116 = zero rows — the deadline doesn't exist in this company.
|
||||
if (error.code === 'PGRST116') {
|
||||
return NextResponse.json({ error: 'Deadline not found' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
/**
|
||||
* DELETE /api/deadlines/[id]
|
||||
* Delete a user deadline, or durably dismiss a system-generated one.
|
||||
*
|
||||
* System rows are soft-dismissed instead of hard-deleted: the nightly
|
||||
* backfill cron treats a missing upcoming system row as a repair case and
|
||||
* recreates it within 24 hours, so a hard delete silently undoes itself.
|
||||
* A dismissed row stays in the table (hidden from every surface) and
|
||||
* satisfies the generator and backfill the same way a completed row does.
|
||||
*/
|
||||
export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'deadline.delete',
|
||||
async (_request, ctx, { params }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId } = ctx
|
||||
|
||||
const { data: existing, error: fetchError } = await supabase
|
||||
.from('deadlines')
|
||||
.select('id, source')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (fetchError) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(fetchError) }, { status: 500 })
|
||||
}
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: 'Deadline not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
if (existing.source === 'system') {
|
||||
const { data: dismissedRows, error: dismissError } = await supabase
|
||||
.from('deadlines')
|
||||
.update({ dismissed_at: new Date().toISOString() })
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.eq('source', 'system')
|
||||
.select('id')
|
||||
|
||||
if (dismissError) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(dismissError) }, { status: 500 })
|
||||
}
|
||||
// The row can vanish between lookup and update (generator cleanup
|
||||
// during a concurrent regeneration); report 404 rather than a
|
||||
// phantom success that persisted nothing.
|
||||
if (!dismissedRows || dismissedRows.length === 0) {
|
||||
return NextResponse.json({ error: 'Deadline not found' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json({ success: true, dismissed: true })
|
||||
}
|
||||
|
||||
const { error, count } = await supabase
|
||||
.from('deadlines')
|
||||
.delete({ count: 'exact' })
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
|
||||
}
|
||||
// Zero rows = wrong id / another company's deadline — not a success.
|
||||
if (count === 0) {
|
||||
return NextResponse.json({ error: 'Deadline not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,81 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { updateDeadlineStatus, isValidTransition } from '@/lib/deadlines/status-engine'
|
||||
import type { DeadlineStatus } from '@/types'
|
||||
|
||||
const ALL_STATUSES = [
|
||||
'upcoming',
|
||||
'action_needed',
|
||||
'in_progress',
|
||||
'submitted',
|
||||
'confirmed',
|
||||
'overdue',
|
||||
] as const satisfies readonly DeadlineStatus[]
|
||||
|
||||
const PatchStatusSchema = z.object({
|
||||
status: z.enum(ALL_STATUSES),
|
||||
})
|
||||
|
||||
/**
|
||||
* PATCH /api/deadlines/[id]/status
|
||||
* Manually update a deadline's status
|
||||
*/
|
||||
export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'deadline.set_status',
|
||||
async (request, ctx, { params }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId, log } = ctx
|
||||
|
||||
const validation = await validateBody(request, PatchStatusSchema, {
|
||||
log,
|
||||
operation: 'deadline.set_status',
|
||||
})
|
||||
if (!validation.success) return validation.response
|
||||
|
||||
const result = await updateDeadlineStatus(supabase, id, companyId, validation.data.status)
|
||||
|
||||
if (!result.success) {
|
||||
return NextResponse.json({ error: result.error }, { status: 400 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
/**
|
||||
* GET /api/deadlines/[id]/status
|
||||
* Get current status and valid transitions
|
||||
*/
|
||||
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'deadline.get_status',
|
||||
async (_request, ctx, { params }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId } = ctx
|
||||
|
||||
const { data: deadline, error } = await supabase
|
||||
.from('deadlines')
|
||||
.select('status, is_completed, due_date')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (error || !deadline) {
|
||||
return NextResponse.json({ error: 'Deadline not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
// Calculate valid transitions from current status
|
||||
const validTransitions = ALL_STATUSES.filter((status) =>
|
||||
isValidTransition(deadline.status, status)
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
currentStatus: deadline.status,
|
||||
isCompleted: deadline.is_completed,
|
||||
dueDate: deadline.due_date,
|
||||
validTransitions,
|
||||
})
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,99 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateDeadlineSchema } from '@/lib/api/schemas'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
/**
|
||||
* GET /api/deadlines
|
||||
* List deadlines for the authenticated user
|
||||
* Query params:
|
||||
* - status: 'all' | 'pending' | 'completed' (default: 'all')
|
||||
* - type: DeadlineType (optional)
|
||||
* - from: ISO date string (optional)
|
||||
* - to: ISO date string (optional)
|
||||
*/
|
||||
export const GET = withRouteContext('deadline.list', async (request, ctx) => {
|
||||
const { supabase, companyId } = ctx
|
||||
|
||||
// Parse query params
|
||||
const { searchParams } = new URL(request.url)
|
||||
const status = searchParams.get('status') || 'all'
|
||||
const type = searchParams.get('type')
|
||||
const from = searchParams.get('from')
|
||||
const to = searchParams.get('to')
|
||||
|
||||
// Build query. Dismissed system deadlines are an explicit opt-out and
|
||||
// never listed.
|
||||
let query = supabase
|
||||
.from('deadlines')
|
||||
.select('*, customer:customers(id, name)')
|
||||
.eq('company_id', companyId)
|
||||
.is('dismissed_at', null)
|
||||
|
||||
// Apply filters
|
||||
if (status === 'pending') {
|
||||
query = query.eq('is_completed', false)
|
||||
} else if (status === 'completed') {
|
||||
query = query.eq('is_completed', true)
|
||||
}
|
||||
|
||||
if (type) {
|
||||
query = query.eq('deadline_type', type)
|
||||
}
|
||||
|
||||
if (from) {
|
||||
query = query.gte('due_date', from)
|
||||
}
|
||||
|
||||
if (to) {
|
||||
query = query.lte('due_date', to)
|
||||
}
|
||||
|
||||
const { data, error } = await query.order('due_date', { ascending: true })
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
})
|
||||
|
||||
/**
|
||||
* POST /api/deadlines
|
||||
* Create a new deadline
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'deadline.create',
|
||||
async (request, ctx) => {
|
||||
const { supabase, companyId, user } = ctx
|
||||
|
||||
const validation = await validateBody(request, CreateDeadlineSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
// Insert the deadline
|
||||
const { data, error } = await supabase
|
||||
.from('deadlines')
|
||||
.insert({
|
||||
user_id: user.id,
|
||||
company_id: companyId,
|
||||
title: body.title,
|
||||
due_date: body.due_date,
|
||||
due_time: body.due_time || null,
|
||||
deadline_type: body.deadline_type,
|
||||
priority: body.priority || 'normal',
|
||||
customer_id: body.customer_id || null,
|
||||
notes: body.notes || null,
|
||||
})
|
||||
.select('*, customer:customers(id, name)')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
import { createServiceRoleClient } from '@/lib/supabase/service-client'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { updateDeadlineStatuses } from '@/lib/deadlines/status-engine'
|
||||
import { withCronContext } from '@/lib/api/with-cron-context'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
|
||||
/**
|
||||
* GET /api/deadlines/status/cron: daily 06:00 UTC.
|
||||
* Updates deadline statuses across all companies.
|
||||
*/
|
||||
export const GET = withCronContext('cron.deadlines_status', async (_request, ctx) => {
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
||||
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
|
||||
if (!supabaseUrl || !supabaseServiceKey) {
|
||||
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
details: { reason: 'Missing Supabase configuration' },
|
||||
})
|
||||
}
|
||||
|
||||
const supabase = createServiceRoleClient(supabaseUrl, supabaseServiceKey)
|
||||
|
||||
const result = await updateDeadlineStatuses(supabase)
|
||||
|
||||
ctx.log.info('deadline status cron summary', {
|
||||
updated: result.updated,
|
||||
newlyOverdue: result.newlyOverdue,
|
||||
newlyActionNeeded: result.newlyActionNeeded,
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
updated: result.updated,
|
||||
newlyOverdue: result.newlyOverdue,
|
||||
newlyActionNeeded: result.newlyActionNeeded,
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user