├── .prettierrc ├── app ├── favicon.ico ├── page.tsx ├── discount │ ├── page.tsx │ ├── useUrlParams.ts │ ├── Analysis.tsx │ └── DiscountContent.tsx ├── api │ ├── [trpc] │ │ └── route.ts │ ├── getJourney │ │ ├── extractSplitPoints.ts │ │ └── getJourney.ts │ └── analyzeJourney.ts ├── globals.css └── layout.tsx ├── .vscode ├── settings.json ├── extensions.json └── launch.json ├── public └── train.jpg ├── pnpm-workspace.yaml ├── utils ├── priceUtils.ts ├── types.ts ├── trpc-init.ts ├── db-vendo-client-types.d.ts ├── journeyUtils.ts ├── TRPCProvider.tsx ├── fetchAndValidateJson.ts ├── formatUtils.ts ├── schemas.ts ├── parseHinfahrtRecon.ts ├── deutschlandTicketUtils.ts └── createUrl.ts ├── .dockerignore ├── postcss.config.mjs ├── CREDITS.md ├── .gitignore ├── sample-verbindung.txt ├── next-env.d.ts ├── components ├── discount │ ├── JourneyInfoRow.tsx │ ├── JourneyIcon.tsx │ ├── useUrlParams.ts │ ├── ErrorDisplay.tsx │ ├── StatusBox.tsx │ ├── SplitOptionsCard.tsx │ └── OriginalJourneyCard.tsx ├── JourneyCard │ ├── JourneyDuration.tsx │ ├── LegDuration.tsx │ ├── journey-card-utils.tsx │ ├── getTransferStations.ts │ ├── LegDetails.tsx │ └── JourneyCard.tsx ├── Layout │ ├── Hero.tsx │ └── Navbar.tsx ├── SearchForm │ ├── HelpSection.tsx │ ├── useLocalStorage.ts │ ├── URLInput.tsx │ └── SearchForm.tsx ├── Journey.tsx └── SplitOptions │ ├── getOptionsToShow.ts │ ├── Segment.tsx │ ├── calculateSplitOptionPricing.ts │ └── SplitOptions.tsx ├── .github ├── workflows │ ├── release-drafter.yml │ ├── CI.yaml │ ├── close-stale-issues-and-prs.yaml │ └── docker-image.yml ├── dependabot.yml ├── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md └── release-drafter.yml ├── next.config.js ├── .oxlintrc.json ├── docker-compose └── docker-compose.yaml ├── tsconfig.json ├── Dockerfile ├── package.json ├── README.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTE.md └── LICENSE /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "useTabs": true 3 | } 4 | -------------------------------------------------------------------------------- /app/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BetterBahn/betterbahn/HEAD/app/favicon.ico -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true, 3 | "oxc.enable": true 4 | } 5 | -------------------------------------------------------------------------------- /public/train.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BetterBahn/betterbahn/HEAD/public/train.jpg -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | onlyBuiltDependencies: 2 | - '@tailwindcss/oxide' 3 | - puppeteer 4 | - sharp 5 | -------------------------------------------------------------------------------- /utils/priceUtils.ts: -------------------------------------------------------------------------------- 1 | export const formatPriceDE = (price: number): string => { 2 | return `${price.toFixed(2).replace(".", ",")} €`; 3 | }; -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | node_modules/ 3 | 4 | # Next.js 5 | .next/ 6 | out/ 7 | build/ 8 | dist/ 9 | 10 | # Enviroment files 11 | .env -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "oxc.oxc-vscode", 4 | "esbenp.prettier-vscode", 5 | "bradlc.vscode-tailwindcss", 6 | "davidanson.vscode-markdownlint" 7 | ] 8 | } -------------------------------------------------------------------------------- /postcss.config.mjs: -------------------------------------------------------------------------------- 1 | // PostCSS-Konfiguration für TailwindCSS 2 | const config = { 3 | // Plugin-Liste: TailwindCSS für Utility-first CSS 4 | plugins: ["@tailwindcss/postcss"], 5 | }; 6 | 7 | export default config; 8 | -------------------------------------------------------------------------------- /CREDITS.md: -------------------------------------------------------------------------------- 1 | # Image Credits 2 | 3 | - **Train Photo**: Photo by Mihail Cioinica 4 | Url: 5 | License: Unsplash License (Free to use) 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | node_modules/ 3 | 4 | # Next.js 5 | .next/ 6 | out/ 7 | build/ 8 | dist/ 9 | 10 | # Enviroment files 11 | .env 12 | 13 | # JetBrains editors 14 | .idea 15 | 16 | # etc 17 | .DS_Store 18 | 19 | # TypeScript 20 | /tsconfig.tsbuildinfo -------------------------------------------------------------------------------- /sample-verbindung.txt: -------------------------------------------------------------------------------- 1 | Verbindung am Di. 02.12.2025 2 | • von Magdeburg Hbf, Abfahrt 15:01 Uhr Gl. 6 mit IC 2036 3 | • nach Oldenburg(Oldb)Hbf, Ankunft 18:23 Uhr Gl. 6 mit IC 2036 4 | Verbindung ansehen: https://www.bahn.de/buchung/start?vbid=7847e36d-f342-4f21-9ed3-6b41f0a5d0df -------------------------------------------------------------------------------- /next-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | import "./.next/types/routes.d.ts"; 4 | 5 | // NOTE: This file should not be edited 6 | // see https://nextjs.org/docs/app/api-reference/config/typescript for more information. 7 | -------------------------------------------------------------------------------- /app/page.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { Hero } from "@/components/Layout/Hero"; 4 | import { SearchForm } from "@/components/SearchForm/SearchForm"; 5 | 6 | export default function Home() { 7 | return ( 8 | <> 9 | 10 | 11 | 12 | ); 13 | } 14 | -------------------------------------------------------------------------------- /components/discount/JourneyInfoRow.tsx: -------------------------------------------------------------------------------- 1 | import type { ReactNode } from "react"; 2 | 3 | interface JourneyInfoRowProps { 4 | children: ReactNode; 5 | } 6 | 7 | export function JourneyInfoRow({ children }: JourneyInfoRowProps) { 8 | return
{children}
; 9 | } -------------------------------------------------------------------------------- /components/JourneyCard/JourneyDuration.tsx: -------------------------------------------------------------------------------- 1 | import type { VendoJourney } from "@/utils/schemas"; 2 | import { formatDuration } from "@/utils/formatUtils"; 3 | 4 | export const JourneyDuration = ({ journey }: { journey: VendoJourney }) => { 5 | const duration = formatDuration(journey); 6 | return duration || "Duration unavailable"; 7 | }; 8 | -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | update_release_draft: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: release-drafter/release-drafter@v6 13 | env: 14 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 15 | -------------------------------------------------------------------------------- /next.config.js: -------------------------------------------------------------------------------- 1 | // Next.js Konfigurationsdatei 2 | module.exports = { 3 | // Standalone-Output für Docker-Deployment aktivieren 4 | // Dies erstellt eine eigenständige Version der App mit allen Abhängigkeiten 5 | output: "standalone", 6 | typescript: { 7 | ignoreBuildErrors: true // temporarily, since some type errors still exists and are ambiguous 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /utils/types.ts: -------------------------------------------------------------------------------- 1 | import type { VendoStation } from "@/utils/schemas"; 2 | 3 | export interface TrainLine { 4 | name?: string; 5 | product?: string; 6 | } 7 | 8 | export interface SplitPoint { 9 | departure: Date; 10 | arrival: Date; 11 | station: VendoStation; 12 | trainLine?: TrainLine; 13 | loadFactor?: unknown; 14 | legIndex: number; 15 | stopIndex: number; 16 | } 17 | -------------------------------------------------------------------------------- /.oxlintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "categories": { 3 | "correctness": "error", 4 | "nursery": "warn", 5 | "pedantic": "warn", 6 | "suspicious": "warn" 7 | }, 8 | "rules": { 9 | "max-lines-per-function": "off", 10 | "max-lines": "off", 11 | "max-depth": "off" 12 | }, 13 | "env": { 14 | "browser": true, 15 | "node": true 16 | }, 17 | "ignorePatterns": ["next-env.d.ts"] 18 | } 19 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "npm" 4 | directory: "/" 5 | schedule: 6 | interval: "monthly" 7 | 8 | - package-ecosystem: "github-actions" 9 | directory: "/" 10 | schedule: 11 | interval: "monthly" 12 | 13 | - package-ecosystem: "docker" 14 | directory: "/" 15 | schedule: 16 | interval: "monthly" 17 | -------------------------------------------------------------------------------- /components/JourneyCard/LegDuration.tsx: -------------------------------------------------------------------------------- 1 | import type { VendoLeg } from "@/utils/schemas"; 2 | 3 | export const LegDuration = ({ leg }: { leg: VendoLeg }) => { 4 | const diffMs = leg.arrival.getTime() - leg.departure.getTime(); 5 | const diffMins = Math.floor(diffMs / 60000); 6 | const hours = Math.floor(diffMins / 60); 7 | const minutes = diffMins % 60; 8 | return `${hours}h ${minutes}m`; 9 | }; 10 | -------------------------------------------------------------------------------- /app/discount/page.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { Suspense } from "react"; 4 | import { DiscountContent } from "./DiscountContent"; 5 | 6 | const Discount = () => ( 7 |
8 | {/* Suspense is for useSearchParams https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout */} 9 | 10 | 11 | 12 |
13 | ); 14 | 15 | export default Discount; 16 | -------------------------------------------------------------------------------- /.github/workflows/CI.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v6 10 | - uses: pnpm/action-setup@v4 11 | - uses: actions/setup-node@v6 12 | - name: Install modules 13 | run: pnpm install 14 | - name: Run Typecheck 15 | run: pnpm tsc 16 | - name: Run Oxlint 17 | run: pnpm run oxlint 18 | - run: pnpm run build 19 | -------------------------------------------------------------------------------- /utils/trpc-init.ts: -------------------------------------------------------------------------------- 1 | import { initTRPC } from "@trpc/server"; 2 | import SuperJSON from "superjson"; 3 | import { prettifyError, ZodError } from "zod/v4"; 4 | 5 | export const t = initTRPC.create({ 6 | transformer: SuperJSON, 7 | errorFormatter(opts) { 8 | const { shape, error } = opts; 9 | 10 | return { 11 | ...shape, 12 | data: { 13 | ...shape.data, 14 | zodError: 15 | error.cause instanceof ZodError ? prettifyError(error.cause) : null, 16 | }, 17 | }; 18 | }, 19 | }); 20 | -------------------------------------------------------------------------------- /docker-compose/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | betterbahn: 3 | image: ghcr.io/betterbahn/betterbahn:latest 4 | restart: unless-stopped 5 | environment: 6 | - TZ=Europe/Berlin # Timezone, dont Remove or else There will be time issues with tickets. 7 | ports: 8 | - "3000:3000" 9 | read_only: true 10 | user: "1000:1000" 11 | tmpfs: 12 | - /tmp 13 | privileged: false 14 | cap_drop: 15 | - ALL 16 | security_opt: 17 | - no-new-privileges=true 18 | -------------------------------------------------------------------------------- /app/api/[trpc]/route.ts: -------------------------------------------------------------------------------- 1 | import { t } from "@/utils/trpc-init"; 2 | import { fetchRequestHandler } from "@trpc/server/adapters/fetch"; 3 | import { analyzeJourney } from "../analyzeJourney"; 4 | import { getJourney } from "../getJourney/getJourney"; 5 | 6 | const appRouter = t.router({ getJourney, analyzeJourney }); 7 | 8 | export type AppRouter = typeof appRouter; 9 | 10 | const handler = (req: Request) => 11 | fetchRequestHandler({ 12 | endpoint: "/api", 13 | req, 14 | router: appRouter, 15 | onError(opts) { 16 | console.error("TRPC Error", opts.error.message); 17 | }, 18 | }); 19 | 20 | export { handler as GET, handler as POST }; 21 | -------------------------------------------------------------------------------- /app/discount/useUrlParams.ts: -------------------------------------------------------------------------------- 1 | import { useSearchParams } from "next/navigation"; 2 | 3 | export const useUrlParams = () => { 4 | const searchParams = useSearchParams(); 5 | 6 | return { 7 | bahnCard: searchParams.has("bahnCard") 8 | ? Number.parseInt(searchParams.get("bahnCard")!, 10) 9 | : null, 10 | vbid: searchParams.get("vbid")!, 11 | travelClass: Number.parseInt(searchParams.get("travelClass")!, 10), 12 | hasDeutschlandTicket: searchParams.get("hasDeutschlandTicket") === "true", 13 | passengerAge: searchParams.get("passengerAge") 14 | ? Number.parseInt(searchParams.get("passengerAge")!, 10) 15 | : undefined, 16 | }; 17 | }; 18 | -------------------------------------------------------------------------------- /components/JourneyCard/journey-card-utils.tsx: -------------------------------------------------------------------------------- 1 | import type { VendoLeg } from "@/utils/schemas"; 2 | 3 | export const TrainIdentifier = ({ leg }: { leg: VendoLeg }) => { 4 | // Try to get the best train identifier 5 | if (leg.line?.name) { 6 | return leg.line.name; 7 | } 8 | 9 | if (leg.line?.product && leg.line?.productName) { 10 | return `${leg.line.product} ${leg.line.productName}`; 11 | } 12 | 13 | if (leg.line?.product) { 14 | return leg.line.product; 15 | } 16 | 17 | if (leg.line?.mode && typeof leg.line.mode === "string") { 18 | return leg.line.mode; 19 | } 20 | 21 | if (leg.mode) { 22 | return leg.mode; 23 | } 24 | 25 | return "Train"; 26 | }; 27 | -------------------------------------------------------------------------------- /components/discount/JourneyIcon.tsx: -------------------------------------------------------------------------------- 1 | export function JourneyIcon() { 2 | return ( 3 |
4 | 12 | 17 | 18 |
19 |
20 |
21 | ); 22 | } -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: Suggest an idea for this project 4 | title: "[FEAT] A brief, descriptive title" 5 | labels: 'enhancement, needs-triage' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /components/JourneyCard/getTransferStations.ts: -------------------------------------------------------------------------------- 1 | import type { VendoLeg } from "@/utils/schemas"; 2 | 3 | export const getTransferStations = (nonWalkingLegs: VendoLeg[]) => { 4 | if (nonWalkingLegs.length <= 1) { 5 | return []; 6 | } 7 | 8 | const transferStations: string[] = []; 9 | 10 | for (let i = 0; i < nonWalkingLegs.length - 1; i++) { 11 | const currentLeg = nonWalkingLegs[i]; 12 | const nextLeg = nonWalkingLegs[i + 1]; 13 | 14 | // Transfer happens at the destination of current leg / origin of next leg 15 | const transferStation = 16 | currentLeg.destination?.name || nextLeg.origin?.name; 17 | 18 | if (transferStation && !transferStations.includes(transferStation)) { 19 | transferStations.push(transferStation); 20 | } 21 | } 22 | 23 | return transferStations; 24 | }; 25 | -------------------------------------------------------------------------------- /components/discount/useUrlParams.ts: -------------------------------------------------------------------------------- 1 | import { useEffect, useState } from "react"; 2 | 3 | export const useUrlParams = () => { 4 | const [hasDeutschlandTicket, setHasDeutschlandTicket] = useState(false); 5 | const [travelClass, setTravelClass] = useState("2"); 6 | const [bahnCard, setBahnCard] = useState(null); 7 | 8 | useEffect(() => { 9 | if (typeof window === "undefined") { 10 | return; 11 | } 12 | 13 | const searchParams = new URLSearchParams(window.location.search); 14 | 15 | setHasDeutschlandTicket( 16 | searchParams.get("hasDeutschlandTicket") === "true" 17 | ); 18 | 19 | setTravelClass(searchParams.get("travelClass") || "2"); 20 | setBahnCard(searchParams.get("bahnCard")); 21 | }, []); 22 | 23 | return { hasDeutschlandTicket, travelClass, bahnCard }; 24 | }; 25 | -------------------------------------------------------------------------------- /components/Layout/Hero.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import train from "../../public/train.jpg"; 3 | 4 | export const Hero = () => { 5 | return ( 6 |
12 | {/* Hauptslogan mit hervorgehobenem Text */} 13 |
14 | Gleicher Zug, Gleiche Zeit,{" "} 15 | 16 | Besserer Preis 17 | 18 |
19 |
20 | ); 21 | }; 22 | 23 | -------------------------------------------------------------------------------- /components/SearchForm/HelpSection.tsx: -------------------------------------------------------------------------------- 1 | export const HelpSection = () => ( 2 |
3 |

4 | So findest du den Text zum Teilen: 5 |

6 |
    7 |
  1. 8 | Gehe auf bahn.de und plane deine Verbindung 9 |
  2. 10 |
  3. Wähle deine gewünschte Verbindung aus
  4. 11 |
  5. 12 | Klicke auf die drei kleinen Punkte oben in der Ecke der Verbindung 13 |
  6. 14 |
  7. 15 | Klicke auf "Verbindung Teilen" 16 |
  8. 17 |
  9. 18 | Klicke auf "Infos Kopieren" 19 |
  10. 20 |
  11. Füge den kompletten kopierten Text hier ein
  12. 21 |
22 |
23 | ); 24 | -------------------------------------------------------------------------------- /components/Journey.tsx: -------------------------------------------------------------------------------- 1 | import type { VendoJourney } from "@/utils/schemas"; 2 | import { JourneyCard } from "./JourneyCard/JourneyCard"; 3 | 4 | interface Props { 5 | isSelected?: boolean; 6 | onClick: () => void; 7 | journey: VendoJourney; 8 | } 9 | 10 | export const Journey = ({ journey, onClick, isSelected }: Props) => ( 11 |
16 | 17 | 18 | {isSelected && ( 19 |

20 | ✅ Diese Verbindung ausgewählt - Scroll nach unten für Split-Ticket 21 | Analyse 22 |

23 | )} 24 |
25 | ); 26 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Next.js: debug server-side", 6 | "type": "node-terminal", 7 | "request": "launch", 8 | "command": "pnpm run dev" 9 | }, 10 | { 11 | "name": "Next.js: debug client-side", 12 | "type": "chrome", 13 | "request": "launch", 14 | "url": "http://localhost:3000" 15 | }, 16 | { 17 | "name": "Next.js: debug full stack", 18 | "type": "node", 19 | "request": "launch", 20 | "program": "${workspaceFolder}/node_modules/next/dist/bin/next", 21 | "runtimeArgs": ["--inspect"], 22 | "skipFiles": ["/**"], 23 | "serverReadyAction": { 24 | "action": "debugWithEdge", 25 | "killOnServerStop": true, 26 | "pattern": "- Local:.+(https?://.+)", 27 | "uriFormat": "%s", 28 | "webRoot": "${workspaceFolder}" 29 | } 30 | } 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2024", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "strict": true, 12 | "noEmit": true, 13 | "esModuleInterop": true, 14 | "module": "esnext", 15 | "moduleResolution": "bundler", 16 | "resolveJsonModule": true, 17 | "isolatedModules": true, 18 | "jsx": "react-jsx", 19 | "incremental": true, 20 | "plugins": [ 21 | { 22 | "name": "next" 23 | } 24 | ], 25 | "paths": { 26 | "@/*": [ 27 | "./*" 28 | ] 29 | } 30 | }, 31 | "include": [ 32 | "next-env.d.ts", 33 | "**/*.ts", 34 | "**/*.tsx", 35 | ".next/types/**/*.ts", 36 | ".next/dev/types/**/*.ts" 37 | ], 38 | "exclude": [ 39 | "node_modules", 40 | ".next" 41 | ] 42 | } 43 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:25-alpine AS builder 2 | ENV PNPM_HOME="/pnpm" 3 | ENV PATH="$PNPM_HOME:$PATH" 4 | RUN npm install -g pnpm 5 | WORKDIR /app 6 | COPY . . 7 | RUN pnpm install --frozen-lockfile 8 | RUN pnpm run build 9 | 10 | FROM node:25-alpine AS runner 11 | WORKDIR /app 12 | ENV TZ=Europe/Berlin 13 | ENV NODE_ENV=production 14 | ENV NEXT_TELEMETRY_DISABLED=1 15 | COPY --from=builder /app/.next/standalone ./ 16 | COPY --from=builder /app/.next/static ./.next/static 17 | 18 | # Some data files used at runtime are not included in standalone 19 | COPY --from=builder /app/node_modules/.pnpm/db-hafas-stations@2.0.0 ./node_modules/.pnpm/db-hafas-stations@2.0.0 20 | 21 | USER node 22 | EXPOSE 3000 23 | HEALTHCHECK --interval=30s --timeout=10s --start-period=20s --retries=5 \ 24 | CMD IP=$(hostname -i | awk '{print $1}'); wget -q -O - "http://$IP:${PORT:-3000}" > /dev/null || exit 1 25 | 26 | CMD ["node", "server.js"] 27 | -------------------------------------------------------------------------------- /app/globals.css: -------------------------------------------------------------------------------- 1 | @import "tailwindcss"; 2 | 3 | :root { 4 | --background: #ffffff; 5 | --foreground: #171717; 6 | --primary: #4B6058; 7 | color-scheme: light dark; 8 | font-synthesis: none; 9 | text-rendering: optimizeLegibility; 10 | -webkit-font-smoothing: antialiased; 11 | -moz-osx-font-smoothing: grayscale; 12 | } 13 | 14 | @theme inline { 15 | --color-background: var(--background); 16 | --color-foreground: var(--foreground); 17 | --color-primary: var(--primary); 18 | --font-sans: var(--font-geist-sans); 19 | --font-mono: var(--font-geist-mono); 20 | --background-image-train: url("/train.jpg"); 21 | } 22 | 23 | body { 24 | background: var(--background); 25 | color: var(--foreground); 26 | font-family: Arial, Helvetica, sans-serif; 27 | } 28 | 29 | @media (prefers-color-scheme: dark) { 30 | :root { 31 | --background: #171717; 32 | --foreground: #ffffff; 33 | --primary: #4B6058; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /components/SearchForm/useLocalStorage.ts: -------------------------------------------------------------------------------- 1 | import { useEffect, useState } from "react"; 2 | 3 | export const useLocalStorage = (key: string, initialValue: T) => { 4 | const [value, setValueInternal] = useState(() => initialValue); 5 | 6 | const initialize = () => { 7 | if (typeof window === "undefined") { 8 | return initialValue; 9 | } 10 | 11 | const stringified = window.localStorage.getItem(key); 12 | 13 | if (stringified === null) { 14 | return initialValue; 15 | } 16 | 17 | return JSON.parse(stringified) as T; 18 | }; 19 | 20 | // prevents hydration error so that state is only initialized after server is defined 21 | useEffect(() => { 22 | setValueInternal(initialize()); 23 | }, []); 24 | 25 | const setValueExternal = (newValue: T) => { 26 | setValueInternal(newValue); 27 | window.localStorage.setItem(key, JSON.stringify(newValue)); 28 | }; 29 | 30 | return [value, setValueExternal] as const; 31 | }; 32 | -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name-template: 'v$RESOLVED_VERSION' 2 | tag-template: 'v$RESOLVED_VERSION' 3 | template: | 4 | # What's Changed 5 | 6 | $CHANGES 7 | 8 | **Full Changelog**: https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION 9 | 10 | categories: 11 | - title: '⚠️ Breaking ⚠️' 12 | label: 'type: breaking' 13 | - title: 'New Features' 14 | label: 'type: feature' 15 | - title: 'Bug Fixes' 16 | label: 'type: bug' 17 | - title: 'Documentation' 18 | label: 'type: docs' 19 | - title: 'Other changes' 20 | - title: 'Dependency Updates' 21 | label: 'type: dependencies' 22 | 23 | version-resolver: 24 | major: 25 | labels: 26 | - 'type: breaking' 27 | minor: 28 | labels: 29 | - 'type: feature' 30 | patch: 31 | labels: 32 | - 'type: bug' 33 | - 'type: docs' 34 | - 'type: dependencies' 35 | - 'type: security' 36 | 37 | exclude-labels: 38 | - 'skip-changelog' -------------------------------------------------------------------------------- /app/layout.tsx: -------------------------------------------------------------------------------- 1 | import { Navbar } from "@/components/Layout/Navbar"; 2 | import { Geist, Geist_Mono } from "next/font/google"; 3 | import type { ReactNode } from "react"; 4 | import "./globals.css"; 5 | import { TRPCReactProvider } from "@/utils/TRPCProvider"; 6 | 7 | const geistSans = Geist({ 8 | variable: "--font-geist-sans", 9 | subsets: ["latin"], 10 | }); 11 | 12 | const geistMono = Geist_Mono({ 13 | variable: "--font-geist-mono", 14 | subsets: ["latin"], 15 | }); 16 | 17 | export const metadata = { 18 | title: "Better Bahn - Split-Ticketing", 19 | description: "Eine App von Lukas Weihrauch", 20 | }; 21 | 22 | export default function RootLayout({ children }: { children: ReactNode }) { 23 | return ( 24 | 25 | 26 | 29 | 30 | {children} 31 | 32 | 33 | 34 | ); 35 | } 36 | -------------------------------------------------------------------------------- /utils/db-vendo-client-types.d.ts: -------------------------------------------------------------------------------- 1 | declare module "db-vendo-client" { 2 | interface VendoClient { 3 | journeys( 4 | from: string, 5 | to: string, 6 | options: SearchJourneysOptions 7 | ): Promise; 8 | } 9 | 10 | export function createClient( 11 | dbProfile: unknown, 12 | userAgent: string 13 | ): VendoClient; 14 | 15 | export interface SearchJourneysOptions { 16 | results: number; 17 | stopovers: boolean; 18 | notOnlyFastRoutes: boolean; 19 | remarks: boolean; 20 | transfers: number; 21 | firstClass: boolean; 22 | departure?: Date; 23 | loyaltyCard?: { 24 | type: string; 25 | discount: number; 26 | class: number; 27 | }; 28 | age?: number; 29 | deutschlandTicketDiscount?: boolean; 30 | deutschlandTicketConnectionsOnly?: boolean; 31 | } 32 | } 33 | 34 | declare module "db-vendo-client/format/loyalty-cards" { 35 | export const data: Record; 36 | } 37 | 38 | declare module "db-vendo-client/p/db/index" { 39 | export const profile: unknown; 40 | } 41 | -------------------------------------------------------------------------------- /components/discount/ErrorDisplay.tsx: -------------------------------------------------------------------------------- 1 | interface ErrorDisplayProps { 2 | error: string; 3 | } 4 | 5 | // Helper function to convert URLs in text to clickable links 6 | function renderTextWithLinks(text: string) { 7 | const urlRegex = /(https?:\/\/[^\s]+)/g; 8 | const parts = text.split(urlRegex); 9 | 10 | return parts.map((part, index) => { 11 | if (urlRegex.test(part)) { 12 | return ( 13 | 20 | {part} 21 | 22 | ); 23 | } 24 | return part; 25 | }); 26 | } 27 | 28 | export function ErrorDisplay({ error }: ErrorDisplayProps) { 29 | return ( 30 |
31 |
32 |
⚠️
33 |
34 | Fehler: {renderTextWithLinks(error)} 35 |
36 |
37 |
38 | ); 39 | } -------------------------------------------------------------------------------- /components/discount/StatusBox.tsx: -------------------------------------------------------------------------------- 1 | export interface Progress { 2 | checked: number; 3 | total: number; 4 | currentStation: string | null; 5 | } 6 | 7 | export const StatusBox = ({ 8 | progress: { checked, currentStation, total }, 9 | }: { 10 | progress: Progress; 11 | }) => ( 12 |
13 |
14 |
15 | Prüfe {currentStation}... 16 |
17 | 18 | {/* Progress bar */} 19 |
20 |
26 |
27 | 28 | {/* Progress information */} 29 |
30 | {Math.round((checked / total) * 100)}% — {checked} / {total} Stationen 31 | geprüft 32 |
33 |
34 | ); 35 | -------------------------------------------------------------------------------- /.github/workflows/close-stale-issues-and-prs.yaml: -------------------------------------------------------------------------------- 1 | name: Close inactive issues and PRs 2 | on: 3 | schedule: 4 | - cron: "30 1 * * *" 5 | 6 | jobs: 7 | close-issues: 8 | runs-on: ubuntu-latest 9 | permissions: 10 | issues: write 11 | pull-requests: write 12 | steps: 13 | - uses: actions/stale@v10 14 | with: 15 | exempt-issue-labels: do-not-stale,enhancement 16 | days-before-stale: 30 17 | days-before-close: 14 18 | stale-issue-message: "This issue is stale because it has been open for 30 days with no activity. It will be closed in 14 days if there is no activity." 19 | close-issue-message: "This issue was closed because it has been inactive for 14 days since being marked as stale." 20 | stale-pr-message: "This PR is stale because it has been open for 30 days with no activity. It will be closed in 14 days if there is no activity." 21 | close-pr-message: "This PR was closed because it has been inactive for 14 days since being marked as stale." 22 | repo-token: ${{ secrets.GITHUB_TOKEN }} 23 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Create a report to help us improve 4 | title: "[BUG] A brief, descriptive title" 5 | labels: 'bug, needs-triage' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 16 | 1. Go to '...' 17 | 2. Click on '....' 18 | 3. Scroll down to '....' 19 | 4. See error 20 | 21 | **Expected behavior** 22 | A clear and concise description of what you expected to happen. 23 | 24 | **Screenshots** 25 | If applicable, add screenshots to help explain your problem. You can drag and drop images here. 26 | 27 | **Desktop (please complete the following information):** 28 | 29 | - OS: [e.g. iOS, Windows 10, Ubuntu 22.04] 30 | - Browser (if applicable): [e.g. Chrome, Safari, Firefox] 31 | - Version [e.g. 22] 32 | 33 | **Smartphone (please complete the following information):** 34 | 35 | - Device: [e.g. iPhone 13] 36 | - OS: [e.g. iOS 16.1] 37 | - Browser (if applicable): [e.g. stock browser, Safari] 38 | - Version [e.g. 22] 39 | 40 | **Additional context** 41 | Add any other context about the problem here. For example, are you behind a firewall? Did this work in a previous version? 42 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "db_ticket", 3 | "version": "0.1.0", 4 | "private": true, 5 | "license": "AGPL-3.0-only", 6 | "scripts": { 7 | "dev": "next dev", 8 | "build": "next build", 9 | "start": "next start", 10 | "deploy": "docker build", 11 | "oxlint": "oxlint" 12 | }, 13 | "dependencies": { 14 | "@tanstack/react-query": "^5.90.12", 15 | "@trpc/client": "^11.7.2", 16 | "@trpc/next": "^11.7.2", 17 | "@trpc/react-query": "^11.7.2", 18 | "@trpc/server": "^11.8.0", 19 | "@trpc/tanstack-react-query": "^11.7.2", 20 | "db-hafas-stations": "^2.0.0", 21 | "db-vendo-client": "^6.10.6", 22 | "next": "16.0.10", 23 | "react": "^19.2.3", 24 | "react-dom": "^19.2.3", 25 | "superjson": "^2.2.6" 26 | }, 27 | "devDependencies": { 28 | "@tailwindcss/postcss": "^4.1.18", 29 | "@types/node": "25.0.1", 30 | "@types/react": "^19.2.7", 31 | "@types/react-dom": "^19.2.3", 32 | "oxlint": "^1.32.0", 33 | "tailwindcss": "^4.1.18", 34 | "typescript": "^5.9.3", 35 | "zod": "^4.1.13" 36 | }, 37 | "devEngines": { 38 | "packageManager": { 39 | "name": "pnpm", 40 | "version": "10.15.0", 41 | "onFail": "download" 42 | } 43 | }, 44 | "packageManager": "pnpm@10.19.0" 45 | } -------------------------------------------------------------------------------- /components/SearchForm/URLInput.tsx: -------------------------------------------------------------------------------- 1 | import { useState, type Dispatch } from "react"; 2 | import { HelpSection } from "./HelpSection"; 3 | 4 | export const URLInput = ({ 5 | setUrl, 6 | url, 7 | }: { 8 | url: string; 9 | setUrl: Dispatch; 10 | }) => { 11 | const [showHelp, setShowHelp] = useState(false); 12 | 13 | return ( 14 |
15 |
16 | 19 | 27 |
28 | setUrl(e.target.value)} 32 | placeholder={`Dein "Teilen"-Text von der Deutschen Bahn`} 33 | className="w-full px-3 py-2 resize-vertical border-b-2 border-gray-300 focus:ring-2 focus:ring-primary " 34 | /> 35 | 36 | {showHelp && } 37 |
38 | ); 39 | }; 40 | -------------------------------------------------------------------------------- /components/discount/SplitOptionsCard.tsx: -------------------------------------------------------------------------------- 1 | import type { SplitAnalysis } from "@/app/api/analyzeJourney"; 2 | import { SplitOptions } from "@/components/SplitOptions/SplitOptions"; 3 | import type { VendoJourney } from "@/utils/schemas"; 4 | 5 | interface Props { 6 | splitOptions: SplitAnalysis[]; 7 | selectedJourney: VendoJourney; 8 | loading: boolean; 9 | } 10 | 11 | export const SplitOptionsCardContent = ({ 12 | splitOptions, 13 | selectedJourney, 14 | loading, 15 | }: Props) => { 16 | if (loading) { 17 | return ( 18 |
19 |
20 | Analysiere Optionen... 21 |
22 | ); 23 | } 24 | 25 | if (splitOptions.length === 0) { 26 | return ( 27 |
28 |

29 | Für diese Verbindung konnten keine günstigeren Split-Ticket Optionen 30 | gefunden werden. 31 |

32 |

33 | Das ursprüngliche Ticket ist bereits die beste Option. 34 |

35 |
36 | ); 37 | } 38 | 39 | return ( 40 | 45 | ); 46 | }; 47 | -------------------------------------------------------------------------------- /utils/journeyUtils.ts: -------------------------------------------------------------------------------- 1 | import type { 2 | VendoJourney, 3 | VendoLeg, 4 | VendoOriginOrDestination, 5 | } from "@/utils/schemas"; 6 | 7 | export const getLineInfoFromLeg = (leg: VendoLeg) => { 8 | if (leg.walking) return null; 9 | return leg.line?.name || leg.line?.product || "Unknown"; 10 | }; 11 | 12 | /** 13 | * Gets the display name for a station, stop, or location 14 | * @param stop - Can be a VendoStation, VendoStop, or VendoLocation (all have a 'name' property) 15 | * @returns The name of the location or "Unknown" if not available 16 | */ 17 | export const getStationName = (stop?: VendoOriginOrDestination) => 18 | stop?.name || "Unknown"; 19 | 20 | const calculateTransferTimeInMinutes = (leg: VendoLeg) => { 21 | if (!leg.walking || !leg.departure || !leg.arrival) return 0; 22 | return Math.round((leg.arrival.getTime() - leg.departure.getTime()) / 60000); 23 | }; 24 | 25 | // Filter out walking legs and get non-walking legs with transfer times 26 | export const getJourneyLegsWithTransfers = (journey: VendoJourney) => { 27 | const legs = journey?.legs || []; 28 | 29 | return legs 30 | .map((leg, i) => { 31 | if (leg.walking) return null; 32 | const next = legs[i + 1]; 33 | return Object.assign({}, leg, { 34 | transferTimeAfter: next?.walking 35 | ? calculateTransferTimeInMinutes(next) 36 | : 0, 37 | }); 38 | }) 39 | .filter(Boolean) as (VendoLeg & { transferTimeAfter: number })[]; 40 | }; 41 | -------------------------------------------------------------------------------- /app/api/getJourney/extractSplitPoints.ts: -------------------------------------------------------------------------------- 1 | import type { VendoJourney } from "@/utils/schemas"; 2 | import type { SplitPoint, TrainLine } from "@/utils/types"; 3 | import { TRPCError } from "@trpc/server"; 4 | 5 | export function extractSplitPoints(journey: VendoJourney) { 6 | const map = new Map(); 7 | 8 | journey.legs.forEach((leg, legIndex) => { 9 | if (leg.walking || !leg.stopovers) { 10 | return; 11 | } 12 | 13 | leg.stopovers.forEach((s, stopIndex) => { 14 | if ( 15 | (legIndex === 0 && stopIndex === 0) || 16 | (legIndex === journey.legs.length - 1 && 17 | stopIndex === leg.stopovers!.length - 1) 18 | ) { 19 | return; 20 | } 21 | 22 | if (s.arrival && s.departure && s.stop && !map.has(s.stop.id)) { 23 | const trainLine: TrainLine | undefined = 24 | typeof leg.line === "object" 25 | ? { 26 | name: leg.line.name, 27 | product: leg.line.product || leg.line.productName, 28 | } 29 | : undefined; 30 | 31 | map.set(s.stop.id, { 32 | station: { id: s.stop.id, name: s.stop.name || "" }, 33 | arrival: s.arrival, 34 | departure: s.departure, 35 | trainLine, 36 | loadFactor: s.loadFactor, 37 | legIndex, 38 | stopIndex, 39 | }); 40 | } 41 | }); 42 | }); 43 | 44 | const uniqueStops = Array.from(map.values()); 45 | 46 | if (uniqueStops.length === 0) { 47 | throw new TRPCError({ 48 | code: "INTERNAL_SERVER_ERROR", 49 | message: "No split points found", 50 | }); 51 | } 52 | 53 | return uniqueStops; 54 | } 55 | -------------------------------------------------------------------------------- /utils/TRPCProvider.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import type { AppRouter } from "@/app/api/[trpc]/route"; 4 | import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; 5 | import { 6 | httpBatchLink, 7 | httpSubscriptionLink, 8 | loggerLink, 9 | splitLink, 10 | } from "@trpc/client"; 11 | import { createTRPCReact } from "@trpc/react-query"; 12 | import SuperJSON from "superjson"; 13 | 14 | const queryClient = new QueryClient({ 15 | defaultOptions: { 16 | queries: { 17 | refetchOnMount: false, 18 | refetchOnReconnect: false, 19 | refetchOnWindowFocus: false, 20 | refetchInterval: false, 21 | refetchIntervalInBackground: false, 22 | retry: false, 23 | }, 24 | }, 25 | }); 26 | 27 | export const trpc = createTRPCReact(); 28 | 29 | const trpcClient = trpc.createClient({ 30 | links: [ 31 | // adds pretty logs to your console in development and logs errors in production 32 | loggerLink(), 33 | splitLink({ 34 | // uses the httpSubscriptionLink for subscriptions 35 | condition: (op) => op.type === "subscription", 36 | true: httpSubscriptionLink({ 37 | transformer: SuperJSON, 38 | url: `/api`, 39 | }), 40 | false: httpBatchLink({ 41 | transformer: SuperJSON, 42 | url: `/api`, 43 | }), 44 | }), 45 | ], 46 | }); 47 | 48 | export function TRPCReactProvider( 49 | props: Readonly<{ 50 | children: React.ReactNode; 51 | }> 52 | ) { 53 | return ( 54 | 55 | 56 | {props.children} 57 | 58 | 59 | ); 60 | } 61 | -------------------------------------------------------------------------------- /utils/fetchAndValidateJson.ts: -------------------------------------------------------------------------------- 1 | import { type ZodType, prettifyError } from "zod/v4"; 2 | 3 | export const fetchAndValidateJson = async < 4 | T extends ZodType, 5 | Method extends "GET" | "POST" 6 | >({ 7 | url, 8 | method, 9 | schema, 10 | body, 11 | headers, 12 | }: { 13 | url: string; 14 | method?: Method; 15 | schema: T; 16 | body?: Method extends "GET" ? never : unknown; 17 | headers?: HeadersInit; 18 | }) => { 19 | const init: RequestInit = { 20 | method: method ?? "GET", 21 | headers: { 22 | "Content-Type": "application/json", 23 | Accept: "application/json", 24 | ...headers, 25 | }, 26 | }; 27 | 28 | if (method !== "GET") { 29 | init.body = JSON.stringify(body); 30 | } 31 | 32 | const response = await fetch(url, init); 33 | 34 | if (!response.ok) { 35 | const errorMessage = 36 | response.status === 500 37 | ? `Server error (500). Diese Problem ist uns bekannt und wir arbeiten daran, es zu beheben. Ein Status über den Fehler finden Sie unter https://github.com/l2xu/betterbahn/issues/57` 38 | : `Failed to fetch ${url}: ${response.status} ${response.statusText}`; 39 | 40 | throw new Error(errorMessage); 41 | } 42 | 43 | let json: unknown; 44 | 45 | try { 46 | json = await response.json(); 47 | } catch { 48 | throw new Error(`Failed to parse JSON of fetch ${url}`); 49 | } 50 | 51 | const validationResult = schema.safeParse(json); 52 | 53 | if (!validationResult.success) { 54 | throw new Error( 55 | `Validation of fetch ${url} failed: ${prettifyError( 56 | validationResult.error 57 | )}` 58 | ); 59 | } 60 | 61 | return { 62 | response, 63 | data: validationResult.data, 64 | }; 65 | }; 66 | -------------------------------------------------------------------------------- /utils/formatUtils.ts: -------------------------------------------------------------------------------- 1 | import type { VendoJourney, VendoPrice } from "@/utils/schemas"; 2 | 3 | /** 4 | * Formatiert Zeit für deutsche Anzeige (HH:MM) 5 | */ 6 | export const formatTime = (dateTime?: Date) => { 7 | /** 8 | * TODO check if leg.departure / leg.arrival are always 9 | * defined. if true, make dateTime non-optional 10 | */ 11 | if (!dateTime) { 12 | return "?"; 13 | } 14 | 15 | return dateTime.toLocaleTimeString("de-DE", { 16 | hour: "2-digit", 17 | minute: "2-digit", 18 | }); 19 | }; 20 | 21 | /** 22 | * Formatiert Reisedauer basierend auf Legs 23 | */ 24 | export const formatDuration = (journey: VendoJourney) => { 25 | if (!journey?.legs || journey.legs.length === 0) return null; 26 | const departure = journey.legs[0].departure; 27 | const arrival = journey.legs[journey.legs.length - 1].arrival; 28 | const durationMs = arrival.getTime() - departure.getTime(); 29 | const hours = Math.floor(durationMs / (1000 * 60 * 60)); 30 | const minutes = Math.floor((durationMs % (1000 * 60 * 60)) / (1000 * 60)); 31 | return `${hours}h ${minutes}m`; 32 | }; 33 | 34 | /** 35 | * Zählt Anzahl der Umstiege 36 | */ 37 | export const getChangesCount = (journey: VendoJourney) => { 38 | if (!journey?.legs) { 39 | return 0; 40 | } 41 | 42 | return Math.max(0, journey.legs.length - 1); 43 | }; 44 | 45 | export const formatPriceWithTwoDecimals = (price?: VendoPrice | number) => { 46 | if (!price && price !== 0) { 47 | return null; 48 | } 49 | 50 | let amount; 51 | 52 | if (price && typeof price === "object") { 53 | amount = price.amount; 54 | } else { 55 | amount = price; 56 | } 57 | 58 | if (isNaN(amount)) { 59 | return null; 60 | } 61 | 62 | return `${amount.toFixed(2).replace(".", ",")}€`; 63 | }; 64 | -------------------------------------------------------------------------------- /app/discount/Analysis.tsx: -------------------------------------------------------------------------------- 1 | import { OriginalJourneyCard } from "@/components/discount/OriginalJourneyCard"; 2 | import { SplitOptionsCardContent } from "@/components/discount/SplitOptionsCard"; 3 | import type { Progress } from "@/components/discount/StatusBox"; 4 | import type { VendoJourney } from "@/utils/schemas"; 5 | import { trpc } from "@/utils/TRPCProvider"; 6 | import { useState, type Dispatch } from "react"; 7 | import type { SplitAnalysis } from "../api/analyzeJourney"; 8 | import { useUrlParams } from "./useUrlParams"; 9 | 10 | interface Props { 11 | journey: VendoJourney; 12 | setProgress: Dispatch; 13 | setAnalysisError: Dispatch; 14 | } 15 | 16 | export const ComparisonView = ({ 17 | journey, 18 | setProgress, 19 | setAnalysisError, 20 | }: Props) => { 21 | const params = useUrlParams(); 22 | const [splitOptions, setSplitPoints] = useState(null); 23 | 24 | const analysisSubscription = trpc.analyzeJourney.useSubscription( 25 | { ...params, journey }, 26 | { 27 | onError: (err) => setAnalysisError(err.message), 28 | onData(data) { 29 | switch (data.type) { 30 | case "processing": { 31 | setProgress(data); 32 | break; 33 | } 34 | case "complete": { 35 | setProgress(null); 36 | setSplitPoints(data.splitOptions); 37 | break; 38 | } 39 | } 40 | }, 41 | } 42 | ); 43 | 44 | if (splitOptions === null) { 45 | return; 46 | } 47 | 48 | return ( 49 |
50 |
51 | 52 |
53 |
54 |
55 |

Split-Ticket Optionen

56 | 61 |
62 |
63 |
64 | ); 65 | }; 66 | -------------------------------------------------------------------------------- /components/SplitOptions/getOptionsToShow.ts: -------------------------------------------------------------------------------- 1 | import type { SplitAnalysis } from "@/app/api/analyzeJourney"; 2 | import type { VendoJourney } from "@/utils/schemas"; 3 | import { calculateSplitOptionPricing } from "./calculateSplitOptionPricing"; 4 | 5 | /** Determine which split options to show based on pricing availability */ 6 | export const getOptionsToShow = ({ 7 | splitOptions, 8 | hasDeutschlandTicket, 9 | originalJourney, 10 | }: { 11 | splitOptions: SplitAnalysis[]; 12 | hasDeutschlandTicket: boolean; 13 | originalJourney: VendoJourney; 14 | }) => { 15 | if (splitOptions.length === 0) { 16 | return []; 17 | } 18 | 19 | // Calculate pricing for all options first 20 | const optionsWithPricing = splitOptions.map((option) => ({ 21 | ...option, 22 | pricing: calculateSplitOptionPricing({ 23 | splitOption: option, 24 | hasDeutschlandTicket, 25 | originalJourney, 26 | }), 27 | })); 28 | 29 | // Sort by savings (highest first) 30 | const sortedOptions = optionsWithPricing.toSorted( 31 | (a, b) => 32 | (b.pricing.adjustedSavings ?? 0) - (a.pricing.adjustedSavings ?? 0) 33 | ); 34 | 35 | // If user has Deutschland-Ticket, always show only the cheapest option 36 | if (hasDeutschlandTicket) { 37 | return [sortedOptions[0]]; 38 | } 39 | 40 | // For users without Deutschland-Ticket 41 | const bestOption = sortedOptions[0]; 42 | 43 | // If the best option has complete pricing (no partial or missing pricing), show only that 44 | if ( 45 | !bestOption.pricing.cannotShowPrice && 46 | !bestOption.pricing.hasPartialPricing 47 | ) { 48 | return [bestOption]; 49 | } 50 | 51 | // If the best option has pricing issues, show options until we find one with complete pricing 52 | const optionsToShow = []; 53 | let foundCompleteOption = false; 54 | 55 | for (const option of sortedOptions) { 56 | optionsToShow.push(option); 57 | 58 | // If this option has complete pricing, we can stop 59 | if (!option.pricing.cannotShowPrice && !option.pricing.hasPartialPricing) { 60 | foundCompleteOption = true; 61 | break; 62 | } 63 | } 64 | 65 | // If we never found a complete option, show all options (they all have pricing issues) 66 | return foundCompleteOption ? optionsToShow : sortedOptions; 67 | }; 68 | -------------------------------------------------------------------------------- /components/JourneyCard/LegDetails.tsx: -------------------------------------------------------------------------------- 1 | import type { VendoLeg } from "@/utils/schemas"; 2 | import { formatTime } from "@/utils/formatUtils"; 3 | import { TrainIdentifier } from "./journey-card-utils"; 4 | import { LegDuration } from "./LegDuration"; 5 | 6 | export const LegDetails = ({ 7 | leg, 8 | legIndex, 9 | }: { 10 | leg: VendoLeg; 11 | legIndex: number; 12 | }) => { 13 | if (leg.walking) { 14 | return ( 15 |
16 | 17 | 🚶 Walk 18 | 19 |
20 | ); 21 | } 22 | 23 | return ( 24 |
25 |
26 | 27 | Leg {legIndex + 1}: 28 | 29 | 30 | 31 | {leg.line?.mode && ( 32 | 33 | {typeof leg.line.mode === "string" 34 | ? leg.line.mode 35 | : JSON.stringify(leg.line.mode)} 36 | 37 | )} 38 | 39 |
40 |
41 | {leg.origin?.name} 42 | 43 | ({formatTime(leg.departure)} 44 | {leg.departurePlatform && , Pl. {leg.departurePlatform}}) 45 | 46 | 47 | {leg.destination?.name} 48 | 49 | ({formatTime(leg.arrival)} 50 | {leg.arrivalPlatform && , Pl. {leg.arrivalPlatform}}) 51 | 52 | 53 | 54 | 55 | {leg.delay && leg.delay > 0 && ( 56 | 57 | +{leg.delay}min 58 | 59 | )} 60 | {leg.cancelled && ( 61 | 62 | ⚠️ Cancelled 63 | 64 | )} 65 |
66 |
67 | ); 68 | }; 69 | -------------------------------------------------------------------------------- /app/discount/DiscountContent.tsx: -------------------------------------------------------------------------------- 1 | import { ErrorDisplay } from "@/components/discount/ErrorDisplay"; 2 | import { StatusBox, type Progress } from "@/components/discount/StatusBox"; 3 | import { Journey } from "@/components/Journey"; 4 | import type { VendoJourney } from "@/utils/schemas"; 5 | import { trpc } from "@/utils/TRPCProvider"; 6 | import { useState } from "react"; 7 | import { ComparisonView } from "./Analysis"; 8 | import { useUrlParams } from "./useUrlParams"; 9 | 10 | export const DiscountContent = () => { 11 | const params = useUrlParams(); 12 | const journeysQuery = trpc.getJourney.useQuery(params); 13 | 14 | const [analysisProgress, setAnalysisProgress] = useState( 15 | null 16 | ); 17 | 18 | const [analysisError, setAnalysisError] = useState(null); 19 | 20 | const [selectedJourney, setSelectedJourney] = useState( 21 | null 22 | ); 23 | 24 | if (journeysQuery.isError) { 25 | return ; 26 | } 27 | 28 | if (analysisError) { 29 | return ; 30 | } 31 | 32 | if (journeysQuery.isLoading) { 33 | return ( 34 |
35 |
36 | Lade Reise... 37 |
38 | ); 39 | } 40 | 41 | return ( 42 |
43 | {analysisProgress !== null && } 44 | 45 |
46 |
47 | Wähle deine Verbindung 48 |
49 | {(journeysQuery.data ?? []).map((journey, index) => ( 50 | setSelectedJourney(journey)} 57 | /> 58 | ))} 59 |
60 | 61 | {selectedJourney ? ( 62 | 67 | ) : ( 68 | journeysQuery.isSuccess && 69 | journeysQuery.data.length === 1 && ( 70 | 75 | ) 76 | )} 77 |
78 | ); 79 | }; 80 | -------------------------------------------------------------------------------- /utils/schemas.ts: -------------------------------------------------------------------------------- 1 | import z from "zod/v4"; 2 | 3 | const vendoStationSchema = z.object({ 4 | id: z.string(), 5 | name: z.string().optional(), 6 | }); 7 | 8 | export type VendoStation = z.infer; 9 | 10 | const vendoStopSchema = z.object({ 11 | id: z.string(), 12 | name: z.string().optional(), 13 | }); 14 | 15 | const vendoLocationSchema = z.object({ 16 | id: z.string(), 17 | name: z.string().optional(), 18 | }); 19 | 20 | const vendoPriceSchema = z.object({ 21 | amount: z.number(), 22 | hint: z.string().nullable().optional(), 23 | }); 24 | 25 | export type VendoPrice = z.infer; 26 | 27 | const vendoLineSchema = z.object({ 28 | name: z.string(), 29 | product: z.string().optional(), 30 | productName: z.string().optional(), 31 | mode: z.string().or(z.object()).optional(), 32 | }); 33 | 34 | const originOrDestinationSchema = vendoStationSchema 35 | .or(vendoStopSchema) 36 | .or(vendoLocationSchema); 37 | 38 | export type VendoOriginOrDestination = 39 | | z.infer 40 | | undefined; 41 | 42 | /** 43 | * allows parent schemas to be used with both 44 | * vendo-client (outputs string dates) as well as 45 | * tRPC (uses SuperJSON, feeding real Date objects into schema) 46 | */ 47 | const dateOrDateStringSchema = z 48 | .string() 49 | .transform((s) => new Date(s)) 50 | .or(z.date()); 51 | 52 | const stopoverSchema = z.object({ 53 | // TODO test removing optional() 54 | arrival: dateOrDateStringSchema.nullable().optional(), 55 | departure: dateOrDateStringSchema.nullable().optional(), 56 | stop: vendoStopSchema.optional(), 57 | loadFactor: z.unknown(), 58 | }); 59 | 60 | const vendoLegSchema = z.object({ 61 | departure: dateOrDateStringSchema, 62 | line: vendoLineSchema.optional(), 63 | arrival: dateOrDateStringSchema, 64 | mode: z.string().optional(), 65 | walking: z.unknown(), 66 | departurePlatform: z.string().nullable().optional(), 67 | arrivalPlatform: z.string().nullable().optional(), 68 | delay: z.number().optional(), 69 | cancelled: z.boolean().optional(), 70 | stopovers: z.array(stopoverSchema).optional(), 71 | origin: originOrDestinationSchema.optional(), 72 | destination: originOrDestinationSchema.optional(), 73 | }); 74 | 75 | export type VendoLeg = z.infer; 76 | 77 | export const vendoJourneySchema = z.object({ 78 | legs: z.array(vendoLegSchema), 79 | price: vendoPriceSchema.optional(), 80 | duration: z.unknown().optional(), 81 | }); 82 | 83 | export type VendoJourney = z.infer; 84 | 85 | export const vbidSchema = z.object({ 86 | hinfahrtRecon: z.string(), 87 | hinfahrtDatum: z.string(), 88 | }); 89 | 90 | export type VbidSchema = z.infer; 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BetterBahn 2 | 3 | BetterBahn is a web app for finding the best train journeys in Germany. While split ticketing is supported to help save money, it is rather the exception. The app will be extended with many more features in the future. 4 | You can find out more about the project on our [website](https://betterbahn.de). 5 | 6 | ## Technology 7 | 8 | This project uses the [db-vendo-client](https://github.com/public-transport/db-vendo-client) for accessing Deutsche Bahn ticketing data, which is licensed under the ISC License. 9 | 10 | ## Legal Notice 11 | 12 | This is not an official repository or project of Deutsche Bahn AG. It is an independent project and not affiliated with or endorsed by Deutsche Bahn. To use this code or the db-vendo-client permission from the Deutsche Bahn AG is necessary. 13 | 14 | ## Getting Started 15 | 16 | ### Prerequisites 17 | 18 | - [Node.js](https://nodejs.org/en/) 19 | - [pnpm](https://pnpm.io/) (see below for installation) 20 | - [git](https://git-scm.com/) 21 | 22 | ### To run the project locally 23 | 24 | 1. Clone the repository and navigate to the folder 25 | 26 | ```shell 27 | git clone https://github.com/l2xu/betterbahn.git 28 | cd betterbahn 29 | ``` 30 | 31 | 2. Install dependencies with `pnpm install` 32 | 33 | You can install pnpm via corepack (included with Node.js): 34 | 35 | ```shell 36 | corepack enable 37 | corepack prepare pnpm@latest --activate 38 | ``` 39 | 40 | or via npm: 41 | 42 | ```shell 43 | npm install -g pnpm@latest-10 44 | ``` 45 | 46 | then run `pnpm install` in the project directory. 47 | 48 | 3. Start the development server with `pnpm run dev` and navigate to `http://localhost:3000` in your browser. 49 | 50 | ## Docker 51 | 52 | You can also build and run BetterBahn as a Docker container. A `Dockerfile` is included in the repository. 53 | 54 | ## Docker Compose 55 | 56 | You can run the app with docker compose: 57 | 58 | ### Default/Development 59 | 60 | `docker compose -f docker-compose/docker-compose.yaml --project-directory=./ up -d` 61 | 62 | 63 | 64 | ## Installation Guides 65 | 66 | For detailed installation instructions on different platforms: 67 | 68 | - [Windows Installation (DE)](docs/Windows-Installation-de.md) 69 | - [Linux Installation (DE)](docs/Linux-Installation-de.md) 70 | - [Windows Installation (EN)](docs/Windows-Installation-en.md) 71 | - [Linux Installation (EN)](docs/Linux-Installation-en.md) 72 | 73 | ## License 74 | 75 | This project is licensed under the AGPL-3.0-only. See the [LICENSE](./LICENSE) file for details. 76 | 77 | ## Community and Contribution 78 | 79 | Join the [Discord community](https://discord.gg/9pFXzs6XRK) to ask questions, share feedback, and connect with other users and contributors. 80 | 81 | Want to contribute? Please read the [Code of Conduct](/CODE_OF_CONDUCT.md) and see the [Contributing Guide](/CONTRIBUTE.md) for details on how to get started. 82 | 83 | ## How it works 84 | 85 | BetterBahn searches for train journeys and can use split ticketing to help you find cheaper options—though this is usually the exception, not the rule. For a detailed explanation and demonstration, check out the [YouTube video](https://www.youtube.com/watch?v=SxKtI8f5QTU). 86 | 87 | ## About the Author 88 | 89 | Created by [Lukas Weihrauch](https://lukasweihrauch.de). 90 | 91 | --- 92 | 93 | Made with ❤️ for train travelers in Germany. 94 | -------------------------------------------------------------------------------- /.github/workflows/docker-image.yml: -------------------------------------------------------------------------------- 1 | name: Docker 2 | 3 | on: 4 | push: 5 | branches: [ "**" ] 6 | # Publish semver tags as releases. 7 | tags: [ 'v*.*' ] 8 | pull_request: 9 | branches: [ "main" ] 10 | 11 | env: 12 | # Use docker.io for Docker Hub if empty 13 | REGISTRY: ghcr.io 14 | # github.repository as / 15 | IMAGE_NAME: ${{ github.repository }} 16 | 17 | 18 | jobs: 19 | build: 20 | 21 | runs-on: ubuntu-latest 22 | permissions: 23 | contents: read 24 | packages: write 25 | 26 | steps: 27 | - name: Checkout repository 28 | uses: actions/checkout@v6 29 | 30 | # Set up BuildKit Docker container builder to be able to build 31 | # multi-platform images and export cache 32 | # https://github.com/docker/setup-buildx-action 33 | - name: Set up Docker Buildx 34 | uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 35 | 36 | # Login against a Docker registry except on PR 37 | # https://github.com/docker/login-action 38 | - name: Log into registry ${{ env.REGISTRY }} 39 | if: github.event_name != 'pull_request' 40 | uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0 41 | with: 42 | registry: ${{ env.REGISTRY }} 43 | username: ${{ github.actor }} 44 | password: ${{ secrets.GITHUB_TOKEN }} 45 | 46 | # Check if any version tags exist 47 | - name: Check for existing version tags 48 | id: check-tags 49 | run: | 50 | if git tag --list 'v*.*' | grep -q .; then 51 | echo "has_version_tags=true" >> $GITHUB_OUTPUT 52 | else 53 | echo "has_version_tags=false" >> $GITHUB_OUTPUT 54 | fi 55 | 56 | # Extract metadata (tags, labels) for Docker 57 | # https://github.com/docker/metadata-action 58 | - name: Extract Docker metadata 59 | id: meta 60 | uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0 61 | with: 62 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 63 | tags: | 64 | type=raw,value=testing-${{ github.ref_name }},enable=${{ !startsWith(github.ref, 'refs/tags/v') }} 65 | type=raw,value=testing-main,enable=${{ github.ref == 'refs/heads/main' }} 66 | type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' && steps.check-tags.outputs.has_version_tags == 'false' }} 67 | type=raw,value=${{ github.ref_name }},enable=${{ startsWith(github.ref, 'refs/tags/v') }} 68 | type=semver,pattern={{version}} 69 | type=semver,pattern={{major}}.{{minor}} 70 | type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') }} 71 | 72 | # Build and push Docker image with Buildx (don't push on PR) 73 | # https://github.com/docker/build-push-action 74 | - name: Build and push Docker image 75 | id: build-and-push 76 | uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 77 | with: 78 | context: . 79 | push: ${{ github.event_name != 'pull_request' }} 80 | tags: ${{ steps.meta.outputs.tags }} 81 | labels: ${{ steps.meta.outputs.labels }} 82 | cache-from: type=gha 83 | cache-to: type=gha,mode=max 84 | platforms: linux/amd64,linux/arm64 -------------------------------------------------------------------------------- /components/Layout/Navbar.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | import Link from "next/link"; 3 | import { useState } from "react"; 4 | 5 | export const Navbar = () => { 6 | const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); 7 | 8 | return ( 9 |
10 | 107 |
108 | ); 109 | }; 110 | -------------------------------------------------------------------------------- /components/SplitOptions/Segment.tsx: -------------------------------------------------------------------------------- 1 | import type { VendoJourney } from "@/utils/schemas"; 2 | import { createSegmentSearchUrl } from "@/utils/createUrl"; 3 | import { 4 | legIsFlixTrain, 5 | isLegCoveredByDeutschlandTicket, 6 | } from "@/utils/deutschlandTicketUtils"; 7 | import { 8 | getJourneyLegsWithTransfers, 9 | getLineInfoFromLeg, 10 | getStationName, 11 | } from "@/utils/journeyUtils"; 12 | import { formatTime } from "@/utils/formatUtils"; 13 | import { formatPriceDE } from "@/utils/priceUtils"; 14 | 15 | export const Segment = ({ 16 | segment, 17 | index, 18 | segmentsWithoutPricing, 19 | hasDeutschlandTicket, 20 | bahnCard, 21 | travelClass 22 | }: { 23 | segment: VendoJourney; 24 | index: number; 25 | segmentsWithoutPricing: number[]; 26 | hasDeutschlandTicket: boolean; 27 | bahnCard: string | null; 28 | travelClass: string 29 | }) => { 30 | const segmentHasFlixTrain = getJourneyLegsWithTransfers(segment).some((leg) => 31 | legIsFlixTrain(leg) 32 | ); 33 | const hasUnknownPrice = segmentsWithoutPricing?.includes(index); 34 | 35 | // Check if segment is covered by Deutschland-Ticket 36 | const segmentCoveredByDeutschlandTicket = 37 | hasDeutschlandTicket && 38 | getJourneyLegsWithTransfers(segment).every((leg) => 39 | isLegCoveredByDeutschlandTicket(leg, hasDeutschlandTicket) 40 | ); 41 | 42 | return ( 43 |
44 |
45 |
46 | {getJourneyLegsWithTransfers(segment).map((leg, legIndex) => ( 47 | 48 | {getLineInfoFromLeg(leg)} 49 | {legIndex < getJourneyLegsWithTransfers(segment).length - 1 && ( 50 | 51 | )} 52 | 53 | ))} 54 |
55 |
56 | {getStationName(segment.legs[0].origin)} ( 57 | {formatTime(segment.legs[0].departure)}) →{" "} 58 | {getStationName(segment.legs[segment.legs.length - 1].destination)} ( 59 | {formatTime(segment.legs[segment.legs.length - 1].arrival)}) 60 |
61 |
62 |
63 |
64 | {segmentCoveredByDeutschlandTicket ? ( 65 | 66 | ✓ D-Ticket 67 | 68 | ) : hasUnknownPrice ? ( 69 | 73 | {segmentHasFlixTrain ? "FlixTrain" : "Preis unbekannt"} 74 | 75 | ) : ( 76 | 77 | {segment.price?.amount === undefined 78 | ? "Preis auf Anfrage" 79 | : formatPriceDE(segment.price.amount)} 80 | 81 | )} 82 |
83 | 100 |
101 |
102 | ); 103 | }; 104 | -------------------------------------------------------------------------------- /utils/parseHinfahrtRecon.ts: -------------------------------------------------------------------------------- 1 | import zlib from "node:zlib"; 2 | import { z } from "zod/v4"; 3 | import type { VbidSchema } from "./schemas"; 4 | import { fetchAndValidateJson } from "./fetchAndValidateJson"; 5 | 6 | const _parseHinfahrtRecon = (hinfahrtRecon: string) => { 7 | /** 8 | * This is an attempt to parse the hinfahrtRecon value in contrast to the straight-forward 9 | * regex of parseHinfartReconCrude(). 10 | * hinfahrtRecon is a rather bizarre and non-standard format, with some but not all parts 11 | * encoded with base64, gzip, and/or containing a JSON string, and with at least 12 | * two different kinds of string separators, only one of which ("¶") this code *should* need. 13 | * Parsing hinfahrtRecon like this was successful at least once, 14 | * but gunzipping (gzip decompression) failed at other times 15 | * which is why this function is not (yet) used. 16 | */ 17 | 18 | const sections = hinfahrtRecon.split("¶"); 19 | const scIndex = sections.findIndex((s) => s === "SC"); 20 | 21 | if (scIndex === -1) { 22 | throw new Error("Can't process vbid: Couldn't find 'SC' in hinfahrtRecon"); 23 | } 24 | 25 | const scGzipBase64WithPrefix = sections[scIndex + 1]; 26 | 27 | if (!scGzipBase64WithPrefix.startsWith("1_")) { 28 | throw new Error( 29 | "Can't process vbid: hinfahrtRecon 'SC' unexpectedly doesn't start with '1_'" 30 | ); 31 | } 32 | 33 | const scGzipBase64 = scGzipBase64WithPrefix.slice("1_".length); 34 | const scGzipBuffer = Buffer.from(scGzipBase64, "base64"); 35 | 36 | let scJsonString = ""; 37 | 38 | try { 39 | scJsonString = zlib.gunzipSync(scGzipBuffer).toString("utf-8"); 40 | } catch { 41 | throw new Error( 42 | "Can't process vbid: hinfahrtRecon 'SC' failed to get gunzipped" 43 | ); 44 | } 45 | 46 | let scUnvalidatedJson = ""; 47 | 48 | try { 49 | scUnvalidatedJson = JSON.parse(scJsonString); 50 | } catch { 51 | throw new Error( 52 | "Can't process vbid: hinfahrtRecon 'SC' JSON parsing failed (invalid JSON)" 53 | ); 54 | } 55 | 56 | const scJsonSchema = z.object({ 57 | req: z.object({ 58 | arrLoc: z 59 | .array( 60 | z.object({ 61 | lid: z.string(), 62 | }) 63 | ) 64 | .min(1), 65 | depLoc: z 66 | .array( 67 | z.object({ 68 | lid: z.string(), 69 | }) 70 | ) 71 | .min(1), 72 | }), 73 | }); 74 | 75 | const scValidatedJsonResult = scJsonSchema.safeParse(scUnvalidatedJson); 76 | 77 | if (!scValidatedJsonResult.success) { 78 | throw new Error( 79 | "Can't process vbid: hinfahrtRecon 'SC' JSON doesn't match schema" 80 | ); 81 | } 82 | 83 | return { 84 | arrLid: scValidatedJsonResult.data.req.arrLoc[0].lid, 85 | departLid: scValidatedJsonResult.data.req.depLoc[0].lid, 86 | }; 87 | }; 88 | 89 | const reconLegSchema = z.object({ 90 | halte: z 91 | .array( 92 | z.object({ 93 | id: z.string(), 94 | }) 95 | ) 96 | .min(0), // Allow empty arrays for walking segments or transfers 97 | }); 98 | 99 | const reconResponseSchema = z.object({ 100 | verbindungen: z 101 | .array( 102 | z.object({ 103 | verbindungsAbschnitte: z.array(reconLegSchema).min(1), 104 | }) 105 | ) 106 | .min(1), 107 | }); 108 | 109 | export const parseHinfahrtReconWithAPI = async ( 110 | vbidResponse: VbidSchema, 111 | cookies: string[] 112 | ) => { 113 | return await fetchAndValidateJson({ 114 | url: "https://www.bahn.de/web/api/angebote/recon", 115 | schema: reconResponseSchema, 116 | method: "POST", 117 | headers: { 118 | "Content-Type": "application/json", 119 | Cookie: cookies.join("; "), 120 | }, 121 | body: { 122 | klasse: "KLASSE_2", 123 | reisende: [ 124 | { 125 | typ: "ERWACHSENER", 126 | ermaessigungen: [ 127 | { 128 | art: "KEINE_ERMAESSIGUNG", 129 | klasse: "KLASSENLOS", 130 | }, 131 | ], 132 | anzahl: 1, 133 | alter: [], 134 | }, 135 | ], 136 | anfrageZeitpunkt: vbidResponse.hinfahrtDatum, 137 | ctxRecon: vbidResponse.hinfahrtRecon, 138 | reservierungsKontingenteVorhanden: false, 139 | nurDeutschlandTicketVerbindungen: false, 140 | deutschlandTicketVorhanden: false, 141 | sitzplatzOnly: false, 142 | }, 143 | }); 144 | }; 145 | -------------------------------------------------------------------------------- /components/JourneyCard/JourneyCard.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { formatTime } from "@/utils/formatUtils"; 4 | import { formatPriceDE } from "@/utils/priceUtils"; 5 | import type { VendoJourney } from "@/utils/schemas"; 6 | import { getTransferStations } from "./getTransferStations"; 7 | import { JourneyDuration } from "./JourneyDuration"; 8 | import { LegDetails } from "./LegDetails"; 9 | import { useUrlParams } from "../discount/useUrlParams"; 10 | 11 | export const JourneyCard = ({ 12 | journey, 13 | isSelected = false, 14 | onClick, 15 | }: { 16 | journey: VendoJourney; 17 | isSelected?: boolean; 18 | onClick: () => void; 19 | }) => { 20 | const firstLeg = journey.legs.at(0); 21 | const lastLeg = journey.legs.at(-1); 22 | const nonWalkingLegs = journey.legs.filter((leg) => !leg.walking); 23 | const transferCountWithoutWalking = Math.max(0, nonWalkingLegs.length - 1); 24 | const transferStationsWithoutWalking = getTransferStations(nonWalkingLegs); 25 | const { travelClass } = useUrlParams(); 26 | 27 | const priceDisplay = 28 | journey.price?.amount === undefined 29 | ? "Preis auf Anfrage" 30 | : formatPriceDE(journey.price.amount); 31 | 32 | return ( 33 |
41 | {/* Journey Header - Similar to SplitOptions */} 42 |
43 |
44 | Verbindung: 45 | 46 | {formatTime(firstLeg?.departure)} → {formatTime(lastLeg?.arrival)} 47 | 48 | {transferCountWithoutWalking > 0 && 49 | transferStationsWithoutWalking.length > 0 && ( 50 | 51 | 🚆 via {transferStationsWithoutWalking.join(", ")} 52 | 53 | )} 54 |
55 |
56 |
57 | 58 |
59 |
60 | {priceDisplay} 61 |
62 |
63 |
64 | 65 | {/* Route Summary */} 66 |
67 | {firstLeg?.origin?.name || "Unbekannt"} →{" "} 68 | {lastLeg?.destination?.name || "Unbekannt"} 69 | {transferCountWithoutWalking > 0 && ( 70 | 71 | ({transferCountWithoutWalking} Umstieg 72 | {transferCountWithoutWalking > 1 ? "e" : ""}) 73 | 74 | )} 75 |
76 | 77 | {/* Journey Legs - Similar to SplitOptions segments */} 78 |
79 | {journey.legs 80 | .filter((leg) => !leg.walking) 81 | .map((leg, legIndex) => ( 82 | 83 | ))} 84 |
85 | 86 | {/* Journey Summary - Similar to SplitOptions pricing summary */} 87 |
88 |
89 |
90 | Gesamt: {priceDisplay} 91 |
92 |
93 | {travelClass === "1" ? "1. Klasse" : "2. Klasse"} 94 | {transferCountWithoutWalking > 0 && 95 | transferStationsWithoutWalking.length > 0 && ( 96 | 97 | • {transferCountWithoutWalking} Umstieg 98 | {transferCountWithoutWalking > 1 ? "e" : ""} 99 | 100 | )} 101 |
102 |
103 |
104 |
105 | 106 |
107 |
108 | {firstLeg?.departure.toLocaleDateString("de-DE", { 109 | day: "2-digit", 110 | month: "2-digit", 111 | })}{" "} 112 | • {formatTime(firstLeg?.departure)}-{formatTime(lastLeg?.arrival)} 113 |
114 |
115 |
116 |
117 | ); 118 | }; 119 | -------------------------------------------------------------------------------- /utils/deutschlandTicketUtils.ts: -------------------------------------------------------------------------------- 1 | import type { VendoLeg } from "@/utils/schemas"; 2 | import { getStationName } from "./journeyUtils"; 3 | 4 | // Definiere spezifische IC/ICE-Strecken, die vom Deutschland-Ticket abgedeckt werden 5 | const deutschlandTicketICRoutes = [ 6 | { 7 | name: "Berlin - BER - Elsterwerda", 8 | stations: [ 9 | "Berlin Hbf", 10 | "Flughafen BER Terminal 1-2", 11 | "BER", 12 | "Doberlug-Kirchhain", 13 | "Elsterwerda", 14 | ], 15 | trains: ["IC", "ICE 1076"], // Alle IC-Züge auf dieser Strecke plus spezifischer ICE 16 | }, 17 | { 18 | name: "Berlin - Prenzlau", 19 | stations: [ 20 | "Berlin Südkreuz", 21 | "Berlin Spandau", 22 | "Berlin Gesundbrunnen", 23 | "Prenzlau", 24 | ], 25 | trains: ["IC", "ICE"], // IC- und ICE-Züge auf dieser Strecke 26 | }, 27 | { 28 | name: "Potsdam - Berlin - Cottbus", 29 | stations: ["Potsdam", "Berlin Hbf", "Cottbus"], 30 | trains: ["IC 2431", "IC 2432"], // Nur diese spezifischen IC-Züge 31 | }, 32 | { 33 | name: "Dresden - Freiberg - Chemnitz", 34 | stations: ["Dresden", "Freiberg", "Chemnitz"], 35 | }, 36 | { 37 | name: "Dortmund - Siegen - Dillenburg", 38 | stations: [ 39 | "Dortmund Hbf", 40 | "Witten Hbf", 41 | "Iserlohn-Letmathe", 42 | "Altena (Westf)", 43 | "Werdohl", 44 | "Plettenberg", 45 | "Finnentrop", 46 | "Lennestadt-Grevenbrück", 47 | "Lennestadt-Altenhundem", 48 | "Kreuztal", 49 | "Siegen-Weidenau", 50 | "Siegen Hbf", 51 | "Dillenburg", 52 | ], 53 | trains: [ 54 | "IC 2223", 55 | "IC 2225", 56 | "IC 2229", 57 | "IC 2323", 58 | "IC 2325", 59 | "IC 2327", 60 | "IC 2222", 61 | "IC 2224", 62 | "IC 2226", 63 | "IC 2320", 64 | "IC 2324", 65 | "IC 2326", 66 | "IC 2328", 67 | ], 68 | }, 69 | { 70 | name: "Bremen - Oldenburg - Emden - Norddeich", 71 | stations: [ 72 | "Bremen Hbf", 73 | "Delmenhorst", 74 | "Hude", 75 | "Oldenburg(Oldb)Hbf", 76 | "Bad Zwischenahn", 77 | "Westerstede-Ocholt", 78 | "Augustfehn", 79 | "Leer(Ostfriesl)", 80 | "Emden Hbf", 81 | ], 82 | }, 83 | { 84 | name: "Rostock - Stralsund", 85 | stations: ["Rostock", "Ribnitz-Damgarten", "Velgast", "Stralsund"], 86 | }, 87 | { 88 | name: "Erfurt - Weimar - Jena - Gera", 89 | stations: ["Erfurt", "Weimar", "Jena", "Gera"], 90 | }, 91 | { 92 | name: "Stuttgart - Horb - Singen - Konstanz", 93 | stations: ["Stuttgart", "Horb", "Singen", "Konstanz"], 94 | }, 95 | ]; 96 | 97 | const isICRouteCoveredByDeutschlandTicket = (leg: VendoLeg) => { 98 | if (!leg?.line || !leg.origin || !leg.destination) return false; 99 | const product = leg.line.product?.toLowerCase(); 100 | if (!product || !["national", "nationalexpress"].includes(product)) 101 | return false; 102 | 103 | const originName = getStationName(leg.origin).toLowerCase(); 104 | const destinationName = getStationName(leg.destination).toLowerCase(); 105 | const lineName = leg.line.name?.toUpperCase() || ""; 106 | 107 | return deutschlandTicketICRoutes.some((route) => { 108 | const stationsLower = route.stations.map((s) => s.toLowerCase()); 109 | const originOnRoute = stationsLower.some( 110 | (s) => originName.includes(s) || s.includes(originName) 111 | ); 112 | const destinationOnRoute = stationsLower.some( 113 | (s) => destinationName.includes(s) || s.includes(destinationName) 114 | ); 115 | if (!originOnRoute || !destinationOnRoute) return false; 116 | 117 | if (route.trains?.length) { 118 | return route.trains.some((pattern) => { 119 | if (pattern === "IC") 120 | return lineName.includes("IC") && !lineName.includes("ICE"); 121 | if (pattern === "ICE") return lineName.includes("ICE"); 122 | return lineName.includes(pattern); 123 | }); 124 | } 125 | return true; // no specific trains listed 126 | }); 127 | }; 128 | 129 | export const legIsFlixTrain = (leg: VendoLeg) => { 130 | if (!leg?.line) return false; 131 | const name = leg.line.name?.toUpperCase() || ""; 132 | const product = leg.line.product?.toUpperCase() || ""; 133 | return /FLX|FLIXTRAIN/.test(name + product); 134 | }; 135 | 136 | export const isLegCoveredByDeutschlandTicket = ( 137 | leg: VendoLeg, 138 | hasDeutschlandTicket: boolean 139 | ) => { 140 | if (!hasDeutschlandTicket) return false; 141 | if (leg.walking) return true; 142 | if (!leg.line || legIsFlixTrain(leg)) return false; // FlixTrains never covered 143 | const product = leg.line.product?.toLowerCase() || ""; 144 | return ( 145 | !["nationalexpress", "national"].includes(product) || 146 | isICRouteCoveredByDeutschlandTicket(leg) 147 | ); 148 | }; 149 | -------------------------------------------------------------------------------- /app/api/analyzeJourney.ts: -------------------------------------------------------------------------------- 1 | import { 2 | vendoJourneySchema, 3 | type VendoJourney, 4 | type VendoStation, 5 | } from "@/utils/schemas"; 6 | import { t } from "@/utils/trpc-init"; 7 | import { TRPCError } from "@trpc/server"; 8 | import type { SearchJourneysOptions } from "db-vendo-client"; 9 | import { data as loyaltyCards } from "db-vendo-client/format/loyalty-cards"; 10 | import { z } from "zod/v4"; 11 | import { extractSplitPoints } from "./getJourney/extractSplitPoints"; 12 | import { dbClient } from "./getJourney/getJourney"; 13 | 14 | export interface SplitAnalysis { 15 | splitStations: VendoStation[]; 16 | segments: VendoJourney[]; 17 | } 18 | 19 | export const analyzeJourney = t.procedure 20 | .input( 21 | z.object({ 22 | journey: vendoJourneySchema, 23 | travelClass: z.int(), 24 | passengerAge: z.int().optional(), 25 | bahnCard: z.int().nullable(), 26 | hasDeutschlandTicket: z.boolean(), 27 | }) 28 | ) 29 | .subscription(async function* ({ input }) { 30 | // Split-Kandidaten aus vorhandenen Legs ableiten (keine zusätzlichen API Calls) 31 | const splitPoints = extractSplitPoints(input.journey); 32 | 33 | const splitOptions: SplitAnalysis[] = []; 34 | 35 | for (let i = 0; i < splitPoints.length; i++) { 36 | const splitPoint = splitPoints[i]; 37 | 38 | yield { 39 | type: "processing", 40 | checked: i, 41 | currentStation: splitPoint.station?.name ?? null, 42 | total: splitPoints.length, 43 | } as const; 44 | 45 | const origin = input.journey.legs.at(0)!.origin; 46 | const destination = input.journey.legs.at(-1)!.destination; 47 | 48 | const queryOptions: SearchJourneysOptions = { 49 | results: 1, 50 | stopovers: true, 51 | firstClass: input.travelClass === 1, 52 | notOnlyFastRoutes: true, 53 | remarks: true, 54 | transfers: 3, 55 | age: input.passengerAge, 56 | deutschlandTicketDiscount: input.hasDeutschlandTicket, 57 | loyaltyCard: 58 | input.bahnCard && [25, 50, 100].includes(input.bahnCard) 59 | ? { 60 | type: loyaltyCards.BAHNCARD, 61 | discount: input.bahnCard, 62 | class: input.travelClass || 2, 63 | } 64 | : undefined, 65 | }; 66 | 67 | const fetchJourney = async (params: { 68 | from: string; 69 | to: string; 70 | targetDeparture: Date; 71 | }) => { 72 | const untyped = await dbClient.journeys(params.from, params.to, { 73 | ...queryOptions, 74 | departure: params.targetDeparture, 75 | }); 76 | 77 | const validated = z 78 | .object({ 79 | journeys: z.array(vendoJourneySchema), 80 | }) 81 | .parse(untyped); 82 | 83 | const expected = params.targetDeparture.getTime(); 84 | 85 | return ( 86 | validated.journeys.find( 87 | (journey) => 88 | Math.abs(journey.legs[0].departure.getTime() - expected) <= 60_000 // 1 Minute Toleranz 89 | ) || null 90 | ); 91 | }; 92 | 93 | try { 94 | const [firstJourney, secondJourney] = await Promise.all([ 95 | fetchJourney({ 96 | from: origin!.id, 97 | to: splitPoint.station.id, 98 | targetDeparture: input.journey.legs.at(0)!.departure, 99 | }), 100 | fetchJourney({ 101 | from: splitPoint.station.id, 102 | to: destination!.id, 103 | targetDeparture: splitPoint.departure, 104 | }), 105 | ]); 106 | 107 | if ( 108 | !firstJourney || 109 | !secondJourney || 110 | (firstJourney.price?.amount === undefined && 111 | secondJourney.price?.amount === undefined) 112 | ) { 113 | continue; 114 | } 115 | 116 | let totalPrice: number | null = null; // null = unknown 117 | 118 | // TODO this filter can probably be moved to frontend, no filtering on backend necessary 119 | if ( 120 | firstJourney.price?.amount !== undefined && 121 | secondJourney.price?.amount !== undefined 122 | ) { 123 | totalPrice = firstJourney.price.amount + secondJourney.price.amount; 124 | const originalPrice = input.journey.price?.amount || 0; 125 | 126 | if (totalPrice >= originalPrice) { 127 | continue; 128 | } 129 | } 130 | 131 | splitOptions.push({ 132 | splitStations: [splitPoint.station], 133 | segments: [firstJourney, secondJourney], 134 | }); 135 | } catch (error) { 136 | throw new TRPCError({ 137 | code: "INTERNAL_SERVER_ERROR", 138 | message: `Error analyzing single split at ${splitPoint.station.name}`, 139 | cause: error, 140 | }); 141 | } 142 | } 143 | 144 | yield { 145 | type: "complete", 146 | splitOptions, 147 | } as const; 148 | }); 149 | -------------------------------------------------------------------------------- /components/SearchForm/SearchForm.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import { useRouter } from "next/navigation"; 4 | import { useState } from "react"; 5 | import { URLInput } from "./URLInput"; 6 | import { useLocalStorage } from "./useLocalStorage"; 7 | 8 | export const SearchForm = () => { 9 | const router = useRouter(); 10 | const [url, setUrl] = useState(""); 11 | const [urlParseError, setUrlParseError] = useState(null); 12 | 13 | const [bahnCard, setBahnCard] = useLocalStorage("bahnCard", "none"); 14 | 15 | const [hasDeutschlandTicket, setHasDeutschlandTicket] = useLocalStorage( 16 | "hasDeutschlandTicket", 17 | false 18 | ); 19 | 20 | const [passengerAge, setPassengerAge] = useLocalStorage( 21 | "passengerAge", 22 | "" 23 | ); 24 | 25 | const [travelClass, setTravelClass] = useLocalStorage("travelClass", "2"); 26 | 27 | const handleUrlParsingAndNavigation = () => { 28 | if (!url.trim()) { 29 | setUrlParseError( 30 | "Bitte geben Sie Text mit einer DB-Buchungs-URL ein oder fügen Sie einen direkten DB-Buchungslink ein" 31 | ); 32 | return; 33 | } 34 | 35 | const regexResult = url.match(/vbid=([\w-]+)/); 36 | const vbid = regexResult?.[1]; 37 | 38 | if (!vbid) { 39 | setUrlParseError( 40 | "Keine gültige DB-Buchungs-URL gefunden. Bitte fügen Sie Text mit einem Deutsche Bahn Buchungslink ein (von bahn.de mit /buchung/start Pfad) oder überprüfen Sie, ob Ihre URL korrekt ist." 41 | ); 42 | return; 43 | } 44 | 45 | const searchParams = new URLSearchParams({ 46 | vbid, 47 | hasDeutschlandTicket: String(hasDeutschlandTicket), 48 | passengerAge: String(passengerAge), 49 | travelClass, 50 | // autoSearch: "true", // Flag to indicate auto-search should happen 51 | }); 52 | 53 | if (bahnCard !== "none") { 54 | searchParams.set("bahnCard", bahnCard); 55 | } 56 | 57 | router.push(`/discount?${searchParams.toString()}`); 58 | }; 59 | 60 | return ( 61 |
62 | {/* Unified Input and Search Section */} 63 |
64 | 65 |
66 | 81 | setPassengerAge(e.target.value)} 85 | placeholder="Alter des Reisenden" 86 | min="0" 87 | max="120" 88 | className="w-full px-3 py-2 resize-vertical border-b-2 border-gray-300 focus:ring-2 focus:ring-primary" 89 | /> 90 | 102 | 114 |
115 | 116 | 123 |
124 | 125 | {urlParseError && ( 126 |
127 | Fehler: {urlParseError} 128 |
129 | )} 130 |
131 | ); 132 | }; 133 | -------------------------------------------------------------------------------- /components/discount/OriginalJourneyCard.tsx: -------------------------------------------------------------------------------- 1 | import { isLegCoveredByDeutschlandTicket } from "@/utils/deutschlandTicketUtils"; 2 | import { 3 | formatDuration, 4 | formatPriceWithTwoDecimals, 5 | formatTime, 6 | getChangesCount, 7 | } from "@/utils/formatUtils"; 8 | import type { VendoJourney } from "@/utils/schemas"; 9 | import { JourneyIcon } from "./JourneyIcon"; 10 | import { JourneyInfoRow } from "./JourneyInfoRow"; 11 | import { useUrlParams } from "./useUrlParams"; 12 | 13 | interface Props { 14 | selectedJourney: VendoJourney; 15 | } 16 | 17 | export const OriginalJourneyCard = ({ selectedJourney }: Props) => { 18 | const { hasDeutschlandTicket, travelClass, bahnCard } = useUrlParams(); 19 | 20 | const trainLegs = selectedJourney.legs?.filter((leg) => !leg.walking) || []; 21 | 22 | const isFullyCoveredByDticket = 23 | hasDeutschlandTicket && 24 | trainLegs.length > 0 && 25 | trainLegs.every((leg) => 26 | isLegCoveredByDeutschlandTicket(leg, hasDeutschlandTicket) 27 | ); 28 | 29 | const formattedPrice = formatPriceWithTwoDecimals(selectedJourney.price); 30 | 31 | let priceDisplay; 32 | 33 | if (formattedPrice !== null) { 34 | priceDisplay = formattedPrice; 35 | } else if (isFullyCoveredByDticket) { 36 | priceDisplay = "0,00€"; 37 | } else { 38 | priceDisplay = "Preis auf Anfrage"; 39 | } 40 | 41 | const renderSelectedJourney = () => ( 42 |
43 |
44 |
45 | 46 |
47 | {/* Departure */} 48 |
49 |
50 | 51 | {selectedJourney.legs?.[0] 52 | ? formatTime(selectedJourney.legs[0].departure) 53 | : ""} 54 | 55 | 56 | {selectedJourney.legs[0].origin?.name} 57 | 58 |
59 |
60 |
Original
61 |
{priceDisplay}
62 |
63 |
64 | 65 | {/* Journey details */} 66 | 67 | 68 | {formatDuration(selectedJourney) || "Dauer unbekannt"} 69 | 70 | · 71 | 72 | {getChangesCount(selectedJourney)} Zwischenstopp 73 | {getChangesCount(selectedJourney) === 1 ? "" : "s"} 74 | 75 | 76 | DB 77 | 78 | 79 | 80 | {/* Arrival */} 81 |
82 |
83 | 84 | {selectedJourney.legs?.[selectedJourney.legs.length - 1] 85 | ? formatTime( 86 | selectedJourney.legs[selectedJourney.legs.length - 1] 87 | .arrival 88 | ) 89 | : ""} 90 | 91 | 92 | {selectedJourney.legs.at(-1)?.destination?.name} 93 | 94 |
95 |
96 |
97 |
98 | 99 | {/* Additional details */} 100 |
101 |
102 |
103 |

Klasse

104 |

{travelClass}. Klasse

105 |
106 |
107 |

BahnCard

108 |

109 | {bahnCard === null ? "Keine" : `BahnCard ${bahnCard}`} 110 |

111 |
112 |
113 | 114 | {hasDeutschlandTicket && ( 115 |
116 |

Deutschland-Ticket

117 |

✓ Vorhanden

118 |
119 | )} 120 | 121 | {selectedJourney.price?.hint && ( 122 |
123 |

{selectedJourney.price.hint}

124 |
125 | )} 126 |
127 |
128 |
129 | ); 130 | 131 | return ( 132 |
133 |

Deine Verbindung

134 | {selectedJourney ? ( 135 | renderSelectedJourney() 136 | ) : ( 137 |
Deine Verbindung wird geladen...
138 | )} 139 |
140 | ); 141 | }; 142 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to a positive environment for our community include: 12 | 13 | * Demonstrating empathy and kindness toward other people 14 | * Being respectful of differing opinions, viewpoints, and experiences 15 | * Giving and gracefully accepting constructive feedback 16 | * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 17 | * Focusing on what is best not just for us as individuals, but for the overall community 18 | 19 | Examples of unacceptable behavior include: 20 | 21 | * The use of sexualized language or imagery, and sexual attention or advances of any kind 22 | * Trolling, insulting or derogatory comments, and personal or political attacks 23 | * Public or private harassment 24 | * Publishing others' private information, such as a physical or email address, without their explicit permission 25 | * Other conduct which could reasonably be considered inappropriate in a professional setting 26 | 27 | ## Our Responsibilities 28 | 29 | Project maintainers are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 32 | 33 | ## Scope 34 | 35 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 36 | 37 | ## Enforcement 38 | 39 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project team responsible for enforcement at ****. All complaints will be reviewed and investigated promptly and fairly. 40 | 41 | All project maintainers are obligated to respect the privacy and security of the reporter of any incident. 42 | 43 | ## Enforcement Guidelines 44 | 45 | Project maintainers will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 46 | 47 | ### 1. Correction 48 | 49 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 50 | 51 | **Consequence**: A private, written warning from project maintainers, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 52 | 53 | ### 2. Warning 54 | 55 | **Community Impact**: A violation through a single incident or series of actions. 56 | 57 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interaction in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 58 | 59 | ### 3. Temporary Ban 60 | 61 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 62 | 63 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 64 | 65 | ### 4. Permanent Ban 66 | 67 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 68 | 69 | **Consequence**: A permanent ban from any sort of public interaction within the project community. 70 | 71 | ## Attribution 72 | 73 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 74 | 75 | [homepage]: https://www.contributor-covenant.org 76 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 77 | -------------------------------------------------------------------------------- /CONTRIBUTE.md: -------------------------------------------------------------------------------- 1 | # How to Contribute to BetterBahn 2 | 3 | We are thrilled that you're interested in contributing to BetterBahn! Every contribution, no matter how small, is valuable and greatly appreciated. These guidelines will help you understand the process. 4 | 5 | ## Table of Contents 6 | 7 | * [Code of Conduct](#code-of-conduct) 8 | * [How Can I Help?](#how-can-i-help) 9 | * [Reporting Bugs](#reporting-bugs) 10 | * [Suggesting New Features](#suggesting-new-features) 11 | * [Submitting Your First Pull Request](#submitting-your-first-pull-request) 12 | * [Git Commit Messages](#git-commit-messages) 13 | 14 | ## Code of Conduct 15 | 16 | This project and everyone participating in it is governed by our [Code of Conduct](/CODE_OF_CONDUCT.md). Please take a moment to read it. We expect all contributors to adhere to this code to ensure an open and welcoming environment. 17 | 18 | ## How Can I Help? 19 | 20 | There are many ways to contribute to the project. We welcome every form of support! 21 | 22 | ### Reporting Bugs 23 | 24 | If you find a bug, we kindly ask you to proceed as follows: 25 | 26 | 1. **Search existing issues:** Check under [Issues](https://github.com/l2xu/betterbahn/issues) to see if the bug has already been reported. 27 | 2. **Gather information:** To help us fix the bug quickly, we need as much information as possible. 28 | * The version of BetterBahn you are using. 29 | * Your operating system and its version. 30 | * A clear and concise description of the bug. 31 | * Steps to reproduce the bug. 32 | * What you expected to happen versus what actually happened. 33 | * Any relevant error messages or screenshots. 34 | 3. **Create a new issue:** If the bug hasn't been reported yet, create a new issue using our [Bug Report Template](https://github.com/l2xu/betterbahn/issues/new?template=bug_report.md). 35 | 36 | ### Suggesting New Features 37 | 38 | Do you have an idea for a new feature or an enhancement? 39 | 40 | 1. **Search existing issues:** Check if your idea has already been suggested under [Issues](https://github.com/l2xu/betterbahn/issues). 41 | 2. **Create a new issue:** Describe your idea in as much detail as possible using our [Feature Request Template](https://github.com/l2xu/betterbahn/issues/new?template=feature_request.md). Explain the problem your idea solves and why it would be useful for the project. 42 | 43 | ### Submitting Your First Pull Request 44 | 45 | Code contributions are the heart of an open-source project. Here is the basic workflow for submitting a Pull Request (PR): 46 | 47 | 1. **Find or create an issue:** Every PR should relate to an existing issue. If one doesn't exist, create one and briefly discuss the planned change with the maintainers. 48 | 2. **Fork the repository:** Click the "Fork" button in the top-right corner of the project's GitHub page. 49 | 3. **Clone your fork locally:** 50 | 51 | ```shell 52 | git clone [https://github.com/YOUR-USERNAME/](https://github.com/YOUR-USERNAME/)betterbahn.git 53 | ``` 54 | 55 | 4. **Create a new branch:** Choose a descriptive name for your branch (e.g., `feature/new-login-feature` or `fix/calculation-bug`). 56 | 57 | ```shell 58 | git checkout -b feature/descriptive-name 59 | ``` 60 | 61 | 5. **Make your changes:** Implement your feature or fix the bug. 62 | 6. **Add tests:** If you are adding a new feature, please include corresponding unit or integration tests. 63 | 7. **Run the tests (Not implemented yet!):** Ensure that all tests pass successfully. 64 | 65 | ```shell 66 | # Example command, adapt it for your project 67 | pnpm test 68 | ``` 69 | 70 | 8. **Commit your changes:** Write a clear and concise commit message (see [Style Guides](#git-commit-messages)). 71 | 72 | ```shell 73 | git add . 74 | git commit -m "feat: Add new login feature (closes #123)" 75 | ``` 76 | 77 | 9. **Push your changes to your fork:** 78 | 79 | ```shell 80 | git push origin feature/descriptive-name 81 | ``` 82 | 83 | 10. **Open a Pull Request:** Go to your fork on GitHub and click "Compare & pull request". 84 | * Choose the `main` branch of the original project as the base branch. 85 | * Give your PR a descriptive title and a detailed description of your changes. Reference the related issue (e.g., "Closes #123"). 86 | 11. **Wait for the review:** The project maintainers will review your code and may leave feedback or request changes. 87 | 88 | ## Git Commit Messages 89 | 90 | We follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification. This helps us automate changelog generation and keeps the project history readable. 91 | 92 | Each commit message should consist of a type, an optional scope, and a description: 93 | `(): ` 94 | 95 | * **feat:** A new feature. 96 | * **fix:** A bug fix. 97 | * **docs:** Changes to the documentation. 98 | * **style:** Code formatting, missing semicolons, etc. (no change in code logic). 99 | * **refactor:** Code changes that neither fix a bug nor add a feature. 100 | * **test:** Adding or correcting tests. 101 | * **chore:** Changes to the build process or auxiliary tools. 102 | 103 | **Example:** `feat(auth): Implement OAuth2 authentication` 104 | 105 | Thank you for your contribution! 106 | -------------------------------------------------------------------------------- /components/SplitOptions/calculateSplitOptionPricing.ts: -------------------------------------------------------------------------------- 1 | import type { SplitAnalysis } from "@/app/api/analyzeJourney"; 2 | import { 3 | isLegCoveredByDeutschlandTicket, 4 | legIsFlixTrain, 5 | } from "@/utils/deutschlandTicketUtils"; 6 | import { getJourneyLegsWithTransfers } from "@/utils/journeyUtils"; 7 | import type { VendoJourney } from "@/utils/schemas"; 8 | 9 | /** Berechne Split-Option Preisgestaltung mit Deutschland-Ticket Logik */ 10 | export const calculateSplitOptionPricing = ({ 11 | splitOption, 12 | hasDeutschlandTicket, 13 | originalJourney, 14 | }: { 15 | splitOption: SplitAnalysis; 16 | hasDeutschlandTicket: boolean; 17 | originalJourney: VendoJourney; 18 | }) => { 19 | let totalPrice: number | null = null; // null = unknown 20 | 21 | if ( 22 | splitOption.segments[0].price?.amount !== undefined && 23 | splitOption.segments[1].price?.amount !== undefined 24 | ) { 25 | totalPrice = 26 | splitOption.segments[0].price.amount + 27 | splitOption.segments[1].price.amount; 28 | } 29 | 30 | let savings: number | null = null; 31 | 32 | if (totalPrice !== null && originalJourney.price?.amount !== undefined) { 33 | savings = originalJourney.price.amount - totalPrice; 34 | } 35 | 36 | if (!splitOption || !splitOption.segments) { 37 | return { 38 | ...splitOption, 39 | isFullyCovered: false, 40 | hasRegionalTrains: false, 41 | cannotShowPrice: false, 42 | hasPartialPricing: false, 43 | segmentsWithoutPricing: [] as number[], 44 | adjustedTotalPrice: totalPrice, 45 | adjustedSavings: savings, 46 | hasFlixTrains: null, 47 | }; 48 | } 49 | 50 | // Überprüfe ob Split-Option Regionalzüge enthält 51 | const hasRegionalTrains = splitOption.segments.some((segment) => { 52 | const trainLegs = getJourneyLegsWithTransfers(segment); 53 | return trainLegs.some((leg) => { 54 | const product = leg.line?.product?.toLowerCase() || ""; 55 | const regionalProducts = [ 56 | "regional", 57 | "regionalbahn", 58 | "regionalexpress", 59 | "sbahn", 60 | "suburban", 61 | ]; 62 | return regionalProducts.includes(product); 63 | }); 64 | }); 65 | 66 | const hasFlixTrains = splitOption.segments.some((segment) => { 67 | const trainLegs = getJourneyLegsWithTransfers(segment); 68 | return trainLegs.some((leg) => legIsFlixTrain(leg)); 69 | }); 70 | 71 | let cannotShowPrice: boolean; 72 | let hasPartialPricing: boolean; 73 | let segmentsWithoutPricing: number[] = []; 74 | let allSegmentsCovered: boolean; 75 | 76 | allSegmentsCovered = splitOption.segments.every((segment) => { 77 | const trainLegs = getJourneyLegsWithTransfers(segment); 78 | return trainLegs.every((leg) => 79 | isLegCoveredByDeutschlandTicket(leg, hasDeutschlandTicket) 80 | ); 81 | }); 82 | 83 | if (hasDeutschlandTicket) { 84 | cannotShowPrice = false; 85 | hasPartialPricing = false; 86 | } else { 87 | let segmentsWithPrice = 0; 88 | let totalSegments = splitOption.segments.length; 89 | 90 | splitOption.segments.forEach((segment, index) => { 91 | const hasPrice = segment.price; 92 | 93 | const segmentHasFlixTrain = getJourneyLegsWithTransfers(segment).some( 94 | (leg) => legIsFlixTrain(leg) 95 | ); 96 | 97 | // Consider a segment as having no pricing if: 98 | // 1. It has no price data, OR 99 | // 2. It contains FlixTrain services (which we can't price) 100 | if (!hasPrice || segmentHasFlixTrain) { 101 | segmentsWithoutPricing.push(index); 102 | } else { 103 | segmentsWithPrice++; 104 | } 105 | }); 106 | 107 | cannotShowPrice = segmentsWithPrice === 0; 108 | hasPartialPricing = 109 | segmentsWithPrice > 0 && segmentsWithPrice < totalSegments; 110 | } 111 | 112 | let adjustedTotalPrice = totalPrice; 113 | let adjustedSavings = savings; 114 | 115 | if (originalJourney) { 116 | // The API already returns prices with BahnCard discounts applied 117 | const originalJourneyApiPrice = originalJourney.price?.amount || 0; 118 | 119 | if (hasDeutschlandTicket) { 120 | let totalUncoveredPrice = 0; 121 | 122 | for (const segment of splitOption.segments) { 123 | const trainLegs = getJourneyLegsWithTransfers(segment); 124 | const segmentCovered = trainLegs.every((leg) => 125 | isLegCoveredByDeutschlandTicket(leg, hasDeutschlandTicket) 126 | ); 127 | const segmentPrice = segment.price?.amount || 0; 128 | 129 | if (!segmentCovered && segmentPrice > 0) { 130 | totalUncoveredPrice += segmentPrice; 131 | } 132 | } 133 | 134 | adjustedTotalPrice = totalUncoveredPrice; 135 | } else if (hasPartialPricing) { 136 | // For partial pricing, only sum up segments with available pricing 137 | let partialTotalPrice = 0; 138 | 139 | splitOption.segments.forEach((segment, index) => { 140 | if (!segmentsWithoutPricing.includes(index)) { 141 | partialTotalPrice += segment.price?.amount || 0; 142 | } 143 | }); 144 | 145 | adjustedTotalPrice = partialTotalPrice; 146 | } 147 | 148 | if (adjustedTotalPrice !== null) { 149 | adjustedSavings = Math.max( 150 | 0, 151 | originalJourneyApiPrice - adjustedTotalPrice 152 | ); 153 | } 154 | } 155 | 156 | return { 157 | ...splitOption, 158 | isFullyCovered: allSegmentsCovered && hasDeutschlandTicket, 159 | hasRegionalTrains, 160 | hasFlixTrains, 161 | cannotShowPrice, 162 | hasPartialPricing, 163 | segmentsWithoutPricing, 164 | adjustedTotalPrice, 165 | adjustedSavings, 166 | }; 167 | }; 168 | -------------------------------------------------------------------------------- /utils/createUrl.ts: -------------------------------------------------------------------------------- 1 | import type { VendoJourney } from "./schemas"; 2 | 3 | interface Station { 4 | id?: string; 5 | stationId?: string; 6 | uicCode?: string; 7 | evaId?: string; 8 | name?: string; 9 | longitude?: number; 10 | latitude?: number; 11 | x?: number; 12 | y?: number; 13 | } 14 | 15 | /** 16 | * Formats a date for DB URL parameters 17 | * @returns {string} Formatted date string 18 | */ 19 | function formatDate(date: Date): string { 20 | let formattedDate = date 21 | .toISOString() 22 | .replace(/\+\d{2}:\d{2}$/, "") 23 | .replace(/Z$/, "") 24 | .replace(/\.\d{3}/, ""); 25 | if (/T\d{2}:\d{2}$/.test(formattedDate)) formattedDate += ":58"; // ensure seconds 26 | if (!formattedDate.includes("T")) formattedDate += "T08:32:58"; // default time 27 | return formattedDate; 28 | } 29 | 30 | /** 31 | * Creates a station ID string in DB format 32 | * @param {Object} station - Station object with name, id, and coordinates 33 | * @returns {string} Encoded station ID 34 | */ 35 | function createStationId(station: Station): string { 36 | const stationString = Object.entries({ 37 | A: "1", 38 | O: station.name, 39 | X: station.x ?? station.longitude ?? "", 40 | Y: station.y ?? station.latitude ?? "", 41 | U: "80", 42 | L: station.id, 43 | B: "1", 44 | p: "1750104613", 45 | }) 46 | .map(([k, v]) => `${k}=${v}`) 47 | .join("@"); 48 | return encodeURIComponent(stationString); 49 | } 50 | 51 | /** 52 | * Creates a urlParameter that encodes the available Bahncard 53 | * @param {number} travelClass - Travel class (1 or 2) 54 | * @param {string | null} bahnCard - Type of Bahncard ("25", "50", or null for none) 55 | * @returns {string} Encoded Bahncard parameter 56 | */ 57 | function createBcParameter(travelClass: number, bahnCard: string | null): string { 58 | switch (bahnCard) { 59 | case "25": 60 | return `13:17:KLASSE_${travelClass}:1` 61 | case "50": 62 | return `13:23:KLASSE_${travelClass}:1` 63 | default: 64 | return "13:16:KLASSENLOS:1" 65 | } 66 | } 67 | 68 | /** 69 | * Creates a DB search URL for a journey segment 70 | * @param {Object} segment - Journey segment object 71 | * @param {number} travelClass - Travel class (1 or 2) 72 | * @param {boolean} hasDeutschlandTicket - Deutschlandticket 73 | * @param {string | null} bahnCard - Type of Bahncard ("25", "50", or null for none) 74 | * @returns {string} DB website search URL 75 | */ 76 | export function createSegmentSearchUrl( 77 | segment: VendoJourney, 78 | travelClass: number = 2, 79 | hasDeutschlandTicket: boolean, 80 | bahnCard: string | null 81 | ): string { 82 | if (!segment?.legs?.length) 83 | throw new Error("Invalid segment: missing legs data"); 84 | const legs = segment.legs; 85 | const firstLeg = legs[0]; 86 | const lastLeg = legs[legs.length - 1]; 87 | const cleanDate = formatDate(firstLeg.departure); 88 | const bcParameter = createBcParameter(travelClass, bahnCard) 89 | 90 | // Modern URL building with proper validation 91 | 92 | // Properly validate required data with explicit checks for optional properties 93 | if ( 94 | !firstLeg?.origin || 95 | !firstLeg.origin.name || 96 | !lastLeg?.destination || 97 | !lastLeg.destination.name 98 | ) { 99 | throw new Error( 100 | "Missing origin, destination, or station names in journey legs" 101 | ); 102 | } 103 | 104 | const parts = [ 105 | "sts=true", 106 | `so=${encodeURIComponent(firstLeg.origin.name)}`, 107 | `zo=${encodeURIComponent(lastLeg.destination.name)}`, 108 | `kl=${travelClass}`, 109 | `r=${bcParameter}`, 110 | ]; 111 | 112 | const originId = addStationId(firstLeg.origin, "s", parts); 113 | const destId = addStationId(lastLeg.destination, "z", parts); 114 | 115 | parts.push("sot=ST", "zot=ST"); 116 | 117 | if (originId && firstLeg.origin.name) { 118 | parts.push(`soei=${originId}`); 119 | } 120 | 121 | if (destId && lastLeg.destination.name) { 122 | parts.push(`zoei=${destId}`); 123 | } 124 | 125 | parts.push( 126 | `hd=${cleanDate}`, 127 | "hza=D", 128 | "hz=%5B%5D", 129 | "ar=false", 130 | "s=false", 131 | "d=false", 132 | "vm=00,01,02,03,04,05,06,07,08,09", 133 | "fm=false", 134 | "bp=false", 135 | "dlt=false", 136 | `dltv=${hasDeutschlandTicket}` 137 | ); 138 | 139 | return `https://www.bahn.de/buchung/fahrplan/suche#${parts.join("&")}`; 140 | } 141 | 142 | /** 143 | * Helper function to add station ID to URL parameters 144 | * @param {Object} station - Station object 145 | * @param {string} type - Station type ('s' for origin, 'z' for destination) 146 | * @param {Array} parts - URL parts array to modify 147 | * @returns {string|null} Station ID if found 148 | */ 149 | /** 150 | * Known problematic station mappings - station IDs that don't match expected names 151 | */ 152 | const PROBLEMATIC_STATION_IDS: Record = { 153 | // Add known problematic mappings here 154 | 8002235: "Senden", // This ID seems to resolve to Senden instead of Gengenbach 155 | }; 156 | 157 | /** 158 | * Validates if a station ID should be used based on the station name 159 | * @param {string} stationId - The station ID 160 | * @param {string} stationName - The station name 161 | * @returns {boolean} - Whether the station ID is safe to use 162 | */ 163 | function shouldUseStationId(stationId: string, stationName: string) { 164 | if (!stationId || !stationName) return false; 165 | const problematicName = PROBLEMATIC_STATION_IDS[stationId]; 166 | if ( 167 | problematicName && 168 | !stationName.toLowerCase().includes(problematicName.toLowerCase()) 169 | ) { 170 | console.warn( 171 | `Skipping problematic station ID ${stationId} for ${stationName} (maps to ${problematicName})` 172 | ); 173 | return false; 174 | } 175 | return true; 176 | } 177 | 178 | function addStationId(station: Station, type: string, parts: string[]) { 179 | const stationId = 180 | station.id || station.stationId || station.uicCode || station.evaId; 181 | 182 | if ( 183 | stationId && 184 | station.name && 185 | shouldUseStationId(stationId, station.name) 186 | ) { 187 | const stationData = createStationId({ 188 | name: station.name, 189 | id: stationId, 190 | x: station.longitude || station.x, 191 | y: station.latitude || station.y, 192 | }); 193 | parts.push(`${type}oid=${stationData}`); 194 | return stationId; 195 | } 196 | 197 | return null; 198 | } 199 | -------------------------------------------------------------------------------- /app/api/getJourney/getJourney.ts: -------------------------------------------------------------------------------- 1 | import { fetchAndValidateJson } from "@/utils/fetchAndValidateJson"; 2 | import { parseHinfahrtReconWithAPI } from "@/utils/parseHinfahrtRecon"; 3 | import { vbidSchema, vendoJourneySchema } from "@/utils/schemas"; 4 | import { t } from "@/utils/trpc-init"; 5 | import { TRPCError } from "@trpc/server"; 6 | import { createClient, type SearchJourneysOptions } from "db-vendo-client"; 7 | import { data as loyaltyCards } from "db-vendo-client/format/loyalty-cards"; 8 | import { profile as dbProfile } from "db-vendo-client/p/db/index"; 9 | import { prettifyError, z } from "zod/v4"; 10 | 11 | export const dbClient = createClient(dbProfile, "mail@lukasweihrauch.de"); 12 | 13 | export const getJourney = t.procedure 14 | .input( 15 | z.object({ 16 | vbid: z.string(), 17 | travelClass: z.int(), 18 | bahnCard: z.int().nullable(), 19 | passengerAge: z.int().optional(), 20 | hasDeutschlandTicket: z.boolean(), 21 | }) 22 | ) 23 | .query(async ({ input }) => { 24 | const vbidRequest = await fetchAndValidateJson({ 25 | url: `https://www.bahn.de/web/api/angebote/verbindung/${input.vbid}`, 26 | schema: vbidSchema, 27 | }); 28 | 29 | const cookies = vbidRequest.response.headers.getSetCookie(); 30 | const { data } = await parseHinfahrtReconWithAPI(vbidRequest.data, cookies); 31 | 32 | // Find first segment with halte data for start station 33 | const firstSegmentWithHalte = 34 | data.verbindungen[0].verbindungsAbschnitte.find( 35 | (segment) => segment.halte.length > 0 36 | ); 37 | 38 | const lastSegmentWithHalte = 39 | data.verbindungen[0].verbindungsAbschnitte.findLast( 40 | (segment) => segment.halte.length > 0 41 | ); 42 | 43 | if (!firstSegmentWithHalte || !lastSegmentWithHalte) { 44 | throw new Error("No segments with station data found"); 45 | } 46 | 47 | const soidValue = firstSegmentWithHalte.halte[0].id; 48 | const zoidValue = lastSegmentWithHalte.halte.at(-1)!.id; 49 | const fromStationId = soidValue.match(/@L=(\d+)/)?.[1]; 50 | const toStationId = zoidValue.match(/@L=(\d+)/)?.[1]; 51 | 52 | if (!fromStationId || !toStationId) { 53 | throw new TRPCError({ 54 | code: "INTERNAL_SERVER_ERROR", 55 | message: "missing soid or zoid", 56 | }); 57 | } 58 | 59 | const options: SearchJourneysOptions = { 60 | results: 10, 61 | stopovers: true, 62 | // Bei genauer Abfahrtszeit wollen wir exakte Treffer, nicht verschiedene Alternativen 63 | notOnlyFastRoutes: true, 64 | remarks: true, // Verbindungshinweise einschließen 65 | transfers: -1, // System entscheidet über optimale Anzahl Umstiege 66 | // Reiseklasse-Präferenz setzen - verwende firstClass boolean Parameter 67 | firstClass: input.travelClass === 1, // true für erste Klasse, false für zweite Klasse 68 | age: input.passengerAge, // Passagieralter für angemessene Preisgestaltung hinzufügen 69 | departure: new Date(vbidRequest.data.hinfahrtDatum), 70 | }; 71 | 72 | if (input.bahnCard !== null && [25, 50, 100].includes(input.bahnCard)) { 73 | options.loyaltyCard = { 74 | type: loyaltyCards.BAHNCARD, 75 | discount: input.bahnCard, 76 | class: input.travelClass, 77 | }; 78 | } 79 | 80 | if (input.hasDeutschlandTicket) { 81 | options.deutschlandTicketDiscount = true; 82 | // Diese Option kann helfen, genauere Preise zurückzugeben wenn Deutschland-Ticket verfügbar ist 83 | options.deutschlandTicketConnectionsOnly = false; // Wir wollen alle Verbindungen, aber mit genauen Preisen 84 | } 85 | 86 | const journeys = await dbClient.journeys( 87 | fromStationId, 88 | toStationId, 89 | options 90 | ); 91 | 92 | const parseResult = z 93 | .object({ journeys: z.array(vendoJourneySchema) }) 94 | .safeParse(journeys); 95 | 96 | if (!parseResult.success) { 97 | throw new TRPCError({ 98 | code: "INTERNAL_SERVER_ERROR", 99 | message: `Validation of 'journeys' response of DB-API failed: ${prettifyError( 100 | parseResult.error 101 | )}`, 102 | cause: parseResult.error, 103 | }); 104 | } 105 | 106 | const uniqueJourneys = parseResult.data.journeys.filter( 107 | (journey, index, arr) => { 108 | if (journey.legs.length === 0) { 109 | return false; 110 | } 111 | 112 | const journeySignature = journey.legs 113 | .map( 114 | (leg) => 115 | `${leg.line?.name || "walk"}-${leg.origin?.id}-${ 116 | leg.destination?.id 117 | }-${leg.departure}` 118 | ) 119 | .join("|"); 120 | 121 | const key = `${journeySignature}-${ 122 | journey.price?.amount || "no-price" 123 | }`; 124 | return ( 125 | arr.findIndex((j) => { 126 | if (!j.legs || j.legs.length === 0) { 127 | return false; 128 | } 129 | 130 | const jSignature = j.legs 131 | .map( 132 | (leg) => 133 | `${leg.line?.name || "walk"}-${leg.origin?.id}-${ 134 | leg.destination?.id 135 | }-${leg.departure}` 136 | ) 137 | .join("|"); 138 | 139 | const jKey = `${jSignature}-${j.price?.amount || "no-price"}`; 140 | return jKey === key; 141 | }) === index 142 | ); 143 | } 144 | ); 145 | 146 | // Sort by departure time 147 | const sortedJourneys = uniqueJourneys.toSorted( 148 | (a, b) => a.legs[0].departure.getTime() - b.legs[0].departure.getTime() 149 | ); 150 | 151 | // Only show journeys matching the original search time 152 | const originalDepartureTime = new Date(vbidRequest.data.hinfahrtDatum); 153 | 154 | // Find the journey that best matches the original departure time 155 | const closestJourney = sortedJourneys.reduce((closest, current) => { 156 | if (!closest) return current; 157 | const closestDiff = Math.abs( 158 | closest.legs[0].departure.getTime() - originalDepartureTime.getTime() 159 | ); 160 | const currentDiff = Math.abs( 161 | current.legs[0].departure.getTime() - originalDepartureTime.getTime() 162 | ); 163 | return currentDiff < closestDiff ? current : closest; 164 | }, sortedJourneys[0]); 165 | 166 | if (!closestJourney) { 167 | return []; 168 | } 169 | 170 | // Get the departure time of the closest journey 171 | const targetDepartureTime = closestJourney.legs[0].departure.getTime(); 172 | 173 | // Return only journeys with the exact same departure time as the closest match 174 | return sortedJourneys.filter( 175 | (journey) => journey.legs[0].departure.getTime() === targetDepartureTime 176 | ); 177 | }); 178 | -------------------------------------------------------------------------------- /components/SplitOptions/SplitOptions.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import type { SplitAnalysis } from "@/app/api/analyzeJourney"; 4 | import { formatDuration, formatTime } from "@/utils/formatUtils"; 5 | import { getStationName } from "@/utils/journeyUtils"; 6 | import { formatPriceDE } from "@/utils/priceUtils"; 7 | import type { VendoJourney } from "@/utils/schemas"; 8 | import { useState } from "react"; 9 | import { useUrlParams } from "../discount/useUrlParams"; 10 | import { getOptionsToShow } from "./getOptionsToShow"; 11 | import { Segment } from "./Segment"; 12 | 13 | // Komponente zur Anzeige von Split-Ticket Optionen 14 | export const SplitOptions = ({ 15 | splitOptions, 16 | originalJourney, 17 | loadingSplits, 18 | }: { 19 | splitOptions: SplitAnalysis[]; 20 | originalJourney: VendoJourney; 21 | loadingSplits: unknown; 22 | }) => { 23 | // State für erweiterte Optionsanzeige (erste Option standardmäßig erweitert) 24 | const [expandedOption, setExpandedOption] = useState(0); 25 | 26 | const { hasDeutschlandTicket, travelClass, bahnCard } = useUrlParams(); 27 | 28 | const optionsToDisplay = getOptionsToShow({ 29 | splitOptions, 30 | hasDeutschlandTicket, 31 | originalJourney, 32 | }); 33 | 34 | if (loadingSplits) { 35 | return ( 36 |
37 |
38 |

Analysiere Split-Ticket Optionen...

39 |
40 | ); 41 | } 42 | 43 | if (!splitOptions || splitOptions.length === 0) { 44 | return ( 45 |
46 |

47 | Keine günstigeren Split-Ticket Optionen gefunden. 48 |

49 |

50 | Die direkte Verbindung scheint die kostengünstigste Option zu sein. 51 |

52 |
53 | ); 54 | } 55 | 56 | return ( 57 | <> 58 |
59 | {optionsToDisplay.map((splitOption, splitIndex) => { 60 | const splitPricing = splitOption.pricing; 61 | 62 | if (splitPricing.cannotShowPrice) { 63 | return ( 64 |
68 |
69 |
70 | Option {splitIndex + 1} 71 |
72 |
73 | ⚠️ Preisberechnung für 74 | {splitPricing.hasFlixTrains ? " FlixTrain und" : ""}{" "} 75 | Regionalverkehr nicht möglich. Manuelle Prüfung 76 | erforderlich. 77 |
78 |
79 |
80 | ); 81 | } 82 | 83 | const isExpanded = expandedOption === splitIndex; 84 | const departureLeg = splitOption.segments[0].legs[0]; 85 | const lastSegment = 86 | splitOption.segments[splitOption.segments.length - 1]; 87 | const arrivalLeg = lastSegment.legs[lastSegment.legs.length - 1]; 88 | 89 | const totalChanges = 90 | splitOption.segments.reduce( 91 | (acc, s) => acc + s.legs.length - 1, 92 | 0 93 | ) + 94 | (splitOption.segments.length - 1); 95 | 96 | return ( 97 |
105 |
108 | setExpandedOption(isExpanded ? null : splitIndex) 109 | } 110 | > 111 |
112 |
113 | 121 | 126 | 127 |
128 |
129 |
130 | 131 |
132 |
133 |
134 | 135 | {formatTime(departureLeg.departure)} 136 | 137 | 138 | {getStationName(departureLeg.origin)} 139 | 140 |
141 |
142 | {splitPricing.isFullyCovered ? ( 143 |
144 |
145 | Deutschland-Ticket 146 |
147 |
148 | ✓ Vollständig enthalten 149 |
150 |
151 | ) : ( 152 | <> 153 |
154 | Spare{" "} 155 | {splitPricing.adjustedSavings === null 156 | ? "?" 157 | : formatPriceDE(splitPricing.adjustedSavings)} 158 |
159 |
160 | {splitPricing.adjustedTotalPrice === null 161 | ? "?" 162 | : formatPriceDE( 163 | splitPricing.adjustedTotalPrice 164 | )} 165 | {splitPricing.hasPartialPricing && ( 166 | * 167 | )} 168 |
169 | 170 | )} 171 |
172 |
173 | 174 |
175 | 176 | {formatDuration({ legs: [departureLeg, arrivalLeg] }) || 177 | "Dauer unbekannt"} 178 | 179 | · 180 | 181 | {totalChanges} Zwischenstopp 182 | {totalChanges === 1 ? "" : "s"} 183 | 184 | 185 | DB 186 | 187 |
188 | 189 | {splitOption.splitStations && 190 | splitOption.splitStations.length > 0 && ( 191 |
192 | Über:{" "} 193 | 194 | {splitOption.splitStations 195 | .map((s) => s?.name) 196 | .join(", ")} 197 | 198 |
199 | )} 200 | 201 |
202 |
203 | 204 | {formatTime(arrivalLeg.arrival)} 205 | 206 | 207 | {getStationName(arrivalLeg.destination)} 208 | 209 |
210 |
211 |
212 | 213 |
214 | 222 | 227 | 228 |
229 |
230 |
231 | 232 | {isExpanded && ( 233 |
234 |
235 |

236 | Die Teile deiner Reise 237 |

238 |
239 | {splitOption.segments.map((segment, segmentIndex) => ( 240 | 251 | ))} 252 |
253 | {splitPricing.hasPartialPricing && ( 254 |
255 | * Einige Segmente haben unbekannte Preise (z.B. 256 | Regional- züge, FlixTrain). Der Gesamtpreis und die 257 | Ersparnis basieren auf verfügbaren Daten. 258 |
259 | )} 260 |
261 |
262 | )} 263 |
264 | ); 265 | })} 266 |
267 | 268 | ); 269 | }; 270 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------