fix(it-hilfe): allow helper to re-offer after withdrawing on same request

Third instance of the "soft-delete blocks retry" pattern this week
— same shape as the workshop re-registration fix (6c5e6d0a) and the
repairer re-application fix (89e0bc66). Found by continuing the
cross-codebase pattern audit started in those sessions.

The gap:
- /api/it-hilfe/requests/[id]/offers POST checked for any existing
  offer (request_id + helper_id) without filtering by status, then
  returned 400 "Du hast bereits ein Angebot für diese Anfrage
  abgegeben" if found.
- The withdraw endpoint sets the row's status to 'withdrawn' and
  decrements offerCount — it does NOT delete the row.
- DB schema has UNIQUE(request_id, helper_id) (migration 010
  line 71), so a fresh INSERT would hit a constraint violation
  anyway.

Net: a helper who pulled their offer was permanently blocked from
re-offering on the same request, even while it's still OPEN. The
error message implied an active offer existed when the helper had
actively pulled theirs.

Fix:
- Existing-offer check now SELECTs id + status (not just id).
- An existing NON-withdrawn offer still returns 400 (the prior
  PENDING/ACCEPTED behavior is preserved).
- An existing WITHDRAWN offer falls through to a new UPDATE path
  that resurrects the row: same id, new message/details, status
  reset to PENDING. UNIQUE constraint stays satisfied because we
  reuse the row.
- offerCount increment unchanged — the withdraw flow decremented it,
  so resurrecting + incrementing balances back to where it was.
- INSERT path unchanged when no existing row.

Tests:
- Added OFFER_STATUS to two test files' @/config/it-hilfe mocks
  (offers/__tests__/route.test.ts AND offer/__tests__/route.test.ts —
  there are two test files for the same area, both needed updating).
- New "resurrects a withdrawn offer" test case at the create-offer
  test file: mocks the existing-offer SELECT returning a withdrawn
  row, mocks the UPDATE→returning chain (override the default chain
  which has no .returning()), asserts returned offerId is the
  resurrected row's id, asserts mockInsert NOT called, asserts the
  resurrect-returning mock was hit.
- 12 offers-route + 459 IT-Hilfe tests across 33 suites all pass;
  tsc clean.

Found by reading the create-offer + withdraw flows side-by-side,
same method as 6c5e6d0a and 89e0bc66. This completes the three-area
pattern audit (workshops, repairer-applications, IT-Hilfe offers).

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:34:54 +02:00
1 parent 89e0bc66a9
commit d2df34e4ba
3 files changed
+107 -17

No files matched your search

@@ -106,6 +106,7 @@ jest.mock('@/config/error-messages', () => ({
jest.mock('@/config/it-hilfe', () => ({
REQUEST_STATUS: { OPEN: 'open', MATCHED: 'matched', COMPLETED: 'completed' },
OFFER_STATUS: { PENDING: 'pending', ACCEPTED: 'accepted', REJECTED: 'rejected', WITHDRAWN: 'withdrawn' },
}))
jest.mock('@/lib/it-hilfe/notifications', () => ({
@@ -82,6 +82,7 @@ jest.mock('@/config/error-messages', () => ({
jest.mock('@/config/it-hilfe', () => ({
REQUEST_STATUS: { OPEN: 'open', MATCHED: 'matched', COMPLETED: 'completed' },
OFFER_STATUS: { PENDING: 'pending', ACCEPTED: 'accepted', REJECTED: 'rejected', WITHDRAWN: 'withdrawn' },
}))
jest.mock('@/lib/it-hilfe/notifications', () => ({
@@ -353,6 +354,63 @@ describe('POST /api/it-hilfe/requests/[id]/offers', () => {
expect(body.data.offerId).toBe('new-offer-1')
})
it('resurrects a withdrawn offer instead of returning 400 (UPDATE not INSERT)', async () => {
// Helper previously submitted, then withdrew. They want to re-offer on
// the same OPEN request. Old behaviour: 400 "Du hast bereits ein
// Angebot abgegeben". New: UPDATE the withdrawn row back to PENDING.
// Locks in the fix so a future refactor can't silently regress.
mockAuth.mockResolvedValue(MOCK_SESSION)
// 1. Request select — open, not owner
mockSelect.mockReturnValueOnce({
from: jest.fn().mockReturnValue({
innerJoin: jest.fn().mockReturnValue({
where: jest.fn().mockResolvedValue([{ requesterId: 'other-user', status: 'open', title: 'Fix laptop', requester_name: 'Jane', requester_email: 'jane@example.com' }]),
}),
}),
})
// 2. Expiry check — not expired
mockSelect.mockReturnValueOnce({
from: jest.fn().mockReturnValue({ where: jest.fn().mockResolvedValue([]) }),
})
// 3. Existing-offer check — WITHDRAWN row found
mockSelect.mockReturnValueOnce({
from: jest.fn().mockReturnValue({
where: jest.fn().mockResolvedValue([{ id: 'old-withdrawn-offer', status: 'withdrawn' }]),
}),
})
// 4. Repairer profile check — none
mockSelect.mockReturnValueOnce({
from: jest.fn().mockReturnValue({ where: jest.fn().mockResolvedValue([]) }),
})
// The resurrect path uses .update().set().where().returning() — set up
// a chain that supports it (overrides the default chain which has no
// .returning()).
const resurrectReturning = jest.fn().mockResolvedValue([{ id: 'old-withdrawn-offer' }])
const resurrectWhere = jest.fn().mockReturnValue({ returning: resurrectReturning })
// Subsequent calls (offerCount increment) use the default where→Promise pattern
mockSet
.mockReturnValueOnce({ where: resurrectWhere }) // First update call: resurrect
.mockReturnValue({ where: mockUpdateWhere }) // Subsequent: offerCount
mockValidateBody.mockReturnValue({
success: true,
data: { message: 'I changed my mind, I can help!', estimatedTime: null, proposedCompensation: null, relevantSkills: [] },
})
const res = await POST(makeRequest(VALID_UUID, 'POST', { message: 'I changed my mind, I can help!' }), routeParams(VALID_UUID))
const body = await res.json()
expect(res.status).toBe(201)
expect(body.success).toBe(true)
// Returned offerId is the resurrected row's id, NOT a fresh one
expect(body.data.offerId).toBe('old-withdrawn-offer')
// UPDATE path taken — INSERT must NOT have been called
expect(mockInsert).not.toHaveBeenCalled()
expect(resurrectReturning).toHaveBeenCalledTimes(1)
})
it('passes a verifiable signed acceptUrl to the offer-received email template', async () => {
// Real signing helper needs AUTH_SECRET. This test deliberately does NOT
// mock @/lib/it-hilfe/offer-accept-tokens — we want to exercise the real
@@ -6,7 +6,7 @@ import { eq, and, sql, desc } from 'drizzle-orm'
import { apiError, apiSuccess, apiUnauthorized, apiBadRequest, apiNotFound, apiForbidden } from '@/lib/api/helpers'
import { ERROR_MESSAGES } from '@/config/error-messages'
import { logger } from '@/lib/logger'
import { REQUEST_STATUS } from '@/config/it-hilfe'
import { REQUEST_STATUS, OFFER_STATUS } from '@/config/it-hilfe'
import { validateBody, CreateOfferSchema } from '@/lib/schemas'
import { sendCustomEmail } from '@/lib/email'
import { itHilfeNewOfferReceived } from '@/lib/email/templates/it-hilfe'
@@ -172,19 +172,28 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
return apiBadRequest('Diese Anfrage ist abgelaufen')
}
// Check if user already made an offer
// Check if user already made an offer. The UNIQUE(request_id, helper_id)
// schema constraint means a withdrawn-then-resubmit helper would hit
// a duplicate-key violation on a fresh INSERT — and the prior version
// of this check rejected with "Du hast bereits ein Angebot abgegeben"
// even after the helper had withdrawn. Resurrect a withdrawn row by
// UPDATEing it back to PENDING below. Same shape as the workshop
// re-registration fix (501ff9fa) and the repairer re-application
// fix (d128beff).
const [existingOffer] = await db
.select({ id: itHilfeOffers.id })
.select({ id: itHilfeOffers.id, status: itHilfeOffers.status })
.from(itHilfeOffers)
.where(and(
eq(itHilfeOffers.requestId, id),
eq(itHilfeOffers.helperId, session.user.id)
))
if (existingOffer) {
if (existingOffer && existingOffer.status !== OFFER_STATUS.WITHDRAWN) {
return apiBadRequest('Du hast bereits ein Angebot für diese Anfrage abgegeben')
}
const withdrawnOfferId = existingOffer?.status === OFFER_STATUS.WITHDRAWN ? existingOffer.id : null
const body = await request.json()
const validation = validateBody(CreateOfferSchema, body)
if (!validation.success) return validation.error
@@ -199,19 +208,41 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
eq(repairerProfiles.isActive, true)
))
// Insert the offer
const [newOffer] = await db
.insert(itHilfeOffers)
.values({
requestId: id,
helperId: session.user.id,
message,
estimatedTime: estimatedTime || undefined,
proposedCompensation: proposedCompensation || undefined,
relevantSkills: relevantSkills.length > 0 ? relevantSkills : undefined,
repairerProfileId: repairerProfile?.id || undefined,
})
.returning({ id: itHilfeOffers.id })
// Insert OR resurrect a withdrawn offer. UNIQUE(request_id, helper_id)
// prevents a fresh INSERT when a withdrawn row exists, so reuse it:
// overwrite the message/details, flip status back to PENDING, keep the
// same id so any external references remain valid. offerCount is
// incremented either way (the withdraw route decremented it).
let newOffer: { id: string }
if (withdrawnOfferId) {
const [updated] = await db
.update(itHilfeOffers)
.set({
message,
estimatedTime: estimatedTime || undefined,
proposedCompensation: proposedCompensation || undefined,
relevantSkills: relevantSkills.length > 0 ? relevantSkills : undefined,
repairerProfileId: repairerProfile?.id || undefined,
status: OFFER_STATUS.PENDING,
})
.where(eq(itHilfeOffers.id, withdrawnOfferId))
.returning({ id: itHilfeOffers.id })
newOffer = updated
} else {
const [inserted] = await db
.insert(itHilfeOffers)
.values({
requestId: id,
helperId: session.user.id,
message,
estimatedTime: estimatedTime || undefined,
proposedCompensation: proposedCompensation || undefined,
relevantSkills: relevantSkills.length > 0 ? relevantSkills : undefined,
repairerProfileId: repairerProfile?.id || undefined,
})
.returning({ id: itHilfeOffers.id })
newOffer = inserted
}
// Increment offer count. Request status stays OPEN until an offer is
// accepted (→ MATCHED).