feat: Download-Weiterleitung /app für Flyer und QR-Codes (D3)
- Android → Google Play, UTM-Werte als Play-referrer (Play Console) - iPhone → App Store, sobald APP_STORE_URL gesetzt ist (D5); bis dahin Web - sonst → Web-Startseite; ?ref=<Code> führt auf die Einladungsseite /r/<Code> - nur sichere UTM-Werte werden übernommen, nie gecacht (302, no-store) - Zählung pro Tag/Quelle/Gerät in Redis, Anzeige im Admin unter Empfehlungen → Übersicht (30 Tage) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8143e7b667
commit
94c143e17d
8 files changed
+293
No files matched your search
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* /app — Download-Weiterleitung (src/lib/app-redirect.ts, app-redirect-stats.ts).
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("server-only", () => ({}));
|
||||
const redisStore = new Map<string, Map<string, number>>();
|
||||
vi.mock("@/lib/redis", () => ({
|
||||
redis: {
|
||||
hincrby: vi.fn(async (key: string, field: string, by: number) => {
|
||||
const hash = redisStore.get(key) ?? new Map<string, number>();
|
||||
hash.set(field, (hash.get(field) ?? 0) + by);
|
||||
redisStore.set(key, hash);
|
||||
return hash.get(field);
|
||||
}),
|
||||
expire: vi.fn(async () => 1),
|
||||
hgetall: vi.fn(async (key: string) => Object.fromEntries(redisStore.get(key) ?? new Map())),
|
||||
},
|
||||
}));
|
||||
|
||||
import { PLAY_STORE_URL } from "@/lib/app-links";
|
||||
import { detectPlatform, resolveAppRedirect } from "@/lib/app-redirect";
|
||||
import { countAppRedirect, getAppRedirectStats } from "@/lib/app-redirect-stats";
|
||||
|
||||
const ORIGIN = "https://pawfeed.org";
|
||||
const ANDROID = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/128 Mobile Safari/537.36";
|
||||
const IPHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Mobile/15E148 Safari/604.1";
|
||||
const DESKTOP = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/128 Safari/537.36";
|
||||
|
||||
const params = (query: string) => new URLSearchParams(query);
|
||||
|
||||
describe("detectPlatform", () => {
|
||||
it("recognises Android, iPhone and everything else", () => {
|
||||
expect(detectPlatform(ANDROID)).toBe("android");
|
||||
expect(detectPlatform(IPHONE)).toBe("ios");
|
||||
expect(detectPlatform(DESKTOP)).toBe("other");
|
||||
expect(detectPlatform(null)).toBe("other");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAppRedirect", () => {
|
||||
it("sends Android to Google Play with the UTM values as Play referrer", () => {
|
||||
const result = resolveAppRedirect(ANDROID, params("utm_source=flyer&utm_campaign=tierheim-xy"), ORIGIN);
|
||||
expect(result.platform).toBe("android");
|
||||
expect(result.source).toBe("flyer");
|
||||
expect(result.location.startsWith(PLAY_STORE_URL)).toBe(true);
|
||||
const referrer = new URL(result.location).searchParams.get("referrer");
|
||||
expect(referrer).toBe("utm_source=flyer&utm_campaign=tierheim-xy");
|
||||
});
|
||||
|
||||
it("sends iPhones to the web start page while there is no App Store URL", () => {
|
||||
const result = resolveAppRedirect(IPHONE, params("utm_source=sticker"), ORIGIN, null);
|
||||
expect(result.location).toBe("https://pawfeed.org/?utm_source=sticker");
|
||||
});
|
||||
|
||||
it("sends iPhones to the App Store once the URL is configured", () => {
|
||||
const store = "https://apps.apple.com/app/id123";
|
||||
expect(resolveAppRedirect(IPHONE, params(""), ORIGIN, store).location).toBe(store);
|
||||
});
|
||||
|
||||
it("turns ?ref=<code> into the invite page on the web", () => {
|
||||
const result = resolveAppRedirect(DESKTOP, params("ref=bubi-7k3m&utm_source=qr"), ORIGIN, null);
|
||||
expect(result.location).toBe("https://pawfeed.org/r/BUBI-7K3M?utm_source=qr");
|
||||
});
|
||||
|
||||
it("drops unsafe UTM values and invalid codes instead of passing them on", () => {
|
||||
const result = resolveAppRedirect(DESKTOP, params("utm_source=<script>&ref=nope"), ORIGIN, null);
|
||||
expect(result.location).toBe("https://pawfeed.org/");
|
||||
expect(result.source).toBe("direct");
|
||||
});
|
||||
|
||||
it("uses the plain Play URL without any campaign data", () => {
|
||||
expect(resolveAppRedirect(ANDROID, params(""), ORIGIN).location).toBe(PLAY_STORE_URL);
|
||||
});
|
||||
});
|
||||
|
||||
describe("app redirect stats", () => {
|
||||
beforeEach(() => redisStore.clear());
|
||||
|
||||
it("sums clicks per source and platform over the requested days", async () => {
|
||||
const today = new Date("2026-10-02T10:00:00Z");
|
||||
const yesterday = new Date("2026-10-01T10:00:00Z");
|
||||
await countAppRedirect("flyer", "android", today);
|
||||
await countAppRedirect("flyer", "android", yesterday);
|
||||
await countAppRedirect("flyer", "ios", today);
|
||||
await countAppRedirect("direct", "other", today);
|
||||
|
||||
const stats = await getAppRedirectStats(30, today);
|
||||
|
||||
expect(stats[0]).toEqual({ source: "flyer", android: 2, ios: 1, other: 0, total: 3 });
|
||||
expect(stats[1]).toEqual({ source: "direct", android: 0, ios: 0, other: 1, total: 1 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { resolveAppRedirect } from "@/lib/app-redirect";
|
||||
import { countAppRedirect } from "@/lib/app-redirect-stats";
|
||||
|
||||
/**
|
||||
* /app — Download-Weiterleitung für Flyer, Sticker und QR-Codes
|
||||
* (z. B. pawfeed.org/app?utm_source=flyer). Logik: src/lib/app-redirect.ts.
|
||||
* Öffentlich (siehe isPublicRoute in src/proxy.ts), nie gecacht, weil das
|
||||
* Ziel vom Gerät abhängt.
|
||||
*/
|
||||
|
||||
function resolveOrigin(request: NextRequest): string {
|
||||
const proto = request.headers.get("x-forwarded-proto") ?? "https";
|
||||
const host = request.headers.get("x-forwarded-host") ?? request.headers.get("host") ?? "pawfeed.org";
|
||||
return `${proto}://${host}`;
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const target = resolveAppRedirect(
|
||||
request.headers.get("user-agent"),
|
||||
request.nextUrl.searchParams,
|
||||
resolveOrigin(request)
|
||||
);
|
||||
await countAppRedirect(target.source, target.platform);
|
||||
|
||||
const response = NextResponse.redirect(target.location, 302);
|
||||
response.headers.set("Cache-Control", "no-store");
|
||||
return response;
|
||||
}
|
||||
@@ -88,6 +88,40 @@ export function OverviewTab() {
|
||||
</ul>
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
title="Download-Link /app (30 Tage)"
|
||||
hint="Aufrufe von pawfeed.org/app nach utm_source (z. B. ?utm_source=flyer) und Gerät. „direct“ = ohne Quelle."
|
||||
>
|
||||
{data.appRedirects.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">Noch keine Aufrufe.</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto rounded-xl border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/50 text-left text-xs uppercase tracking-wide text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-3 py-2">Quelle</th>
|
||||
<th className="px-3 py-2 text-right">Android</th>
|
||||
<th className="px-3 py-2 text-right">iPhone</th>
|
||||
<th className="px-3 py-2 text-right">Andere</th>
|
||||
<th className="px-3 py-2 text-right">Gesamt</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.appRedirects.map((row) => (
|
||||
<tr key={row.source} className="border-t">
|
||||
<td className="px-3 py-2 font-mono">{row.source}</td>
|
||||
<td className="px-3 py-2 text-right tabular-nums">{row.android}</td>
|
||||
<td className="px-3 py-2 text-right tabular-nums">{row.ios}</td>
|
||||
<td className="px-3 py-2 text-right tabular-nums">{row.other}</td>
|
||||
<td className="px-3 py-2 text-right font-semibold tabular-nums">{row.total}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section title="Letzte Einlösungen">
|
||||
<ul className="divide-y rounded-xl border">
|
||||
{data.recent.map((o) => (
|
||||
|
||||
@@ -6,3 +6,10 @@
|
||||
export const ANDROID_PACKAGE_ID = "org.pawfeed.app";
|
||||
|
||||
export const PLAY_STORE_URL = `https://play.google.com/store/apps/details?id=${ANDROID_PACKAGE_ID}`;
|
||||
|
||||
/**
|
||||
* App-Store-Eintrag der iOS-App. Bleibt null, bis die App freigegeben ist
|
||||
* (Phase-0-Aufgabe D5) — bis dahin leitet /app iPhones auf die Web-Startseite.
|
||||
* Eintragen genügt, /app nutzt den Wert automatisch.
|
||||
*/
|
||||
export const APP_STORE_URL: string | null = null;
|
||||
@@ -0,0 +1,49 @@
|
||||
import "server-only";
|
||||
import { redis } from "@/lib/redis";
|
||||
import type { AppPlatform } from "@/lib/app-redirect";
|
||||
|
||||
/**
|
||||
* Zählt Aufrufe von /app pro Tag, Quelle (utm_source) und Plattform in
|
||||
* Redis-Hashes: appredirect:<YYYY-MM-DD> → { "<source>|<platform>": n }.
|
||||
* Fail-open: ohne Redis wird nicht gezählt, die Weiterleitung klappt trotzdem.
|
||||
*/
|
||||
|
||||
const KEY_PREFIX = "appredirect:";
|
||||
const RETENTION_SECONDS = 120 * 24 * 60 * 60;
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
const dayKey = (date: Date) => `${KEY_PREFIX}${date.toISOString().slice(0, 10)}`;
|
||||
|
||||
export async function countAppRedirect(source: string, platform: AppPlatform, now: Date = new Date()): Promise<void> {
|
||||
try {
|
||||
const key = dayKey(now);
|
||||
await redis.hincrby(key, `${source}|${platform}`, 1);
|
||||
await redis.expire(key, RETENTION_SECONDS);
|
||||
} catch (err) {
|
||||
console.error("[app-redirect] count failed", err);
|
||||
}
|
||||
}
|
||||
|
||||
export type AppRedirectStat = { source: string; android: number; ios: number; other: number; total: number };
|
||||
|
||||
/** Summen der letzten `days` Tage, sortiert nach Gesamtzahl. */
|
||||
export async function getAppRedirectStats(days: number, now: Date = new Date()): Promise<AppRedirectStat[]> {
|
||||
const bySource = new Map<string, AppRedirectStat>();
|
||||
try {
|
||||
const keys = Array.from({ length: days }, (_, i) => dayKey(new Date(now.getTime() - i * DAY_MS)));
|
||||
const hashes = await Promise.all(keys.map((key) => redis.hgetall(key)));
|
||||
for (const hash of hashes) {
|
||||
for (const [field, value] of Object.entries(hash ?? {})) {
|
||||
const [source, platform] = field.split("|") as [string, AppPlatform];
|
||||
const stat = bySource.get(source) ?? { source, android: 0, ios: 0, other: 0, total: 0 };
|
||||
const n = Number(value) || 0;
|
||||
if (platform === "android" || platform === "ios" || platform === "other") stat[platform] += n;
|
||||
stat.total += n;
|
||||
bySource.set(source, stat);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[app-redirect] stats failed", err);
|
||||
}
|
||||
return [...bySource.values()].sort((a, b) => b.total - a.total);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { APP_STORE_URL, PLAY_STORE_URL } from "@/lib/app-links";
|
||||
import { normalizeReferralCode } from "@/lib/referral-code";
|
||||
|
||||
/**
|
||||
* Download-Weiterleitung /app — Ziel für Flyer, Sticker und QR-Codes.
|
||||
* Pure Logik (kein Request-Objekt), damit sie ohne Server testbar ist.
|
||||
*
|
||||
* Android → Google Play, UTM-Angaben als Play-"referrer" (Play Console → Akquisition)
|
||||
* iOS → App Store, sobald APP_STORE_URL gesetzt ist; bis dahin die Web-Startseite
|
||||
* sonst → Web-Startseite
|
||||
*
|
||||
* Mit ?ref=<Empfehlungscode> landen Web/iOS-ohne-App auf /r/<code>; Android
|
||||
* bekommt den Code im referrer mit (die App liest ihn noch nicht aus — dafür
|
||||
* bräuchte es die Play Install Referrer API, also einen nativen Build).
|
||||
*/
|
||||
|
||||
export type AppPlatform = "android" | "ios" | "other";
|
||||
|
||||
export const UTM_KEYS = ["utm_source", "utm_medium", "utm_campaign", "utm_content"] as const;
|
||||
type UtmKey = (typeof UTM_KEYS)[number];
|
||||
|
||||
// Nur harmlose Zeichen, damit nichts Fremdes in Weiterleitungs-URLs oder Zähler-Schlüssel gelangt.
|
||||
const UTM_VALUE_PATTERN = /^[a-z0-9_-]{1,50}$/;
|
||||
|
||||
export function detectPlatform(userAgent: string | null | undefined): AppPlatform {
|
||||
const ua = (userAgent ?? "").toLowerCase();
|
||||
if (ua.includes("android")) return "android";
|
||||
// iPadOS meldet sich als "Macintosh" — mit Touch ist das nicht sicher erkennbar; dann landet es im Web.
|
||||
if (/iphone|ipad|ipod/.test(ua)) return "ios";
|
||||
return "other";
|
||||
}
|
||||
|
||||
export function sanitizeUtm(params: URLSearchParams): Partial<Record<UtmKey, string>> {
|
||||
const result: Partial<Record<UtmKey, string>> = {};
|
||||
for (const key of UTM_KEYS) {
|
||||
const value = params.get(key)?.trim().toLowerCase();
|
||||
if (value && UTM_VALUE_PATTERN.test(value)) result[key] = value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export type AppRedirect = {
|
||||
location: string;
|
||||
platform: AppPlatform;
|
||||
/** Für die Zählung: utm_source oder "direct". */
|
||||
source: string;
|
||||
};
|
||||
|
||||
export function resolveAppRedirect(
|
||||
userAgent: string | null | undefined,
|
||||
params: URLSearchParams,
|
||||
origin: string,
|
||||
appStoreUrl: string | null = APP_STORE_URL
|
||||
): AppRedirect {
|
||||
const platform = detectPlatform(userAgent);
|
||||
const utm = sanitizeUtm(params);
|
||||
const referralCode = normalizeReferralCode(params.get("ref"));
|
||||
const source = utm.utm_source ?? "direct";
|
||||
const utmQuery = new URLSearchParams(utm).toString();
|
||||
|
||||
if (platform === "android") {
|
||||
const referrer = new URLSearchParams(utm);
|
||||
if (referralCode) referrer.set("ref", referralCode);
|
||||
const location = referrer.size > 0 ? `${PLAY_STORE_URL}&referrer=${encodeURIComponent(referrer.toString())}` : PLAY_STORE_URL;
|
||||
return { location, platform, source };
|
||||
}
|
||||
|
||||
if (platform === "ios" && appStoreUrl) {
|
||||
return { location: appStoreUrl, platform, source };
|
||||
}
|
||||
|
||||
const path = referralCode ? `/r/${referralCode}` : "/";
|
||||
return { location: `${origin}${path}${utmQuery ? `?${utmQuery}` : ""}`, platform, source };
|
||||
}
|
||||
@@ -29,6 +29,7 @@ const isPublicRoute = createRouteMatcher([
|
||||
"/kinderschutz",
|
||||
"/join(.*)",
|
||||
"/r/(.*)", // öffentliche Einladungsseite des Empfehlungsprogramms
|
||||
"/app", // Download-Weiterleitung für Flyer/QR-Codes (src/app/app/route.ts)
|
||||
"/api/webhooks/(.*)",
|
||||
"/api/auth/(.*)",
|
||||
"/api/cron/(.*)",
|
||||
|
||||
@@ -6,6 +6,9 @@ import { router, protectedProcedure } from "@/trpc/init";
|
||||
import { assertAdmin } from "@/trpc/routers/admin";
|
||||
import { creditInviter, rebuildOwnerRankCache, recomputeReferralRanks } from "@/lib/referrals";
|
||||
import { MAX_REFERRAL_RANKS, REFERRAL_COLOR_PATTERN, REFERRAL_ICON_KEYS, REFERRAL_PERKS } from "@/lib/referral-ranks";
|
||||
import { getAppRedirectStats } from "@/lib/app-redirect-stats";
|
||||
|
||||
const APP_REDIRECT_STATS_DAYS = 30;
|
||||
|
||||
/**
|
||||
* Admin-Seite „Empfehlungen“ (/p/[secret]/referrals). Lesen ab MODERATOR,
|
||||
@@ -158,11 +161,13 @@ export const referralAdminRouter = router({
|
||||
select: { id: true, registrationIp: true, ...firstPetSelect },
|
||||
});
|
||||
const inviterById = new Map(inviters.map((i) => [i.id, i]));
|
||||
const appRedirects = await getAppRedirectStats(APP_REDIRECT_STATS_DAYS);
|
||||
|
||||
return {
|
||||
redeemed7, redeemed30, qualified7, qualified30, ownersWithPet,
|
||||
inviteFactor30: ownersWithPet > 0 ? qualified30 / ownersWithPet : 0,
|
||||
sources: sources.map((s) => ({ source: s.acquisitionSource, count: s._count._all })),
|
||||
appRedirects,
|
||||
topInviters: topInviters.map(({ pets, ...o }) => ({ ...o, pet: pets[0] ?? null })),
|
||||
recent: recent.map(({ pets, registrationIp, invitedById, ...o }) => {
|
||||
const inviter = invitedById ? inviterById.get(invitedById) : undefined;
|
||||
|
||||
Reference in new issue
Block a user