diff --git a/Dockerfile b/Dockerfile index 827091b..220f5d6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,7 +17,7 @@ FROM node:22-alpine AS run WORKDIR /app # ffmpeg wandelt die Kursvideos in HLS um RUN apk add --no-cache openssl ffmpeg && addgroup -S app && adduser -S app -G app -ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0 UPLOAD_DIR=/app/uploads VIDEO_DIR=/app/videos +ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0 UPLOAD_DIR=/app/uploads VIDEO_DIR=/app/videos LIVEKIT_KEY_FILE=/app/livekit/keys.yaml COPY --from=build /app/.next/standalone ./ COPY --from=build /app/.next/static ./.next/static COPY --from=build /app/public ./public @@ -26,7 +26,7 @@ COPY --from=build /app/src/lib/permissions.ts ./src/lib/permissions.ts COPY --from=build /app/src/lib/payments/catalog.ts ./src/lib/payments/catalog.ts COPY --from=deps /app/node_modules ./node_modules COPY docker/entrypoint.sh /entrypoint.sh -RUN mkdir -p /app/uploads /app/videos && chown -R app:app /app/uploads /app/videos && chmod +x /entrypoint.sh +RUN mkdir -p /app/uploads /app/videos /app/livekit && chown -R app:app /app/uploads /app/videos /app/livekit && chmod 700 /app/livekit && chmod +x /entrypoint.sh USER app EXPOSE 3000 ENTRYPOINT ["/entrypoint.sh"] diff --git a/docker-compose.yml b/docker-compose.yml index 23cf0b2..ae1b392 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -31,10 +31,26 @@ services: - uploads:/app/uploads # Kursvideos (umgewandelt und verschlüsselt), nie direkt erreichbar - videos:/app/videos + # Schlüssel für den Call-Server, teilt sich die App mit LiveKit + - livekit:/app/livekit ports: - "127.0.0.1:3000:3000" + # Call-Server für Beratungen (Video/Audio), selbst gehostet. Host-Netz wegen WebRTC; + # Signalisierung nur auf 127.0.0.1:7880 (davor Caddy), Medien über 7881/tcp und 7882/udp. + livekit: + image: livekit/livekit-server:v1.8.4 + restart: unless-stopped + network_mode: host + command: ["--config", "/etc/livekit.yaml", "--node-ip", "${PUBLIC_IP:-45.81.234.158}"] + volumes: + - ./docker/livekit.yaml:/etc/livekit.yaml:ro + - livekit:/keys:ro + depends_on: + - app + volumes: db: uploads: videos: + livekit: diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index f44a0ef..8fcda57 100644 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -1,5 +1,10 @@ #!/bin/sh set -e +# Schlüssel für den Call-Server (LiveKit) einmalig erzeugen; der LiveKit-Container liest dieselbe Datei +if [ -d /app/livekit ] && [ ! -s /app/livekit/keys.yaml ]; then + node -e "const c=require('crypto');require('fs').writeFileSync('/app/livekit/keys.yaml','sanamare: '+c.randomBytes(32).toString('hex')+'\n',{mode:0o600})" + echo "LiveKit-Schlüssel erzeugt" +fi echo "Datenbank-Migrationen …" npx prisma migrate deploy echo "Grunddaten …" diff --git a/docker/livekit.yaml b/docker/livekit.yaml new file mode 100644 index 0000000..f5b6cf0 --- /dev/null +++ b/docker/livekit.yaml @@ -0,0 +1,18 @@ +# LiveKit (Call-Server für Beratungen). Läuft im Host-Netz: +# - 7880: Signalisierung, nur lokal; von außen über Caddy (call.sanamare.de) +# - 7881/tcp und 7882/udp: Audio/Video, in der Firewall freigegeben +port: 7880 +bind_addresses: + - 127.0.0.1 +rtc: + tcp_port: 7881 + udp_port: 7882 + use_external_ip: false +# Schlüssel erzeugt der Shop beim Start (docker/entrypoint.sh) +key_file: /keys/keys.yaml +room: + # Nur Kundin und Beraterin; leere Räume schließen nach 5 Minuten + max_participants: 2 + empty_timeout: 300 +logging: + level: info diff --git a/package-lock.json b/package-lock.json index 36ecf9c..4018b4f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,6 +13,7 @@ "@prisma/client": "6.19.3", "bcryptjs": "3.0.3", "hls.js": "1.7.3", + "livekit-client": "2.23.0", "next": "15.5.28", "react": "19.1.10", "react-dom": "19.1.10", @@ -28,6 +29,12 @@ "typescript": "5.9.3" } }, + "node_modules/@bufbuild/protobuf": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-1.10.1.tgz", + "integrity": "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==", + "license": "(Apache-2.0 AND BSD-3-Clause)" + }, "node_modules/@emnapi/runtime": { "version": "1.11.3", "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", @@ -999,6 +1006,21 @@ "url": "https://opencollective.com/libvips" } }, + "node_modules/@livekit/mutex": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@livekit/mutex/-/mutex-1.1.1.tgz", + "integrity": "sha512-EsshAucklmpuUAfkABPxJNhzj9v2sG7JuzFDL4ML1oJQSV14sqrpTYnsaOudMAw9yOaW53NU3QQTlUQoRs4czw==", + "license": "Apache-2.0" + }, + "node_modules/@livekit/protocol": { + "version": "1.52.1", + "resolved": "https://registry.npmjs.org/@livekit/protocol/-/protocol-1.52.1.tgz", + "integrity": "sha512-X8DxKlNbzk6Lh+v630+mjdFHSotdAFwIyzxSRSUql2DbTxCnlpa7JsvFGc6Na3mXiex2OFh0iiQtWwOBP0rIYA==", + "license": "Apache-2.0", + "dependencies": { + "@bufbuild/protobuf": "^1.10.0" + } + }, "node_modules/@next/env": { "version": "15.5.28", "resolved": "https://registry.npmjs.org/@next/env/-/env-15.5.28.tgz", @@ -1234,6 +1256,13 @@ "tslib": "^2.8.0" } }, + "node_modules/@types/dom-mediacapture-record": { + "version": "1.0.22", + "resolved": "https://registry.npmjs.org/@types/dom-mediacapture-record/-/dom-mediacapture-record-1.0.22.tgz", + "integrity": "sha512-mUMZLK3NvwRLcAAT9qmcK+9p7tpU2FHdDsntR3YI4+GY88XrgG4XiE7u1Q2LAN2/FZOz/tdMDC3GQCR4T8nFuw==", + "license": "MIT", + "peer": true + }, "node_modules/@types/node": { "version": "22.20.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", @@ -1488,6 +1517,15 @@ "@esbuild/win32-x64": "0.25.12" } }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, "node_modules/exsolve": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.1.3.tgz", @@ -1580,6 +1618,58 @@ "jiti": "lib/jiti-cli.mjs" } }, + "node_modules/jose": { + "version": "6.2.13", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.13.tgz", + "integrity": "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/livekit-client": { + "version": "2.23.0", + "resolved": "https://registry.npmjs.org/livekit-client/-/livekit-client-2.23.0.tgz", + "integrity": "sha512-j9Kg86nJjBjNFUD+ukp2jwMCGa0k+YD5gU//RzAM+ZY3pbG631QCte7fQjwqWMmtBzhDJL9nKYuOLMv/9IbAxg==", + "license": "Apache-2.0", + "dependencies": { + "@livekit/mutex": "1.1.1", + "@livekit/protocol": "1.52.1", + "events": "^3.3.0", + "jose": "^6.1.0", + "loglevel": "^1.9.2", + "machina": "^7.0.0", + "sdp-transform": "^2.15.0", + "tslib": "2.8.1", + "typed-emitter": "^2.1.0", + "webrtc-adapter": "9.0.6" + }, + "peerDependencies": { + "@types/dom-mediacapture-record": "^1" + } + }, + "node_modules/loglevel": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.9.2.tgz", + "integrity": "sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==", + "license": "MIT", + "engines": { + "node": ">= 0.6.0" + }, + "funding": { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/loglevel" + } + }, + "node_modules/machina": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/machina/-/machina-7.0.1.tgz", + "integrity": "sha512-0Xkgs8NeBvO2hW6bjJT8ewLWrMfh1haMPstaghpASWjXkLjRhtDiaJG1Kb7mslaOHxZYxpH7PIjpmirRVYbMMA==", + "license": "MIT", + "engines": { + "node": ">=22.22" + } + }, "node_modules/nanoid": { "version": "3.3.20", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", @@ -1855,12 +1945,37 @@ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" } }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "tslib": "^2.1.0" + } + }, "node_modules/scheduler": { "version": "0.26.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz", "integrity": "sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA==", "license": "MIT" }, + "node_modules/sdp": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/sdp/-/sdp-3.2.2.tgz", + "integrity": "sha512-xZocWwfyp4hkbN4hLWxMjmv2Q8aNa9MhmOZ7L9aCZPT+dZsgRr6wZRrSYE3HTdyk/2pZKPSgqI7ns7Een1xMSA==", + "license": "MIT" + }, + "node_modules/sdp-transform": { + "version": "2.15.0", + "resolved": "https://registry.npmjs.org/sdp-transform/-/sdp-transform-2.15.0.tgz", + "integrity": "sha512-KrOH82c/W+GYQ0LHqtr3caRpM3ITglq3ljGUIb8LTki7ByacJZ9z+piSGiwZDsRyhQbYBOBJgr2k6X4BZXi3Kw==", + "license": "MIT", + "bin": { + "sdp-verify": "checker.js" + } + }, "node_modules/semver": { "version": "7.8.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", @@ -1998,6 +2113,15 @@ "fsevents": "~2.3.3" } }, + "node_modules/typed-emitter": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/typed-emitter/-/typed-emitter-2.1.0.tgz", + "integrity": "sha512-g/KzbYKbH5C2vPkaXGu8DJlHrGKHLsM25Zg9WuC9pMGfuvT+X25tZQWo5fK1BjBm8+UrVE9LDCvaY0CQk+fXDA==", + "license": "MIT", + "optionalDependencies": { + "rxjs": "*" + } + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -2019,6 +2143,19 @@ "dev": true, "license": "MIT" }, + "node_modules/webrtc-adapter": { + "version": "9.0.6", + "resolved": "https://registry.npmjs.org/webrtc-adapter/-/webrtc-adapter-9.0.6.tgz", + "integrity": "sha512-CHbl2ZQbxx164IgWRgzJno4hWtM4tFbRam1QfI3Yxhs3w/DvqluVxVWeXs3oL5/fbGkSNLKo0Ty5MgUWceNhog==", + "license": "BSD-3-Clause", + "dependencies": { + "sdp": "^3.2.0" + }, + "engines": { + "node": ">=6.0.0", + "npm": ">=3.10.0" + } + }, "node_modules/zod": { "version": "4.6.7", "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", diff --git a/package.json b/package.json index ee3f800..5e83536 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "@prisma/client": "6.19.3", "bcryptjs": "3.0.3", "hls.js": "1.7.3", + "livekit-client": "2.23.0", "next": "15.5.28", "react": "19.1.10", "react-dom": "19.1.10", diff --git a/prisma/migrations/20261021080000_consulting/migration.sql b/prisma/migrations/20261021080000_consulting/migration.sql new file mode 100644 index 0000000..87fe9ac --- /dev/null +++ b/prisma/migrations/20261021080000_consulting/migration.sql @@ -0,0 +1,160 @@ +-- CreateTable +CREATE TABLE "Advisor" ( + "id" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "slug" TEXT NOT NULL, + "displayName" TEXT NOT NULL, + "tagline" TEXT NOT NULL DEFAULT '', + "bio" TEXT NOT NULL DEFAULT '', + "photo" TEXT NOT NULL DEFAULT '', + "topics" TEXT[], + "methods" TEXT[], + "languages" TEXT[], + "status" TEXT NOT NULL DEFAULT 'draft', + "commission" INTEGER NOT NULL DEFAULT 0, + "minNoticeHours" INTEGER NOT NULL DEFAULT 12, + "maxDaysAhead" INTEGER NOT NULL DEFAULT 60, + "maxPerDay" INTEGER NOT NULL DEFAULT 0, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Advisor_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "AdvisorOffer" ( + "id" TEXT NOT NULL, + "advisorId" TEXT NOT NULL, + "name" TEXT NOT NULL, + "description" TEXT NOT NULL DEFAULT '', + "duration" INTEGER NOT NULL, + "price" INTEGER NOT NULL, + "mode" TEXT NOT NULL DEFAULT 'both', + "buffer" INTEGER NOT NULL DEFAULT 10, + "active" BOOLEAN NOT NULL DEFAULT true, + "approved" BOOLEAN NOT NULL DEFAULT false, + "sort" INTEGER NOT NULL DEFAULT 0, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "AdvisorOffer_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "AvailabilityRule" ( + "id" TEXT NOT NULL, + "advisorId" TEXT NOT NULL, + "weekday" INTEGER NOT NULL, + "start" INTEGER NOT NULL, + "end" INTEGER NOT NULL, + + CONSTRAINT "AvailabilityRule_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "AvailabilityException" ( + "id" TEXT NOT NULL, + "advisorId" TEXT NOT NULL, + "date" TEXT NOT NULL, + "kind" TEXT NOT NULL, + "start" INTEGER, + "end" INTEGER, + "note" TEXT NOT NULL DEFAULT '', + + CONSTRAINT "AvailabilityException_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Appointment" ( + "id" TEXT NOT NULL, + "number" TEXT NOT NULL, + "customerId" TEXT NOT NULL, + "advisorId" TEXT NOT NULL, + "offerId" TEXT, + "offerName" TEXT NOT NULL, + "duration" INTEGER NOT NULL, + "price" INTEGER NOT NULL, + "mode" TEXT NOT NULL, + "startsAt" TIMESTAMP(3) NOT NULL, + "endsAt" TIMESTAMP(3) NOT NULL, + "status" TEXT NOT NULL DEFAULT 'requested', + "concern" TEXT NOT NULL DEFAULT '', + "advisorMessage" TEXT NOT NULL DEFAULT '', + "advisorNote" TEXT NOT NULL DEFAULT '', + "expiresAt" TIMESTAMP(3), + "orderId" TEXT, + "roomName" TEXT NOT NULL, + "cancelledBy" TEXT NOT NULL DEFAULT '', + "cancelReason" TEXT NOT NULL DEFAULT '', + "reminded24" BOOLEAN NOT NULL DEFAULT false, + "reminded1" BOOLEAN NOT NULL DEFAULT false, + "consentAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Appointment_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "AppointmentProposal" ( + "id" TEXT NOT NULL, + "appointmentId" TEXT NOT NULL, + "startsAt" TIMESTAMP(3) NOT NULL, + "endsAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "AppointmentProposal_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "Advisor_userId_key" ON "Advisor"("userId"); + +-- CreateIndex +CREATE UNIQUE INDEX "Advisor_slug_key" ON "Advisor"("slug"); + +-- CreateIndex +CREATE INDEX "AvailabilityException_advisorId_date_idx" ON "AvailabilityException"("advisorId", "date"); + +-- CreateIndex +CREATE UNIQUE INDEX "Appointment_number_key" ON "Appointment"("number"); + +-- CreateIndex +CREATE UNIQUE INDEX "Appointment_orderId_key" ON "Appointment"("orderId"); + +-- CreateIndex +CREATE UNIQUE INDEX "Appointment_roomName_key" ON "Appointment"("roomName"); + +-- CreateIndex +CREATE INDEX "Appointment_advisorId_startsAt_idx" ON "Appointment"("advisorId", "startsAt"); + +-- CreateIndex +CREATE INDEX "Appointment_customerId_idx" ON "Appointment"("customerId"); + +-- CreateIndex +CREATE INDEX "Appointment_status_expiresAt_idx" ON "Appointment"("status", "expiresAt"); + +-- AddForeignKey +ALTER TABLE "Advisor" ADD CONSTRAINT "Advisor_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "AdvisorOffer" ADD CONSTRAINT "AdvisorOffer_advisorId_fkey" FOREIGN KEY ("advisorId") REFERENCES "Advisor"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "AvailabilityRule" ADD CONSTRAINT "AvailabilityRule_advisorId_fkey" FOREIGN KEY ("advisorId") REFERENCES "Advisor"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "AvailabilityException" ADD CONSTRAINT "AvailabilityException_advisorId_fkey" FOREIGN KEY ("advisorId") REFERENCES "Advisor"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Appointment" ADD CONSTRAINT "Appointment_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Appointment" ADD CONSTRAINT "Appointment_advisorId_fkey" FOREIGN KEY ("advisorId") REFERENCES "Advisor"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Appointment" ADD CONSTRAINT "Appointment_offerId_fkey" FOREIGN KEY ("offerId") REFERENCES "AdvisorOffer"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Appointment" ADD CONSTRAINT "Appointment_orderId_fkey" FOREIGN KEY ("orderId") REFERENCES "Order"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "AppointmentProposal" ADD CONSTRAINT "AppointmentProposal_appointmentId_fkey" FOREIGN KEY ("appointmentId") REFERENCES "Appointment"("id") ON DELETE CASCADE ON UPDATE CASCADE; + diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 3f0e840..8a0c5d4 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -42,6 +42,8 @@ model User { addresses Address[] courseAccess CourseAccess[] progress LessonProgress[] + advisor Advisor? + appointments Appointment[] @relation("CustomerAppointments") createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } @@ -282,6 +284,7 @@ model Order { events OrderEvent[] invoices Invoice[] courseAccess CourseAccess[] + appointment Appointment? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } @@ -514,3 +517,132 @@ model NewsletterRecipient { @@unique([campaignId, email]) @@index([campaignId, status]) } + +// ---------- Beratung (Kartenlegen) ---------- + +// Profil einer Beraterin. Gehört zu einem Team-Zugang mit der Rolle „Beraterin“. +model Advisor { + id String @id @default(cuid()) + userId String @unique + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + slug String @unique + displayName String + tagline String @default("") + bio String @default("") + photo String @default("") + topics String[] + methods String[] + languages String[] + // "draft" (in Arbeit), "pending" (wartet auf Freigabe), "approved" (online), "paused" + status String @default("draft") + // Provision des Shops in Prozent + commission Int @default(0) + // Buchungsregeln + minNoticeHours Int @default(12) + maxDaysAhead Int @default(60) + maxPerDay Int @default(0) + offers AdvisorOffer[] + rules AvailabilityRule[] + exceptions AvailabilityException[] + appointments Appointment[] + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt +} + +model AdvisorOffer { + id String @id @default(cuid()) + advisorId String + advisor Advisor @relation(fields: [advisorId], references: [id], onDelete: Cascade) + name String + description String @default("") + // Minuten + duration Int + // Cent, brutto + price Int + // "video", "audio" oder "both" + mode String @default("both") + // Pause danach in Minuten + buffer Int @default(10) + active Boolean @default(true) + // Neue oder geänderte Angebote gibt der Inhaber frei + approved Boolean @default(false) + sort Int @default(0) + appointments Appointment[] + createdAt DateTime @default(now()) +} + +// Wochenplan: Wochentag 1 = Montag … 7 = Sonntag, Zeiten in Minuten ab Mitternacht (deutsche Zeit) +model AvailabilityRule { + id String @id @default(cuid()) + advisorId String + advisor Advisor @relation(fields: [advisorId], references: [id], onDelete: Cascade) + weekday Int + start Int + end Int +} + +// Ausnahmen an einem Tag (YYYY-MM-DD, deutsche Zeit): "off" = frei (ganzer Tag oder Zeitraum), "extra" = zusätzliche Zeit +model AvailabilityException { + id String @id @default(cuid()) + advisorId String + advisor Advisor @relation(fields: [advisorId], references: [id], onDelete: Cascade) + date String + kind String + start Int? + end Int? + note String @default("") + + @@index([advisorId, date]) +} + +model Appointment { + id String @id @default(cuid()) + number String @unique + customerId String + customer User @relation("CustomerAppointments", fields: [customerId], references: [id], onDelete: Cascade) + advisorId String + advisor Advisor @relation(fields: [advisorId], references: [id], onDelete: Restrict) + offerId String? + offer AdvisorOffer? @relation(fields: [offerId], references: [id], onDelete: SetNull) + // Kopie der Angebotsdaten zum Zeitpunkt der Anfrage + offerName String + duration Int + price Int + // "video" oder "audio" + mode String + startsAt DateTime + endsAt DateTime + // requested, proposed, confirmed (wartet auf Zahlung), booked, done, declined, expired, cancelled, noshow + status String @default("requested") + concern String @default("") + // Nachricht der Beraterin bei Absage oder Gegenvorschlag + advisorMessage String @default("") + // Private Notiz der Beraterin + advisorNote String @default("") + // Frist der Anfrage (48 h) bzw. der Zahlung (24 h) + expiresAt DateTime? + orderId String? @unique + order Order? @relation(fields: [orderId], references: [id], onDelete: SetNull) + roomName String @unique + cancelledBy String @default("") + cancelReason String @default("") + reminded24 Boolean @default(false) + reminded1 Boolean @default(false) + // Zustimmung zur vorzeitigen Leistung (Widerruf) beim Bezahlen + consentAt DateTime? + proposals AppointmentProposal[] + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([advisorId, startsAt]) + @@index([customerId]) + @@index([status, expiresAt]) +} + +model AppointmentProposal { + id String @id @default(cuid()) + appointmentId String + appointment Appointment @relation(fields: [appointmentId], references: [id], onDelete: Cascade) + startsAt DateTime + endsAt DateTime +} diff --git a/prisma/seed.ts b/prisma/seed.ts index 808f649..88a9f40 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -26,6 +26,16 @@ async function main() { create: { name: "Versand", description: "Sieht Bestellungen und trägt Versand und Sendungsnummern ein.", permissions: ["dashboard.view", "orders.view", "orders.edit", "products.view", "stock.edit"] }, update: {}, }); + await db.role.upsert({ + where: { name: "Beraterin" }, + create: { name: "Beraterin", description: "Kartenlegerin: pflegt eigenes Profil, Angebote und Zeiten und sieht nur die eigenen Termine.", permissions: ["consulting.own"] }, + update: {}, + }); + await db.role.upsert({ + where: { name: "Esoterik-Leitung" }, + create: { name: "Esoterik-Leitung", description: "Verwaltet alle Beraterinnen und Termine und gibt Profile frei.", permissions: ["dashboard.view", "consulting.own", "consulting.manage", "orders.view"] }, + update: {}, + }); await db.role.upsert({ where: { name: "Redaktion" }, create: { name: "Redaktion", description: "Pflegt Produkttexte, Seiten und die Startseite.", permissions: ["dashboard.view", "products.view", "products.edit", "content.edit", "appearance.edit"] }, diff --git a/src/app/(shop)/beratung/[slug]/page.tsx b/src/app/(shop)/beratung/[slug]/page.tsx new file mode 100644 index 0000000..f25e352 --- /dev/null +++ b/src/app/(shop)/beratung/[slug]/page.tsx @@ -0,0 +1,81 @@ +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { db } from "@/lib/db"; +import { can, getCurrentUser } from "@/lib/auth"; +import { NOTICE, freeSlots, getConsultingSettings } from "@/lib/consulting"; +import { Icon } from "@/components/Icon"; +import { Alert } from "@/components/shop/Blocks"; +import { BookingForm } from "@/components/shop/BookingForm"; + +export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) { + const a = await db.advisor.findUnique({ where: { slug: (await params).slug } }); + return { title: a ? `${a.displayName} · Kartenlegen` : "Beratung", description: a?.tagline }; +} + +export default async function AdvisorPage({ params }: { params: Promise<{ slug: string }> }) { + const { slug } = await params; + const [user, settings] = await Promise.all([getCurrentUser(), getConsultingSettings()]); + const a = await db.advisor.findUnique({ + where: { slug }, + include: { offers: { where: { active: true, approved: true }, orderBy: [{ sort: "asc" }, { price: "asc" }] }, rules: true, exceptions: true }, + }); + // Nicht freigegebene Profile sieht nur das Team (zur Vorschau) und die Beraterin selbst + const preview = a && a.status !== "approved" && (a.userId === user?.id || can(user, "consulting.manage")); + if (!a || (a.status !== "approved" && !preview)) notFound(); + const slots: Record = {}; + for (const o of a.offers) { + const map = await freeSlots(a, o, { days: 35 }); + slots[o.id] = [...map.entries()].map(([date, list]) => ({ date, slots: list.map((d) => d.toISOString()) })); + } + return ( +
+ + {preview &&
} +
+
+
+ {a.photo ? ( + // eslint-disable-next-line @next/next/no-img-element + + ) : ( + + )} +
+

{a.displayName}

+ {a.tagline &&

{a.tagline}

} +
+
+
{[...a.topics, ...a.methods].map((t) => {t})}
+ {a.languages.length > 0 &&

Sprachen: {a.languages.join(", ")}

} + {a.bio &&
{a.bio}
} +

{NOTICE}

+
+ So läuft es ab +
+ Du fragst einen Wunschtermin an, das ist kostenlos. {a.displayName} bestätigt ihn oder schlägt andere Zeiten vor. Erst dann bezahlst du, und der Termin ist fest. Zur Legung öffnest du 10 Minuten vorher unter „Meine Termine“ den Raum, direkt im Browser mit Kamera und Mikrofon (oder nur Mikrofon). Es wird nichts aufgezeichnet. Bis {settings.refundHours} Stunden vorher kannst du kostenlos absagen. +
+
+
+ +
+
+ ); +} diff --git a/src/app/(shop)/beratung/actions.ts b/src/app/(shop)/beratung/actions.ts new file mode 100644 index 0000000..1672795 --- /dev/null +++ b/src/app/(shop)/beratung/actions.ts @@ -0,0 +1,163 @@ +"use server"; +import { cookies } from "next/headers"; +import { redirect } from "next/navigation"; +import { revalidatePath } from "next/cache"; +import { db } from "@/lib/db"; +import { getCurrentUser } from "@/lib/auth"; +import { requestOrigin } from "@/lib/social/config"; +import { nextOrderNumber, type AddressData } from "@/lib/checkout"; +import { availablePayments } from "@/lib/checkout"; +import { getDefinition } from "@/lib/payments/catalog"; +import { getCredentials } from "@/lib/payments/credentials"; +import { createCheckoutSession } from "@/lib/payments/stripe"; +import { createPaypalOrder } from "@/lib/payments/paypal"; +import { autoInvoice } from "@/lib/invoices"; +import { mailOrderPlaced, sendLater } from "@/lib/mail/send"; +import { cancelOrderById } from "@/lib/order-cancel"; +import { getSettings } from "@/lib/settings"; +import { acceptProposal, cancelAppointment, createRequest, fmtDateTime, getConsultingSettings } from "@/lib/consulting"; + +export type FormState = { errors?: Record; message?: string } | null; + +const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim(); + +/** Kundin fragt einen Termin an. */ +export async function requestAppointment(_prev: FormState, fd: FormData): Promise { + const user = await getCurrentUser(); + if (!user) return { message: "Bitte melde dich zuerst an." }; + const errors: Record = {}; + const start = new Date(str(fd, "start")); + if (Number.isNaN(start.getTime())) errors.start = "Bitte wähle einen Termin."; + const mode = str(fd, "mode") === "audio" ? "audio" : "video"; + if (fd.get("adult") !== "on") errors.adult = "Die Beratung ist erst ab 18 Jahren möglich."; + if (fd.get("notice") !== "on") errors.notice = "Bitte bestätige den Hinweis."; + const firstName = str(fd, "firstName"); + if (!firstName) errors.firstName = "Bitte gib deinen Vornamen an."; + const phone = str(fd, "phone"); + if (phone.length < 5) errors.phone = "Bitte gib eine Telefonnummer für Rückfragen an."; + if (Object.keys(errors).length) return { errors, message: "Bitte prüfe die markierten Felder." }; + // Name und Telefon im Konto ergänzen, damit Mails und Rechnung passen + if (firstName !== user.firstName || phone !== user.phone) await db.user.update({ where: { id: user.id }, data: { firstName, phone, ...(str(fd, "lastName") ? { lastName: str(fd, "lastName") } : {}) } }); + const r = await createRequest({ user: { ...user, firstName }, advisorId: str(fd, "advisorId"), offerId: str(fd, "offerId"), start, mode, concern: str(fd, "concern") }); + if (!r.ok) return { message: r.error }; + revalidatePath("/konto/termine"); + redirect(`/konto/termine?angefragt=${r.appointment.number}`); +} + +export async function chooseProposal(fd: FormData) { + const user = await getCurrentUser(); + if (!user) redirect("/konto/anmelden?weiter=/konto/termine"); + const r = await acceptProposal(str(fd, "id"), str(fd, "proposalId"), user.id); + revalidatePath("/konto/termine"); + redirect(r.ok ? `/beratung/bezahlen/${str(fd, "id")}` : "/konto/termine?fehler=vorschlag"); +} + +export async function cancelByCustomer(fd: FormData) { + const user = await getCurrentUser(); + if (!user) redirect("/konto/anmelden?weiter=/konto/termine"); + const a = await db.appointment.findFirst({ where: { id: str(fd, "id"), customerId: user.id } }); + if (a) await cancelAppointment(a.id, "customer", str(fd, "reason")); + revalidatePath("/konto/termine"); + redirect("/konto/termine?abgesagt=1"); +} + +/** Bezahlen eines bestätigten Termins: Bestellung mit einer Beratungs-Position anlegen und zur Zahlung. */ +export async function payAppointment(_prev: FormState, fd: FormData): Promise { + const user = await getCurrentUser(); + if (!user) return { message: "Bitte melde dich erneut an." }; + const a = await db.appointment.findFirst({ where: { id: str(fd, "id"), customerId: user.id }, include: { advisor: true, order: true } }); + if (!a || a.status !== "confirmed" || (a.expiresAt && a.expiresAt < new Date())) return { message: "Dieser Termin kann nicht mehr bezahlt werden." }; + const errors: Record = {}; + const shop = await getSettings(); + if (shop.checkout.requireTerms && fd.get("terms") !== "on") errors.terms = "Bitte bestätige die AGB und die Widerrufsbelehrung."; + const withinWithdrawal = a.startsAt.getTime() - Date.now() < 14 * 86400e3; + if (withinWithdrawal && fd.get("consent") !== "on") errors.consent = "Bitte bestätige die Zustimmung zum vorzeitigen Beginn."; + const address: AddressData = { + firstName: str(fd, "firstName"), + lastName: str(fd, "lastName"), + company: str(fd, "company"), + street: str(fd, "street"), + extra: "", + zip: str(fd, "zip"), + city: str(fd, "city"), + country: str(fd, "country") || "DE", + }; + if (!address.firstName) errors.firstName = "Bitte eintragen"; + if (!address.lastName) errors.lastName = "Bitte eintragen"; + if (address.street.length < 3) errors.street = "Bitte eintragen"; + if (!/^[0-9A-Za-z -]{4,10}$/.test(address.zip)) errors.zip = "Bitte prüfen"; + if (address.city.length < 2) errors.city = "Bitte eintragen"; + // Zahlart: nur, was für Beratungen erlaubt ist + const s = await getConsultingSettings(); + const daysAhead = (a.startsAt.getTime() - Date.now()) / 86400e3; + const methods = (await availablePayments(a.price, true)).filter((m) => { + const p = getDefinition(m.code)?.provider; + return p === "stripe" || p === "paypal" || (s.allowManualPayments && daysAhead > s.manualMinDays && m.code !== "cod"); + }); + const payment = methods.find((m) => m.id === str(fd, "paymentMethodId")); + if (!payment) errors.paymentMethodId = "Bitte wähle eine Zahlungsart."; + if (Object.keys(errors).length) return { errors, message: "Bitte prüfe die markierten Felder." }; + + // Eine frühere, nicht abgeschlossene Zahlung ersetzen + if (a.order && a.order.status === "PENDING" && a.order.paymentStatus === "OPEN") await cancelOrderById(a.order.id, "System", { mail: false }); + + const total = a.price + (payment!.fee ?? 0); + const tax = Math.round(total - total / 1.19); + const label = `Beratung: ${a.offerName} mit ${a.advisor.displayName}, ${fmtDateTime(a.startsAt)} (${a.duration} Min., ${a.mode === "audio" ? "Audio" : "Video"})`; + const order = await db.$transaction(async (tx) => + tx.order.create({ + data: { + number: await nextOrderNumber(tx), + userId: user.id, + email: user.email, + phone: user.phone, + paymentMethod: payment!.code, + shippingMethod: "Online-Beratung (kein Versand)", + shippingAddress: address, + subtotal: a.price, + shippingCost: 0, + paymentFee: payment!.fee ?? 0, + taxAmount: tax, + total, + items: { create: [{ name: label, sku: a.number, unitPrice: a.price, quantity: 1, taxRate: 19, total: a.price }] }, + events: { + create: [ + { message: `Beratung ${a.number} zur Zahlung, Zahlungsart: ${payment!.name}` }, + ...(withinWithdrawal ? [{ message: "Kundin hat zugestimmt, dass die Beratung vor Ablauf der Widerrufsfrist erbracht wird, und bestätigt, dass ihr Widerrufsrecht mit vollständiger Erbringung erlischt.", author: "System" }] : []), + ], + }, + }, + }), + ); + await db.appointment.update({ where: { id: a.id }, data: { orderId: order.id, consentAt: withinWithdrawal ? new Date() : null } }); + await autoInvoice(order.id, "order"); + (await cookies()).set("sm_last_order", order.id, { httpOnly: true, sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * 30 }); + + const def = getDefinition(payment!.code); + const appUrl = await requestOrigin(); + const back = `/beratung/bezahlen/${a.id}?abgebrochen=1`; + let target: string; + try { + if (def?.provider === "stripe") { + const creds = await getCredentials(); + const session = await createCheckoutSession({ secretKey: creds.stripe.secretKey, order, stripeType: def.stripeType!, appUrl, cancelPath: back }); + await db.order.update({ where: { id: order.id }, data: { paymentRef: session.id } }); + target = session.url; + } else if (def?.provider === "paypal") { + const creds = await getCredentials(); + const pp = await createPaypalOrder(creds.paypal, order, appUrl, back); + await db.order.update({ where: { id: order.id }, data: { paymentRef: pp.id } }); + target = pp.url; + } else { + // Vorkasse/Rechnung: Termin bleibt bestätigt, bis das Geld da ist und im Admin als bezahlt markiert wird + // Frist für die Überweisung: bis 2 Tage vor dem Termin + await db.appointment.update({ where: { id: a.id }, data: { expiresAt: new Date(a.startsAt.getTime() - 2 * 86400e3) } }); + sendLater(() => mailOrderPlaced(order.id, "placed")); + target = `/konto/termine?zahlung=${a.number}`; + } + } catch (e) { + await db.orderEvent.create({ data: { orderId: order.id, message: `Zahlung konnte nicht gestartet werden: ${e instanceof Error ? e.message : e}` } }); + return { message: "Die Zahlung konnte nicht gestartet werden. Bitte wähle eine andere Zahlungsart oder versuche es gleich noch einmal." }; + } + redirect(target); +} diff --git a/src/app/(shop)/beratung/bezahlen/[id]/page.tsx b/src/app/(shop)/beratung/bezahlen/[id]/page.tsx new file mode 100644 index 0000000..efaf3fb --- /dev/null +++ b/src/app/(shop)/beratung/bezahlen/[id]/page.tsx @@ -0,0 +1,65 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { db } from "@/lib/db"; +import { getCurrentUser } from "@/lib/auth"; +import { formatPrice } from "@/lib/money"; +import { availablePayments } from "@/lib/checkout"; +import { getDefinition } from "@/lib/payments/catalog"; +import { COUNTRIES, getSettings } from "@/lib/settings"; +import { fmtDateTime, getConsultingSettings } from "@/lib/consulting"; +import { Alert } from "@/components/shop/Blocks"; +import { AppointmentPayForm } from "@/components/shop/AppointmentPayForm"; + +export const metadata = { title: "Beratung bezahlen", robots: { index: false } }; + +export default async function PayAppointmentPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ abgebrochen?: string }> }) { + const [{ id }, { abgebrochen }, user] = await Promise.all([params, searchParams, getCurrentUser()]); + if (!user) redirect(`/konto/anmelden?weiter=/beratung/bezahlen/${id}`); + const a = await db.appointment.findFirst({ where: { id, customerId: user.id }, include: { advisor: true } }); + if (!a) notFound(); + if (a.status === "booked") redirect(`/konto/termine?bezahlt=${a.number}`); + const open = a.status === "confirmed" && (!a.expiresAt || a.expiresAt > new Date()); + const [shop, s, saved] = await Promise.all([getSettings(), getConsultingSettings(), db.address.findFirst({ where: { userId: user.id }, orderBy: { isDefault: "desc" } })]); + const daysAhead = (a.startsAt.getTime() - Date.now()) / 86400e3; + const methods = (await availablePayments(a.price, true)).filter((m) => { + const p = getDefinition(m.code)?.provider; + return p === "stripe" || p === "paypal" || (s.allowManualPayments && daysAhead > s.manualMinDays && m.code !== "cod"); + }); + return ( +
+
+
+ Termin {a.number} +

Beratung bezahlen

+ {abgebrochen &&
Es wurde nichts abgebucht. Versuch es gern noch einmal.
} + {!open ? ( + Die Frist ist abgelaufen oder der Termin wurde abgesagt. Zu meinen Terminen + ) : ( + <> + {a.expiresAt &&

Bitte bezahle bis {fmtDateTime(a.expiresAt)}, sonst wird der Termin wieder frei.

} + ({ id: m.id, name: m.name, description: m.description, fee: m.fee }))} + address={saved ?? { firstName: user.firstName, lastName: user.lastName }} + countries={Object.entries(COUNTRIES)} + requireTerms={shop.checkout.requireTerms} + withinWithdrawal={a.startsAt.getTime() - Date.now() < 14 * 86400e3} + total={a.price + (methods[0]?.fee ?? 0)} + /> + + )} +
+ +
+
+ ); +} diff --git a/src/app/(shop)/beratung/page.tsx b/src/app/(shop)/beratung/page.tsx new file mode 100644 index 0000000..b6575c3 --- /dev/null +++ b/src/app/(shop)/beratung/page.tsx @@ -0,0 +1,99 @@ +import Link from "next/link"; +import { db } from "@/lib/db"; +import { formatPrice } from "@/lib/money"; +import { NOTICE, PUBLIC_ADVISOR, fmtDateTime, freeSlots, getConsultingSettings } from "@/lib/consulting"; +import { Icon } from "@/components/Icon"; + +export async function generateMetadata() { + const s = await getConsultingSettings(); + return { title: s.navLabel, description: "Kartenlegen per Video- oder Audio-Call: Beraterin wählen, Wunschtermin anfragen, nach der Bestätigung bezahlen." }; +} + +export default async function ConsultingPortal({ searchParams }: { searchParams: Promise<{ thema?: string; methode?: string; sprache?: string; frei?: string }> }) { + const q = await searchParams; + const settings = await getConsultingSettings(); + const all = await db.advisor.findMany({ + where: PUBLIC_ADVISOR, + orderBy: { displayName: "asc" }, + include: { offers: { where: { active: true, approved: true }, orderBy: { price: "asc" } }, rules: true, exceptions: true }, + }); + // Nächster freier Termin je Beraterin (kürzestes Angebot, nächste 14 Tage) + const withNext = await Promise.all( + all.map(async (a) => { + const shortest = [...a.offers].sort((x, y) => x.duration - y.duration)[0]; + const slots = shortest ? await freeSlots(a, shortest, { days: 14 }) : new Map(); + const first = [...slots.values()][0]?.[0] as Date | undefined; + return { a, next: first ?? null }; + }), + ); + const facet = (k: "topics" | "methods" | "languages") => [...new Set(all.flatMap((a) => a[k]))].sort((x, y) => x.localeCompare(y, "de")); + const weekEnd = Date.now() + 7 * 86400e3; + const list = withNext.filter(({ a, next }) => + (!q.thema || a.topics.includes(q.thema)) && (!q.methode || a.methods.includes(q.methode)) && (!q.sprache || a.languages.includes(q.sprache)) && (!q.frei || (next && next.getTime() < weekEnd)), + ); + const link = (patch: Record) => { + const p = new URLSearchParams(Object.entries({ ...q, ...patch }).filter(([, v]) => v) as [string, string][]); + return `/beratung${p.size ? `?${p}` : ""}`; + }; + const Chips = ({ k, label, values }: { k: "thema" | "methode" | "sprache"; label: string; values: string[] }) => + values.length > 1 ? ( +
+ {label} + {values.map((v) => {v})} +
+ ) : null; + + return ( +
+ Beratung +

{settings.navLabel}

+

Wähle deine Beraterin, frag einen Wunschtermin an und bezahle erst, wenn sie bestätigt hat. Die Legung findet als Video- oder Audio-Call direkt hier im Browser statt, ganz ohne App.

+

{NOTICE}

+ + {all.length > 0 && ( +
+ + + +
+ Diese Woche frei + {(q.thema || q.methode || q.sprache || q.frei) && Filter zurücksetzen} +
+
+ )} + + {list.length === 0 ? ( +
+ +

{all.length ? "Keine Beraterin passt zu diesen Filtern." : "Hier stellen sich bald unsere Beraterinnen vor."}

+
+ ) : ( +
+ {list.map(({ a, next }) => { + const from = a.offers[0]; + return ( + + {a.photo ? ( + // eslint-disable-next-line @next/next/no-img-element + + ) : ( + + )} +
+ {a.displayName} + {a.tagline &&

{a.tagline}

} +
{[...a.topics, ...a.methods].slice(0, 5).map((t) => {t})}
+

+ {from && <>ab {formatPrice(from.price)} / {from.duration} Min.} + {a.languages.length > 0 && <> · {a.languages.join(", ")}} +

+

{next ? `Nächster freier Termin: ${fmtDateTime(next)}` : "Gerade keine freien Termine"}

+
+ + ); + })} +
+ )} +
+ ); +} diff --git a/src/app/(shop)/beratung/raum/[id]/page.tsx b/src/app/(shop)/beratung/raum/[id]/page.tsx new file mode 100644 index 0000000..16b52ac --- /dev/null +++ b/src/app/(shop)/beratung/raum/[id]/page.tsx @@ -0,0 +1,52 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { db } from "@/lib/db"; +import { getCurrentUser } from "@/lib/auth"; +import { fmtDateTime, roomWindow } from "@/lib/consulting"; +import { LIVEKIT_URL, roomToken } from "@/lib/livekit"; +import { Alert } from "@/components/shop/Blocks"; +import { CallRoom } from "@/components/shop/CallRoom"; + +export const metadata = { title: "Beratungsraum", robots: { index: false } }; + +export default async function RoomPage({ params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + const user = await getCurrentUser(); + if (!user) redirect(`/konto/anmelden?weiter=/beratung/raum/${id}`); + const a = await db.appointment.findUnique({ where: { id }, include: { advisor: true, customer: { select: { firstName: true } } } }); + // Nur die beiden Beteiligten + if (!a || (a.customerId !== user.id && a.advisor.userId !== user.id)) notFound(); + const isAdvisor = a.advisor.userId === user.id; + const back = isAdvisor ? "/admin/beratung" : "/konto/termine"; + const w = roomWindow(a); + const now = new Date(); + let problem = ""; + if (a.status !== "booked" && a.status !== "done") problem = "Dieser Termin ist nicht gebucht."; + else if (now < w.opens) problem = `Der Raum öffnet ${fmtDateTime(w.opens)}.`; + else if (now > w.closes) problem = "Dieser Termin ist vorbei."; + let token = ""; + if (!problem) { + try { + token = await roomToken({ room: a.roomName, identity: `${isAdvisor ? "b" : "k"}-${user.id}`, name: isAdvisor ? a.advisor.displayName : a.customer.firstName || "Kundin", notBefore: w.opens, expires: w.closes }); + } catch (e) { + problem = e instanceof Error ? e.message : "Der Raum ist gerade nicht erreichbar."; + } + } + return ( +
+
+
+ {a.offerName} · {a.number} +

{isAdvisor ? `Termin mit ${a.customer.firstName || "Kundin"}` : `Deine Beratung mit ${a.advisor.displayName}`}

+

{fmtDateTime(a.startsAt)} bis {new Intl.DateTimeFormat("de-DE", { timeZone: "Europe/Berlin", hour: "2-digit", minute: "2-digit" }).format(a.endsAt)} Uhr · {a.mode === "audio" ? "Audio-Call" : "Video-Call"} · wird nicht aufgezeichnet

+
+ Zurück +
+ {problem ? ( + Zurück zu den Terminen + ) : ( + + )} +
+ ); +} diff --git a/src/app/(shop)/kasse/danke/[id]/page.tsx b/src/app/(shop)/kasse/danke/[id]/page.tsx index f9e144c..e360da8 100644 --- a/src/app/(shop)/kasse/danke/[id]/page.tsx +++ b/src/app/(shop)/kasse/danke/[id]/page.tsx @@ -1,6 +1,6 @@ import Link from "next/link"; import { cookies } from "next/headers"; -import { notFound } from "next/navigation"; +import { notFound, redirect } from "next/navigation"; import { db } from "@/lib/db"; import { getCurrentUser } from "@/lib/auth"; import { formatPrice } from "@/lib/money"; @@ -18,6 +18,9 @@ export default async function ThanksPage({ params }: { params: Promise<{ id: str if (!order) notFound(); const allowed = jar.get("sm_last_order")?.value === order.id || (user && order.userId === user.id); if (!allowed) notFound(); + // Bezahlte Beratung: direkt zu „Meine Termine“ + const appointment = await db.appointment.findUnique({ where: { orderId: order.id } }); + if (appointment) redirect(`/konto/termine?bezahlt=${appointment.number}`); const payment = await db.paymentMethod.findUnique({ where: { code: order.paymentMethod } }); const cfg = (payment?.config ?? {}) as Record; diff --git a/src/app/(shop)/kategorie/[slug]/page.tsx b/src/app/(shop)/kategorie/[slug]/page.tsx index 527e662..9c5d241 100644 --- a/src/app/(shop)/kategorie/[slug]/page.tsx +++ b/src/app/(shop)/kategorie/[slug]/page.tsx @@ -2,6 +2,7 @@ import { notFound } from "next/navigation"; import Link from "next/link"; import { db } from "@/lib/db"; import { ProductList } from "@/components/shop/ProductList"; +import { getConsultingSettings } from "@/lib/consulting"; export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params; @@ -25,8 +26,10 @@ export default async function CategoryPage({ // Eine Oberkategorie ist eine eigene Rubrik: Titelbild, Text und nur ihre Produkte samt Unterkategorien const rubric = category.parent ?? category; const subs = rubric.children; - const chips = subs.length - ? [{ label: "Alle", href: `/kategorie/${rubric.slug}`, active: !category.parent }, ...subs.map((c) => ({ label: c.name, href: `/kategorie/${c.slug}`, active: c.id === category.id }))] + const consulting = await getConsultingSettings(); + const extra = consulting.navParent && rubric.slug === consulting.navParent ? [{ label: consulting.navLabel, href: "/beratung", active: false }] : []; + const chips = subs.length || extra.length + ? [{ label: "Alle", href: `/kategorie/${rubric.slug}`, active: !category.parent }, ...subs.map((c) => ({ label: c.name, href: `/kategorie/${c.slug}`, active: c.id === category.id })), ...extra] : undefined; const ids = category.parent ? [category.id] : [category.id, ...subs.map((c) => c.id)]; const crumbs = ( diff --git a/src/app/(shop)/konto/termine/page.tsx b/src/app/(shop)/konto/termine/page.tsx new file mode 100644 index 0000000..653574c --- /dev/null +++ b/src/app/(shop)/konto/termine/page.tsx @@ -0,0 +1,119 @@ +import Link from "next/link"; +import { redirect } from "next/navigation"; +import { db } from "@/lib/db"; +import { getCurrentUser } from "@/lib/auth"; +import { formatPrice } from "@/lib/money"; +import { STATUS, fmtDateTime, getConsultingSettings, roomWindow } from "@/lib/consulting"; +import { Icon } from "@/components/Icon"; +import { Alert } from "@/components/shop/Blocks"; +import { AccountShell } from "@/components/shop/account/AccountShell"; +import { CancelAppointmentButton } from "@/components/shop/CancelAppointmentButton"; +import { chooseProposal } from "@/app/(shop)/beratung/actions"; + +export const metadata = { title: "Meine Termine" }; + +export default async function MyAppointments({ searchParams }: { searchParams: Promise<{ angefragt?: string; bezahlt?: string; zahlung?: string; abgesagt?: string; fehler?: string }> }) { + const user = await getCurrentUser(); + if (!user) redirect("/konto/anmelden?weiter=/konto/termine"); + const q = await searchParams; + const [list, s] = await Promise.all([ + db.appointment.findMany({ where: { customerId: user.id }, orderBy: { startsAt: "desc" }, include: { advisor: { select: { displayName: true, slug: true, photo: true } }, proposals: { orderBy: { startsAt: "asc" } } } }), + getConsultingSettings(), + ]); + const now = new Date(); + const active = list.filter((a) => ["requested", "proposed", "confirmed", "booked"].includes(a.status)).sort((x, y) => +x.startsAt - +y.startsAt); + const past = list.filter((a) => !active.includes(a)); + return ( + + {q.angefragt &&
Du bekommst eine Mail, sobald die Beraterin geantwortet hat. Bezahlt wird erst nach der Bestätigung.
} + {q.bezahlt &&
Die Bestätigung mit Kalenderdatei kommt per Mail.
} + {q.zahlung &&
Sobald das Geld da ist, ist der Termin fest gebucht.
} + {q.abgesagt &&
} + {q.fehler &&
} + + {active.length === 0 ? ( +
+ +

Du hast gerade keine offenen Termine.

+ {s.navLabel} buchen +
+ ) : ( +
+ {active.map((a) => { + const w = roomWindow(a); + const roomOpen = a.status === "booked" && now >= w.opens && now <= w.closes; + const hoursLeft = (a.startsAt.getTime() - now.getTime()) / 3600e3; + return ( +
+
+
+ {STATUS[a.status].label} +

{a.offerName} mit {a.advisor.displayName}

+

{fmtDateTime(a.startsAt)} · {a.duration} Min. · {a.mode === "audio" ? "Audio-Call" : "Video-Call"} · {formatPrice(a.price)}

+
+ {a.number} +
+ {a.status === "requested" &&

Wartet auf die Antwort von {a.advisor.displayName}{a.expiresAt ? ` (spätestens ${fmtDateTime(a.expiresAt)})` : ""}.

} + {a.status === "proposed" && ( +
+

{a.advisor.displayName} schlägt dir andere Zeiten vor:{a.advisorMessage && <>
„{a.advisorMessage}“}

+
+ {a.proposals.map((p) => ( +
+ + + +
+ ))} +
+
+ )} + {a.status === "confirmed" && ( +
+ Jetzt bezahlen + {a.expiresAt && bis {fmtDateTime(a.expiresAt)}} +
+ )} + {a.status === "booked" && ( +
+ {roomOpen ? ( + Raum betreten + ) : ( + Raum öffnet {fmtDateTime(w.opens)} + )} + In den Kalender +
+ )} + {now < a.startsAt && ( + = s.refundHours ? "Du bekommst den vollen Betrag zurück." : `Weniger als ${s.refundHours} Stunden vor dem Termin gibt es nach den Stornoregeln keine Erstattung.`} + /> + )} +
+ ); + })} +
+ )} + + {past.length > 0 && ( +
+

Frühere Termine und Anfragen

+
+ {past.map((a) => ( +
+
+
+ {a.offerName} mit {a.advisor.displayName} +

{fmtDateTime(a.startsAt)} · {STATUS[a.status].label}

+
+ Neu buchen +
+
+ ))} +
+
+ )} +
+ ); +} diff --git a/src/app/admin/(panel)/beratung/actions.ts b/src/app/admin/(panel)/beratung/actions.ts new file mode 100644 index 0000000..fbbeedb --- /dev/null +++ b/src/app/admin/(panel)/beratung/actions.ts @@ -0,0 +1,281 @@ +"use server"; +import { revalidatePath } from "next/cache"; +import { db } from "@/lib/db"; +import { assertPermission, audit, can, type CurrentUser } from "@/lib/auth"; +import { fail, ok, type ActionResult } from "@/lib/action-result"; +import { parsePrice } from "@/lib/money"; +import { slugify } from "@/lib/slug"; +import { cancelAppointment, confirmRequest, declineRequest, getConsultingSettings, getOwnAdvisor, parseMinutes, proposeTimes, saveConsultingSettings } from "@/lib/consulting"; + +// Alles für Beraterinnen und die Verwaltung der Beratung. „Nur eigene“ wird hier im Server geprüft: +// eine Beraterin ohne consulting.manage kommt nur an ihr eigenes Profil und ihre eigenen Termine. + +const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim(); +const list = (fd: FormData, k: string) => str(fd, k).split(",").map((s) => s.trim()).filter(Boolean).slice(0, 12); +const done = () => { + revalidatePath("/admin/beratung", "layout"); + revalidatePath("/beratung", "layout"); + return ok(); +}; + +/** Profil, das bearbeitet werden darf: das eigene, oder mit consulting.manage jedes (über advisorId). */ +async function targetAdvisor(fd: FormData) { + const user = await assertPermission("consulting.own"); + const wanted = str(fd, "advisorId"); + if (wanted && can(user, "consulting.manage")) { + const a = await db.advisor.findUnique({ where: { id: wanted } }); + if (!a) throw new Error("Beraterin nicht gefunden."); + return { user, advisor: a, manager: true }; + } + return { user, advisor: await getOwnAdvisor(user), manager: can(user, "consulting.manage") }; +} + +/** Termin, auf den die Person zugreifen darf. */ +async function ownAppointment(user: CurrentUser, id: string) { + const a = await db.appointment.findUnique({ where: { id }, include: { advisor: true } }); + if (!a) return null; + if (a.advisor.userId !== user.id && !can(user, "consulting.manage")) return null; + return a; +} + +// ---------- Profil ---------- + +export async function saveProfile(_prev: ActionResult, fd: FormData): Promise { + const { user, advisor, manager } = await targetAdvisor(fd); + const displayName = str(fd, "displayName"); + if (!displayName) return fail("Bitte gib einen Namen ein.", { displayName: "Bitte eintragen" }); + let slug = slugify(str(fd, "slug") || displayName); + if (!slug) return fail("Bitte gib eine Web-Adresse ein.", { slug: "Bitte eintragen" }); + if (await db.advisor.findFirst({ where: { slug, NOT: { id: advisor.id } } })) return fail("Diese Web-Adresse ist schon vergeben.", { slug: "Vergeben" }); + let photo = ""; + try { + photo = ((JSON.parse(str(fd, "photo") || "[]") as string[]).find((p) => typeof p === "string" && p.startsWith("/")) ?? ""); + } catch {} + const n = (k: string, min: number, max: number, def: number) => Math.min(max, Math.max(min, Math.round(Number(str(fd, k)) || def))); + await db.advisor.update({ + where: { id: advisor.id }, + data: { + displayName: displayName.slice(0, 80), + slug, + tagline: str(fd, "tagline").slice(0, 200), + bio: String(fd.get("bio") ?? "").trim().slice(0, 5000), + photo, + topics: list(fd, "topics"), + methods: list(fd, "methods"), + languages: list(fd, "languages"), + minNoticeHours: n("minNoticeHours", 1, 720, 12), + maxDaysAhead: n("maxDaysAhead", 1, 120, 60), + maxPerDay: n("maxPerDay", 0, 20, 0), + }, + }); + await audit(user, "Beraterin-Profil gespeichert", `${displayName}${manager && advisor.userId !== user.id ? " (vom Team)" : ""}`); + return done(); +} + +/** Beraterin schickt ihr Profil zur Freigabe. */ +export async function submitProfile(fd: FormData) { + const { advisor } = await targetAdvisor(fd); + if (advisor.status === "draft" || advisor.status === "paused") await db.advisor.update({ where: { id: advisor.id }, data: { status: "pending" } }); + done(); +} + +// ---------- Angebote ---------- + +export async function saveOffer(_prev: ActionResult, fd: FormData): Promise { + const { user, advisor, manager } = await targetAdvisor(fd); + const settings = await getConsultingSettings(); + const id = str(fd, "id"); + const name = str(fd, "name"); + const duration = Math.round(Number(str(fd, "duration"))); + const price = parsePrice(str(fd, "price")); + const buffer = Math.max(0, Math.min(120, Math.round(Number(str(fd, "buffer")) || 0))); + const mode = ["video", "audio", "both"].includes(str(fd, "mode")) ? str(fd, "mode") : "both"; + const errors: Record = {}; + if (!name) errors.name = "Bitte eintragen"; + if (!Number.isFinite(duration) || duration < 10 || duration > 240) errors.duration = "10 bis 240 Minuten"; + if (price == null || price <= 0) errors.price = "Bitte einen Preis, z. B. 39,00"; + else if (settings.minPrice && price < settings.minPrice) errors.price = `Mindestens ${(settings.minPrice / 100).toFixed(2).replace(".", ",")} €`; + else if (settings.maxPrice && price > settings.maxPrice) errors.price = `Höchstens ${(settings.maxPrice / 100).toFixed(2).replace(".", ",")} €`; + if (Object.keys(errors).length) return fail("Bitte prüfe die markierten Felder.", errors); + const data = { name: name.slice(0, 80), description: str(fd, "description").slice(0, 500), duration, price: price!, buffer, mode, active: fd.get("active") === "on" }; + if (id) { + const old = await db.advisorOffer.findFirst({ where: { id, advisorId: advisor.id } }); + if (!old) return fail("Angebot nicht gefunden."); + // Preis oder Dauer geändert: neu freigeben lassen (außer das Team ändert selbst) + const changed = old.price !== data.price || old.duration !== data.duration; + await db.advisorOffer.update({ where: { id }, data: { ...data, approved: manager ? true : old.approved && !changed } }); + } else { + const last = await db.advisorOffer.findFirst({ where: { advisorId: advisor.id }, orderBy: { sort: "desc" } }); + await db.advisorOffer.create({ data: { ...data, advisorId: advisor.id, approved: manager, sort: (last?.sort ?? -1) + 1 } }); + } + await audit(user, id ? "Beratungsangebot geändert" : "Beratungsangebot angelegt", `${advisor.displayName}: ${name}`); + done(); + return ok(manager ? "Gespeichert." : "Gespeichert. Neue Angebote und geänderte Preise erscheinen nach der Freigabe durch den Shop."); +} + +export async function deleteOffer(fd: FormData) { + const { advisor } = await targetAdvisor(fd); + const id = str(fd, "id"); + const used = await db.appointment.count({ where: { offerId: id } }); + // Mit Terminen: nur abschalten, damit die Historie stimmt + if (used) await db.advisorOffer.updateMany({ where: { id, advisorId: advisor.id }, data: { active: false } }); + else await db.advisorOffer.deleteMany({ where: { id, advisorId: advisor.id } }); + done(); +} + +// ---------- Verfügbarkeit ---------- + +export async function saveRules(_prev: ActionResult, fd: FormData): Promise { + const { advisor } = await targetAdvisor(fd); + let rows: { weekday: number; start: string; end: string }[] = []; + try { + rows = JSON.parse(str(fd, "rules") || "[]"); + } catch {} + const clean: { weekday: number; start: number; end: number }[] = []; + for (const r of rows) { + const start = parseMinutes(String(r.start ?? "")); + const end = parseMinutes(String(r.end ?? "")); + if (!Number.isInteger(r.weekday) || r.weekday < 1 || r.weekday > 7 || start == null || end == null) continue; + if (end <= start) return fail(`Bei ${["", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"][r.weekday]} endet eine Zeit vor ihrem Beginn.`); + clean.push({ weekday: r.weekday, start, end }); + } + await db.$transaction([db.availabilityRule.deleteMany({ where: { advisorId: advisor.id } }), ...clean.map((r) => db.availabilityRule.create({ data: { ...r, advisorId: advisor.id } }))]); + return done(); +} + +export async function addException(_prev: ActionResult, fd: FormData): Promise { + const { advisor } = await targetAdvisor(fd); + const from = str(fd, "from"); + const to = str(fd, "to") || from; + const kind = str(fd, "kind") === "extra" ? "extra" : "off"; + if (!/^\d{4}-\d{2}-\d{2}$/.test(from) || !/^\d{4}-\d{2}-\d{2}$/.test(to) || to < from) return fail("Bitte gib ein gültiges Datum an."); + const start = str(fd, "start") ? parseMinutes(str(fd, "start")) : null; + const end = str(fd, "end") ? parseMinutes(str(fd, "end")) : null; + if (kind === "extra" && (start == null || end == null)) return fail("Für zusätzliche Zeiten brauche ich Beginn und Ende."); + if ((start == null) !== (end == null) || (start != null && end != null && end <= start)) return fail("Bitte gib Beginn und Ende an (oder beides leer für den ganzen Tag)."); + const days: string[] = []; + for (let d = from; d <= to && days.length < 62; ) { + days.push(d); + const [y, m, dd] = d.split("-").map(Number); + const n = new Date(Date.UTC(y, m - 1, dd + 1)); + d = n.toISOString().slice(0, 10); + } + await db.availabilityException.createMany({ data: days.map((date) => ({ advisorId: advisor.id, date, kind, start, end, note: str(fd, "note").slice(0, 100) })) }); + done(); + return ok(days.length > 1 ? `${days.length} Tage eingetragen.` : "Eingetragen."); +} + +export async function deleteException(fd: FormData) { + const { advisor } = await targetAdvisor(fd); + await db.availabilityException.deleteMany({ where: { id: str(fd, "id"), advisorId: advisor.id } }); + done(); +} + +// ---------- Anfragen und Termine ---------- + +export async function respond(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("consulting.own"); + const a = await ownAppointment(user, str(fd, "id")); + if (!a) return fail("Termin nicht gefunden."); + const action = str(fd, "do"); + const message = str(fd, "message"); + let r: { ok: boolean; error?: string }; + if (action === "confirm") r = await confirmRequest(a.id); + else if (action === "decline") r = await declineRequest(a.id, message); + else if (action === "propose") { + const starts = ["p1", "p2", "p3"].map((k) => str(fd, k)).filter(Boolean).map((v) => new Date(v)); + if (starts.some((d) => Number.isNaN(d.getTime()))) return fail("Ungültiger Termin."); + r = await proposeTimes(a.id, starts, message); + } else return fail("Unbekannte Aktion."); + if (!r.ok) return fail(r.error ?? "Das hat nicht geklappt."); + await audit(user, `Terminanfrage ${action === "confirm" ? "bestätigt" : action === "decline" ? "abgelehnt" : "mit Gegenvorschlag beantwortet"}`, a.number); + done(); + return ok(action === "confirm" ? "Bestätigt. Die Kundin bekommt jetzt den Zahlungslink." : action === "decline" ? "Abgelehnt. Die Kundin wurde informiert." : "Vorschläge verschickt."); +} + +export async function cancelByAdvisor(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("consulting.own"); + const a = await ownAppointment(user, str(fd, "id")); + if (!a) return fail("Termin nicht gefunden."); + const reason = str(fd, "reason"); + if (!reason) return fail("Bitte gib der Kundin kurz einen Grund an.", { reason: "Bitte eintragen" }); + // Eigene Absage: volle Erstattung; das Team sagt im Namen des Shops ab + const by = a.advisor.userId === user.id ? "advisor" : "shop"; + const r = await cancelAppointment(a.id, by, reason); + if (!r.ok) return fail(r.error); + await audit(user, "Beratungstermin abgesagt", `${a.number}: ${reason}`); + done(); + return ok("Abgesagt. Die Kundin wurde informiert und bekommt den Betrag erstattet."); +} + +export async function saveNote(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("consulting.own"); + const a = await ownAppointment(user, str(fd, "id")); + if (!a) return fail("Termin nicht gefunden."); + await db.appointment.update({ where: { id: a.id }, data: { advisorNote: String(fd.get("note") ?? "").slice(0, 3000) } }); + return done(); +} + +export async function markNoShow(fd: FormData) { + const user = await assertPermission("consulting.own"); + const a = await ownAppointment(user, str(fd, "id")); + if (!a || !["booked", "done"].includes(a.status) || a.startsAt.getTime() + 15 * 60e3 > Date.now()) return; + await db.appointment.update({ where: { id: a.id }, data: { status: "noshow" } }); + await audit(user, "Kundin nicht erschienen", a.number); + done(); +} + +// ---------- Verwaltung ---------- + +export async function setAdvisorStatus(fd: FormData) { + const user = await assertPermission("consulting.manage"); + const id = str(fd, "advisorId"); + const status = str(fd, "status"); + if (!["approved", "paused", "draft"].includes(status)) return; + const a = await db.advisor.update({ where: { id }, data: { status } }); + // Mit der Freigabe des Profils auch die Angebote freigeben, die es schon gibt + if (status === "approved") await db.advisorOffer.updateMany({ where: { advisorId: id }, data: { approved: true } }); + await audit(user, status === "approved" ? "Beraterin freigegeben" : status === "paused" ? "Beraterin pausiert" : "Beraterin zurück in Bearbeitung", a.displayName); + done(); +} + +export async function approveOffer(fd: FormData) { + const user = await assertPermission("consulting.manage"); + const o = await db.advisorOffer.update({ where: { id: str(fd, "id") }, data: { approved: true }, include: { advisor: true } }); + await audit(user, "Beratungsangebot freigegeben", `${o.advisor.displayName}: ${o.name}`); + done(); +} + +export async function setCommission(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("consulting.settings"); + const v = Math.round(Number(str(fd, "commission").replace(",", "."))); + if (!Number.isFinite(v) || v < 0 || v > 100) return fail("Bitte 0 bis 100 Prozent.", { commission: "0–100" }); + const a = await db.advisor.update({ where: { id: str(fd, "advisorId") }, data: { commission: v } }); + await audit(user, "Provision geändert", `${a.displayName}: ${v} %`); + return done(); +} + +export async function saveSettings(_prev: ActionResult, fd: FormData): Promise { + const user = await assertPermission("consulting.settings"); + const old = await getConsultingSettings(); + const h = (k: string, min: number, max: number) => Math.min(max, Math.max(min, Math.round(Number(str(fd, k)) || 0))); + const price = (k: string) => (str(fd, k) ? (parsePrice(str(fd, k)) ?? 0) : 0); + const next = { + ...old, + requestHours: h("requestHours", 4, 168), + payHours: h("payHours", 1, 96), + refundHours: h("refundHours", 0, 336), + minPrice: price("minPrice"), + maxPrice: price("maxPrice"), + allowManualPayments: fd.get("allowManualPayments") === "on", + manualMinDays: h("manualMinDays", 1, 60), + navParent: slugify(str(fd, "navParent")), + navLabel: str(fd, "navLabel").slice(0, 40) || "Kartenlegen", + }; + if (next.maxPrice && next.minPrice > next.maxPrice) return fail("Der Mindestpreis ist höher als der Höchstpreis."); + await saveConsultingSettings(next); + await audit(user, "Beratung: Einstellungen geändert"); + revalidatePath("/", "layout"); + return ok(); +} + diff --git a/src/app/admin/(panel)/beratung/alle/page.tsx b/src/app/admin/(panel)/beratung/alle/page.tsx new file mode 100644 index 0000000..62585b7 --- /dev/null +++ b/src/app/admin/(panel)/beratung/alle/page.tsx @@ -0,0 +1,61 @@ +import Link from "next/link"; +import type { Prisma } from "@prisma/client"; +import { db } from "@/lib/db"; +import { requireAdmin } from "@/lib/auth"; +import { formatPrice } from "@/lib/money"; +import { STATUS, fmtDateTime } from "@/lib/consulting"; +import { Card, Empty, PageHead, Pill } from "@/components/admin/ui"; +import { AdvisorCancelForm } from "@/components/admin/ConsultForms"; + +export const metadata = { title: "Alle Termine" }; + +const FILTERS: { key: string; label: string; where: Prisma.AppointmentWhereInput }[] = [ + { key: "offen", label: "Offen", where: { status: { in: ["requested", "proposed", "confirmed"] } } }, + { key: "gebucht", label: "Gebucht", where: { status: "booked" } }, + { key: "vorbei", label: "Vorbei", where: { status: { in: ["done", "noshow"] } } }, + { key: "abgesagt", label: "Abgesagt & verfallen", where: { status: { in: ["cancelled", "declined", "expired"] } } }, +]; + +export default async function AllAppointments({ searchParams }: { searchParams: Promise<{ f?: string }> }) { + await requireAdmin("consulting.manage"); + const { f } = await searchParams; + const filter = FILTERS.find((x) => x.key === f) ?? FILTERS[1]; + const rows = await db.appointment.findMany({ + where: filter.where, + orderBy: { startsAt: filter.key === "gebucht" || filter.key === "offen" ? "asc" : "desc" }, + take: 200, + include: { advisor: { select: { displayName: true } }, customer: { select: { firstName: true, lastName: true, email: true } }, order: { select: { id: true, number: true } } }, + }); + return ( +
+ + + + {rows.length === 0 ? ( +
+ ) : ( +
+ + + + {rows.map((r) => ( + + + + + + + + + + ))} + +
TerminKundinBeraterinAngebotPreisStatus
{fmtDateTime(r.startsAt)}
{r.number}
{[r.customer.firstName, r.customer.lastName].filter(Boolean).join(" ") || "–"}
{r.customer.email}
{r.advisor.displayName}{r.offerName}
{r.duration} Min. · {r.mode === "audio" ? "Audio" : "Video"}
{formatPrice(r.price)}{r.order &&
{r.order.number}
}
{STATUS[r.status].label}{r.cancelReason &&
{r.cancelReason}
}
{["requested", "proposed", "confirmed", "booked"].includes(r.status) && }
+
+ )} +
+
+ ); +} diff --git a/src/app/admin/(panel)/beratung/angebote/page.tsx b/src/app/admin/(panel)/beratung/angebote/page.tsx new file mode 100644 index 0000000..5372e1d --- /dev/null +++ b/src/app/admin/(panel)/beratung/angebote/page.tsx @@ -0,0 +1,54 @@ +import { db } from "@/lib/db"; +import { can } from "@/lib/auth"; +import { centsToInput, formatPrice } from "@/lib/money"; +import { ConfirmButton } from "@/components/admin/AdminForm"; +import { Card, Empty, PageHead, Pill } from "@/components/admin/ui"; +import { OfferForm } from "@/components/admin/OfferForm"; +import { approveOffer, deleteOffer } from "../actions"; +import { AdvisorStatus, AdvisorTabs, loadAdvisor } from "../shared"; + +export const metadata = { title: "Meine Angebote" }; + +const MODE: Record = { both: "Video oder Audio", video: "Video", audio: "Audio" }; + +export default async function AdvisorOffers({ searchParams }: { searchParams: Promise<{ b?: string }> }) { + const { b } = await searchParams; + const { advisor, foreign, user } = await loadAdvisor(b); + const offers = await db.advisorOffer.findMany({ where: { advisorId: advisor.id }, orderBy: { sort: "asc" } }); + const manager = can(user, "consulting.manage"); + return ( +
+ + + + {offers.length === 0 && } + {offers.map((o) => ( +
+ +
+

{o.name}

+

{o.duration} Min. · {formatPrice(o.price)} · {MODE[o.mode]}{o.buffer ? ` · ${o.buffer} Min. Pause danach` : ""}

+
+ + {!o.active && Aus} + {o.approved ? Freigegeben : Wartet auf Freigabe} + +
+
+ {manager && !o.approved && ( +
+ + +
+ )} + + +
+
+ ))} + + + +
+ ); +} diff --git a/src/app/admin/(panel)/beratung/beraterinnen/page.tsx b/src/app/admin/(panel)/beratung/beraterinnen/page.tsx new file mode 100644 index 0000000..d916571 --- /dev/null +++ b/src/app/admin/(panel)/beratung/beraterinnen/page.tsx @@ -0,0 +1,72 @@ +import Link from "next/link"; +import { db } from "@/lib/db"; +import { can, requireAdmin } from "@/lib/auth"; +import { Field } from "@/components/Field"; +import { AdminForm } from "@/components/admin/AdminForm"; +import { Card, Empty, PageHead, Pill } from "@/components/admin/ui"; +import { setAdvisorStatus, setCommission } from "../actions"; + +export const metadata = { title: "Beraterinnen" }; + +const STATUS: Record = { + draft: { tone: "neutral", label: "In Bearbeitung" }, + pending: { tone: "gold", label: "Wartet auf Freigabe" }, + approved: { tone: "success", label: "Online" }, + paused: { tone: "danger", label: "Pausiert" }, +}; + +function StatusButton({ id, status, label, primary }: { id: string; status: string; label: string; primary?: boolean }) { + return ( +
+ + + +
+ ); +} + +export default async function AdvisorsPage() { + const user = await requireAdmin("consulting.manage"); + const advisors = await db.advisor.findMany({ + orderBy: [{ status: "asc" }, { displayName: "asc" }], + include: { + user: { select: { email: true, active: true } }, + offers: { select: { approved: true, active: true } }, + _count: { select: { appointments: { where: { status: { in: ["requested", "proposed", "confirmed", "booked"] } } } } }, + }, + }); + const canCommission = can(user, "consulting.settings"); + return ( +
+ + {advisors.length === 0 && Zum Team} + {advisors.map((a) => { + const pendingOffers = a.offers.filter((o) => !o.approved).length; + const st = STATUS[a.status] ?? STATUS.draft; + return ( + {st.label}}> +

+ {a.offers.length} {a.offers.length === 1 ? "Angebot" : "Angebote"}{pendingOffers ? `, davon ${pendingOffers} zur Freigabe` : ""} · {a._count.appointments} offene oder gebuchte Termine · Provision {a.commission} % +

+
+ {a.status !== "approved" && } + {a.status === "approved" && } + {a.status === "pending" && } + Profil + Angebote{pendingOffers ? ` (${pendingOffers} neu)` : ""} + Zeiten + Termine + {a.status === "approved" && Im Shop ansehen} +
+ {canCommission && ( + + + + + )} +
+ ); + })} +
+ ); +} diff --git a/src/app/admin/(panel)/beratung/einstellungen/page.tsx b/src/app/admin/(panel)/beratung/einstellungen/page.tsx new file mode 100644 index 0000000..009c44b --- /dev/null +++ b/src/app/admin/(panel)/beratung/einstellungen/page.tsx @@ -0,0 +1,50 @@ +import { requireAdmin } from "@/lib/auth"; +import { centsToInput } from "@/lib/money"; +import { getConsultingSettings } from "@/lib/consulting"; +import { isLivekitReady, LIVEKIT_URL } from "@/lib/livekit"; +import { Field } from "@/components/Field"; +import { AdminForm } from "@/components/admin/AdminForm"; +import { Card, PageHead, Switch } from "@/components/admin/ui"; +import { saveSettings } from "../actions"; + +export const metadata = { title: "Beratung einstellen" }; + +export default async function ConsultingSettingsPage() { + await requireAdmin("consulting.settings"); + const [s, call] = await Promise.all([getConsultingSettings(), isLivekitReady()]); + return ( +
+ + + +
+ + +
+
+ + + + +
+ + +
+ + +
+ +
+ + +
+
+
+ +

+ {call ? "Schlüssel vorhanden." : "Noch keine Schlüssel, der Shop erzeugt sie beim nächsten Start."} Adresse: {LIVEKIT_URL}. Die Calls laufen über deinen eigenen Server (LiveKit), es wird nichts aufgezeichnet. +

+
+
+ ); +} diff --git a/src/app/admin/(panel)/beratung/page.tsx b/src/app/admin/(panel)/beratung/page.tsx new file mode 100644 index 0000000..0561658 --- /dev/null +++ b/src/app/admin/(panel)/beratung/page.tsx @@ -0,0 +1,132 @@ +import Link from "next/link"; +import { db } from "@/lib/db"; +import { formatPrice } from "@/lib/money"; +import { STATUS, fmtDateTime, fmtTime, freeSlots, roomWindow } from "@/lib/consulting"; +import { ConfirmButton } from "@/components/admin/AdminForm"; +import { Card, Empty, PageHead, Pill } from "@/components/admin/ui"; +import { AdvisorCancelForm, NoteForm, RespondForm } from "@/components/admin/ConsultForms"; +import { markNoShow, submitProfile } from "./actions"; +import { AdvisorStatus, AdvisorTabs, loadAdvisor } from "./shared"; + +export const metadata = { title: "Meine Termine" }; + +const left = (d: Date) => { + const h = Math.max(0, Math.round((d.getTime() - Date.now()) / 3600e3)); + return h >= 24 ? `noch ${Math.floor(h / 24)} Tag${h >= 48 ? "e" : ""} ${h % 24} Std.` : `noch ${h} Std.`; +}; + +export default async function AdvisorDashboard({ searchParams }: { searchParams: Promise<{ b?: string }> }) { + const { b } = await searchParams; + const { advisor, foreign } = await loadAdvisor(b); + const now = new Date(); + const [requests, waiting, upcoming, past, plan] = await Promise.all([ + db.appointment.findMany({ where: { advisorId: advisor.id, status: { in: ["requested", "proposed"] } }, orderBy: { startsAt: "asc" }, include: { customer: { select: { firstName: true } }, proposals: { orderBy: { startsAt: "asc" } }, offer: true } }), + db.appointment.findMany({ where: { advisorId: advisor.id, status: "confirmed" }, orderBy: { startsAt: "asc" }, include: { customer: { select: { firstName: true } } } }), + db.appointment.findMany({ where: { advisorId: advisor.id, status: "booked" }, orderBy: { startsAt: "asc" }, include: { customer: { select: { firstName: true } } } }), + db.appointment.findMany({ where: { advisorId: advisor.id, status: { in: ["done", "noshow", "cancelled", "declined", "expired"] } }, orderBy: { startsAt: "desc" }, take: 15, include: { customer: { select: { firstName: true } } } }), + db.advisor.findUnique({ where: { id: advisor.id }, include: { rules: true, exceptions: true } }), + ]); + // Freie Zeiten für Gegenvorschläge, je Anfrage passend zur Dauer + const slotOptions = new Map(); + for (const r of requests.filter((r) => r.status === "requested")) { + const map = await freeSlots(plan!, { duration: r.duration, buffer: r.offer?.buffer ?? 10 }, { exceptId: r.id, days: 28 }); + slotOptions.set( + r.id, + [...map.entries()].slice(0, 21).map(([, slots]) => ({ + label: new Intl.DateTimeFormat("de-DE", { timeZone: "Europe/Berlin", weekday: "long", day: "2-digit", month: "2-digit" }).format(slots[0]), + options: slots.filter((s) => s.getTime() !== r.startsAt.getTime()).map((s) => ({ value: s.toISOString(), label: `${new Intl.DateTimeFormat("de-DE", { timeZone: "Europe/Berlin", weekday: "short", day: "2-digit", month: "2-digit" }).format(s)}, ${fmtTime(s)} Uhr` })), + })).filter((g) => g.options.length), + ); + } + const name = (c: { firstName: string }) => c.firstName || "Kundin"; + return ( +
+ + + + {!foreign && (advisor.status === "draft" || advisor.status === "paused") && ( +
+ +
+ )} +
+ + + {requests.length === 0 ? : requests.map((r) => ( +
+
+ {fmtDateTime(r.startsAt)} + {STATUS[r.status].label} + {r.expiresAt && {left(r.expiresAt)}} +
+

{name(r.customer)} · {r.offerName} · {r.duration} Min. · {r.mode === "audio" ? "Audio" : "Video"} · {formatPrice(r.price)} · {r.number}

+ {r.concern &&

„{r.concern}“

} + {r.status === "requested" ? ( + + ) : ( +

Vorgeschlagen: {r.proposals.map((p) => fmtDateTime(p.startsAt)).join(", ")}. Die Kundin wählt noch.

+ )} +
+ ))} +
+ + {waiting.length > 0 && ( + + {waiting.map((r) => ( +
+
{fmtDateTime(r.startsAt)}{r.expiresAt && Zahlung {left(r.expiresAt)}}
+

{name(r.customer)} · {r.offerName} · {r.mode === "audio" ? "Audio" : "Video"} · {r.number}

+
+ ))} +
+ )} + + + {upcoming.length === 0 ? : upcoming.map((r) => { + const w = roomWindow(r); + const open = now >= w.opens && now <= w.closes; + return ( +
+
+ {fmtDateTime(r.startsAt)} + Gebucht + {open ? ( + Call starten + ) : ( + Raum öffnet {fmtDateTime(w.opens)} + )} +
+

{name(r.customer)} · {r.offerName} · {r.duration} Min. · {r.mode === "audio" ? "Audio-Call" : "Video-Call"} · {r.number}

+ {r.concern &&

„{r.concern}“

} + + {now < r.startsAt && } + {now.getTime() > r.startsAt.getTime() + 15 * 60e3 && ( + + )} +
+ ); + })} +
+ + {past.length > 0 && ( + +
+ + + + {past.map((r) => ( + + + + + + + ))} + +
TerminKundinAngebotStatus
{fmtDateTime(r.startsAt)}
{r.number}
{name(r.customer)}{r.offerName}{STATUS[r.status].label}
+
+
+ )} +
+ ); +} diff --git a/src/app/admin/(panel)/beratung/profil/page.tsx b/src/app/admin/(panel)/beratung/profil/page.tsx new file mode 100644 index 0000000..19db244 --- /dev/null +++ b/src/app/admin/(panel)/beratung/profil/page.tsx @@ -0,0 +1,53 @@ +import { Field, TextareaField } from "@/components/Field"; +import { AdminForm } from "@/components/admin/AdminForm"; +import { Card, PageHead } from "@/components/admin/ui"; +import { ImageManager } from "@/components/admin/ImageManager"; +import { Alert } from "@/components/shop/Blocks"; +import { saveProfile } from "../actions"; +import { AdvisorStatus, AdvisorTabs, loadAdvisor } from "../shared"; + +export const metadata = { title: "Mein Profil" }; + +export default async function AdvisorProfile({ searchParams }: { searchParams: Promise<{ b?: string }> }) { + const { b } = await searchParams; + const { advisor, foreign } = await loadAdvisor(b); + return ( +
+ + + +
+ + Aussagen wie „heilt“, „löst Blockaden garantiert“ oder „ersetzt die Therapie“ sind nicht erlaubt und können abgemahnt werden. Beschreibe lieber, wie du arbeitest und wobei du begleitest. + +
+ + + + + + +
+ Foto + +
+
+ + + + + + +
+ + +
+ +
+ + + +
+
+ ); +} diff --git a/src/app/admin/(panel)/beratung/shared.tsx b/src/app/admin/(panel)/beratung/shared.tsx new file mode 100644 index 0000000..de6d8da --- /dev/null +++ b/src/app/admin/(panel)/beratung/shared.tsx @@ -0,0 +1,53 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { db } from "@/lib/db"; +import { can, requireAdmin } from "@/lib/auth"; +import { getOwnAdvisor } from "@/lib/consulting"; +import { Alert } from "@/components/shop/Blocks"; + +/** Eigenes Profil, oder mit consulting.manage das über ?b= gewählte. */ +export async function loadAdvisor(b?: string) { + const user = await requireAdmin("consulting.own"); + const manager = can(user, "consulting.manage"); + // Inhaber und Leitung ohne eigenes Profil landen in der Übersicht, statt ungewollt eins anzulegen + if (!b && manager && !(await db.advisor.findUnique({ where: { userId: user.id } }))) redirect("/admin/beratung/beraterinnen"); + const advisor = b && manager ? await db.advisor.findUnique({ where: { id: b } }) : await getOwnAdvisor(user); + if (!advisor) notFound(); + return { user, manager, advisor, foreign: advisor.userId !== user.id }; +} + +const TABS = [ + { href: "/admin/beratung", label: "Termine" }, + { href: "/admin/beratung/profil", label: "Profil" }, + { href: "/admin/beratung/angebote", label: "Angebote" }, + { href: "/admin/beratung/zeiten", label: "Zeiten" }, +]; + +export function AdvisorTabs({ current, advisorId, foreign }: { current: string; advisorId: string; foreign: boolean }) { + const q = foreign ? `?b=${advisorId}` : ""; + return ( + + ); +} + +const STATUS_TEXT: Record = { + draft: { kind: undefined, title: "Dein Profil ist noch nicht online.", text: "Fülle Profil, Angebote und Zeiten aus und schick es dann zur Freigabe. Der Shop prüft es und schaltet es frei." }, + pending: { kind: undefined, title: "Dein Profil wartet auf Freigabe.", text: "Der Shop sieht es sich an und schaltet es frei. Bis dahin kannst du weiter alles bearbeiten." }, + paused: { kind: "danger", title: "Dein Profil ist pausiert.", text: "Es ist gerade nicht im Shop zu sehen. Gebuchte Termine bleiben bestehen." }, +}; + +export function AdvisorStatus({ status, foreign, children }: { status: string; foreign: boolean; children?: React.ReactNode }) { + const t = STATUS_TEXT[status]; + if (!t) return null; + return ( +
+ + {foreign ? null : t.text} {children} + +
+ ); +} diff --git a/src/app/admin/(panel)/beratung/zeiten/page.tsx b/src/app/admin/(panel)/beratung/zeiten/page.tsx new file mode 100644 index 0000000..d4b00d0 --- /dev/null +++ b/src/app/admin/(panel)/beratung/zeiten/page.tsx @@ -0,0 +1,68 @@ +import { db } from "@/lib/db"; +import { berlinParts, minutesLabel } from "@/lib/consulting"; +import { Field, SelectField } from "@/components/Field"; +import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm"; +import { Card, Empty, PageHead } from "@/components/admin/ui"; +import { WeeklyPlan } from "@/components/admin/WeeklyPlan"; +import { addException, deleteException } from "../actions"; +import { AdvisorStatus, AdvisorTabs, loadAdvisor } from "../shared"; + +export const metadata = { title: "Meine Zeiten" }; + +const dayFmt = (date: string) => new Intl.DateTimeFormat("de-DE", { weekday: "short", day: "2-digit", month: "2-digit", year: "numeric", timeZone: "UTC" }).format(new Date(`${date}T12:00:00Z`)); + +export default async function AdvisorTimes({ searchParams }: { searchParams: Promise<{ b?: string }> }) { + const { b } = await searchParams; + const { advisor, foreign } = await loadAdvisor(b); + const today = berlinParts(new Date()).date; + const [rules, exceptions] = await Promise.all([ + db.availabilityRule.findMany({ where: { advisorId: advisor.id }, orderBy: [{ weekday: "asc" }, { start: "asc" }] }), + db.availabilityException.findMany({ where: { advisorId: advisor.id, date: { gte: today } }, orderBy: [{ date: "asc" }, { start: "asc" }] }), + ]); + return ( +
+ + + + + ({ weekday: r.weekday, start: minutesLabel(r.start), end: minutesLabel(r.end) }))} /> + + + {exceptions.length === 0 ? ( + + ) : ( +
+ + + {exceptions.map((e) => ( + + + + + + + ))} + +
{dayFmt(e.date)}{e.kind === "off" ? (e.start == null ? "ganzer Tag frei" : `frei ${minutesLabel(e.start)}–${minutesLabel(e.end!)}`) : `zusätzlich ${minutesLabel(e.start!)}–${minutesLabel(e.end!)}`}{e.note}
+
+ )} + + + + + + +
+ + +
+
+ + +
+ +
+
+
+ ); +} diff --git a/src/app/admin/(panel)/bestellungen/actions.ts b/src/app/admin/(panel)/bestellungen/actions.ts index cac2782..6d6ad18 100644 --- a/src/app/admin/(panel)/bestellungen/actions.ts +++ b/src/app/admin/(panel)/bestellungen/actions.ts @@ -13,7 +13,9 @@ import type { AddressData } from "@/lib/checkout"; import { cancelLabel, canCreateLabels, createLabel, getDhlConfig } from "@/lib/dhl"; import { autoInvoice, cancelInvoice, createInvoice } from "@/lib/invoices"; import { mailCancelled, mailPaymentReceived, mailShipped, sendLater } from "@/lib/mail/send"; -import { grantCourseAccess, isDigitalOrder, revokeCourseAccess } from "@/lib/courses"; +import { grantCourseAccess, isDigitalOrder } from "@/lib/courses"; +import { cancelOrderById } from "@/lib/order-cancel"; +import { bookAppointmentForOrder, cancelAppointmentForOrder } from "@/lib/consulting"; const authorName = (u: { firstName: string; lastName: string; email: string }) => [u.firstName, u.lastName].filter(Boolean).join(" ") || u.email; @@ -52,6 +54,7 @@ export async function updateOrder(_prev: ActionResult, fd: FormData): Promise mailPaymentReceived(id)); await grantCourseAccess(id); + await bookAppointmentForOrder(id); } if (status === "SHIPPED" && order.status !== "SHIPPED") { await autoInvoice(id, "shipped"); @@ -73,36 +76,11 @@ export async function addOrderNote(fd: FormData) { export async function cancelOrder(fd: FormData) { const user = await assertPermission("orders.refund"); const id = String(fd.get("id")); - const order = await db.order.findUnique({ where: { id } }); - if (!order || order.status === "CANCELLED" || order.status === "REFUNDED") return; - const wasPaid = order.paymentStatus === "PAID"; - let refundNote = ""; - if (wasPaid && getDefinition(order.paymentMethod)?.provider === "stripe" && order.paymentRef.startsWith("pi_")) { - try { - const creds = await getCredentials(); - await refundPayment(creds.stripe.secretKey, order.paymentRef); - refundNote = " Betrag über Stripe erstattet."; - } catch (e) { - refundNote = ` Stripe-Erstattung fehlgeschlagen (${e instanceof Error ? e.message : e}) – bitte im Stripe-Dashboard erstatten.`; - } - } else if (wasPaid) { - refundNote = " Bitte den Betrag manuell erstatten (z. B. im PayPal-Konto oder per Überweisung)."; - } - await db.$transaction(async (tx) => { - await restock(tx, id); - await tx.order.update({ - where: { id }, - data: { - status: wasPaid ? "REFUNDED" : "CANCELLED", - paymentStatus: wasPaid && refundNote.includes("erstattet.") ? "REFUNDED" : order.paymentStatus, - events: { create: { message: `${wasPaid ? "Erstattet" : "Storniert"}, Bestand zurückgebucht.${refundNote}`, author: authorName(user) } }, - }, - }); - }); - await cancelInvoice(id, authorName(user)); - await revokeCourseAccess(id); - sendLater(() => mailCancelled(id, wasPaid)); - await audit(user, wasPaid ? "Bestellung erstattet" : "Bestellung storniert", order.number); + const r = await cancelOrderById(id, authorName(user)); + if (!r) return; + // Gehört eine Beratung dazu, wird sie mit abgesagt + await cancelAppointmentForOrder(id, "shop"); + await audit(user, r.wasPaid ? "Bestellung erstattet" : "Bestellung storniert", r.order.number); revalidatePath(`/admin/bestellungen/${id}`); } diff --git a/src/app/admin/(panel)/emails/page.tsx b/src/app/admin/(panel)/emails/page.tsx index 32e1130..90148af 100644 --- a/src/app/admin/(panel)/emails/page.tsx +++ b/src/app/admin/(panel)/emails/page.tsx @@ -6,7 +6,7 @@ import { MAIL_TEMPLATES, getTemplateDef } from "@/lib/mail/templates"; import { getMailConfig, isMailReady } from "@/lib/mail/config"; import { Card, Empty, PageHead, Pill } from "@/components/admin/ui"; -const GROUPS = ["Bestellung", "Produkt", "Konto", "Newsletter", "Team"] as const; +const GROUPS = ["Bestellung", "Beratung", "Produkt", "Konto", "Newsletter", "Team"] as const; export default async function EmailsPage({ searchParams }: { searchParams: Promise<{ tab?: string }> }) { await requireAdmin("emails.edit"); diff --git a/src/app/admin/(panel)/page.tsx b/src/app/admin/(panel)/page.tsx index e5933ce..5c904c8 100644 --- a/src/app/admin/(panel)/page.tsx +++ b/src/app/admin/(panel)/page.tsx @@ -1,4 +1,5 @@ import Link from "next/link"; +import { redirect } from "next/navigation"; import { db } from "@/lib/db"; import { can, requireAdmin } from "@/lib/auth"; import { formatPrice } from "@/lib/money"; @@ -14,6 +15,8 @@ const PAID = { in: ["PAID", "PROCESSING", "SHIPPED", "COMPLETED"] as ("PAID" | " export default async function Dashboard({ searchParams }: { searchParams: Promise<{ "kein-zugriff"?: string }> }) { const user = await requireAdmin(); const noAccess = (await searchParams)["kein-zugriff"]; + // Beraterinnen ohne Dashboard landen direkt in ihrem Bereich + if (!can(user, "dashboard.view") && can(user, "consulting.own") && !noAccess) redirect("/admin/beratung"); if (!can(user, "dashboard.view")) { return (
diff --git a/src/app/api/beratung/ics/[id]/route.ts b/src/app/api/beratung/ics/[id]/route.ts new file mode 100644 index 0000000..0c12f29 --- /dev/null +++ b/src/app/api/beratung/ics/[id]/route.ts @@ -0,0 +1,16 @@ +import { db } from "@/lib/db"; +import { can, getCurrentUser } from "@/lib/auth"; +import { icsFor } from "@/lib/consulting"; + +export const dynamic = "force-dynamic"; + +/** Kalenderdatei für die Kundin, die Beraterin oder das Team. */ +export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + const user = await getCurrentUser(); + const a = await db.appointment.findUnique({ where: { id }, include: { advisor: true } }); + if (!user || !a || !(a.customerId === user.id || a.advisor.userId === user.id || can(user, "consulting.manage"))) return new Response("Nicht gefunden", { status: 404 }); + return new Response(icsFor(a, a.advisor.displayName), { + headers: { "Content-Type": "text/calendar; charset=utf-8", "Content-Disposition": `attachment; filename="termin-${a.number}.ics"`, "Cache-Control": "private, no-store" }, + }); +} diff --git a/src/app/api/payments/paypal/return/route.ts b/src/app/api/payments/paypal/return/route.ts index 2ec2d11..45c1e08 100644 --- a/src/app/api/payments/paypal/return/route.ts +++ b/src/app/api/payments/paypal/return/route.ts @@ -21,6 +21,7 @@ export async function GET(req: NextRequest) { await db.orderEvent.create({ data: { orderId: order.id, message: `PayPal-Zahlung fehlgeschlagen: ${e instanceof Error ? e.message : e}` } }); return NextResponse.redirect(new URL("/kasse/zahlung?abgebrochen=1", appUrl)); } - await finishCheckoutSession(); + // Bei Beratungen nichts am Warenkorb ändern + if (!(await db.appointment.findUnique({ where: { orderId: order.id } }))) await finishCheckoutSession(); return NextResponse.redirect(new URL(`/kasse/danke/${order.id}`, appUrl)); } diff --git a/src/app/api/payments/stripe/return/route.ts b/src/app/api/payments/stripe/return/route.ts index a027c19..a634d8b 100644 --- a/src/app/api/payments/stripe/return/route.ts +++ b/src/app/api/payments/stripe/return/route.ts @@ -24,6 +24,7 @@ export async function GET(req: NextRequest) { } catch (e) { await db.orderEvent.create({ data: { orderId: order.id, message: `Stripe-Prüfung fehlgeschlagen: ${e instanceof Error ? e.message : e}` } }); } - await finishCheckoutSession(); + // Bei Beratungen nichts am Warenkorb ändern + if (!(await db.appointment.findUnique({ where: { orderId: order.id } }))) await finishCheckoutSession(); return NextResponse.redirect(new URL(`/kasse/danke/${order.id}`, appUrl)); } diff --git a/src/components/Icon.tsx b/src/components/Icon.tsx index 82ff602..b1c7954 100644 --- a/src/components/Icon.tsx +++ b/src/components/Icon.tsx @@ -40,6 +40,9 @@ const PATHS = { trash: (<>), edit: (<>), eye: (<>), + calendar: (<>), + video: (<>), + mic: (<>), play: (<>), image: (<>), grip: , diff --git a/src/components/admin/AdminNav.tsx b/src/components/admin/AdminNav.tsx index 9f220e4..0e22957 100644 --- a/src/components/admin/AdminNav.tsx +++ b/src/components/admin/AdminNav.tsx @@ -10,6 +10,7 @@ const BADGE: Record string }> = { newCustomers: { cls: "", title: (n) => `${n} ${n === 1 ? "neuer Kunde" : "neue Kunden"} seit deinem letzten Besuch` }, newSubscribers: { cls: "", title: (n) => `${n} ${n === 1 ? "neue Anmeldung" : "neue Anmeldungen"} seit deinem letzten Besuch` }, lowStock: { cls: " ad-nav__badge--warn", title: (n) => `${n} Artikel mit wenig oder keinem Bestand` }, + openRequests: { cls: " ad-nav__badge--strong", title: (n) => `${n} offene ${n === 1 ? "Terminanfrage" : "Terminanfragen"}` }, }; export function AdminNav({ groups }: { groups: { group: string; items: NavItem[] }[] }) { diff --git a/src/components/admin/ConsultForms.tsx b/src/components/admin/ConsultForms.tsx new file mode 100644 index 0000000..438e859 --- /dev/null +++ b/src/components/admin/ConsultForms.tsx @@ -0,0 +1,120 @@ +"use client"; +import { useActionState, useState } from "react"; +import { useFormStatus } from "react-dom"; +import type { ActionResult } from "@/lib/action-result"; +import { cancelByAdvisor, respond, saveNote } from "@/app/admin/(panel)/beratung/actions"; +import { Icon } from "../Icon"; + +function Submit({ label, className = "sm-btn sm-btn--primary sm-btn--sm" }: { label: string; className?: string }) { + const { pending } = useFormStatus(); + return ; +} + +function Result({ state }: { state: ActionResult }) { + if (!state?.message) return null; + return {state.message}; +} + +type SlotGroup = { label: string; options: { value: string; label: string }[] }; + +/** Antwort auf eine Anfrage: bestätigen, andere Zeiten vorschlagen oder ablehnen. */ +export function RespondForm({ id, slots }: { id: string; slots: SlotGroup[] }) { + const [state, action] = useActionState(respond, null); + const [mode, setMode] = useState<"" | "propose" | "decline">(""); + if (state?.ok) return ; + return ( +
+
+
+ + + + + + +
+ {mode === "propose" && ( +
+ + + {slots.length === 0 ? ( +

In den nächsten Wochen sind keine passenden freien Zeiten eingetragen. Trag unter „Zeiten“ welche ein.

+ ) : ( +
+ {["p1", "p2", "p3"].map((k, i) => ( + + ))} +
+ )} +