fix(repairer): allow re-application after rejection or required-changes

Same "soft-delete blocks retry" pattern as last session's workshop
fix (6c5e6d0a), found by the same method — reading apply + reject +
request-changes flows side-by-side. The pattern recurs across the
codebase wherever state transitions to a terminal-looking flag
without addressing what happens when the user wants another attempt.

The gap:
  /api/repairer/apply checks for an existing row, then:
    APPROVED   → "dein Profil wurde bereits freigeschaltet" ✓
    PENDING    → "ERROR_MESSAGES.PENDING_APPLICATION"        ✓
    everything else → "Du hast bereits ein Reparateur-Profil" ✗

That last branch lumps REJECTED and REQUIRES_CHANGES into a
misleading rejection: the user does NOT have a profile (rejected),
or has a half-formed one the admin asked them to update (requires_
changes) — but is blocked from doing either. The reject route
(admin/repairer-applications/[id]/reject) sets status='rejected'
on the row instead of deleting it (line 61); request-changes does
the same with 'requires_changes'. The UNIQUE(userId) constraint
on repairer_applications then prevents inserting a fresh row.

Fix:
- When the existing row has status REJECTED or REQUIRES_CHANGES,
  the apply route now UPDATEs the existing row with the new
  submission, resets status to PENDING, and clears the admin-side
  review fields (admin_notes, reviewed_by, reviewed_at) so the
  next reviewer sees a clean slate.
- When the existing row has status APPROVED or PENDING, behavior
  is unchanged (returns 400 with the existing messages).
- Row id stays stable across re-submissions so any admin-side
  links/notifications keyed by application id keep working.

The original code's comment even acknowledged the issue:
"For any other status (rejected, etc.), they already have an
application" — but the right answer is "let them try again."

Tests:
- Added `update` to the @/db mock + chain mocks for set/where/
  returning so the new UPDATE path is exercised.
- Flipped the "rejected → 400" test to "rejected → 200 (UPDATE,
  not INSERT)" and added the same case for REQUIRES_CHANGES.
- Verifies mockUpdate called once and mockInsert NOT called on
  the re-apply paths.
- 8 apply-route tests pass; 127 repairer tests across 15 suites
  all green; tsc clean.

Found by reading apply/route.ts:52-68 alongside reject/route.ts:58-67
and request-changes/route.ts:57-60 — the cancel+register pattern
that yielded 6c5e6d0a applies here too.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
g-butandClaude Opus 4.7 committed 2026-05-25 20:16:34 +02:00
1 parent 6c5e6d0a67
commit 89e0bc66a9
2 files changed
+119 -37

No files matched your search

@@ -12,6 +12,10 @@ const mockSelect = jest.fn()
const mockInsert = jest.fn()
const mockValues = jest.fn()
const mockReturning = jest.fn()
const mockUpdate = jest.fn()
const mockSet = jest.fn()
const mockUpdateWhere = jest.fn()
const mockUpdateReturning = jest.fn()
jest.mock('@/auth', () => ({
auth: (...args: unknown[]) => mockAuth.apply(null, args),
@@ -34,6 +38,7 @@ jest.mock('@/db', () => ({
db: {
select: (...args: unknown[]) => mockSelect(...args),
insert: (...args: unknown[]) => { mockInsert(...args); return { values: mockValues } },
update: (...args: unknown[]) => { mockUpdate(...args); return { set: mockSet } },
},
}))
@@ -211,6 +216,11 @@ beforeEach(() => {
// Default: successful insert
mockReturning.mockResolvedValue([{ id: 'app-1' }])
mockValues.mockReturnValue({ returning: mockReturning })
// Default: successful update (for re-applications)
mockUpdateReturning.mockResolvedValue([{ id: 'app-existing' }])
mockUpdateWhere.mockReturnValue({ returning: mockUpdateReturning })
mockSet.mockReturnValue({ where: mockUpdateWhere })
})
// ============================================================================
@@ -277,14 +287,55 @@ describe('POST /api/repairer/apply — duplicate checks', () => {
expect(response.status).toBe(400)
})
it('returns 400 when application already exists (any status)', async () => {
const mockWhere = jest.fn().mockResolvedValue([{ id: 'app-existing', status: 'rejected' }])
const mockFrom = jest.fn().mockReturnValue({ where: mockWhere })
mockSelect.mockReturnValue({ from: mockFrom })
it('re-submits (200, UPDATE) when prior application was REJECTED', async () => {
// The user was rejected; they're re-applying. The route should reuse
// the existing row (UPDATE) — UNIQUE(userId) prevents inserting a new
// one — and reset its status to PENDING. Prior to this fix the route
// returned 400 "Du hast bereits ein Reparateur-Profil" and locked the
// user out forever.
let selectCallCount = 0
mockSelect.mockImplementation(() => {
selectCallCount++
if (selectCallCount === 1) {
const mockWhere = jest.fn().mockResolvedValue([{ id: 'app-existing', status: 'rejected' }])
const mockFrom = jest.fn().mockReturnValue({ where: mockWhere })
return { from: mockFrom }
}
const mockWhere = jest.fn().mockResolvedValue([{ email: 'admin@revamp-it.ch' }])
const mockFrom = jest.fn().mockReturnValue({ where: mockWhere })
return { from: mockFrom }
})
const req = makeRequest(makeValidFormDataBody())
const response = await POST(req)
expect(response.status).toBe(400)
expect(response.status).toBe(200)
const body = await response.json()
expect(body.success).toBe(true)
expect(body.data.applicationId).toBe('app-existing')
// UPDATE was called, INSERT was NOT.
expect(mockUpdate).toHaveBeenCalledTimes(1)
expect(mockInsert).not.toHaveBeenCalled()
})
it('re-submits (200, UPDATE) when prior application was REQUIRES_CHANGES', async () => {
let selectCallCount = 0
mockSelect.mockImplementation(() => {
selectCallCount++
if (selectCallCount === 1) {
const mockWhere = jest.fn().mockResolvedValue([{ id: 'app-existing', status: 'requires_changes' }])
const mockFrom = jest.fn().mockReturnValue({ where: mockWhere })
return { from: mockFrom }
}
const mockWhere = jest.fn().mockResolvedValue([{ email: 'admin@revamp-it.ch' }])
const mockFrom = jest.fn().mockReturnValue({ where: mockWhere })
return { from: mockFrom }
})
const req = makeRequest(makeValidFormDataBody())
const response = await POST(req)
expect(response.status).toBe(200)
expect(mockUpdate).toHaveBeenCalledTimes(1)
expect(mockInsert).not.toHaveBeenCalled()
})
})
+63 -32
View File
@@ -49,12 +49,15 @@ export const POST = withAuth(async (request: NextRequest, session: ValidSession)
termsAccepted
} = validation.data
// Check if user already has a repairer application
// Check if user already has a repairer application. The userId column
// has a UNIQUE constraint so there's at most one row per user — but its
// status determines what re-applying means.
const existingApplication = await db
.select({ id: repairerApplications.id, status: repairerApplications.status })
.from(repairerApplications)
.where(eq(repairerApplications.userId, session.user.id))
let existingApplicationId: string | null = null
if (existingApplication.length > 0) {
const app = existingApplication[0]
if (app.status === APPROVAL_STATUS.APPROVED) {
@@ -63,8 +66,12 @@ export const POST = withAuth(async (request: NextRequest, session: ValidSession)
if (app.status === APPROVAL_STATUS.PENDING) {
return apiBadRequest(ERROR_MESSAGES.PENDING_APPLICATION)
}
// For any other status (rejected, etc.), they already have an application
return apiBadRequest('Du hast bereits ein Reparateur-Profil')
// REJECTED or REQUIRES_CHANGES: the user has been told the application
// didn't pass and is now resubmitting. Reuse the row (UNIQUE(userId)
// prevents inserting a fresh one anyway) — overwrite the fields with
// the new submission, reset status to PENDING, clear the admin-side
// review fields so the next reviewer sees a clean slate.
existingApplicationId = app.id
}
// Handle file uploads (simplified - in production, you'd upload to cloud storage)
@@ -84,35 +91,59 @@ export const POST = withAuth(async (request: NextRequest, session: ValidSession)
}
}
// Create repairer application
const [createdApplication] = await db
.insert(repairerApplications)
.values({
userId: session.user.id,
businessName: businessName || null,
businessType,
description,
yearsExperience,
phone,
website: website || null,
address,
city,
postalCode,
serviceRadiusKm: serviceRadius,
remoteServices,
hourlyRateCents: hourlyRate ? Math.round(hourlyRate * 100) : null,
emergencyFeeCents: emergencyFee ? Math.round(emergencyFee * 100) : null,
homeVisitFeeCents: homeVisitFee ? Math.round(homeVisitFee * 100) : null,
servicesOffered,
specializations,
certifications,
insuranceInfo: insuranceInfo || null,
portfolioImages,
verificationDocuments: certificationDocs,
termsAccepted,
status: APPROVAL_STATUS.PENDING,
})
.returning({ id: repairerApplications.id })
// Create OR re-submit repairer application. UPDATE when the user has a
// prior REJECTED / REQUIRES_CHANGES row (captured above), INSERT
// otherwise. The row's id stays stable across re-submissions so any
// admin-side links/notifications referencing the application id keep
// working.
const applicationFields = {
userId: session.user.id,
businessName: businessName || null,
businessType,
description,
yearsExperience,
phone,
website: website || null,
address,
city,
postalCode,
serviceRadiusKm: serviceRadius,
remoteServices,
hourlyRateCents: hourlyRate ? Math.round(hourlyRate * 100) : null,
emergencyFeeCents: emergencyFee ? Math.round(emergencyFee * 100) : null,
homeVisitFeeCents: homeVisitFee ? Math.round(homeVisitFee * 100) : null,
servicesOffered,
specializations,
certifications,
insuranceInfo: insuranceInfo || null,
portfolioImages,
verificationDocuments: certificationDocs,
termsAccepted,
status: APPROVAL_STATUS.PENDING,
}
let createdApplication: { id: string }
if (existingApplicationId) {
const [updated] = await db
.update(repairerApplications)
.set({
...applicationFields,
// Clear the admin-side review fields so the next reviewer sees a
// clean slate (not the prior reviewer's notes/decision).
adminNotes: null,
reviewedBy: null,
reviewedAt: null,
})
.where(eq(repairerApplications.id, existingApplicationId))
.returning({ id: repairerApplications.id })
createdApplication = updated
} else {
const [inserted] = await db
.insert(repairerApplications)
.values(applicationFields)
.returning({ id: repairerApplications.id })
createdApplication = inserted
}
// Send confirmation email to applicant
const applicantEmailResult = await sendEmail(