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 (
+
+
+ Public page
+ onChange({ ...value, visibility: e.target.value })}
+ >
+ All visibility
+ Public page enabled
+ Public page disabled
+
+
+
+ Routing
+ onChange({ ...value, routing: e.target.value })}
+ >
+ All routing
+ Single destination
+ Weighted destinations
+
+
+
+ Scan activity
+ onChange({ ...value, activity: e.target.value })}
+ >
+ All scan activity
+ Never scanned
+ Has scans
+
+
+
+ );
+}
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 (
+
+
+ {error ? (
+
+ {error}
+
+ ) : null}
+
+ void download("png")}
+ >
+ Download PNG
+
+ void download("svg")}
+ >
+ Download SVG
+
+ window.print()}
+ >
+ Print QR card
+
+
+ void copyText(data)
+ .then(() => toast.success("QR content copied"))
+ .catch(() => toast.error("Unable to copy content."))
+ }
+ >
+ Copy content
+
+
+
+
+ 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"
>
All statuses
@@ -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"
>
All tags
@@ -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([]);
+ }}
+ />
+
+
+
+
+ 0 &&
+ pageCodes.every((code) => selectedIds.includes(code.id))
+ }
+ onChange={(event) =>
+ setSelectedIds(
+ event.target.checked
+ ? [
+ ...new Set([
+ ...selectedIds,
+ ...pageCodes.map((code) => code.id),
+ ]),
+ ].slice(0, 100)
+ : selectedIds.filter(
+ (id) => !pageCodes.some((code) => code.id === id),
+ ),
+ )
+ }
+ />
+ Select page
+
+
+ {selectedCodes.length} selected (max 100)
+
+ setSelectedIds([])}
+ >
+ Clear selection
+
+ void copySelectedLinks()}
+ >
+ Copy selected links
+
+
+ setBulkAction(event.target.value as typeof bulkAction)
+ }
+ >
+ Pause selected
+ Resume selected
+ Enable public pages
+ Disable public pages
+ Add tag
+ Remove tag
+
+ {["add-tag", "remove-tag"].includes(bulkAction) ? (
+ setBulkTag(event.target.value)}
+ />
+ ) : null}
+ setConfirmBulk(true)}
+ >
+ Apply to selected
+
+
+
@@ -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}
+
+ = 100 &&
+ !selectedIds.includes(code.id))
+ }
+ onChange={(event) =>
+ setSelectedIds((ids) =>
+ event.target.checked
+ ? [...ids, code.id]
+ : ids.filter((id) => id !== code.id),
+ )
+ }
+ />
+ {code.name}
+
Short link: {" "}
@@ -637,6 +829,106 @@ function QrCodesPage() {
)}
+
+
+ Codes per page
+ {
+ setPageSize(Number(event.target.value));
+ setPageIndex(0);
+ }}
+ >
+ 10
+ 25
+ 50
+
+
+
+ setPageIndex(currentPage - 1)}
+ >
+ Previous page
+
+
+ Page {currentPage + 1} of {pageCount}
+
+ = pageCount}
+ onClick={() => setPageIndex(currentPage + 1)}
+ >
+ Next page
+
+
+
+
{
+ 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}
+ ))}
+
+
+ setConfirmBulk(false)}
+ >
+ Cancel
+
+
+ bulkUpdate.mutate({
+ ids: selectedCodes.map((code) => code.id),
+ action: bulkAction,
+ ...(["add-tag", "remove-tag"].includes(bulkAction)
+ ? { tag: bulkTag.trim() }
+ : {}),
+ })
+ }
+ >
+ {bulkUpdate.isPending ? "Updating…" : "Confirm update"}
+
+
+
+
+
{
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.
+
+
+
+
+
+ QR type
+ {
+ setType(event.target.value as ToolkitType);
+ setFields({ security: "WPA", medium: "qr" });
+ }}
+ >
+ {toolkitTypes.map(([value, label]) => (
+
+ {label}
+
+ ))}
+
+
+ {type === "wifi" ? (
+ <>
+
+ Security
+ update("security", event.target.value)}
+ >
+ WPA / WPA2 / WPA3 personal
+ WEP
+ Open network
+
+
+
+
+ update("hidden", String(event.target.checked))
+ }
+ />
+ Hidden network
+
+ >
+ ) : null}
+ {fieldDefinitions[type]
+ .filter(
+ ([key]) =>
+ !(
+ type === "wifi" &&
+ key === "password" &&
+ fields.security === "nopass"
+ ),
+ )
+ .map(([key, label, inputType]) => (
+
+ {label}
+ {inputType === "textarea" ? (
+
+ ))}
+ {["phone", "sms", "whatsapp", "contact"].includes(type) ? (
+
+ Include the country code, for example +1 212 555 0123.
+
+ ) : null}
+ {type === "wifi" ? (
+
+ The QR contains the network password. Share it only with people
+ who should have access.
+
+ ) : null}
+ {type === "campaign" ? (
+ <>
+ {
+ try {
+ update("url", cleanTrackingUrl(fields.url || ""));
+ toast.success(
+ "Tracking parameters removed from destination",
+ );
+ } catch (cause) {
+ toast.error((cause as Error).message);
+ }
+ }}
+ >
+ Clean tracking parameters
+
+
+ Keeps other query parameters and anchors. Copy the completed URL
+ into a managed QR destination to track scans and update the
+ target later.
+
+ >
+ ) : null}
+ {error ? (
+
+ {error}
+
+ ) : null}
+
+
Print card
+
+ Card heading
+ setTitle(event.target.value)}
+ />
+
+
+ Card caption
+
+
+
+
+
+
+ );
+}
diff --git a/src/styles.css b/src/styles.css
index 792cf62..229aedc 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -249,3 +249,19 @@ code {
background-color: var(--ds-surface2) !important;
}
}
+
+.toolkit-label { display: grid; gap: .5rem; font-size: .875rem; font-weight: 600; }
+.toolkit-input { width: 100%; min-width: 0; padding: .65rem .8rem; border: 1px solid var(--ds-border); border-radius: .75rem; background: var(--ds-input-bg); color: var(--ds-fg); font-weight: 400; }
+.toolkit-input:focus-visible, .toolkit-button:focus-visible { outline: 2px solid var(--ds-accent); outline-offset: 2px; }
+.toolkit-button { padding: .6rem .85rem; border: 1px solid var(--ds-border); border-radius: .75rem; font-size: .875rem; font-weight: 600; cursor: pointer; }
+.toolkit-button:hover { background: var(--ds-surface2); }
+.toolkit-button:disabled { opacity: .45; cursor: not-allowed; }
+@media print {
+ body:has(#toolkit-print-card) * { visibility: hidden; }
+ body:has(#toolkit-print-card) *:not(:has(#toolkit-print-card)):not(#toolkit-print-card):not(#toolkit-print-card *) { display: none !important; }
+ body:has(#toolkit-print-card), body:has(#toolkit-print-card) *:has(#toolkit-print-card) { height: auto !important; min-height: 0 !important; overflow: visible !important; position: static !important; display: block !important; margin: 0 !important; padding: 0 !important; border: 0 !important; }
+ body:has(#toolkit-print-card) #toolkit-print-card,
+ body:has(#toolkit-print-card) #toolkit-print-card * { visibility: visible; }
+ #toolkit-print-card { position: absolute; inset: 0 auto auto 0; width: 100%; max-width: 160mm; padding: 15mm; break-inside: avoid; }
+ #toolkit-print-card svg { width: 80mm; height: 80mm; }
+}
diff --git a/tests/e2e/library.spec.ts b/tests/e2e/library.spec.ts
new file mode 100644
index 0000000..f2e6397
--- /dev/null
+++ b/tests/e2e/library.spec.ts
@@ -0,0 +1,181 @@
+import { expect, type Page, test } from "@playwright/test";
+
+async function mutate(page: Page, procedure: string, input: unknown) {
+ return page.request.post(`/api/trpc/qrCodes.${procedure}`, {
+ data: { json: input },
+ });
+}
+async function codes(page: Page) {
+ const response = await page.request.get("/api/trpc/qrCodes.list", {
+ params: { input: JSON.stringify({ json: { includeInactive: true } }) },
+ });
+ expect(response.ok()).toBe(true);
+ const body = await response.json();
+ return body.result.data.json as Array<{
+ id: number;
+ name: string;
+ isActive: boolean;
+ isPublic: boolean;
+ tags: string[];
+ }>;
+}
+test("manages selected codes, protects organization boundaries, and paginates", async ({
+ page,
+ browserName,
+}, testInfo) => {
+ test.setTimeout(90_000);
+ const suffix = `${testInfo.project.name}-${Date.now()}-${testInfo.retry}`;
+ await page.goto("/auth/sign-up");
+ await page.getByLabel("Name", { exact: true }).fill("Library QA");
+ await page.getByLabel("Email").fill(`library-${suffix}@easyaccessqr.test`);
+ await page.getByLabel("Password").fill("LibraryTest!123");
+ await page.getByRole("button", { name: "Create Account" }).click();
+ await page.waitForURL("**/app**");
+ await page.getByLabel("Organization name").fill(`Library ${browserName}`);
+ await page.getByLabel("Organization slug").fill(`library-${suffix}`);
+ await page
+ .getByRole("button", { name: "Create organization", exact: true })
+ .click();
+ await expect(
+ page.getByRole("heading", { name: "Welcome to Easy Access QR" }),
+ ).toBeVisible();
+ // Concurrent creation also exercises organization write locking and unique slugs.
+ const created = await Promise.all(
+ Array.from({ length: 12 }, (_, index) =>
+ mutate(page, "create", {
+ name: `Library ${String(index + 1).padStart(2, "0")}`,
+ destinationUrl: "https://example.com",
+ isActive: false,
+ isPublic: false,
+ }),
+ ),
+ );
+ for (const response of created)
+ expect(response.ok(), await response.text()).toBe(true);
+ const initial = await codes(page);
+ expect(initial).toHaveLength(12);
+ await page.goto("/app/qr-codes");
+ await page.getByLabel("Codes per page").selectOption("10");
+ await expect(page.getByTestId("qr-code-row")).toHaveCount(10);
+ await page.getByRole("button", { name: "Next page" }).click();
+ await expect(page.getByTestId("qr-code-row")).toHaveCount(2);
+ await page.getByRole("button", { name: "Previous page" }).click();
+ await page.getByLabel("Select this page").check();
+ await expect(
+ page.getByText("10 selected (max 100)", { exact: true }),
+ ).toBeVisible();
+ await page.getByRole("button", { name: "Clear selection" }).click();
+ await page.getByLabel("Search QR codes").fill("Library 01");
+ await page.getByLabel("Select Library 01", { exact: true }).check();
+ for (const action of [
+ "resume",
+ "pause",
+ "public",
+ "private",
+ "add-tag",
+ "remove-tag",
+ ]) {
+ await page.getByLabel("Bulk action").selectOption(action);
+ if (action.endsWith("tag"))
+ await page.getByLabel("Bulk tag").fill("launch");
+ await page.getByRole("button", { name: "Apply to selected" }).click();
+ await expect(page.getByRole("dialog")).toContainText("Library 01");
+ await page.getByRole("button", { name: "Confirm update" }).click();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ const code = (await codes(page)).find((code) => code.name === "Library 01");
+ if (!code) throw new Error("Expected Library 01 to exist");
+ if (action === "resume" || action === "pause")
+ expect(code.isActive).toBe(action === "resume");
+ if (action === "public" || action === "private")
+ expect(code.isPublic).toBe(action === "public");
+ if (action.endsWith("tag"))
+ expect(code.tags.includes("launch")).toBe(action === "add-tag");
+ await page.getByLabel("Select Library 01", { exact: true }).check();
+ }
+ // Copy is one line per selected tracked short URL.
+ await page.evaluate(() => {
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: {
+ writeText: async (value: string) => {
+ document.body.dataset.copiedLinks = value;
+ },
+ },
+ });
+ });
+ await page.getByRole("button", { name: "Copy selected links" }).click();
+ await expect(page.locator("body")).toHaveAttribute(
+ "data-copied-links",
+ new RegExp(`/r/library-${suffix}/library-01$`),
+ );
+ await page.getByRole("button", { name: "Reset", exact: true }).click();
+ await page.getByText("More filters", { exact: true }).click();
+ await page
+ .getByRole("combobox", { name: "Public page", exact: true })
+ .selectOption("public");
+ await expect(
+ page.getByText("No matching QR codes", { exact: true }),
+ ).toBeVisible();
+ await page
+ .getByRole("combobox", { name: "Public page", exact: true })
+ .selectOption("private");
+ await page
+ .getByRole("combobox", { name: "Routing", exact: true })
+ .selectOption("weighted");
+ await expect(
+ page.getByText("No matching QR codes", { exact: true }),
+ ).toBeVisible();
+ await page
+ .getByRole("combobox", { name: "Routing", exact: true })
+ .selectOption("single");
+ await page
+ .getByRole("combobox", { name: "Scan activity", exact: true })
+ .selectOption("scanned");
+ await expect(
+ page.getByText("No matching QR codes", { exact: true }),
+ ).toBeVisible();
+ await page
+ .getByRole("combobox", { name: "Scan activity", exact: true })
+ .selectOption("never");
+ await expect(page.getByTestId("qr-code-row")).toHaveCount(10);
+ // Starter allows 3 active codes. A failed batch must leave every code paused.
+ const overLimit = await mutate(page, "bulkUpdate", {
+ ids: initial.slice(0, 4).map((code) => code.id),
+ action: "resume",
+ });
+ expect(overLimit.ok()).toBe(false);
+ expect((await codes(page)).every((code) => !code.isActive)).toBe(true);
+ // Two concurrent valid-looking batches cannot exceed the limit together.
+ const concurrent = await Promise.all([
+ mutate(page, "bulkUpdate", {
+ ids: initial.slice(0, 2).map((code) => code.id),
+ action: "resume",
+ }),
+ mutate(page, "bulkUpdate", {
+ ids: initial.slice(2, 4).map((code) => code.id),
+ action: "resume",
+ }),
+ ]);
+ expect(concurrent.filter((response) => response.ok())).toHaveLength(1);
+ expect((await codes(page)).filter((code) => code.isActive)).toHaveLength(2);
+ // QR id 1 belongs to the seeded organization, not this customer.
+ const crossOrg = await mutate(page, "bulkUpdate", {
+ ids: [initial[0].id, 1],
+ action: "public",
+ });
+ expect(crossOrg.ok()).toBe(false);
+ expect((await codes(page)).every((code) => !code.isPublic)).toBe(true);
+ const maxTags = Array.from({ length: 12 }, (_, index) => `tag-${index}`);
+ expect(
+ (await mutate(page, "update", { id: initial[0].id, tags: maxTags })).ok(),
+ ).toBe(true);
+ const tagOverflow = await mutate(page, "bulkUpdate", {
+ ids: [initial[0].id, initial[1].id],
+ action: "add-tag",
+ tag: "overflow",
+ });
+ expect(tagOverflow.ok()).toBe(false);
+ expect(
+ (await codes(page)).every((code) => !code.tags.includes("overflow")),
+ ).toBe(true);
+});
diff --git a/tests/e2e/toolkit.spec.ts b/tests/e2e/toolkit.spec.ts
new file mode 100644
index 0000000..6c33306
--- /dev/null
+++ b/tests/e2e/toolkit.spec.ts
@@ -0,0 +1,170 @@
+import { expect, type Page, test } from "@playwright/test";
+
+async function signIn(page: Page) {
+ await page.goto("/auth/sign-in");
+ await page.getByLabel("Email").fill("owner@easyaccessqr.com");
+ await page.getByLabel("Password").fill("EasyAccessQR!123");
+ await page.getByRole("button", { name: "Sign In", exact: true }).click();
+ await page.waitForURL("**/app**");
+ const workspace = page.getByRole("button", {
+ name: "Nearby Labs nearby-labs",
+ exact: true,
+ });
+ const dashboard = page.getByRole("heading", {
+ name: "Dashboard",
+ exact: true,
+ });
+ await expect(workspace.or(dashboard)).toBeVisible();
+ if (await workspace.isVisible()) await workspace.click();
+ await expect(dashboard).toBeVisible();
+ await page.goto("/app/toolkit");
+ await expect(
+ page.getByRole("heading", { name: "QR toolkit", exact: true }),
+ ).toBeVisible();
+}
+
+test("generates all toolkit types, downloads assets, cleans campaigns, and prints cards", async ({
+ page,
+ isMobile,
+}, testInfo) => {
+ const errors: string[] = [];
+ page.on("pageerror", (error) => errors.push(error.message));
+ await signIn(page);
+ await expect(
+ page.getByRole("button", { name: "Download PNG" }),
+ ).toBeDisabled();
+ await page.getByLabel("Network name").fill("Guest; Wi-Fi");
+ await page.getByLabel("Network password").fill(" pass:word ");
+ await page.getByText("Encoded content", { exact: true }).click();
+ await expect(page.getByTestId("toolkit-payload")).toContainText(
+ "WIFI:T:WPA;S:Guest\\; Wi-Fi;P: pass\\:word ;",
+ );
+ await expect(
+ page.getByRole("img", { name: "QR code preview" }).locator("svg"),
+ ).toBeVisible();
+ for (const extension of ["PNG", "SVG"]) {
+ const downloadPromise = page.waitForEvent("download");
+ await page.getByRole("button", { name: `Download ${extension}` }).click();
+ expect((await downloadPromise).suggestedFilename()).toBe(
+ `scan-me.${extension.toLowerCase()}`,
+ );
+ }
+ await page.getByLabel("Security").selectOption("nopass");
+ await expect(page.getByLabel("Network password")).toHaveCount(0);
+ await expect(page.getByTestId("toolkit-payload")).not.toContainText("word");
+ const cases: Array<{
+ type: string;
+ fields: Record;
+ prefix: string;
+ }> = [
+ {
+ type: "contact",
+ fields: {
+ "Full name": "Jane Doe",
+ "Email address (optional)": "jane@example.com",
+ },
+ prefix: "BEGIN:VCARD",
+ },
+ {
+ type: "email",
+ fields: {
+ "Email address": "jane@example.com",
+ Subject: "Hello & welcome",
+ Message: "From the QR",
+ },
+ prefix: "mailto:jane@example.com?subject=Hello%20%26%20welcome",
+ },
+ {
+ type: "sms",
+ fields: { "Phone number": "+12125550123", Message: "Hello" },
+ prefix: "sms:+12125550123?body=Hello",
+ },
+ {
+ type: "phone",
+ fields: { "Phone number": "+12125550123" },
+ prefix: "tel:+12125550123",
+ },
+ {
+ type: "location",
+ fields: { Latitude: "0", Longitude: "-180" },
+ prefix: "geo:0,-180",
+ },
+ {
+ type: "text",
+ fields: { Text: "Welcome to our store" },
+ prefix: "Welcome to our store",
+ },
+ {
+ type: "whatsapp",
+ fields: { "Phone number": "+12125550123", Message: "Hello" },
+ prefix: "https://wa.me/12125550123?text=Hello",
+ },
+ ];
+ for (const item of cases) {
+ await page.getByLabel("QR type").selectOption(item.type);
+ for (const [label, value] of Object.entries(item.fields))
+ await page.getByLabel(label, { exact: true }).fill(value);
+ await expect(page.getByTestId("toolkit-payload")).toContainText(
+ item.prefix,
+ );
+ await expect(
+ page.getByRole("button", { name: "Download PNG" }),
+ ).toBeEnabled();
+ }
+ await page.getByLabel("QR type").selectOption("campaign");
+ await page
+ .getByLabel("Destination URL")
+ .fill("https://example.com/shop?sku=42&utm_source=old&fbclid=abc#buy");
+ await page.getByRole("button", { name: "Clean tracking parameters" }).click();
+ await expect(page.getByLabel("Destination URL")).toHaveValue(
+ "https://example.com/shop?sku=42#buy",
+ );
+ await page.getByLabel("Campaign source").fill("poster");
+ await page.getByLabel("Campaign name").fill("Fall sale");
+ await expect(page.getByTestId("toolkit-payload")).toContainText(
+ "utm_source=poster&utm_medium=qr&utm_campaign=Fall+sale#buy",
+ );
+ await expect(page.locator("#toolkit-print-card")).toHaveCSS(
+ "background-color",
+ "rgb(255, 255, 255)",
+ );
+ await page.getByLabel("Card heading").fill("Shop the fall collection");
+ await page.getByLabel("Card caption").fill("Scan to explore");
+ await expect(page.locator("#toolkit-print-card")).toContainText(
+ "Shop the fall collection",
+ );
+ await page.evaluate(() => {
+ window.print = () => {
+ document.body.dataset.printRequested = "true";
+ };
+ });
+ await page.getByRole("button", { name: "Print QR card" }).click();
+ await expect(page.locator("body")).toHaveAttribute(
+ "data-print-requested",
+ "true",
+ );
+ await page.screenshot({
+ path: testInfo.outputPath("toolkit-screen.png"),
+ fullPage: true,
+ });
+ await page.emulateMedia({ media: "print" });
+ if (!isMobile)
+ await page.pdf({
+ path: testInfo.outputPath("qr-card.pdf"),
+ format: "A4",
+ printBackground: true,
+ });
+ await expect(page.locator("#toolkit-print-card")).toBeVisible();
+ await expect(page.locator("h1")).toHaveCSS("visibility", "hidden");
+ await page.emulateMedia({ media: "screen" });
+ await page.getByLabel("Destination URL").fill("javascript:alert(1)");
+ await expect(
+ page.getByRole("button", { name: "Download PNG" }),
+ ).toBeDisabled();
+ expect(errors).toEqual([]);
+ expect(
+ await page.evaluate(
+ () => document.documentElement.scrollWidth <= window.innerWidth,
+ ),
+ ).toBe(true);
+});