Bundles the prior autonomous-session output that was sitting unstaged: - Em-dash sweep across src/ + tests/ (en-dash/em-dash to hyphen, ~2280 instances) - country-flag-icons rollout (CountryFlag component, replaces emoji glyphs that never rendered on Windows; lazy-loads the 3x2 SVG index as a single chunk after the per-subpath dynamic-import approach silently failed in webpack) - Admin IA Phase 1+2: 7-domain regroup, 41 to 38 pages, /admin/berths index, redirects (ocr to ai, reports to dashboard, invitations to users), docs/admin-ia-proposal.md - Per-template email tester (registry + endpoint + UI on Email admin page) - Cancel-document mode picker (delete-from-Documenso vs keep-for-audit) - Dashboard PDF report: 25 widgets, SVG charts, date-range picker, 11 resolvers - Customize-widgets per-region sortables at xl+ (charts/rails/feed); single flat sortable below xl when the layout stacks; per-viewport saved orders - Audit doc updates capturing each shipped item - Lint fixes: react-compiler immutability in DonutChart (reduce instead of let-reassign), set-state-in-effect disables in CountryFlag and UploadForSigning preview-bytes effect, unused 'confirm' destructures in interest contract + reservation tabs, unescaped apostrophe in test-template card copy
71 lines
2.5 KiB
TypeScript
71 lines
2.5 KiB
TypeScript
import { eq } from 'drizzle-orm';
|
|
|
|
import { db } from '@/lib/db';
|
|
import { env } from '@/lib/env';
|
|
import { trackedLinks, type NewTrackedLink } from '@/lib/db/schema/tracked-links';
|
|
|
|
/**
|
|
* Phase 4c - service-layer helpers for tracked redirect links. Use
|
|
* `createTrackedLink` from any email-composer flow to wrap an outbound
|
|
* URL in a `/q/<slug>` short-link that records click-throughs.
|
|
*
|
|
* Slug format: random URL-safe ID. Short enough not to overwhelm an
|
|
* inbox preview pane but long enough that collision probability is
|
|
* negligible across the lifetime of the system.
|
|
*/
|
|
|
|
function generateSlug(): string {
|
|
// 8 random bytes → 11-char base64url string. Collision probability
|
|
// across 1M links: ~1e-7. The DB unique index is the backstop.
|
|
const bytes = crypto.getRandomValues(new Uint8Array(8));
|
|
return btoa(String.fromCharCode(...bytes))
|
|
.replace(/\+/g, '-')
|
|
.replace(/\//g, '_')
|
|
.replace(/=+$/, '');
|
|
}
|
|
|
|
export interface CreateTrackedLinkInput {
|
|
portId: string;
|
|
targetUrl: string;
|
|
/** Optional FK to `document_sends.id` so per-email click-throughs are
|
|
* attributable. Leave null for one-off short links. */
|
|
sendId?: string;
|
|
createdByUserId?: string;
|
|
}
|
|
|
|
export async function createTrackedLink(input: CreateTrackedLinkInput) {
|
|
// Retry on slug collision (extremely rare). Three attempts is more
|
|
// than enough - at our slug entropy a single collision in 1M links
|
|
// would be a once-per-century event.
|
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
const slug = generateSlug();
|
|
try {
|
|
const values: NewTrackedLink = {
|
|
portId: input.portId,
|
|
slug,
|
|
targetUrl: input.targetUrl,
|
|
...(input.sendId ? { sendId: input.sendId } : {}),
|
|
...(input.createdByUserId ? { createdByUserId: input.createdByUserId } : {}),
|
|
};
|
|
const [row] = await db.insert(trackedLinks).values(values).returning();
|
|
return row!;
|
|
} catch (err) {
|
|
const msg = err instanceof Error ? err.message : String(err);
|
|
if (msg.includes('uniq_tracked_links_slug') && attempt < 2) continue;
|
|
throw err;
|
|
}
|
|
}
|
|
throw new Error('Failed to mint a unique tracked-link slug after 3 attempts');
|
|
}
|
|
|
|
/** Build the public-facing tracked URL for an existing record. */
|
|
export function buildTrackedUrl(slug: string): string {
|
|
const base = env.NEXT_PUBLIC_APP_URL.replace(/\/$/, '');
|
|
return `${base}/q/${slug}`;
|
|
}
|
|
|
|
/** Look up click stats for a single tracked link. */
|
|
export async function getTrackedLink(id: string) {
|
|
return db.query.trackedLinks.findFirst({ where: eq(trackedLinks.id, id) });
|
|
}
|