mirror of
https://github.com/bitbaum/evig.git
synced 2026-12-04 06:17:02 +01:00
refactor: ruthless audit pass — race conditions, dead code, SSOT
Race conditions fixed: - pools/[id]/join: wrap memberCount check + INSERT in transaction with FOR UPDATE so concurrent joins on a near-full pool can no longer over-book past max_members. - marketplace/orders: rollback (delete order + restore listing) now runs in a transaction. The prior Promise.all could leave the listing stuck in RESERVED if one of the two writes failed. - useTaskActions: useEffect fetch now guards setState with a cancelled flag so unmount before resolution no longer warns / leaks. Dead code removed: - src/config/help-request-status.ts (deprecated shim — migrated all callers to import HELP_REQUEST_STATUS from @/config/activity). - middleware/admin.ts: deprecated requireRole() (zero callers in prod). SSOT consolidated: - CONTACT.phonePlaceholder / phonePlaceholderLandline in src/config/org.ts; 4 components no longer hardcode "+41 79 123 45 67" / landline placeholder. Misc: - SuggestionContext: inline the two trivial types it pulled from features/feedback/types so the context file is self-contained. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
8159f55c57
commit
a7d5c8186a
16 files changed
+124
-93
No files matched your search
@@ -18,8 +18,8 @@ import {
|
||||
HELP_REQUEST_URGENCY_LABELS,
|
||||
type HelpRequestStatus,
|
||||
type HelpRequestUrgency,
|
||||
HELP_REQUEST_STATUS,
|
||||
} from '@/config/activity'
|
||||
import { HELP_REQUEST_STATUS } from '@/config/help-request-status'
|
||||
import {
|
||||
useHelpRequests,
|
||||
useHelpRequestMutations,
|
||||
|
||||
@@ -13,7 +13,7 @@ import { redirect } from 'next/navigation'
|
||||
import { query } from '@/lib/auth/db'
|
||||
import { TABLE_NAMES } from '@/config/database'
|
||||
import { canAccessSection } from '@/lib/permissions'
|
||||
import { HELP_REQUEST_STATUS } from '@/config/help-request-status'
|
||||
import { HELP_REQUEST_STATUS } from '@/config/activity'
|
||||
import { URGENCY } from '@/config/it-hilfe'
|
||||
import { HelpCircle, ArrowLeft, Users, AlertTriangle, CheckCircle } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
|
||||
@@ -79,7 +79,7 @@ jest.mock('drizzle-orm', () => ({
|
||||
),
|
||||
}))
|
||||
|
||||
jest.mock('@/config/help-request-status', () => ({
|
||||
jest.mock('@/config/activity', () => ({
|
||||
HELP_REQUEST_STATUS: { RESOLVED: 'resolved', CANCELLED: 'cancelled' },
|
||||
}))
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
apiBadRequest,
|
||||
} from '@/lib/api/helpers'
|
||||
import { ERROR_MESSAGES } from '@/config/error-messages'
|
||||
import { HELP_REQUEST_STATUS } from '@/config/help-request-status'
|
||||
import { HELP_REQUEST_STATUS } from '@/config/activity'
|
||||
import { validateResolveHelpRequest } from '@/lib/schemas/activity'
|
||||
import { getDbUserId } from '@/lib/api/task-helpers'
|
||||
|
||||
|
||||
@@ -137,14 +137,22 @@ export const POST = withAuth(async (request: NextRequest, session: ValidSession)
|
||||
cancelRedirectUrl: `${APP_URL}/marketplace/checkout/${listing.id}?error=cancelled`,
|
||||
});
|
||||
} catch (gatewayError) {
|
||||
// Rollback: delete order and restore listing to ACTIVE — independent, run in parallel
|
||||
// Rollback: delete order + restore listing to ACTIVE atomically.
|
||||
// Promise.all would leave the listing stuck in RESERVED if the update fails
|
||||
// after the delete succeeds (and vice versa).
|
||||
logger.error('Payrexx gateway creation failed, rolling back order', {
|
||||
error: gatewayError, orderId, listingId: listing.id,
|
||||
});
|
||||
await Promise.all([
|
||||
db.delete(marketplaceOrders).where(eq(marketplaceOrders.id, orderId)),
|
||||
db.update(listings).set({ status: LISTING_STATUS.ACTIVE }).where(eq(listings.id, listing.id)),
|
||||
]);
|
||||
try {
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.delete(marketplaceOrders).where(eq(marketplaceOrders.id, orderId));
|
||||
await tx.update(listings).set({ status: LISTING_STATUS.ACTIVE }).where(eq(listings.id, listing.id));
|
||||
});
|
||||
} catch (rollbackError) {
|
||||
logger.error('Order rollback failed — manual reconciliation required', {
|
||||
error: rollbackError, orderId, listingId: listing.id,
|
||||
});
|
||||
}
|
||||
return apiError(gatewayError, 'Zahlungsgateway konnte nicht erstellt werden. Bitte versuche es erneut.');
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { ERROR_MESSAGES } from '@/config/error-messages'
|
||||
import { db } from '@/db'
|
||||
import { subscriptionPools, poolMemberships } from '@/db/schema'
|
||||
import { eq, and, sql } from 'drizzle-orm'
|
||||
import { TABLE_NAMES, POOL_STATUS, POOL_MEMBERSHIP_STATUS } from '@/config/database'
|
||||
import { POOL_STATUS, POOL_MEMBERSHIP_STATUS } from '@/config/database'
|
||||
import { logger } from '@/lib/logger'
|
||||
|
||||
type Params = { id: string }
|
||||
@@ -23,65 +23,91 @@ export const POST = withAuth(async (
|
||||
const id = context?.params?.id
|
||||
if (!id) return apiBadRequest(ERROR_MESSAGES.POOL_ID_REQUIRED)
|
||||
|
||||
// Load pool
|
||||
const [pool] = await db
|
||||
.select({
|
||||
id: subscriptionPools.id,
|
||||
maxMembers: subscriptionPools.maxMembers,
|
||||
status: subscriptionPools.status,
|
||||
memberCount: sql<number>`(
|
||||
SELECT COUNT(*) FROM ${sql.raw(TABLE_NAMES.POOL_MEMBERSHIPS)} pm
|
||||
WHERE pm.pool_id = ${subscriptionPools.id}
|
||||
AND pm.status = ${POOL_MEMBERSHIP_STATUS.ACTIVE}
|
||||
)`,
|
||||
})
|
||||
.from(subscriptionPools)
|
||||
.where(eq(subscriptionPools.id, id))
|
||||
.limit(1)
|
||||
type JoinResult =
|
||||
| { kind: 'created'; membership: typeof poolMemberships.$inferSelect }
|
||||
| { kind: 'reactivated'; membership: typeof poolMemberships.$inferSelect }
|
||||
| { kind: 'error'; status: number; message: string }
|
||||
|
||||
if (!pool) return apiNotFound(ERROR_MESSAGES.POOL_NOT_FOUND)
|
||||
if (pool.status !== POOL_STATUS.ACTIVE) return apiBadRequest('Dieser Pool ist nicht aktiv')
|
||||
if (Number(pool.memberCount) >= pool.maxMembers) {
|
||||
return apiBadRequest('Dieser Pool ist bereits voll')
|
||||
}
|
||||
|
||||
// Check existing membership
|
||||
const [existing] = await db
|
||||
.select({ id: poolMemberships.id, status: poolMemberships.status })
|
||||
.from(poolMemberships)
|
||||
.where(
|
||||
and(
|
||||
eq(poolMemberships.poolId, id),
|
||||
eq(poolMemberships.userId, session.user.id)
|
||||
)
|
||||
// Lock pool row + count active members + check existing membership atomically.
|
||||
// Without this, two concurrent joins on a near-full pool can both pass the
|
||||
// capacity check and over-book the pool.
|
||||
const result: JoinResult = await db.transaction(async (tx) => {
|
||||
const lockedRows = await tx.execute(
|
||||
sql`SELECT id, max_members, status
|
||||
FROM ${subscriptionPools}
|
||||
WHERE id = ${id}
|
||||
FOR UPDATE`
|
||||
)
|
||||
.limit(1)
|
||||
const pool = lockedRows.rows[0] as
|
||||
| { id: string; max_members: number; status: string }
|
||||
| undefined
|
||||
|
||||
if (existing) {
|
||||
if (existing.status === POOL_MEMBERSHIP_STATUS.ACTIVE) {
|
||||
return apiBadRequest('Du bist bereits Mitglied dieses Pools')
|
||||
if (!pool) {
|
||||
return { kind: 'error', status: 404, message: ERROR_MESSAGES.POOL_NOT_FOUND }
|
||||
}
|
||||
// Re-activate if previously left
|
||||
const [updated] = await db
|
||||
.update(poolMemberships)
|
||||
.set({ status: POOL_MEMBERSHIP_STATUS.ACTIVE, leftAt: null })
|
||||
.where(eq(poolMemberships.id, existing.id))
|
||||
if (pool.status !== POOL_STATUS.ACTIVE) {
|
||||
return { kind: 'error', status: 400, message: 'Dieser Pool ist nicht aktiv' }
|
||||
}
|
||||
|
||||
const [countRow] = await tx
|
||||
.select({ count: sql<number>`COUNT(*)` })
|
||||
.from(poolMemberships)
|
||||
.where(
|
||||
and(
|
||||
eq(poolMemberships.poolId, id),
|
||||
eq(poolMemberships.status, POOL_MEMBERSHIP_STATUS.ACTIVE)
|
||||
)
|
||||
)
|
||||
|
||||
const memberCount = Number(countRow?.count ?? 0)
|
||||
if (memberCount >= pool.max_members) {
|
||||
return { kind: 'error', status: 400, message: 'Dieser Pool ist bereits voll' }
|
||||
}
|
||||
|
||||
const [existing] = await tx
|
||||
.select({ id: poolMemberships.id, status: poolMemberships.status })
|
||||
.from(poolMemberships)
|
||||
.where(
|
||||
and(
|
||||
eq(poolMemberships.poolId, id),
|
||||
eq(poolMemberships.userId, session.user.id)
|
||||
)
|
||||
)
|
||||
.limit(1)
|
||||
|
||||
if (existing) {
|
||||
if (existing.status === POOL_MEMBERSHIP_STATUS.ACTIVE) {
|
||||
return { kind: 'error', status: 400, message: 'Du bist bereits Mitglied dieses Pools' }
|
||||
}
|
||||
const [updated] = await tx
|
||||
.update(poolMemberships)
|
||||
.set({ status: POOL_MEMBERSHIP_STATUS.ACTIVE, leftAt: null })
|
||||
.where(eq(poolMemberships.id, existing.id))
|
||||
.returning()
|
||||
return { kind: 'reactivated', membership: updated }
|
||||
}
|
||||
|
||||
const [membership] = await tx
|
||||
.insert(poolMemberships)
|
||||
.values({
|
||||
poolId: id,
|
||||
userId: session.user.id,
|
||||
role: 'member',
|
||||
status: POOL_MEMBERSHIP_STATUS.ACTIVE,
|
||||
})
|
||||
.returning()
|
||||
return apiSuccess(updated)
|
||||
|
||||
return { kind: 'created', membership }
|
||||
})
|
||||
|
||||
if (result.kind === 'error') {
|
||||
return result.status === 404
|
||||
? apiNotFound(result.message)
|
||||
: apiBadRequest(result.message)
|
||||
}
|
||||
|
||||
const [membership] = await db
|
||||
.insert(poolMemberships)
|
||||
.values({
|
||||
poolId: id,
|
||||
userId: session.user.id,
|
||||
role: 'member',
|
||||
status: POOL_MEMBERSHIP_STATUS.ACTIVE,
|
||||
})
|
||||
.returning()
|
||||
|
||||
logger.info('User joined pool', { poolId: id, userId: session.user.id })
|
||||
return apiSuccess(membership, 201)
|
||||
logger.info('User joined pool', { poolId: id, userId: session.user.id, kind: result.kind })
|
||||
return apiSuccess(result.membership, result.kind === 'created' ? 201 : 200)
|
||||
} catch (error) {
|
||||
logger.error('POST /api/pools/[id]/join failed', { error })
|
||||
return apiError(error, 'Fehler beim Beitreten des Pools')
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { Phone, Mail } from 'lucide-react'
|
||||
import { CONTACT } from '@/config/org'
|
||||
import Heading from '@/components/ui/Heading'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import type { ProfileData } from '../hooks/useProfileData'
|
||||
@@ -53,7 +54,7 @@ export function ContactInfoSection({ profile, email, handleChange }: ContactInfo
|
||||
value={profile.phone}
|
||||
onChange={(e) => handleChange('phone', e.target.value)}
|
||||
className="w-full px-4 py-2.5 border border-neutral-300 dark:border-neutral-600 rounded-lg bg-white dark:bg-neutral-700 text-neutral-900 dark:text-white focus:ring-2 focus:ring-primary-500 focus:border-transparent"
|
||||
placeholder="+41 44 123 45 67 oder 044 123 45 67"
|
||||
placeholder={CONTACT.phonePlaceholderLandline}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
@@ -65,7 +66,7 @@ export function ContactInfoSection({ profile, email, handleChange }: ContactInfo
|
||||
value={profile.mobile}
|
||||
onChange={(e) => handleChange('mobile', e.target.value)}
|
||||
className="w-full px-4 py-2.5 border border-neutral-300 dark:border-neutral-600 rounded-lg bg-white dark:bg-neutral-700 text-neutral-900 dark:text-white focus:ring-2 focus:ring-primary-500 focus:border-transparent"
|
||||
placeholder="+41 79 123 45 67 oder 079 123 45 67"
|
||||
placeholder={CONTACT.phonePlaceholder}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { Phone } from 'lucide-react'
|
||||
import { CONTACT } from '@/config/org'
|
||||
import Heading from '@/components/admin/AdminHeading'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { FormField } from '@/components/ui/form-field'
|
||||
@@ -36,7 +37,7 @@ export function LocationContactSection({ formData, onFieldChange }: Props) {
|
||||
type="tel"
|
||||
value={formData.contact_phone}
|
||||
onChange={(e) => onFieldChange('contact_phone', e.target.value)}
|
||||
placeholder="+41 79 123 45 67"
|
||||
placeholder={CONTACT.phonePlaceholder}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
summarizeWeeklySchedule,
|
||||
type WeekdayId,
|
||||
} from '@/lib/team/schedule'
|
||||
import { CONTACT } from '@/config/org'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Select } from '@/components/ui/select'
|
||||
@@ -165,7 +166,7 @@ export function TeamAvailabilitySection({ form, onChange }: Props) {
|
||||
type="tel"
|
||||
value={form.phone}
|
||||
onChange={(e) => onChange('phone', e.target.value)}
|
||||
placeholder="+41 79 123 45 67"
|
||||
placeholder={CONTACT.phonePlaceholder}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
EMERGENCY_RELATION_LABELS,
|
||||
type EmergencyRelation,
|
||||
} from '@/config/team'
|
||||
import { CONTACT } from '@/config/org'
|
||||
import type { TeamProfileFormState } from './useTeamProfileForm'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Select } from '@/components/ui/select'
|
||||
@@ -34,7 +35,7 @@ export function TeamEmergencySection({ form, onChange }: Props) {
|
||||
id="emergency_contact_phone"
|
||||
value={form.emergency_contact_phone}
|
||||
onChange={(e) => onChange('emergency_contact_phone', e.target.value)}
|
||||
placeholder="+41 79 123 45 67"
|
||||
placeholder={CONTACT.phonePlaceholder}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
PAYMENT_DISPUTE_STATUS,
|
||||
ESCROW_STATUS,
|
||||
} from '../payment-status'
|
||||
import { HELP_REQUEST_STATUS } from '../help-request-status'
|
||||
import { HELP_REQUEST_STATUS } from '../activity'
|
||||
import { HELPER_STATUS, HELPER_STATUS_LABELS } from '../helper-status'
|
||||
|
||||
// ============================================================================
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
/**
|
||||
* @deprecated Import from '@/config/activity' instead.
|
||||
* This file is a compatibility shim — SSOT is activity.ts.
|
||||
*/
|
||||
export { HELP_REQUEST_STATUS, type HelpRequestStatus } from '@/config/activity'
|
||||
@@ -87,6 +87,9 @@ export const CONTACT = {
|
||||
phone: '+41 (0)43 960 32 64',
|
||||
/** Phone in tel: URI format */
|
||||
phoneTel: 'tel:+41439603264',
|
||||
/** Canonical placeholders for user phone input fields */
|
||||
phonePlaceholder: '+41 79 123 45 67',
|
||||
phonePlaceholderLandline: '+41 44 123 45 67',
|
||||
} as const
|
||||
|
||||
// ============================================================================
|
||||
|
||||
@@ -6,7 +6,17 @@
|
||||
'use client'
|
||||
|
||||
import { createContext, useContext, useState, useEffect, ReactNode } from 'react'
|
||||
import { SuggestionContextValue, PageInfo } from '@/features/feedback/types'
|
||||
|
||||
interface PageInfo {
|
||||
path: string
|
||||
title?: string
|
||||
url: string
|
||||
}
|
||||
|
||||
interface SuggestionContextValue {
|
||||
currentPage: PageInfo
|
||||
isVisible: boolean
|
||||
}
|
||||
|
||||
const SuggestionContext = createContext<SuggestionContextValue | undefined>(undefined)
|
||||
|
||||
|
||||
@@ -27,13 +27,16 @@ export function useTaskActions(taskId: string) {
|
||||
const [selectedUserId, setSelectedUserId] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
apiFetch<{ profiles: { user_id: string; name: string | null; email: string }[] }>(
|
||||
'/api/admin/team/profiles',
|
||||
).then((res) => {
|
||||
if (cancelled) return
|
||||
if (res.success && res.data?.profiles) {
|
||||
setStaffMembers(res.data.profiles.map((p) => ({ id: p.user_id, name: p.name, email: p.email })))
|
||||
}
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, [])
|
||||
|
||||
const handleComplete = async () => {
|
||||
|
||||
+1
-19
@@ -8,7 +8,7 @@
|
||||
import { auth } from '@/auth'
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { ROLES, type UserRole } from '@/lib/constants'
|
||||
import type { UserRole } from '@/lib/constants'
|
||||
import { logger } from '@/lib/logger'
|
||||
import { isStaffEmail } from '@/lib/permissions'
|
||||
|
||||
@@ -64,24 +64,6 @@ export async function requirePermission(permission: string) {
|
||||
return session.user
|
||||
}
|
||||
|
||||
/**
|
||||
* Require specific role (legacy)
|
||||
* @deprecated Use requirePermission instead
|
||||
*/
|
||||
export async function requireRole(role: UserRole) {
|
||||
const session = await auth()
|
||||
|
||||
if (!session?.user) {
|
||||
throw new Error('Authentication required')
|
||||
}
|
||||
|
||||
if (session.user.role !== role) {
|
||||
throw new Error(`Role required: ${role}`)
|
||||
}
|
||||
|
||||
return session.user
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin middleware - requires admin access
|
||||
*
|
||||
|
||||
Reference in new issue
Block a user