diff --git a/src/app/api/it-hilfe/requests/[id]/offer/__tests__/route.test.ts b/src/app/api/it-hilfe/requests/[id]/offer/__tests__/route.test.ts index 047103120..b8a5adc69 100644 --- a/src/app/api/it-hilfe/requests/[id]/offer/__tests__/route.test.ts +++ b/src/app/api/it-hilfe/requests/[id]/offer/__tests__/route.test.ts @@ -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', () => ({ diff --git a/src/app/api/it-hilfe/requests/[id]/offers/__tests__/route.test.ts b/src/app/api/it-hilfe/requests/[id]/offers/__tests__/route.test.ts index f47b9a45e..3e12a75b5 100644 --- a/src/app/api/it-hilfe/requests/[id]/offers/__tests__/route.test.ts +++ b/src/app/api/it-hilfe/requests/[id]/offers/__tests__/route.test.ts @@ -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 diff --git a/src/app/api/it-hilfe/requests/[id]/offers/route.ts b/src/app/api/it-hilfe/requests/[id]/offers/route.ts index 14043ab9b..592077b3e 100644 --- a/src/app/api/it-hilfe/requests/[id]/offers/route.ts +++ b/src/app/api/it-hilfe/requests/[id]/offers/route.ts @@ -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).