From c12c0876ac40077f2b348bb9e5a05a0d37a70da2 Mon Sep 17 00:00:00 2001 From: Josh Hamilton Date: Fri, 11 Sep 2026 22:55:31 -0500 Subject: [PATCH] Add QR campaign toolkit and batch library management --- .github/workflows/ci.yml | 2 +- README.md | 38 +++ playwright.config.ts | 2 +- src/components/app-command-menu.tsx | 10 + src/components/qr/qr-library-controls.tsx | 49 ++++ src/components/qr/qr-toolkit-preview.tsx | 143 ++++++++++ src/integrations/trpc/routers/qr-codes.ts | 134 +++++++++- src/lib/plan-limits.ts | 4 +- src/lib/qr-library.test.ts | 62 +++++ src/lib/qr-library.ts | 71 +++++ src/lib/qr-toolkit.test.ts | 140 ++++++++++ src/lib/qr-toolkit.ts | 166 ++++++++++++ src/routeTree.gen.ts | 21 ++ src/routes/app/qr-codes.tsx | 310 +++++++++++++++++++++- src/routes/app/route.tsx | 8 + src/routes/app/toolkit.tsx | 240 +++++++++++++++++ src/styles.css | 16 ++ tests/e2e/library.spec.ts | 181 +++++++++++++ tests/e2e/toolkit.spec.ts | 170 ++++++++++++ 19 files changed, 1742 insertions(+), 25 deletions(-) create mode 100644 src/components/qr/qr-library-controls.tsx create mode 100644 src/components/qr/qr-toolkit-preview.tsx create mode 100644 src/lib/qr-library.test.ts create mode 100644 src/lib/qr-library.ts create mode 100644 src/lib/qr-toolkit.test.ts create mode 100644 src/lib/qr-toolkit.ts create mode 100644 src/routes/app/toolkit.tsx create mode 100644 tests/e2e/library.spec.ts create mode 100644 tests/e2e/toolkit.spec.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2993496..b30f518 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,7 +52,7 @@ jobs: env: DATABASE_URL: postgresql://postgres:postgres@localhost:5432/easyaccessqr BETTER_AUTH_URL: http://127.0.0.1:3000 - BETTER_AUTH_SECRET: ci-super-secret-value + BETTER_AUTH_SECRET: ci-only-secret-at-least-32-characters-long BETTER_AUTH_TRUSTED_ORIGINS: http://127.0.0.1:3000,http://localhost:3000 ALLOWED_HOSTS: localhost,127.0.0.1 API_ALLOWED_ORIGINS: http://127.0.0.1:3000,http://localhost:3000 diff --git a/README.md b/README.md index 7d9cc82..66e5131 100644 --- a/README.md +++ b/README.md @@ -110,3 +110,41 @@ bun run dev - Hitting a short link (`/r/:org/:slug`) records a view and redirects to the selected destination. - If a code is paused, a styled status page is shown. - If a code is public, `?view=1` renders a public QR preview page without auth. + +## Campaign toolkit release + +The QR toolkit is available from workspace navigation at `/app/toolkit`. + +1. **Wi-Fi QR codes** — personal network credentials, hidden networks, and open networks. +2. **Contact QR codes** — vCard 4.0 with name, company, phone, email, and website. +3. **Email QR codes** — recipient, subject, and prefilled message. +4. **SMS QR codes** — international number and prefilled message. +5. **Phone QR codes** — dialer links using international numbers. +6. **Map QR codes** — validated latitude and longitude, including zero coordinates. +7. **Text QR codes** — multiline and Unicode content. +8. **WhatsApp QR codes** — click-to-chat links with prefilled messages. +9. **Campaign URL builder** — source, medium, campaign, term, and content parameters. +10. **Tracking cleanup** — remove UTM and common advertising identifiers while retaining other query parameters and anchors. +11. **Printable QR cards** — custom heading and caption, with PNG/SVG downloads and a print layout. +12. **Bulk pause** — stop redirects for selected codes in one operation. +13. **Bulk resume** — reactivate codes with atomic plan-limit checks. +14. **Bulk visibility** — enable or disable public preview pages. +15. **Bulk tagging** — add or remove a tag, respecting the 12-tag limit. +16. **Bulk link copying** — copy selected tracked URLs, one per line. +17. **Visibility filtering** — find codes with public pages enabled or disabled. +18. **Routing filtering** — distinguish single destinations from weighted routing. +19. **Scan-activity filtering** — find codes that have never been scanned or already have scans. +20. **Library pagination** — 10, 25, or 50 codes per page with selection across pages. + +Toolkit codes embed their content directly: they are not stored as managed codes, +are not editable after printing, and do not produce scan analytics. Network +passwords are included in Wi-Fi codes; share the resulting card appropriately. +Scanner support for contact and action formats depends on the scanning device. +Payload conventions follow [ZXing's barcode content documentation](https://github.com/zxing/zxing/wiki/Barcode-Contents) +and [vCard 4.0 (RFC 6350)](https://www.rfc-editor.org/rfc/rfc6350). + +Batch writes affect at most 100 selected codes in the current organization. A +missing or unauthorized code, tag overflow, or activation-limit failure rolls +back the whole batch. Changing filters clears selection. Individual and batch +activation writes share an organization lock to protect plan limits under +concurrent requests. This release requires no database schema migration. diff --git a/playwright.config.ts b/playwright.config.ts index 96f8bdd..2a9118d 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -30,7 +30,7 @@ export default defineConfig({ ...process.env, BETTER_AUTH_URL: process.env.BETTER_AUTH_URL ?? baseURL, BETTER_AUTH_SECRET: - process.env.BETTER_AUTH_SECRET ?? "playwright-local-secret", + process.env.BETTER_AUTH_SECRET ?? "playwright-local-secret-at-least-32-characters", BETTER_AUTH_TRUSTED_ORIGINS: process.env.BETTER_AUTH_TRUSTED_ORIGINS ?? "http://127.0.0.1:3000,http://localhost:3000", diff --git a/src/components/app-command-menu.tsx b/src/components/app-command-menu.tsx index 1a358ab..52d5fcc 100644 --- a/src/components/app-command-menu.tsx +++ b/src/components/app-command-menu.tsx @@ -134,6 +134,16 @@ export function AppCommandMenu({ icon: QrCode, action: () => navigate({ to: "/app/qr-codes" }), }, + { + id: "go-toolkit", + group: "Navigation", + label: "Open QR toolkit", + description: "/app/toolkit", + keywords: + "wifi contact email sms phone map text whatsapp campaign print", + icon: QrCode, + action: () => navigate({ to: "/app/toolkit" }), + }, { id: "go-analytics", group: "Navigation", diff --git a/src/components/qr/qr-library-controls.tsx b/src/components/qr/qr-library-controls.tsx new file mode 100644 index 0000000..34d41eb --- /dev/null +++ b/src/components/qr/qr-library-controls.tsx @@ -0,0 +1,49 @@ +import type { LibraryFilters } from "@/lib/qr-library"; +export function QrLibraryFilters({ + value, + onChange, +}: { + value: LibraryFilters; + onChange: (value: LibraryFilters) => void; +}) { + return ( +
+ + + +
+ ); +} diff --git a/src/components/qr/qr-toolkit-preview.tsx b/src/components/qr/qr-toolkit-preview.tsx new file mode 100644 index 0000000..208348b --- /dev/null +++ b/src/components/qr/qr-toolkit-preview.tsx @@ -0,0 +1,143 @@ +import type QRCodeStyling from "qr-code-styling"; +import { useEffect, useRef, useState } from "react"; +import { toast } from "sonner"; +import { copyText } from "@/lib/client-export"; +import { downloadQrAsset } from "@/lib/qr-export"; +import { slugifyQrName } from "@/lib/qr-links"; + +export function QrToolkitPreview({ + data, + title, + caption, +}: { + data: string; + title: string; + caption: string; +}) { + const container = useRef(null); + const instance = useRef(null); + const [readyData, setReadyData] = useState(""); + const [error, setError] = useState(""); + useEffect(() => { + let cancelled = false; + setReadyData(""); + setError(""); + instance.current = null; + container.current?.replaceChildren(); + if (!data) return; + void import("qr-code-styling") + .then(async ({ default: QR }) => { + const qr = new QR({ + width: 600, + height: 600, + type: "svg", + data, + margin: 48, + qrOptions: { errorCorrectionLevel: "Q" }, + dotsOptions: { color: "#172522" }, + backgroundOptions: { color: "#ffffff" }, + }); + await qr.getRawData("svg"); + if (cancelled || !container.current) return; + instance.current = qr; + qr.append(container.current); + setReadyData(data); + }) + .catch(() => { + if (!cancelled) + setError( + "Unable to render this QR code. Try shorter content or reload the page.", + ); + }); + return () => { + cancelled = true; + }; + }, [data]); + const ready = Boolean(data && readyData === data); + async function download(extension: "png" | "svg") { + if (!ready || !instance.current) return; + try { + await downloadQrAsset({ + instance: instance.current, + name: slugifyQrName(title) || "qr-card", + extension, + backgroundColor: "#ffffff", + }); + } catch { + toast.error("The download failed. Please try again."); + } + } + return ( +
+
+

{title || "Scan me"}

+
+

+ {caption || "Point your camera at the QR code"} +

+
+ {error ? ( +

+ {error} +

+ ) : null} +
+ + + + +
+
+ + Encoded content + +
+					{data}
+				
+
+
+ ); +} diff --git a/src/integrations/trpc/routers/qr-codes.ts b/src/integrations/trpc/routers/qr-codes.ts index f135cb8..35c7605 100644 --- a/src/integrations/trpc/routers/qr-codes.ts +++ b/src/integrations/trpc/routers/qr-codes.ts @@ -12,6 +12,11 @@ import { MAX_QR_DESTINATIONS, normalizeQrDestinations, } from "@/lib/qr-destinations"; +import { + assertActivationLimit, + bulkQrSchema, + updatedTags, +} from "@/lib/qr-library"; import { orgProcedure } from "../init"; const analyticsRangeDaysSchema = z.union([ @@ -130,8 +135,9 @@ function toDestinationUrlKey(value: string | null | undefined) { async function countActiveQrCodesByOrganization( organizationId: string, + executor: Pick = db, ): Promise { - const rows = await db + const rows = await executor .select({ count: count() }) .from(qrCode) .where( @@ -143,18 +149,24 @@ async function countActiveQrCodesByOrganization( async function assertCanUseAdditionalActiveQrCode({ organizationId, userId, + executor = db, }: { organizationId: string; userId: string; + executor?: Pick; }) { const plan = await resolveOrganizationPlanLimits({ organizationId, userId, + executor, }); const limit = plan.limits.activeQrCodes; if (limit < 0) return; - const activeCount = await countActiveQrCodesByOrganization(organizationId); + const activeCount = await countActiveQrCodesByOrganization( + organizationId, + executor, + ); if (activeCount >= limit) { throw new TRPCError({ code: "PRECONDITION_FAILED", @@ -220,6 +232,7 @@ async function resolveUniqueSlug( organizationId: string, rawSlug: string, excludeId?: number, + executor: Pick = db, ): Promise { const base = slugify(rawSlug) || `qr-${Math.random().toString(36).slice(2, 8)}`; @@ -227,7 +240,7 @@ async function resolveUniqueSlug( let suffix = 2; while (true) { - const existing = await db.query.qrCode.findFirst({ + const existing = await executor.query.qrCode.findFirst({ where: and( eq(qrCode.organizationId, organizationId), eq(qrCode.slug, candidate), @@ -282,25 +295,30 @@ export const qrCodesRouter = { }); }), - create: orgProcedure - .input(qrCreateSchema) - .mutation(async ({ ctx, input }) => { + create: orgProcedure.input(qrCreateSchema).mutation(async ({ ctx, input }) => + db.transaction(async (tx) => { + await tx.execute( + sql`SELECT pg_advisory_xact_lock(hashtext(${ctx.organizationId}))`, + ); if (input.isActive !== false) { await assertCanUseAdditionalActiveQrCode({ organizationId: ctx.organizationId, userId: ctx.session.user.id, + executor: tx, }); } const slug = await resolveUniqueSlug( ctx.organizationId, input.slug ?? input.name, + undefined, + tx, ); const destinationPayload = resolveDestinationPayload({ destinationUrl: input.destinationUrl, destinations: input.destinations, }); - const inserted = await db + const inserted = await tx .insert(qrCode) .values({ organizationId: ctx.organizationId, @@ -320,11 +338,14 @@ export const qrCodesRouter = { slug, }; }), + ), - update: orgProcedure - .input(qrUpdateSchema) - .mutation(async ({ ctx, input }) => { - const current = await db.query.qrCode.findFirst({ + update: orgProcedure.input(qrUpdateSchema).mutation(async ({ ctx, input }) => + db.transaction(async (tx) => { + await tx.execute( + sql`SELECT pg_advisory_xact_lock(hashtext(${ctx.organizationId}))`, + ); + const current = await tx.query.qrCode.findFirst({ where: and( eq(qrCode.id, input.id), eq(qrCode.organizationId, ctx.organizationId), @@ -347,7 +368,12 @@ export const qrCodesRouter = { const nextSlug = input.slug !== undefined - ? await resolveUniqueSlug(ctx.organizationId, input.slug, current.id) + ? await resolveUniqueSlug( + ctx.organizationId, + input.slug, + current.id, + tx, + ) : current.slug; const shouldUpdateDestinations = input.destinationUrl !== undefined || input.destinations !== undefined; @@ -363,10 +389,11 @@ export const qrCodesRouter = { await assertCanUseAdditionalActiveQrCode({ organizationId: ctx.organizationId, userId: ctx.session.user.id, + executor: tx, }); } - await db + await tx .update(qrCode) .set({ ...(input.name !== undefined ? { name: input.name.trim() } : {}), @@ -390,6 +417,87 @@ export const qrCodesRouter = { return { id: current.id, slug: nextSlug }; }), + ), + + bulkUpdate: orgProcedure + .input(bulkQrSchema) + .mutation(async ({ ctx, input }) => { + return db.transaction(async (tx) => { + await tx.execute( + sql`SELECT pg_advisory_xact_lock(hashtext(${ctx.organizationId}))`, + ); + const scope = and( + eq(qrCode.organizationId, ctx.organizationId), + inArray(qrCode.id, input.ids), + ); + const codes = await tx.select().from(qrCode).where(scope).for("update"); + if (codes.length !== input.ids.length) + throw new TRPCError({ + code: "NOT_FOUND", + message: + "Some selected codes are no longer available in this organization. Refresh and select again.", + }); + if (input.action === "resume") { + const plan = await resolveOrganizationPlanLimits({ + organizationId: ctx.organizationId, + userId: ctx.session.user.id, + executor: tx, + }); + const active = await countActiveQrCodesByOrganization( + ctx.organizationId, + tx, + ); + try { + assertActivationLimit( + active, + codes.filter((code) => !code.isActive).length, + plan.limits.activeQrCodes, + ); + } catch (error) { + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: (error as Error).message, + }); + } + } + if (input.action === "add-tag" || input.action === "remove-tag") { + const action = input.action; + let changes: Array<{ id: number; tags: string[] }>; + try { + changes = codes.map((code) => ({ + id: code.id, + tags: updatedTags(code.tags, action, input.tag ?? ""), + })); + } catch (error) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: (error as Error).message, + }); + } + for (const change of changes) + await tx + .update(qrCode) + .set({ tags: change.tags, updatedAt: new Date() }) + .where( + and( + eq(qrCode.id, change.id), + eq(qrCode.organizationId, ctx.organizationId), + ), + ); + } else { + await tx + .update(qrCode) + .set({ + ...(["pause", "resume"].includes(input.action) + ? { isActive: input.action === "resume" } + : { isPublic: input.action === "public" }), + updatedAt: new Date(), + }) + .where(scope); + } + return { count: codes.length }; + }); + }), delete: orgProcedure .input(z.object({ id: z.number().int().positive() })) diff --git a/src/lib/plan-limits.ts b/src/lib/plan-limits.ts index 4533eb0..e549622 100644 --- a/src/lib/plan-limits.ts +++ b/src/lib/plan-limits.ts @@ -106,17 +106,19 @@ export async function resolveOrganizationPlanLimits({ organizationId, userId, userIds, + executor = db, }: { organizationId: string; userId?: string | null; userIds?: string[]; + executor?: Pick; }) { const _unusedUserId = userId; const _unusedUserIds = userIds; void _unusedUserId; void _unusedUserIds; - const orgSubs = await db.query.subscription.findMany({ + const orgSubs = await executor.query.subscription.findMany({ where: eq(subscription.referenceId, organizationId), orderBy: [desc(subscription.periodEnd)], }); diff --git a/src/lib/qr-library.test.ts b/src/lib/qr-library.test.ts new file mode 100644 index 0000000..1d547a6 --- /dev/null +++ b/src/lib/qr-library.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; +import { + assertActivationLimit, + bulkQrSchema, + defaultLibraryFilters, + matchesLibraryFilters, + updatedTags, +} from "./qr-library"; + +describe("library controls", () => { + const code = { isPublic: true, destinations: [{}, {}], scanCount: 0 }; + it("composes all three filters", () => { + expect( + matchesLibraryFilters(code, { + visibility: "public", + routing: "weighted", + activity: "never", + }), + ).toBe(true); + for (const filter of [ + { visibility: "private" }, + { routing: "single" }, + { activity: "scanned" }, + ]) + expect( + matchesLibraryFilters(code, { ...defaultLibraryFilters, ...filter }), + ).toBe(false); + expect(matchesLibraryFilters(code, defaultLibraryFilters)).toBe(true); + }); + it("deduplicates IDs, limits batches, and requires tags", () => { + expect(bulkQrSchema.parse({ ids: [1, 1, 2], action: "pause" }).ids).toEqual( + [1, 2], + ); + for (const input of [ + { ids: [], action: "pause" }, + { ids: [1], action: "delete" }, + { ids: [1], action: "add-tag" }, + { ids: [1], action: "remove-tag", tag: " " }, + { ids: Array(101).fill(1), action: "pause" }, + ]) + expect(bulkQrSchema.safeParse(input).success).toBe(false); + }); + it("adds tags idempotently and removes exact matches", () => { + expect(updatedTags(["launch"], "add-tag", "launch")).toEqual(["launch"]); + expect(updatedTags(["launch", "event"], "remove-tag", "launch")).toEqual([ + "event", + ]); + expect(() => + updatedTags( + Array.from({ length: 12 }, (_, i) => String(i)), + "add-tag", + "extra", + ), + ).toThrow("12-tag"); + }); + it("checks only additional activations and supports unlimited plans", () => { + expect(() => assertActivationLimit(2, 1, 3)).not.toThrow(); + expect(() => assertActivationLimit(3, 1, 3)).toThrow("plan limit"); + expect(() => assertActivationLimit(3, 0, 3)).not.toThrow(); + expect(() => assertActivationLimit(100, 100, -1)).not.toThrow(); + }); +}); diff --git a/src/lib/qr-library.ts b/src/lib/qr-library.ts new file mode 100644 index 0000000..2cd11a7 --- /dev/null +++ b/src/lib/qr-library.ts @@ -0,0 +1,71 @@ +import { z } from "zod"; +export const bulkQrSchema = z + .object({ + ids: z + .array(z.number().int().positive()) + .min(1) + .max(100) + .transform((ids) => [...new Set(ids)]), + action: z.enum([ + "pause", + "resume", + "public", + "private", + "add-tag", + "remove-tag", + ]), + tag: z.string().trim().min(1).max(30).optional(), + }) + .superRefine((input, ctx) => { + if (["add-tag", "remove-tag"].includes(input.action) && !input.tag) + ctx.addIssue({ code: "custom", path: ["tag"], message: "Enter a tag." }); + }); +export type LibraryFilters = { + visibility: string; + routing: string; + activity: string; +}; +export const defaultLibraryFilters: LibraryFilters = { + visibility: "all", + routing: "all", + activity: "all", +}; +export function matchesLibraryFilters( + code: { isPublic: boolean; destinations: unknown[]; scanCount: number }, + filters: LibraryFilters, +) { + if (filters.visibility === "public" && !code.isPublic) return false; + if (filters.visibility === "private" && code.isPublic) return false; + if (filters.routing === "single" && code.destinations.length !== 1) + return false; + if (filters.routing === "weighted" && code.destinations.length < 2) + return false; + if (filters.activity === "never" && code.scanCount !== 0) return false; + if (filters.activity === "scanned" && code.scanCount === 0) return false; + return true; +} +export function updatedTags( + tags: string[], + action: "add-tag" | "remove-tag", + tag: string, +) { + const next = + action === "add-tag" + ? [...new Set([...tags, tag])] + : tags.filter((value) => value !== tag); + if (next.length > 12) + throw new Error( + "A code would exceed the 12-tag limit. Remove a tag first.", + ); + return next; +} +export function assertActivationLimit( + active: number, + additional: number, + limit: number, +) { + if (limit >= 0 && active + additional > limit) + throw new Error( + `This selection would exceed your plan limit of ${limit} active QR codes. Pause codes or select fewer to resume.`, + ); +} diff --git a/src/lib/qr-toolkit.test.ts b/src/lib/qr-toolkit.test.ts new file mode 100644 index 0000000..7d9367d --- /dev/null +++ b/src/lib/qr-toolkit.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it } from "vitest"; +import { + buildToolkitPayload, + campaignUrl, + cleanTrackingUrl, +} from "./qr-toolkit"; + +describe("QR toolkit payloads", () => { + it("escapes Wi-Fi delimiters and preserves password whitespace", () => { + expect( + buildToolkitPayload("wifi", { + ssid: "Cafe;Guest", + password: " pass:word\\ ", + hidden: "true", + }), + ).toBe("WIFI:T:WPA;S:Cafe\\;Guest;P: pass\\:word\\\\ ;H:true;;"); + }); + it("omits passwords on open networks", () => { + expect( + buildToolkitPayload("wifi", { + ssid: "Guest", + password: "secret", + security: "nopass", + }), + ).toBe("WIFI:T:nopass;S:Guest;P:;H:false;;"); + }); + it("validates network byte limits and password requirements", () => { + expect(() => + buildToolkitPayload("wifi", { ssid: "é".repeat(17), security: "nopass" }), + ).toThrow("32 UTF-8 bytes"); + expect(() => buildToolkitPayload("wifi", { ssid: "Guest" })).toThrow( + "password", + ); + }); + it("writes escaped vCards without allowing field injection", () => { + const result = buildToolkitPayload("contact", { + name: "Doe, Jane\nTEL:bad", + organization: "A;B", + phone: "+1 (212) 555-0123", + email: "jane@example.com", + }); + expect(result).toContain("FN:Doe\\, Jane\\nTEL:bad\r\n"); + expect(result).toContain("ORG:A\\;B\r\nTEL;VALUE=uri:tel:+12125550123"); + expect(result).toMatch(/^BEGIN:VCARD\r\nVERSION:4.0/); + expect(result).toMatch(/END:VCARD\r\n$/); + }); + it("folds long Unicode vCard lines at UTF-8 boundaries", () => { + const name = "花".repeat(80); + const result = buildToolkitPayload("contact", { name }); + for (const line of result.split("\r\n")) + expect(new TextEncoder().encode(line).length).toBeLessThanOrEqual(75); + expect(result.replace(/\r\n /g, "")).toContain(`FN:${name}\r\n`); + }); + it("encodes mail headers and message delimiters", () => { + const result = buildToolkitPayload("email", { + email: "hi@example.com", + subject: "A & B", + message: "hello\nworld", + }); + expect(result).toBe( + "mailto:hi@example.com?subject=A%20%26%20B&body=hello%0Aworld", + ); + }); + it.each([ + "phone", + "sms", + "whatsapp", + ] as const)("validates international %s numbers", (type) => { + expect(() => buildToolkitPayload(type, { phone: "123" })).toThrow( + "international", + ); + expect(() => + buildToolkitPayload(type, { phone: "+123456789?body=bad" }), + ).toThrow("international"); + }); + it("builds phone, SMS, and WhatsApp actions", () => { + expect(buildToolkitPayload("phone", { phone: "+1 212 555 0123" })).toBe( + "tel:+12125550123", + ); + expect( + buildToolkitPayload("sms", { + phone: "+12125550123", + message: "Hi & bye", + }), + ).toBe("sms:+12125550123?body=Hi%20%26%20bye"); + expect( + buildToolkitPayload("whatsapp", { + phone: "+12125550123", + message: "Hi!", + }), + ).toBe("https://wa.me/12125550123?text=Hi!"); + }); + it("handles zero coordinates and rejects out-of-range locations", () => { + expect( + buildToolkitPayload("location", { latitude: "0", longitude: "-180" }), + ).toBe("geo:0,-180"); + expect(() => + buildToolkitPayload("location", { latitude: "91", longitude: "0" }), + ).toThrow("Latitude"); + expect(() => + buildToolkitPayload("location", { latitude: "", longitude: "0" }), + ).toThrow("required"); + }); + it("preserves plain text and limits encoded byte size", () => { + expect(buildToolkitPayload("text", { text: " Hello\n世界 " })).toBe( + " Hello\n世界 ", + ); + expect(() => + buildToolkitPayload("text", { text: "界".repeat(600) }), + ).toThrow("too long"); + }); + it("builds UTM links preserving unrelated parameters and anchors", () => { + const result = campaignUrl({ + url: "https://example.com/Path?sku=42&utm_source=old&utm_term=old#buy", + source: "poster", + medium: "qr", + campaign: "Fall sale", + }); + expect(result).toBe( + "https://example.com/Path?sku=42&utm_source=poster&utm_medium=qr&utm_campaign=Fall+sale#buy", + ); + }); + it("removes tracking parameters without altering the destination", () => { + expect( + cleanTrackingUrl( + "https://example.com/a?sku=1&utm_source=x&UTM_TERM=y&fbclid=a&fbclid=b#g", + ), + ).toBe("https://example.com/a?sku=1#g"); + }); + it.each([ + "javascript:alert(1)", + "https://user:pass@example.com", + "not a URL", + ])("rejects unsafe URLs: %s", (url) => { + expect(() => cleanTrackingUrl(url)).toThrow(); + expect(() => + campaignUrl({ url, source: "a", medium: "b", campaign: "c" }), + ).toThrow(); + }); +}); diff --git a/src/lib/qr-toolkit.ts b/src/lib/qr-toolkit.ts new file mode 100644 index 0000000..f7bfe7d --- /dev/null +++ b/src/lib/qr-toolkit.ts @@ -0,0 +1,166 @@ +export const toolkitTypes = [ + ["wifi", "Wi-Fi"], + ["contact", "Contact card"], + ["email", "Email"], + ["sms", "SMS"], + ["phone", "Phone call"], + ["location", "Map location"], + ["text", "Plain text"], + ["whatsapp", "WhatsApp"], + ["campaign", "Campaign URL"], +] as const; +export type ToolkitType = (typeof toolkitTypes)[number][0]; +export type ToolkitFields = Record; + +function required(value: string | undefined, label: string) { + if (!value?.trim()) throw new Error(`${label} is required.`); + return value; +} +function phone(value: string | undefined) { + const normalized = required(value, "Phone number").replace(/[\s().-]/g, ""); + if (!/^\+[1-9]\d{6,14}$/.test(normalized)) + throw new Error( + "Use an international phone number, such as +1 212 555 0123.", + ); + return normalized; +} +function email(value: string | undefined) { + const address = required(value, "Email address").trim(); + if (!/^[^\s@?&#]+@[^\s@?&#]+\.[^\s@?&#]+$/.test(address)) + throw new Error("Enter a valid email address."); + return address; +} +export function httpUrl(value: string) { + let url: URL; + try { + url = new URL(value.trim()); + } catch { + throw new Error("Enter a complete HTTP or HTTPS URL."); + } + if ( + !["http:", "https:"].includes(url.protocol) || + url.username || + url.password + ) + throw new Error("Use an HTTP or HTTPS URL without embedded credentials."); + return url; +} +export function cleanTrackingUrl(value: string) { + const url = httpUrl(value); + for (const key of [...url.searchParams.keys()]) { + if ( + /^utm_/i.test(key) || + ["fbclid", "gclid", "dclid", "msclkid", "mc_cid", "mc_eid"].includes( + key.toLowerCase(), + ) + ) + url.searchParams.delete(key); + } + return url.toString(); +} +export function campaignUrl(fields: ToolkitFields) { + const url = httpUrl(required(fields.url, "Destination URL")); + for (const key of ["source", "medium", "campaign", "term", "content"]) { + const value = fields[key]?.trim(); + if (["source", "medium", "campaign"].includes(key)) + required(value, `Campaign ${key}`); + if (value) url.searchParams.set(`utm_${key}`, value); + else url.searchParams.delete(`utm_${key}`); + } + return url.toString(); +} +const wifiEscape = (value: string) => value.replace(/([\\;,:"])/g, "\\$1"); +const cardEscape = (value: string) => + value + .replace(/\\/g, "\\\\") + .replace(/\r\n|\r|\n/g, "\\n") + .replace(/[,;]/g, "\\$&"); +// vCard lines are folded on UTF-8 octet boundaries, never within a code point. +function foldCardLine(line: string) { + let result = "", + length = 0; + for (const character of line) { + const size = new TextEncoder().encode(character).length; + if (length + size > 75) { + result += "\r\n "; + length = 1; + } + result += character; + length += size; + } + return result; +} +export function buildToolkitPayload( + type: ToolkitType, + fields: ToolkitFields, +): string { + let payload: string; + switch (type) { + case "wifi": { + const ssid = required(fields.ssid, "Network name"); + const security = fields.security || "WPA"; + if (!["WPA", "WEP", "nopass"].includes(security)) + throw new Error("Choose a supported Wi-Fi security type."); + if (new TextEncoder().encode(ssid).length > 32) + throw new Error("Network names must fit within 32 UTF-8 bytes."); + if (security !== "nopass") required(fields.password, "Network password"); + payload = `WIFI:T:${security};S:${wifiEscape(ssid)};P:${security === "nopass" ? "" : wifiEscape(fields.password || "")};H:${fields.hidden === "true"};;`; + break; + } + case "contact": { + const name = required(fields.name, "Full name"); + payload = `${[ + "BEGIN:VCARD", + "VERSION:4.0", + `FN:${cardEscape(name)}`, + fields.organization ? `ORG:${cardEscape(fields.organization)}` : "", + fields.phone ? `TEL;VALUE=uri:tel:${phone(fields.phone)}` : "", + fields.email ? `EMAIL:${cardEscape(email(fields.email))}` : "", + fields.url ? `URL:${httpUrl(fields.url).toString()}` : "", + "END:VCARD", + ] + .filter(Boolean) + .map(foldCardLine) + .join("\r\n")}\r\n`; + break; + } + case "email": + payload = `mailto:${encodeURIComponent(email(fields.email)).replace("%40", "@")}?subject=${encodeURIComponent(fields.subject || "")}&body=${encodeURIComponent(fields.message || "")}`; + break; + case "sms": + payload = `sms:${phone(fields.phone)}?body=${encodeURIComponent(fields.message || "")}`; + break; + case "phone": + payload = `tel:${phone(fields.phone)}`; + break; + case "whatsapp": + payload = `https://wa.me/${phone(fields.phone).slice(1)}?text=${encodeURIComponent(fields.message || "")}`; + break; + case "location": { + const lat = Number(required(fields.latitude, "Latitude")); + const lng = Number(required(fields.longitude, "Longitude")); + if ( + !Number.isFinite(lat) || + !Number.isFinite(lng) || + Math.abs(lat) > 90 || + Math.abs(lng) > 180 + ) + throw new Error( + "Latitude must be −90 to 90 and longitude −180 to 180.", + ); + payload = `geo:${lat},${lng}`; + break; + } + case "text": + payload = required(fields.text, "Text"); + break; + case "campaign": + payload = campaignUrl(fields); + break; + } + if (new TextEncoder().encode(payload).length > 1600) + throw new Error( + "This content is too long for a reliable QR code. Shorten it to 1,600 UTF-8 bytes or fewer.", + ); + return payload; +} diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.ts index 0c52d4b..08c3703 100644 --- a/src/routeTree.gen.ts +++ b/src/routeTree.gen.ts @@ -18,6 +18,7 @@ import { Route as AuthSignUpRouteImport } from './routes/auth/sign-up' import { Route as AuthSignInRouteImport } from './routes/auth/sign-in' import { Route as AuthResetPasswordRouteImport } from './routes/auth/reset-password' import { Route as AuthForgotPasswordRouteImport } from './routes/auth/forgot-password' +import { Route as AppToolkitRouteImport } from './routes/app/toolkit' import { Route as AppQrCodesRouteImport } from './routes/app/qr-codes' import { Route as AppAnalyticsRouteImport } from './routes/app/analytics' import { Route as ApiOgRouteImport } from './routes/api/og' @@ -82,6 +83,11 @@ const AuthForgotPasswordRoute = AuthForgotPasswordRouteImport.update({ path: '/auth/forgot-password', getParentRoute: () => rootRouteImport, } as any) +const AppToolkitRoute = AppToolkitRouteImport.update({ + id: '/toolkit', + path: '/toolkit', + getParentRoute: () => AppRouteRoute, +} as any) const AppQrCodesRoute = AppQrCodesRouteImport.update({ id: '/qr-codes', path: '/qr-codes', @@ -181,6 +187,7 @@ export interface FileRoutesByFullPath { '/api/og': typeof ApiOgRoute '/app/analytics': typeof AppAnalyticsRoute '/app/qr-codes': typeof AppQrCodesRouteWithChildren + '/app/toolkit': typeof AppToolkitRoute '/auth/forgot-password': typeof AuthForgotPasswordRoute '/auth/reset-password': typeof AuthResetPasswordRoute '/auth/sign-in': typeof AuthSignInRoute @@ -209,6 +216,7 @@ export interface FileRoutesByTo { '/api/og': typeof ApiOgRoute '/app/analytics': typeof AppAnalyticsRoute '/app/qr-codes': typeof AppQrCodesRouteWithChildren + '/app/toolkit': typeof AppToolkitRoute '/auth/forgot-password': typeof AuthForgotPasswordRoute '/auth/reset-password': typeof AuthResetPasswordRoute '/auth/sign-in': typeof AuthSignInRoute @@ -239,6 +247,7 @@ export interface FileRoutesById { '/api/og': typeof ApiOgRoute '/app/analytics': typeof AppAnalyticsRoute '/app/qr-codes': typeof AppQrCodesRouteWithChildren + '/app/toolkit': typeof AppToolkitRoute '/auth/forgot-password': typeof AuthForgotPasswordRoute '/auth/reset-password': typeof AuthResetPasswordRoute '/auth/sign-in': typeof AuthSignInRoute @@ -270,6 +279,7 @@ export interface FileRouteTypes { | '/api/og' | '/app/analytics' | '/app/qr-codes' + | '/app/toolkit' | '/auth/forgot-password' | '/auth/reset-password' | '/auth/sign-in' @@ -298,6 +308,7 @@ export interface FileRouteTypes { | '/api/og' | '/app/analytics' | '/app/qr-codes' + | '/app/toolkit' | '/auth/forgot-password' | '/auth/reset-password' | '/auth/sign-in' @@ -327,6 +338,7 @@ export interface FileRouteTypes { | '/api/og' | '/app/analytics' | '/app/qr-codes' + | '/app/toolkit' | '/auth/forgot-password' | '/auth/reset-password' | '/auth/sign-in' @@ -430,6 +442,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthForgotPasswordRouteImport parentRoute: typeof rootRouteImport } + '/app/toolkit': { + id: '/app/toolkit' + path: '/toolkit' + fullPath: '/app/toolkit' + preLoaderRoute: typeof AppToolkitRouteImport + parentRoute: typeof AppRouteRoute + } '/app/qr-codes': { id: '/app/qr-codes' path: '/qr-codes' @@ -576,6 +595,7 @@ const AppQrCodesRouteWithChildren = AppQrCodesRoute._addFileChildren( interface AppRouteRouteChildren { AppAnalyticsRoute: typeof AppAnalyticsRoute AppQrCodesRoute: typeof AppQrCodesRouteWithChildren + AppToolkitRoute: typeof AppToolkitRoute AppIndexRoute: typeof AppIndexRoute AppSettingsApiKeysRoute: typeof AppSettingsApiKeysRoute AppSettingsBillingRoute: typeof AppSettingsBillingRoute @@ -591,6 +611,7 @@ interface AppRouteRouteChildren { const AppRouteRouteChildren: AppRouteRouteChildren = { AppAnalyticsRoute: AppAnalyticsRoute, AppQrCodesRoute: AppQrCodesRouteWithChildren, + AppToolkitRoute: AppToolkitRoute, AppIndexRoute: AppIndexRoute, AppSettingsApiKeysRoute: AppSettingsApiKeysRoute, AppSettingsBillingRoute: AppSettingsBillingRoute, diff --git a/src/routes/app/qr-codes.tsx b/src/routes/app/qr-codes.tsx index 1ffcb97..0a2cccc 100644 --- a/src/routes/app/qr-codes.tsx +++ b/src/routes/app/qr-codes.tsx @@ -26,6 +26,7 @@ import { } from "lucide-react"; import { useMemo, useState } from "react"; import { toast } from "sonner"; +import { QrLibraryFilters } from "@/components/qr/qr-library-controls"; import { QrPreviewModal } from "@/components/qr/qr-preview-modal"; import { Dialog, @@ -47,6 +48,7 @@ import { NativeSelect } from "@/components/ui/native-select"; import { useTRPC } from "@/integrations/trpc/react"; import { authClient } from "@/lib/auth-client"; import { copyText, downloadCsv } from "@/lib/client-export"; +import { defaultLibraryFilters, matchesLibraryFilters } from "@/lib/qr-library"; import { buildQrPublicPreviewPath, buildQrShortPath, @@ -70,6 +72,15 @@ function QrCodesPage() { const queryClient = useQueryClient(); const [previewCodeId, setPreviewCodeId] = useState(null); const [deleteCodeId, setDeleteCodeId] = useState(null); + const [libraryFilters, setLibraryFilters] = useState(defaultLibraryFilters); + const [selectedIds, setSelectedIds] = useState([]); + const [pageIndex, setPageIndex] = useState(0); + const [pageSize, setPageSize] = useState(25); + const [bulkAction, setBulkAction] = useState< + "pause" | "resume" | "public" | "private" | "add-tag" | "remove-tag" + >("pause"); + const [bulkTag, setBulkTag] = useState(""); + const [confirmBulk, setConfirmBulk] = useState(false); const [searchValue, setSearchValue] = useState(""); const [statusFilter, setStatusFilter] = useState("all"); const [tagFilter, setTagFilter] = useState("all"); @@ -128,6 +139,17 @@ function QrCodesPage() { }), ); + const bulkUpdate = useMutation( + trpc.qrCodes.bulkUpdate.mutationOptions({ + onSuccess: async (result) => { + setConfirmBulk(false); + setSelectedIds([]); + await queryClient.invalidateQueries(); + toast.success(`Updated ${result.count} QR codes`); + }, + onError: (error) => toast.error(error.message), + }), + ); const allCodes = useMemo(() => qrCodes ?? [], [qrCodes]); const allTags = useMemo( () => @@ -140,6 +162,7 @@ function QrCodesPage() { const normalizedQuery = searchValue.trim().toLowerCase(); return allCodes .filter((code) => { + if (!matchesLibraryFilters(code, libraryFilters)) return false; if (statusFilter === "active" && !code.isActive) return false; if (statusFilter === "paused" && code.isActive) return false; if (tagFilter !== "all" && !code.tags.includes(tagFilter)) return false; @@ -153,7 +176,43 @@ function QrCodesPage() { if (sortOption === "views") return right.scanCount - left.scanCount; return right.createdAt.getTime() - left.createdAt.getTime(); }); - }, [allCodes, searchValue, sortOption, statusFilter, tagFilter]); + }, [ + allCodes, + searchValue, + sortOption, + statusFilter, + tagFilter, + libraryFilters, + ]); + const pageCount = Math.max(1, Math.ceil(visibleCodes.length / pageSize)); + const currentPage = Math.min(pageIndex, pageCount - 1); + const pageCodes = visibleCodes.slice( + currentPage * pageSize, + (currentPage + 1) * pageSize, + ); + // Hidden selections never participate in a batch operation. + const selectedCodes = visibleCodes.filter((code) => + selectedIds.includes(code.id), + ); + const resetLibrary = () => { + setLibraryFilters(defaultLibraryFilters); + setSelectedIds([]); + setPageIndex(0); + }; + const copySelectedLinks = async () => { + try { + await copyText( + selectedCodes + .map((code) => + toAbsoluteUrl(buildQrShortPath(activeOrganizationSlug, code.slug)), + ) + .join("\n"), + ); + toast.success(`Copied ${selectedCodes.length} short links`); + } catch { + toast.error("Unable to copy links."); + } + }; const previewCode = useMemo( () => allCodes.find((code) => code.id === previewCodeId) ?? null, [allCodes, previewCodeId], @@ -176,7 +235,8 @@ function QrCodesPage() { const hasActiveFilters = Boolean(searchValue.trim()) || statusFilter !== "all" || - tagFilter !== "all"; + tagFilter !== "all" || + Object.values(libraryFilters).some((value) => value !== "all"); const copyShortLink = async (slug: string) => { const path = buildQrShortPath(activeOrganizationSlug, slug); @@ -275,7 +335,11 @@ function QrCodesPage() { setSearchValue(event.target.value)} + onChange={(event) => { + setSearchValue(event.target.value); + setPageIndex(0); + setSelectedIds([]); + }} placeholder="Search name, link, destination, or tag" className="h-10 w-full rounded-xl border border-ds-border bg-ds-input-bg py-2 pl-9 pr-3 text-sm text-ds-fg outline-none transition-colors placeholder:text-ds-text-tertiary focus:border-ds-accent" /> @@ -288,9 +352,11 @@ function QrCodesPage() { - setStatusFilter(event.target.value as StatusFilter) - } + onChange={(event) => { + setPageIndex(0); + setSelectedIds([]); + setStatusFilter(event.target.value as StatusFilter); + }} className="h-10 border border-ds-border bg-ds-input-bg pl-9 text-sm text-ds-fg" > @@ -306,7 +372,11 @@ function QrCodesPage() { setTagFilter(event.target.value)} + onChange={(event) => { + setTagFilter(event.target.value); + setPageIndex(0); + setSelectedIds([]); + }} className="h-10 border border-ds-border bg-ds-input-bg pl-9 text-sm text-ds-fg" > @@ -339,6 +409,7 @@ function QrCodesPage() { type="button" onClick={() => { setSearchValue(""); + resetLibrary(); setStatusFilter("all"); setTagFilter("all"); }} @@ -351,6 +422,107 @@ function QrCodesPage() { +
+
+ + More filters + + { + setLibraryFilters(value); + setPageIndex(0); + setSelectedIds([]); + }} + /> +
+
+
+ + + {selectedCodes.length} selected (max 100) + + + + + {["add-tag", "remove-tag"].includes(bulkAction) ? ( + setBulkTag(event.target.value)} + /> + ) : null} + +
+
@@ -417,6 +589,7 @@ function QrCodesPage() { type="button" onClick={() => { setSearchValue(""); + resetLibrary(); setStatusFilter("all"); setTagFilter("all"); }} @@ -428,7 +601,7 @@ function QrCodesPage() {
) : (
- {visibleCodes.map((code) => ( + {pageCodes.map((code) => (
- {code.name} +
Short link:{" "} @@ -637,6 +829,106 @@ function QrCodesPage() { )}
+ + { + if (!bulkUpdate.isPending) setConfirmBulk(open); + }} + > + + + Update {selectedCodes.length} QR codes? + + This will{" "} + { + { + pause: "pause redirects for", + resume: "resume redirects for", + public: "enable public preview pages for", + private: "disable public preview pages for", + "add-tag": `add the tag “${bulkTag.trim()}” to`, + "remove-tag": `remove the tag “${bulkTag.trim()}” from`, + }[bulkAction] + }{" "} + the selected codes. + + +
    + {selectedCodes.map((code) => ( +
  • {code.name}
  • + ))} +
+ + + + +
+
+ { diff --git a/src/routes/app/route.tsx b/src/routes/app/route.tsx index 32a7c0e..224b8fa 100644 --- a/src/routes/app/route.tsx +++ b/src/routes/app/route.tsx @@ -15,6 +15,7 @@ import { QrCode, Search, Settings, + Wrench, } from "lucide-react"; import { useEffect, useMemo, useState } from "react"; import { @@ -502,6 +503,12 @@ function SidebarContent({ label="QR codes" onNavigate={onNavigate} /> + +> = { + wifi: [ + ["ssid", "Network name"], + ["password", "Network password", "password"], + ], + contact: [ + ["name", "Full name"], + ["organization", "Company (optional)"], + ["phone", "Phone number (optional)", "tel"], + ["email", "Email address (optional)", "email"], + ["url", "Website (optional)", "url"], + ], + email: [ + ["email", "Email address", "email"], + ["subject", "Subject"], + ["message", "Message", "textarea"], + ], + sms: [ + ["phone", "Phone number", "tel"], + ["message", "Message", "textarea"], + ], + phone: [["phone", "Phone number", "tel"]], + location: [ + ["latitude", "Latitude"], + ["longitude", "Longitude"], + ], + text: [["text", "Text", "textarea"]], + whatsapp: [ + ["phone", "Phone number", "tel"], + ["message", "Message", "textarea"], + ], + campaign: [ + ["url", "Destination URL", "url"], + ["source", "Campaign source"], + ["medium", "Campaign medium"], + ["campaign", "Campaign name"], + ["term", "Term (optional)"], + ["content", "Content (optional)"], + ], +}; +function ToolkitPage() { + const [type, setType] = useState("wifi"); + const [fields, setFields] = useState({ + security: "WPA", + medium: "qr", + }); + const [title, setTitle] = useState("Scan me"); + const [caption, setCaption] = useState("Point your camera at the QR code"); + let payload = "", + error = ""; + try { + payload = buildToolkitPayload(type, fields); + } catch (cause) { + error = cause instanceof Error ? cause.message : "Check the content."; + } + const update = (key: string, value: string) => + setFields((current) => ({ ...current, [key]: value })); + return ( +
+
+

+ Campaign essentials +

+

+ QR toolkit +

+

+ Create ready-to-print QR cards for everyday connections. These static + codes contain your content directly; they do not expire, track scans, + or change after printing. +

+
+
+
+ + {type === "wifi" ? ( + <> + + + + ) : null} + {fieldDefinitions[type] + .filter( + ([key]) => + !( + type === "wifi" && + key === "password" && + fields.security === "nopass" + ), + ) + .map(([key, label, inputType]) => ( +