diff --git a/backend/src/config/__tests__/env.test.ts b/backend/src/config/__tests__/env.test.ts new file mode 100644 index 00000000..44280373 --- /dev/null +++ b/backend/src/config/__tests__/env.test.ts @@ -0,0 +1,270 @@ +/** + * backend/src/config/__tests__/env.test.ts + * + * Tests for the backend environment configuration schema (issue #2211). + */ + +import { + resolveBackendAppEnvironment, + getBackendEnvironmentProfile, + loadBackendEnvConfig, + validateBackendEnv, + buildBackendRawEnv, + type BackendAppEnvironment, +} from '../env'; + +const originalWarn = console.warn; +const originalInfo = console.info; + +afterEach(() => { + console.warn = originalWarn; + console.info = originalInfo; +}); + +// ─── resolveBackendAppEnvironment ───────────────────────────────────────────── + +describe('resolveBackendAppEnvironment', () => { + it('uses APP_ENV when set', () => { + expect(resolveBackendAppEnvironment({ APP_ENV: 'staging' })).toBe('staging'); + }); + + it('falls back to NODE_ENV when APP_ENV is absent', () => { + expect(resolveBackendAppEnvironment({ NODE_ENV: 'test' })).toBe('test'); + }); + + it('defaults to development for unknown values', () => { + expect(resolveBackendAppEnvironment({ APP_ENV: 'preview' })).toBe('development'); + expect(resolveBackendAppEnvironment({})).toBe('development'); + }); + + it('APP_ENV takes priority over NODE_ENV', () => { + expect( + resolveBackendAppEnvironment({ APP_ENV: 'staging', NODE_ENV: 'production' }) + ).toBe('staging'); + }); +}); + +// ─── getBackendEnvironmentProfile ───────────────────────────────────────────── + +describe('getBackendEnvironmentProfile', () => { + const envs: BackendAppEnvironment[] = ['development', 'test', 'staging', 'production']; + + it.each(envs)('returns a profile for %s', (env) => { + const profile = getBackendEnvironmentProfile(env); + expect(profile.APP_ENV).toBe(env); + expect(typeof profile.PORT).toBe('number'); + expect(profile.DATABASE_URL).toBeTruthy(); + }); + + it('returns a copy — mutations do not affect the original', () => { + const profile = getBackendEnvironmentProfile('development'); + profile.PORT = 9999; + expect(getBackendEnvironmentProfile('development').PORT).not.toBe(9999); + }); +}); + +// ─── loadBackendEnvConfig ───────────────────────────────────────────────────── + +describe('loadBackendEnvConfig', () => { + it('loads development defaults when no env vars are set', () => { + const config = loadBackendEnvConfig({}, 'development'); + expect(config.APP_ENV).toBe('development'); + expect(config.PORT).toBe(3000); + expect(config.DATABASE_URL).toContain('localhost'); + expect(config.SECRETS_PROVIDER).toBe('local'); + expect(config.REQUIRE_MANAGED_SECRETS).toBe(false); + expect(config.ENABLE_FRAUD_DETECTION).toBe(true); + expect(config.ENABLE_SLA_MONITORING).toBe(true); + }); + + it('loads test defaults', () => { + const config = loadBackendEnvConfig({}, 'test'); + expect(config.APP_ENV).toBe('test'); + expect(config.PORT).toBe(3001); + expect(config.DATABASE_URL).toContain('subtrackr_test'); + expect(config.REDIS_URL).toContain('/1'); + }); + + it('loads staging defaults', () => { + const config = loadBackendEnvConfig({}, 'staging'); + expect(config.APP_ENV).toBe('staging'); + expect(config.SECRETS_PROVIDER).toBe('aws'); + expect(config.REQUIRE_MANAGED_SECRETS).toBe(true); + }); + + it('allows env vars to override profile defaults', () => { + const config = loadBackendEnvConfig( + { + DATABASE_URL: 'postgresql://custom-host:5432/mydb', + REDIS_URL: 'redis://custom-redis:6379', + PORT: '4000', + JWT_SECRET: 'custom-secret-at-least-12chars', + }, + 'development' + ); + expect(config.DATABASE_URL).toBe('postgresql://custom-host:5432/mydb'); + expect(config.REDIS_URL).toBe('redis://custom-redis:6379'); + expect(config.PORT).toBe(4000); + expect(config.JWT_SECRET).toBe('custom-secret-at-least-12chars'); + }); + + it('parses boolean feature flags from string env vars', () => { + const config = loadBackendEnvConfig( + { ENABLE_FRAUD_DETECTION: 'false', ENABLE_SLA_MONITORING: '0' }, + 'development' + ); + expect(config.ENABLE_FRAUD_DETECTION).toBe(false); + expect(config.ENABLE_SLA_MONITORING).toBe(false); + }); + + it('includes optional Shopify fields when set', () => { + const config = loadBackendEnvConfig( + { + SHOPIFY_SHOP_DOMAIN: 'my-shop.myshopify.com', + SHOPIFY_ADMIN_ACCESS_TOKEN: 'shpat_abc123', + }, + 'development' + ); + expect(config.SHOPIFY_SHOP_DOMAIN).toBe('my-shop.myshopify.com'); + expect(config.SHOPIFY_ADMIN_ACCESS_TOKEN).toBe('shpat_abc123'); + }); + + it('throws for invalid DATABASE_URL', () => { + expect(() => + loadBackendEnvConfig( + { DATABASE_URL: 'mysql://localhost/db' }, + 'development' + ) + ).toThrow('DATABASE_URL must be a PostgreSQL connection string'); + }); + + it('throws for invalid REDIS_URL', () => { + expect(() => + loadBackendEnvConfig( + { REDIS_URL: 'amqp://localhost' }, + 'development' + ) + ).toThrow('REDIS_URL must be a Redis connection string'); + }); + + it('throws for JWT_SECRET shorter than 12 characters', () => { + expect(() => + loadBackendEnvConfig({ JWT_SECRET: 'tooshort' }, 'development') + ).toThrow('JWT_SECRET'); + }); +}); + +// ─── validateBackendEnv ─────────────────────────────────────────────────────── + +describe('validateBackendEnv', () => { + it('returns valid config for a development environment without warnings', () => { + const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + const config = validateBackendEnv({}, 'development'); + expect(config.APP_ENV).toBe('development'); + expect(warnSpy).not.toHaveBeenCalled(); + warnSpy.mockRestore(); + }); + + it('warns and falls back to defaults in non-production when env is invalid', () => { + const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + const config = validateBackendEnv({ JWT_SECRET: 'x' }, 'development'); + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining('Environment validation failed') + ); + // Falls back to development profile + expect(config.APP_ENV).toBe('development'); + warnSpy.mockRestore(); + }); + + it('throws in production with placeholder JWT_SECRET', () => { + expect(() => + validateBackendEnv( + { + DATABASE_URL: 'postgresql://prod-db.example.com:5432/subtrackr', + REDIS_URL: 'redis://prod-redis.example.com:6379', + JWT_SECRET: 'production-jwt-secret-required', + SECRETS_PROVIDER: 'aws', + }, + 'production' + ) + ).toThrow('JWT_SECRET'); + }); + + it('throws in production when DATABASE_URL targets localhost', () => { + expect(() => + validateBackendEnv( + { + DATABASE_URL: 'postgresql://localhost:5432/subtrackr', + REDIS_URL: 'redis://prod-redis.example.com:6379', + JWT_SECRET: 'a-strong-production-secret-key!', + SECRETS_PROVIDER: 'aws', + }, + 'production' + ) + ).toThrow('localhost'); + }); + + it('throws in production when SECRETS_PROVIDER is not aws', () => { + expect(() => + validateBackendEnv( + { + DATABASE_URL: 'postgresql://prod-db.example.com:5432/subtrackr', + REDIS_URL: 'redis://prod-redis.example.com:6379', + JWT_SECRET: 'a-strong-production-secret-key!', + SECRETS_PROVIDER: 'local', + }, + 'production' + ) + ).toThrow('aws'); + }); + + it('throws in production when SHOPIFY_SHOP_DOMAIN is set without token', () => { + expect(() => + validateBackendEnv( + { + DATABASE_URL: 'postgresql://prod-db.example.com:5432/subtrackr', + REDIS_URL: 'redis://prod-redis.example.com:6379', + JWT_SECRET: 'a-strong-production-secret-key!', + SECRETS_PROVIDER: 'aws', + SHOPIFY_SHOP_DOMAIN: 'my-shop.myshopify.com', + // SHOPIFY_ADMIN_ACCESS_TOKEN deliberately omitted + }, + 'production' + ) + ).toThrow('SHOPIFY_ADMIN_ACCESS_TOKEN'); + }); + + it('succeeds in production with all required fields valid', () => { + const infoSpy = jest.spyOn(console, 'info').mockImplementation(() => undefined); + const config = validateBackendEnv( + { + DATABASE_URL: 'postgresql://prod-db.example.com:5432/subtrackr', + REDIS_URL: 'redis://prod-redis.example.com:6379', + JWT_SECRET: 'a-strong-production-secret-key!', + SECRETS_PROVIDER: 'aws', + }, + 'production' + ); + expect(config.APP_ENV).toBe('production'); + expect(config.SECRETS_PROVIDER).toBe('aws'); + infoSpy.mockRestore(); + }); +}); + +// ─── buildBackendRawEnv ─────────────────────────────────────────────────────── + +describe('buildBackendRawEnv', () => { + it('merges profile defaults with source overrides', () => { + const raw = buildBackendRawEnv( + { DATABASE_URL: 'postgresql://custom:5432/db' }, + 'development' + ); + expect(raw.DATABASE_URL).toBe('postgresql://custom:5432/db'); + expect(raw.PORT).toBe(3000); // profile default + }); + + it('strips undefined values', () => { + const raw = buildBackendRawEnv({}, 'development'); + expect(Object.values(raw).some((v) => v === undefined)).toBe(false); + }); +}); diff --git a/backend/src/config/env.ts b/backend/src/config/env.ts new file mode 100644 index 00000000..d5d2cefc --- /dev/null +++ b/backend/src/config/env.ts @@ -0,0 +1,328 @@ +/** + * backend/src/config/env.ts + * + * Issue #2211 — Refactored environment configuration schema with Zod validation. + * + * This module provides the canonical, type-safe environment configuration for + * the backend. It is the backend counterpart of `src/config/env.ts` on the + * frontend. + * + * Key features: + * - Full Zod schema for every variable the backend reads from `process.env`. + * - Per-environment profiles with sensible defaults so local development + * works out of the box without a full `.env` file. + * - Production guard: refuses to start when secrets hold placeholder values. + * - `validateBackendEnv()` mirrors `validateEnv()` from the frontend: in + * production it throws, in lower environments it warns and falls back to + * the profile defaults. + * - Re-exports the singleton `backendEnv` for use throughout the codebase. + * + * Usage: + * import { backendEnv } from '../config/env'; + * console.log(backendEnv.DATABASE_URL); + */ + +import { z } from 'zod'; + +// ─── Types ──────────────────────────────────────────────────────────────────── + +export type BackendAppEnvironment = 'development' | 'staging' | 'production' | 'test'; +export type EnvSource = Record; +export type SecretsProvider = 'local' | 'aws'; + +// ─── Per-environment defaults ───────────────────────────────────────────────── + +export interface BackendEnvironmentProfile { + APP_ENV: BackendAppEnvironment; + PORT: number; + DATABASE_URL: string; + REDIS_URL: string; + JWT_SECRET: string; + AWS_REGION: string; + SECRETS_PROVIDER: SecretsProvider; + REQUIRE_MANAGED_SECRETS: boolean; +} + +export const backendEnvironmentProfiles: Record = + { + development: { + APP_ENV: 'development', + PORT: 3000, + DATABASE_URL: 'postgresql://localhost:5432/subtrackr', + REDIS_URL: 'redis://localhost:6379', + JWT_SECRET: 'dev-jwt-secret-key-change-in-prod', + AWS_REGION: 'us-east-1', + SECRETS_PROVIDER: 'local', + REQUIRE_MANAGED_SECRETS: false, + }, + test: { + APP_ENV: 'test', + PORT: 3001, + DATABASE_URL: 'postgresql://localhost:5432/subtrackr_test', + REDIS_URL: 'redis://localhost:6379/1', + JWT_SECRET: 'test-jwt-secret-key', + AWS_REGION: 'us-east-1', + SECRETS_PROVIDER: 'local', + REQUIRE_MANAGED_SECRETS: false, + }, + staging: { + APP_ENV: 'staging', + PORT: 3000, + DATABASE_URL: 'postgresql://staging-db.subtrackr.internal:5432/subtrackr', + REDIS_URL: 'redis://staging-redis.subtrackr.internal:6379', + JWT_SECRET: 'staging-jwt-secret-key', + AWS_REGION: 'us-east-1', + SECRETS_PROVIDER: 'aws', + REQUIRE_MANAGED_SECRETS: true, + }, + production: { + APP_ENV: 'production', + PORT: 8080, + DATABASE_URL: 'postgresql://prod-db.subtrackr.internal:5432/subtrackr', + REDIS_URL: 'redis://prod-redis.subtrackr.internal:6379', + JWT_SECRET: 'production-jwt-secret-required', + AWS_REGION: 'us-east-1', + SECRETS_PROVIDER: 'aws', + REQUIRE_MANAGED_SECRETS: true, + }, + }; + +// ─── Zod schema ─────────────────────────────────────────────────────────────── + +const optionalSecret = z.string().trim().min(1).optional(); + +export const backendEnvSchema = z + .object({ + APP_ENV: z + .enum(['development', 'staging', 'production', 'test']) + .default('development'), + PORT: z.number().int().positive().default(3000), + DATABASE_URL: z + .string() + .min(1, 'DATABASE_URL must not be empty') + .refine((v) => v.startsWith('postgres'), { + message: 'DATABASE_URL must be a PostgreSQL connection string', + }), + REDIS_URL: z + .string() + .min(1, 'REDIS_URL must not be empty') + .refine((v) => v.startsWith('redis'), { + message: 'REDIS_URL must be a Redis connection string', + }), + JWT_SECRET: z + .string() + .min(12, 'JWT_SECRET must be at least 12 characters'), + AWS_REGION: z.string().min(1).default('us-east-1'), + AWS_SECRET_ID: optionalSecret, + SECRETS_PROVIDER: z.enum(['local', 'aws']).default('local'), + REQUIRE_MANAGED_SECRETS: z.boolean().default(false), + // Shopify (optional — only required when SHOPIFY_SHOP_DOMAIN is set) + SHOPIFY_SHOP_DOMAIN: optionalSecret, + SHOPIFY_ADMIN_ACCESS_TOKEN: optionalSecret, + SHOPIFY_WEBHOOK_SECRET: optionalSecret, + // Stripe + STRIPE_SECRET_KEY: optionalSecret, + STRIPE_WEBHOOK_SECRET: optionalSecret, + // Circle + CIRCLE_API_KEY: optionalSecret, + // Stellar / Soroban + STELLAR_NETWORK: z.enum(['mainnet', 'testnet']).optional(), + STELLAR_RPC_URL: optionalSecret, + SOROBAN_CONTRACT_ID: optionalSecret, + // Observability + SENTRY_DSN: optionalSecret, + LOG_LEVEL: z + .enum(['debug', 'info', 'warn', 'error', 'silent']) + .default('info'), + // Feature flags + ENABLE_FRAUD_DETECTION: z.boolean().default(true), + ENABLE_SLA_MONITORING: z.boolean().default(true), + }) + .superRefine((value, ctx) => { + if (value.APP_ENV !== 'production') return; + + // Reject placeholder secrets in production. + const placeholderPattern = + /^(dev-|test-|staging-|production-jwt-secret-required|change-in-prod)/i; + + if (placeholderPattern.test(value.JWT_SECRET)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['JWT_SECRET'], + message: 'JWT_SECRET must be set to a strong secret in production', + }); + } + + if ( + value.DATABASE_URL.includes('localhost') || + value.DATABASE_URL.includes('127.0.0.1') + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['DATABASE_URL'], + message: 'Production must not use a localhost database', + }); + } + + if (value.SECRETS_PROVIDER !== 'aws') { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['SECRETS_PROVIDER'], + message: 'Production must use AWS Secrets Manager (SECRETS_PROVIDER=aws)', + }); + } + + if (value.SHOPIFY_SHOP_DOMAIN && !value.SHOPIFY_ADMIN_ACCESS_TOKEN) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['SHOPIFY_ADMIN_ACCESS_TOKEN'], + message: + 'SHOPIFY_ADMIN_ACCESS_TOKEN is required when SHOPIFY_SHOP_DOMAIN is set', + }); + } + }); + +export type BackendEnv = z.infer; + +// ─── Resolution helpers ─────────────────────────────────────────────────────── + +export function resolveBackendAppEnvironment( + source: EnvSource = process.env +): BackendAppEnvironment { + const explicit = source.APP_ENV ?? source.NODE_ENV; + if (isBackendAppEnvironment(explicit)) return explicit; + return 'development'; +} + +export function getBackendEnvironmentProfile( + env: BackendAppEnvironment +): BackendEnvironmentProfile { + return { ...backendEnvironmentProfiles[env] }; +} + +/** Build the raw merged config object (profile defaults + env overrides). */ +export function buildBackendRawEnv( + source: EnvSource, + APP_ENV: BackendAppEnvironment +): Record { + const profile = backendEnvironmentProfiles[APP_ENV]; + + return stripUndefined({ + ...profile, + APP_ENV, + PORT: parsePort(source.PORT, profile.PORT), + DATABASE_URL: source.DATABASE_URL ?? profile.DATABASE_URL, + REDIS_URL: source.REDIS_URL ?? profile.REDIS_URL, + JWT_SECRET: source.JWT_SECRET ?? profile.JWT_SECRET, + AWS_REGION: source.AWS_REGION ?? profile.AWS_REGION, + AWS_SECRET_ID: source.AWS_SECRET_ID, + SECRETS_PROVIDER: + (source.SECRETS_PROVIDER as SecretsProvider | undefined) ?? profile.SECRETS_PROVIDER, + REQUIRE_MANAGED_SECRETS: parseBoolean( + source.REQUIRE_MANAGED_SECRETS, + profile.REQUIRE_MANAGED_SECRETS + ), + SHOPIFY_SHOP_DOMAIN: source.SHOPIFY_SHOP_DOMAIN, + SHOPIFY_ADMIN_ACCESS_TOKEN: source.SHOPIFY_ADMIN_ACCESS_TOKEN, + SHOPIFY_WEBHOOK_SECRET: source.SHOPIFY_WEBHOOK_SECRET, + STRIPE_SECRET_KEY: source.STRIPE_SECRET_KEY, + STRIPE_WEBHOOK_SECRET: source.STRIPE_WEBHOOK_SECRET, + CIRCLE_API_KEY: source.CIRCLE_API_KEY, + STELLAR_NETWORK: source.STELLAR_NETWORK as 'mainnet' | 'testnet' | undefined, + STELLAR_RPC_URL: source.STELLAR_RPC_URL, + SOROBAN_CONTRACT_ID: source.SOROBAN_CONTRACT_ID, + SENTRY_DSN: source.SENTRY_DSN, + LOG_LEVEL: source.LOG_LEVEL, + ENABLE_FRAUD_DETECTION: parseBoolean(source.ENABLE_FRAUD_DETECTION, true), + ENABLE_SLA_MONITORING: parseBoolean(source.ENABLE_SLA_MONITORING, true), + }); +} + +/** Load and parse the config without any error handling — throws on invalid input. */ +export function loadBackendEnvConfig( + source: EnvSource = process.env, + overrideEnv?: BackendAppEnvironment +): BackendEnv { + const APP_ENV = overrideEnv ?? resolveBackendAppEnvironment(source); + return backendEnvSchema.parse(buildBackendRawEnv(source, APP_ENV)); +} + +/** + * Validate backend environment variables once at startup. + * + * Production throws on validation failure (hard startup guard). + * Non-production logs a warning and falls back to profile defaults. + */ +export function validateBackendEnv( + source: EnvSource = process.env, + overrideEnv?: BackendAppEnvironment +): BackendEnv { + const APP_ENV = overrideEnv ?? resolveBackendAppEnvironment(source); + const result = backendEnvSchema.safeParse(buildBackendRawEnv(source, APP_ENV)); + + if (!result.success) { + const message = formatBackendEnvIssues(result.error.issues); + + if (APP_ENV === 'production') { + throw new Error(message); + } + + // eslint-disable-next-line no-console + console.warn(message); + return loadBackendEnvConfig({}, APP_ENV); + } + + if (APP_ENV !== 'production' && APP_ENV !== 'test') { + // eslint-disable-next-line no-console + console.info('[SubTrackr Backend] Environment validated', { + APP_ENV: result.data.APP_ENV, + PORT: result.data.PORT, + SECRETS_PROVIDER: result.data.SECRETS_PROVIDER, + }); + } + + return result.data; +} + +/** + * Pre-validated singleton for use throughout the backend. Throws at module + * load time in production when the config is invalid. + */ +export const backendEnv: BackendEnv = validateBackendEnv(); + +// ─── Private helpers ────────────────────────────────────────────────────────── + +function isBackendAppEnvironment(value: unknown): value is BackendAppEnvironment { + return ( + value === 'development' || + value === 'staging' || + value === 'production' || + value === 'test' + ); +} + +function parsePort(value: string | undefined, fallback: number): number { + if (!value) return fallback; + const n = parseInt(value, 10); + return Number.isFinite(n) && n > 0 ? n : fallback; +} + +function parseBoolean(value: string | undefined, fallback: boolean): boolean { + if (value === undefined) return fallback; + if (/^(1|true|yes)$/i.test(value)) return true; + if (/^(0|false|no)$/i.test(value)) return false; + return fallback; +} + +function stripUndefined>(input: T): T { + return Object.fromEntries( + Object.entries(input).filter(([, v]) => v !== undefined) + ) as T; +} + +function formatBackendEnvIssues(issues: z.ZodIssue[]): string { + return [ + '[SubTrackr Backend] Environment validation failed:', + ...issues.map((issue) => ` - ${issue.path.join('.')}: ${issue.message}`), + ].join('\n'); +} diff --git a/backend/src/services/__tests__/categorize.test.ts b/backend/src/services/__tests__/categorize.test.ts new file mode 100644 index 00000000..6b348d55 --- /dev/null +++ b/backend/src/services/__tests__/categorize.test.ts @@ -0,0 +1,241 @@ +/** + * backend/src/services/__tests__/categorize.test.ts + * + * Tests for the subscription category auto-tagger (issue #1989). + */ + +import { + categorize, + suggestCategory, + categorizeBulk, + listCategories, + isValidCategory, + type SubscriptionCategory, + type CategorizationInput, +} from '../categorize'; + +// ─── categorize (simple wrapper) ───────────────────────────────────────────── + +describe('categorize', () => { + it('returns streaming for Netflix by provider', () => { + expect(categorize({ name: 'Netflix', provider: 'Netflix' })).toBe('streaming'); + }); + + it('returns streaming for Spotify by name when provider is empty', () => { + expect(categorize({ name: 'Spotify', provider: '' })).toBe('streaming'); + }); + + it('returns infrastructure for AWS by provider', () => { + expect(categorize({ name: 'AWS', provider: 'AWS' })).toBe('infrastructure'); + }); + + it('returns productivity for Notion by name', () => { + expect(categorize({ name: 'Notion' })).toBe('productivity'); + }); + + it('returns gaming for Xbox Game Pass', () => { + expect(categorize({ name: 'Xbox Game Pass', provider: 'Xbox Game Pass' })).toBe('gaming'); + }); + + it('returns security for 1Password by provider', () => { + expect(categorize({ name: 'Password Manager', provider: '1Password' })).toBe('security'); + }); + + it('returns education for Coursera', () => { + expect(categorize({ name: 'Coursera', provider: 'Coursera' })).toBe('education'); + }); + + it('returns health for Headspace by provider', () => { + expect(categorize({ name: 'Mindfulness App', provider: 'Headspace' })).toBe('health'); + }); + + it('returns news for New York Times', () => { + expect(categorize({ name: 'New York Times', provider: 'New York Times' })).toBe('news'); + }); + + it('returns communication for Slack', () => { + expect(categorize({ name: 'Slack', provider: 'Slack' })).toBe('communication'); + }); + + it('returns storage for Dropbox', () => { + expect(categorize({ name: 'Dropbox', provider: 'Dropbox' })).toBe('storage'); + }); + + it('returns design for Figma', () => { + expect(categorize({ name: 'Figma', provider: 'Figma' })).toBe('design'); + }); + + it('returns marketing for Mailchimp', () => { + expect(categorize({ name: 'Mailchimp', provider: 'Mailchimp' })).toBe('marketing'); + }); + + it('returns analytics for Mixpanel', () => { + expect(categorize({ name: 'Mixpanel', provider: 'Mixpanel' })).toBe('analytics'); + }); + + it('returns finance for QuickBooks', () => { + expect(categorize({ name: 'QuickBooks', provider: 'QuickBooks' })).toBe('finance'); + }); + + it('returns other for completely unknown input with no default', () => { + expect(categorize({ name: 'Zxqpwoeiruv' })).toBe('other'); + }); + + it('honours custom fallback category', () => { + expect(categorize({ name: 'Zxqpwoeiruv' }, 'productivity')).toBe('productivity'); + }); + + it('is case-insensitive for provider lookup', () => { + expect(categorize({ name: 'NETFLIX', provider: 'NETFLIX' })).toBe('streaming'); + expect(categorize({ name: 'netflix', provider: 'netflix' })).toBe('streaming'); + }); +}); + +// ─── suggestCategory (full result) ─────────────────────────────────────────── + +describe('suggestCategory', () => { + it('returns high confidence for known providers', () => { + const result = suggestCategory({ name: 'AWS', provider: 'AWS' }); + expect(result.category).toBe('infrastructure'); + expect(result.confidence).toBe('high'); + expect(result.reason).toContain('AWS'); + }); + + it('falls back to keyword match when provider is unknown', () => { + const result = suggestCategory({ + name: 'SuperStream TV', + provider: 'UnknownCo', + }); + expect(result.category).toBe('streaming'); + expect(result.confidence).toBe('medium'); + }); + + it('uses description as a signal when name and provider give no match', () => { + const result = suggestCategory({ + name: 'Monthly Bundle', + provider: 'AcmeCorp', + description: 'Unlimited VPN access across all your devices', + }); + expect(result.category).toBe('security'); + }); + + it('returns low confidence and fallback category when nothing matches', () => { + const result = suggestCategory({ name: 'Foo', provider: 'Bar' }); + expect(result.category).toBe('other'); + expect(result.confidence).toBe('low'); + expect(result.reason).toContain('fallback'); + }); + + it('provider lookup takes priority over keyword match in name', () => { + // "Adobe Creative Cloud" is a known provider → 'design', not 'streaming'. + const result = suggestCategory({ + name: 'Adobe Creative Cloud Premium Streaming', + provider: 'Adobe Creative Cloud', + }); + expect(result.category).toBe('design'); + expect(result.confidence).toBe('high'); + }); + + it('tries name as a provider key when provider field is empty', () => { + const result = suggestCategory({ name: 'Datadog', provider: '' }); + expect(result.category).toBe('infrastructure'); + expect(result.confidence).toBe('high'); + }); + + it('prefix-matches provider names', () => { + // "Netflix Premium" should match the "netflix" provider entry. + const result = suggestCategory({ name: 'Subscription', provider: 'Netflix Premium' }); + expect(result.category).toBe('streaming'); + }); + + it('matches Google Workspace case-insensitively', () => { + const result = suggestCategory({ name: 'google workspace', provider: 'google workspace' }); + expect(result.category).toBe('productivity'); + }); +}); + +// ─── categorizeBulk ────────────────────────────────────────────────────────── + +describe('categorizeBulk', () => { + const inputs: CategorizationInput[] = [ + { name: 'Netflix', provider: 'Netflix' }, + { name: 'AWS Plan', provider: 'AWS' }, + { name: 'Unknown Thing', provider: '' }, + ]; + + it('returns results in the same order as inputs', () => { + const results = categorizeBulk(inputs); + expect(results).toHaveLength(3); + expect(results[0].category).toBe('streaming'); + expect(results[1].category).toBe('infrastructure'); + expect(results[2].category).toBe('other'); + }); + + it('applies a custom fallback to unmatched entries', () => { + const results = categorizeBulk(inputs, 'productivity'); + expect(results[2].category).toBe('productivity'); + }); + + it('handles an empty array', () => { + expect(categorizeBulk([])).toEqual([]); + }); +}); + +// ─── listCategories ─────────────────────────────────────────────────────────── + +describe('listCategories', () => { + it('returns an array of valid category strings', () => { + const cats = listCategories(); + expect(cats.length).toBeGreaterThan(0); + expect(cats).toContain('streaming'); + expect(cats).toContain('other'); + }); + + it('contains no duplicates', () => { + const cats = listCategories(); + expect(new Set(cats).size).toBe(cats.length); + }); +}); + +// ─── isValidCategory ────────────────────────────────────────────────────────── + +describe('isValidCategory', () => { + it('returns true for every listed category', () => { + for (const cat of listCategories()) { + expect(isValidCategory(cat)).toBe(true); + } + }); + + it('returns false for unknown strings', () => { + expect(isValidCategory('unknown')).toBe(false); + expect(isValidCategory('')).toBe(false); + expect(isValidCategory('STREAMING')).toBe(false); + }); +}); + +// ─── Keyword heuristic coverage ─────────────────────────────────────────────── + +describe('keyword heuristics', () => { + const cases: Array<[string, SubscriptionCategory]> = [ + ['VPN Monthly Access', 'security'], + ['Online Learning Platform', 'education'], + ['Fitness & Wellness App', 'health'], + ['Cloud Hosting Service', 'infrastructure'], + ['Personal Finance Dashboard', 'finance'], + ['Cloud Storage Plan', 'infrastructure'], // "cloud" beats "storage" + ['Email Marketing Tool', 'marketing'], + ['User Analytics Platform', 'analytics'], + ['Video Streaming Service', 'streaming'], + ['Chat and Messaging Pro', 'communication'], + ['Photo Backup Plan', 'storage'], + ['Graphic Design Suite', 'design'], + ['News & Magazines Bundle', 'news'], + ['Task Management App', 'productivity'], + ['PC Gaming Subscription', 'gaming'], + ]; + + test.each(cases)('"%s" → %s', (name, expected) => { + const result = categorize({ name, provider: '' }); + expect(result).toBe(expected); + }); +}); diff --git a/backend/src/services/categorize.ts b/backend/src/services/categorize.ts new file mode 100644 index 00000000..8b8e7a4e --- /dev/null +++ b/backend/src/services/categorize.ts @@ -0,0 +1,588 @@ +/** + * backend/src/services/categorize.ts + * + * Issue #1989 — Subscription category auto-tagger with provider heuristics. + * + * Assigns a canonical SubscriptionCategory to a subscription based on: + * 1. An exact provider-name lookup (highest confidence). + * 2. Keyword matching against the subscription name and provider fields. + * 3. A configurable fallback category. + * + * All matching is case-insensitive. The module is pure (no I/O) so it can + * be exercised without a database or network. + * + * Usage: + * import { categorize, suggestCategory } from './categorize'; + * + * const category = categorize({ name: 'Netflix', provider: 'Netflix' }); + * // => 'streaming' + * + * const { category, confidence } = suggestCategory({ name: 'AWS', provider: '' }); + * // => { category: 'infrastructure', confidence: 'high' } + */ + +// ─── Types ──────────────────────────────────────────────────────────────────── + +export type SubscriptionCategory = + | 'streaming' + | 'productivity' + | 'infrastructure' + | 'gaming' + | 'finance' + | 'health' + | 'education' + | 'news' + | 'security' + | 'communication' + | 'storage' + | 'design' + | 'marketing' + | 'analytics' + | 'other'; + +export type CategoryConfidence = 'high' | 'medium' | 'low'; + +export interface CategorizationInput { + /** Display name of the subscription (e.g. "Netflix Premium"). */ + name: string; + /** Provider / vendor name if known (e.g. "Netflix"). */ + provider?: string; + /** Free-text description — used as a fallback signal. */ + description?: string; +} + +export interface CategorizationResult { + category: SubscriptionCategory; + confidence: CategoryConfidence; + /** Human-readable explanation of why this category was chosen. */ + reason: string; +} + +// ─── Provider lookup table ──────────────────────────────────────────────────── +// +// Keys are lowercased provider/brand names. Values are the category and the +// confidence level. Add new entries here as new providers are onboarded. + +type ProviderEntry = { category: SubscriptionCategory; confidence: CategoryConfidence }; + +const PROVIDER_MAP: Record = { + // Streaming + netflix: { category: 'streaming', confidence: 'high' }, + 'disney+': { category: 'streaming', confidence: 'high' }, + 'disney plus': { category: 'streaming', confidence: 'high' }, + hulu: { category: 'streaming', confidence: 'high' }, + 'amazon prime': { category: 'streaming', confidence: 'high' }, + 'amazon prime video': { category: 'streaming', confidence: 'high' }, + 'apple tv+': { category: 'streaming', confidence: 'high' }, + 'apple tv plus': { category: 'streaming', confidence: 'high' }, + hbo: { category: 'streaming', confidence: 'high' }, + 'hbo max': { category: 'streaming', confidence: 'high' }, + max: { category: 'streaming', confidence: 'high' }, + peacock: { category: 'streaming', confidence: 'high' }, + paramount: { category: 'streaming', confidence: 'high' }, + 'paramount+': { category: 'streaming', confidence: 'high' }, + 'discovery+': { category: 'streaming', confidence: 'high' }, + crunchyroll: { category: 'streaming', confidence: 'high' }, + funimation: { category: 'streaming', confidence: 'high' }, + mubi: { category: 'streaming', confidence: 'high' }, + tidal: { category: 'streaming', confidence: 'high' }, + spotify: { category: 'streaming', confidence: 'high' }, + 'apple music': { category: 'streaming', confidence: 'high' }, + 'youtube premium': { category: 'streaming', confidence: 'high' }, + deezer: { category: 'streaming', confidence: 'high' }, + 'amazon music': { category: 'streaming', confidence: 'high' }, + pandora: { category: 'streaming', confidence: 'high' }, + + // Productivity + microsoft: { category: 'productivity', confidence: 'high' }, + 'microsoft 365': { category: 'productivity', confidence: 'high' }, + 'office 365': { category: 'productivity', confidence: 'high' }, + 'google workspace': { category: 'productivity', confidence: 'high' }, + 'g suite': { category: 'productivity', confidence: 'high' }, + notion: { category: 'productivity', confidence: 'high' }, + asana: { category: 'productivity', confidence: 'high' }, + jira: { category: 'productivity', confidence: 'high' }, + confluence: { category: 'productivity', confidence: 'high' }, + atlassian: { category: 'productivity', confidence: 'high' }, + monday: { category: 'productivity', confidence: 'high' }, + 'monday.com': { category: 'productivity', confidence: 'high' }, + trello: { category: 'productivity', confidence: 'high' }, + basecamp: { category: 'productivity', confidence: 'high' }, + clickup: { category: 'productivity', confidence: 'high' }, + linear: { category: 'productivity', confidence: 'high' }, + todoist: { category: 'productivity', confidence: 'high' }, + evernote: { category: 'productivity', confidence: 'high' }, + 'bear notes': { category: 'productivity', confidence: 'high' }, + obsidian: { category: 'productivity', confidence: 'high' }, + zapier: { category: 'productivity', confidence: 'high' }, + 'make.com': { category: 'productivity', confidence: 'high' }, + integromat: { category: 'productivity', confidence: 'high' }, + airtable: { category: 'productivity', confidence: 'high' }, + coda: { category: 'productivity', confidence: 'high' }, + + // Infrastructure / Cloud + aws: { category: 'infrastructure', confidence: 'high' }, + 'amazon web services': { category: 'infrastructure', confidence: 'high' }, + gcp: { category: 'infrastructure', confidence: 'high' }, + 'google cloud': { category: 'infrastructure', confidence: 'high' }, + azure: { category: 'infrastructure', confidence: 'high' }, + 'microsoft azure': { category: 'infrastructure', confidence: 'high' }, + digitalocean: { category: 'infrastructure', confidence: 'high' }, + linode: { category: 'infrastructure', confidence: 'high' }, + akamai: { category: 'infrastructure', confidence: 'high' }, + heroku: { category: 'infrastructure', confidence: 'high' }, + vercel: { category: 'infrastructure', confidence: 'high' }, + netlify: { category: 'infrastructure', confidence: 'high' }, + cloudflare: { category: 'infrastructure', confidence: 'high' }, + fastly: { category: 'infrastructure', confidence: 'high' }, + 'new relic': { category: 'infrastructure', confidence: 'high' }, + datadog: { category: 'infrastructure', confidence: 'high' }, + pagerduty: { category: 'infrastructure', confidence: 'high' }, + sentry: { category: 'infrastructure', confidence: 'high' }, + supabase: { category: 'infrastructure', confidence: 'high' }, + firebase: { category: 'infrastructure', confidence: 'high' }, + mongodb: { category: 'infrastructure', confidence: 'high' }, + 'mongodb atlas': { category: 'infrastructure', confidence: 'high' }, + planetscale: { category: 'infrastructure', confidence: 'high' }, + neon: { category: 'infrastructure', confidence: 'high' }, + railway: { category: 'infrastructure', confidence: 'high' }, + fly: { category: 'infrastructure', confidence: 'high' }, + 'fly.io': { category: 'infrastructure', confidence: 'high' }, + render: { category: 'infrastructure', confidence: 'high' }, + + // Gaming + 'xbox game pass': { category: 'gaming', confidence: 'high' }, + 'xbox ultimate': { category: 'gaming', confidence: 'high' }, + 'playstation plus': { category: 'gaming', confidence: 'high' }, + 'ps plus': { category: 'gaming', confidence: 'high' }, + 'playstation now': { category: 'gaming', confidence: 'high' }, + 'ea play': { category: 'gaming', confidence: 'high' }, + 'ea access': { category: 'gaming', confidence: 'high' }, + 'nintendo switch online': { category: 'gaming', confidence: 'high' }, + steam: { category: 'gaming', confidence: 'high' }, + 'humble bundle': { category: 'gaming', confidence: 'high' }, + 'humble monthly': { category: 'gaming', confidence: 'high' }, + gog: { category: 'gaming', confidence: 'high' }, + 'twitch prime': { category: 'gaming', confidence: 'high' }, + ubisoft: { category: 'gaming', confidence: 'high' }, + 'ubisoft connect': { category: 'gaming', confidence: 'high' }, + 'ubisoft plus': { category: 'gaming', confidence: 'high' }, + 'apple arcade': { category: 'gaming', confidence: 'high' }, + 'google play pass': { category: 'gaming', confidence: 'high' }, + + // Finance + quickbooks: { category: 'finance', confidence: 'high' }, + xero: { category: 'finance', confidence: 'high' }, + 'fresh books': { category: 'finance', confidence: 'high' }, + freshbooks: { category: 'finance', confidence: 'high' }, + 'wave accounting': { category: 'finance', confidence: 'high' }, + expensify: { category: 'finance', confidence: 'high' }, + mint: { category: 'finance', confidence: 'high' }, + ynab: { category: 'finance', confidence: 'high' }, + 'you need a budget': { category: 'finance', confidence: 'high' }, + plaid: { category: 'finance', confidence: 'high' }, + robinhood: { category: 'finance', confidence: 'high' }, + coinbase: { category: 'finance', confidence: 'high' }, + stripe: { category: 'finance', confidence: 'high' }, + paypal: { category: 'finance', confidence: 'high' }, + + // Health & Fitness + peloton: { category: 'health', confidence: 'high' }, + 'apple fitness+': { category: 'health', confidence: 'high' }, + noom: { category: 'health', confidence: 'high' }, + headspace: { category: 'health', confidence: 'high' }, + calm: { category: 'health', confidence: 'high' }, + 'my fitness pal': { category: 'health', confidence: 'high' }, + myfitnesspal: { category: 'health', confidence: 'high' }, + 'whoop': { category: 'health', confidence: 'high' }, + strava: { category: 'health', confidence: 'high' }, + 'eight sleep': { category: 'health', confidence: 'high' }, + teladoc: { category: 'health', confidence: 'high' }, + hims: { category: 'health', confidence: 'high' }, + hers: { category: 'health', confidence: 'high' }, + + // Education + coursera: { category: 'education', confidence: 'high' }, + udemy: { category: 'education', confidence: 'high' }, + udacity: { category: 'education', confidence: 'high' }, + 'linkedin learning': { category: 'education', confidence: 'high' }, + pluralsight: { category: 'education', confidence: 'high' }, + skillshare: { category: 'education', confidence: 'high' }, + duolingo: { category: 'education', confidence: 'high' }, + babbel: { category: 'education', confidence: 'high' }, + rosetta: { category: 'education', confidence: 'high' }, + 'rosetta stone': { category: 'education', confidence: 'high' }, + masterclass: { category: 'education', confidence: 'high' }, + 'khan academy': { category: 'education', confidence: 'high' }, + brilliant: { category: 'education', confidence: 'high' }, + codecademy: { category: 'education', confidence: 'high' }, + egghead: { category: 'education', confidence: 'high' }, + frontendmasters: { category: 'education', confidence: 'high' }, + 'frontend masters': { category: 'education', confidence: 'high' }, + laracasts: { category: 'education', confidence: 'high' }, + leveluptuts: { category: 'education', confidence: 'high' }, + scrimba: { category: 'education', confidence: 'high' }, + + // News & Reading + 'new york times': { category: 'news', confidence: 'high' }, + nyt: { category: 'news', confidence: 'high' }, + 'washington post': { category: 'news', confidence: 'high' }, + 'wall street journal': { category: 'news', confidence: 'high' }, + wsj: { category: 'news', confidence: 'high' }, + bloomberg: { category: 'news', confidence: 'high' }, + economist: { category: 'news', confidence: 'high' }, + 'the economist': { category: 'news', confidence: 'high' }, + medium: { category: 'news', confidence: 'high' }, + substack: { category: 'news', confidence: 'high' }, + apple: { category: 'news', confidence: 'low' }, // too generic without context + 'apple news+': { category: 'news', confidence: 'high' }, + kindle: { category: 'news', confidence: 'high' }, + scribd: { category: 'news', confidence: 'high' }, + audible: { category: 'news', confidence: 'high' }, + + // Security + '1password': { category: 'security', confidence: 'high' }, + lastpass: { category: 'security', confidence: 'high' }, + dashlane: { category: 'security', confidence: 'high' }, + bitwarden: { category: 'security', confidence: 'high' }, + nordvpn: { category: 'security', confidence: 'high' }, + expressvpn: { category: 'security', confidence: 'high' }, + surfshark: { category: 'security', confidence: 'high' }, + protonvpn: { category: 'security', confidence: 'high' }, + mullvad: { category: 'security', confidence: 'high' }, + 'malwarebytes': { category: 'security', confidence: 'high' }, + norton: { category: 'security', confidence: 'high' }, + 'norton 360': { category: 'security', confidence: 'high' }, + mcafee: { category: 'security', confidence: 'high' }, + bitdefender: { category: 'security', confidence: 'high' }, + crowdstrike: { category: 'security', confidence: 'high' }, + okta: { category: 'security', confidence: 'high' }, + authy: { category: 'security', confidence: 'high' }, + + // Communication + slack: { category: 'communication', confidence: 'high' }, + zoom: { category: 'communication', confidence: 'high' }, + 'google meet': { category: 'communication', confidence: 'high' }, + 'microsoft teams': { category: 'communication', confidence: 'high' }, + discord: { category: 'communication', confidence: 'high' }, + intercom: { category: 'communication', confidence: 'high' }, + zendesk: { category: 'communication', confidence: 'high' }, + freshdesk: { category: 'communication', confidence: 'high' }, + hubspot: { category: 'communication', confidence: 'high' }, + mailchimp: { category: 'communication', confidence: 'high' }, + sendgrid: { category: 'communication', confidence: 'high' }, + twilio: { category: 'communication', confidence: 'high' }, + vonage: { category: 'communication', confidence: 'high' }, + ringcentral: { category: 'communication', confidence: 'high' }, + loom: { category: 'communication', confidence: 'high' }, + typeform: { category: 'communication', confidence: 'high' }, + calendly: { category: 'communication', confidence: 'high' }, + + // Storage + dropbox: { category: 'storage', confidence: 'high' }, + 'google one': { category: 'storage', confidence: 'high' }, + 'icloud+': { category: 'storage', confidence: 'high' }, + icloud: { category: 'storage', confidence: 'high' }, + 'onedrive': { category: 'storage', confidence: 'high' }, + box: { category: 'storage', confidence: 'high' }, + backblaze: { category: 'storage', confidence: 'high' }, + pcloud: { category: 'storage', confidence: 'high' }, + 'sync.com': { category: 'storage', confidence: 'high' }, + 'amazon drive': { category: 'storage', confidence: 'high' }, + + // Design + figma: { category: 'design', confidence: 'high' }, + sketch: { category: 'design', confidence: 'high' }, + 'adobe creative cloud': { category: 'design', confidence: 'high' }, + 'adobe cc': { category: 'design', confidence: 'high' }, + adobe: { category: 'design', confidence: 'high' }, + canva: { category: 'design', confidence: 'high' }, + invision: { category: 'design', confidence: 'high' }, + 'abstract.com': { category: 'design', confidence: 'high' }, + zeplin: { category: 'design', confidence: 'high' }, + miro: { category: 'design', confidence: 'high' }, + lucidchart: { category: 'design', confidence: 'high' }, + 'whimsical': { category: 'design', confidence: 'high' }, + framer: { category: 'design', confidence: 'high' }, + webflow: { category: 'design', confidence: 'high' }, + + // Marketing + 'google ads': { category: 'marketing', confidence: 'high' }, + 'facebook ads': { category: 'marketing', confidence: 'high' }, + semrush: { category: 'marketing', confidence: 'high' }, + ahrefs: { category: 'marketing', confidence: 'high' }, + moz: { category: 'marketing', confidence: 'high' }, + hootsuite: { category: 'marketing', confidence: 'high' }, + buffer: { category: 'marketing', confidence: 'high' }, + sproutsocial: { category: 'marketing', confidence: 'high' }, + 'sprout social': { category: 'marketing', confidence: 'high' }, + 'active campaign': { category: 'marketing', confidence: 'high' }, + activecampaign: { category: 'marketing', confidence: 'high' }, + klaviyo: { category: 'marketing', confidence: 'high' }, + 'constant contact': { category: 'marketing', confidence: 'high' }, + salesforce: { category: 'marketing', confidence: 'high' }, + + // Analytics + 'google analytics': { category: 'analytics', confidence: 'high' }, + mixpanel: { category: 'analytics', confidence: 'high' }, + amplitude: { category: 'analytics', confidence: 'high' }, + segment: { category: 'analytics', confidence: 'high' }, + heap: { category: 'analytics', confidence: 'high' }, + hotjar: { category: 'analytics', confidence: 'high' }, + fullstory: { category: 'analytics', confidence: 'high' }, + chartmogul: { category: 'analytics', confidence: 'high' }, + baremetrics: { category: 'analytics', confidence: 'high' }, + profitwell: { category: 'analytics', confidence: 'high' }, + tableau: { category: 'analytics', confidence: 'high' }, + looker: { category: 'analytics', confidence: 'high' }, + metabase: { category: 'analytics', confidence: 'high' }, + posthog: { category: 'analytics', confidence: 'high' }, +}; + +// ─── Keyword heuristics ─────────────────────────────────────────────────────── +// +// Each entry maps a category to a list of keyword fragments. Matching is +// substring-based so "cloud storage" matches both "cloud" → infrastructure +// and "storage" → storage. The first keyword hit wins (order matters). + +interface KeywordRule { + keywords: string[]; + category: SubscriptionCategory; + confidence: CategoryConfidence; +} + +const KEYWORD_RULES: KeywordRule[] = [ + // Infrastructure signals are very specific — check early. + { + keywords: ['cloud', 'server', 'hosting', 'vps', 'cdn', 'api', 'devops', 'ci/cd', 'pipeline', 'kubernetes', 'docker', 'container'], + category: 'infrastructure', + confidence: 'medium', + }, + // Streaming / media + { + keywords: ['streaming', 'video', 'movies', 'music', 'podcast', 'audio', 'tv', 'watch', 'listen', 'channel'], + category: 'streaming', + confidence: 'medium', + }, + // Gaming + { + keywords: ['game', 'gaming', 'games', 'play', 'esports', 'controller'], + category: 'gaming', + confidence: 'medium', + }, + // Security + { + keywords: ['vpn', 'password', 'security', 'antivirus', 'firewall', 'threat', 'encryption', 'vault'], + category: 'security', + confidence: 'medium', + }, + // Education + { + keywords: ['learn', 'course', 'tutorial', 'training', 'education', 'university', 'academy', 'school', 'study', 'lesson'], + category: 'education', + confidence: 'medium', + }, + // Health + { + keywords: ['health', 'fitness', 'gym', 'wellness', 'meditation', 'workout', 'diet', 'nutrition', 'therapy', 'mental'], + category: 'health', + confidence: 'medium', + }, + // Finance + { + keywords: ['accounting', 'invoice', 'billing', 'payroll', 'finance', 'budget', 'expense', 'tax', 'trading', 'investment', 'bookkeeping'], + category: 'finance', + confidence: 'medium', + }, + // Storage + { + keywords: ['storage', 'backup', 'cloud drive', 'file sync', 'photos'], + category: 'storage', + confidence: 'medium', + }, + // Design + { + keywords: ['design', 'creative', 'illustration', 'photo edit', 'prototype', 'wireframe', 'ux', 'ui', 'graphic'], + category: 'design', + confidence: 'medium', + }, + // Marketing + { + keywords: ['marketing', 'seo', 'email campaign', 'crm', 'advertising', 'social media', 'analytics campaign'], + category: 'marketing', + confidence: 'medium', + }, + // Analytics + { + keywords: ['analytics', 'metrics', 'dashboard', 'tracking', 'reporting', 'insights', 'data'], + category: 'analytics', + confidence: 'low', + }, + // Communication + { + keywords: ['chat', 'messaging', 'email', 'communication', 'meeting', 'conference', 'video call', 'support', 'helpdesk'], + category: 'communication', + confidence: 'medium', + }, + // Productivity (broad — keep near the bottom) + { + keywords: ['productivity', 'task', 'project', 'workflow', 'automation', 'notes', 'docs', 'document', 'spreadsheet', 'calendar', 'schedule'], + category: 'productivity', + confidence: 'medium', + }, + // News / reading + { + keywords: ['news', 'newspaper', 'magazine', 'read', 'ebook', 'newsletter', 'journal', 'article'], + category: 'news', + confidence: 'medium', + }, +]; + +// ─── Helpers ────────────────────────────────────────────────────────────────── + +function normalize(value: string): string { + return value.toLowerCase().trim(); +} + +/** Check the provider map for an exact or prefix match. */ +function lookupProvider(input: string): ProviderEntry | undefined { + const key = normalize(input); + if (PROVIDER_MAP[key]) return PROVIDER_MAP[key]; + + // Try prefix match (e.g. "Netflix Premium" → "netflix"). + for (const [providerKey, entry] of Object.entries(PROVIDER_MAP)) { + if (key.startsWith(providerKey) || providerKey.startsWith(key)) { + return entry; + } + } + + return undefined; +} + +/** Run keyword rules against the combined text corpus. */ +function matchKeywords(corpus: string): KeywordRule | undefined { + const lower = normalize(corpus); + for (const rule of KEYWORD_RULES) { + for (const kw of rule.keywords) { + if (lower.includes(kw)) { + return rule; + } + } + } + return undefined; +} + +// ─── Public API ─────────────────────────────────────────────────────────────── + +/** + * Returns the best-guess {@link SubscriptionCategory} for the given input. + * + * This is the simple "just give me a category" wrapper. Use + * {@link suggestCategory} when you also need confidence and provenance. + */ +export function categorize( + input: CategorizationInput, + fallback: SubscriptionCategory = 'other' +): SubscriptionCategory { + return suggestCategory(input, fallback).category; +} + +/** + * Returns a {@link CategorizationResult} with category, confidence, and a + * human-readable reason explaining why that category was chosen. + * + * Resolution order: + * 1. Exact / prefix provider lookup (confidence preserved from map). + * 2. Keyword scan over name + provider + description. + * 3. Fallback category at 'low' confidence. + */ +export function suggestCategory( + input: CategorizationInput, + fallback: SubscriptionCategory = 'other' +): CategorizationResult { + const { name, provider = '', description = '' } = input; + + // 1. Provider lookup — most reliable signal. + if (provider) { + const hit = lookupProvider(provider); + if (hit) { + return { + category: hit.category, + confidence: hit.confidence, + reason: `Matched known provider "${provider}"`, + }; + } + } + + // Also try the subscription name as a provider key. + if (name) { + const hit = lookupProvider(name); + if (hit) { + return { + category: hit.category, + confidence: hit.confidence, + reason: `Matched known provider name "${name}"`, + }; + } + } + + // 2. Keyword heuristics across the full corpus. + const corpus = [name, provider, description].filter(Boolean).join(' '); + const rule = matchKeywords(corpus); + if (rule) { + return { + category: rule.category, + confidence: rule.confidence, + reason: `Keyword match in subscription text (category: ${rule.category})`, + }; + } + + // 3. Fallback. + return { + category: fallback, + confidence: 'low', + reason: 'No provider or keyword match found; using fallback category', + }; +} + +/** + * Categorizes a list of subscriptions in bulk. Returns an array in the same + * order as the input. + */ +export function categorizeBulk( + inputs: CategorizationInput[], + fallback: SubscriptionCategory = 'other' +): CategorizationResult[] { + return inputs.map((input) => suggestCategory(input, fallback)); +} + +/** + * Returns the full list of supported categories, useful for building UI + * filter menus or validating user-supplied category values. + */ +export function listCategories(): SubscriptionCategory[] { + return [ + 'streaming', + 'productivity', + 'infrastructure', + 'gaming', + 'finance', + 'health', + 'education', + 'news', + 'security', + 'communication', + 'storage', + 'design', + 'marketing', + 'analytics', + 'other', + ]; +} + +/** + * Checks whether a string is a valid {@link SubscriptionCategory}. + */ +export function isValidCategory(value: string): value is SubscriptionCategory { + return (listCategories() as string[]).includes(value); +} diff --git a/src/navigation/AppNavigator.tsx b/src/navigation/AppNavigator.tsx index e61e172d..b5de6afb 100644 --- a/src/navigation/AppNavigator.tsx +++ b/src/navigation/AppNavigator.tsx @@ -5,15 +5,32 @@ import { navigationRef } from './navigationRef'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import { useTranslation } from 'react-i18next'; -import { prefetchModule } from '../utils/lazyLoading'; +import { prefetchModule, lazyStack } from '../utils/lazyLoading'; import { RootNavigatorParamList, TabParamList } from './types'; import { useTheme } from '../theme'; import { darkNavigationTheme, lightNavigationTheme } from '../theme/navigationTheme'; import { NavigationErrorBoundary } from './NavigationErrorBoundary'; import { linkingConfig } from './linking'; -// Import feature-based stack modules -import { SubscriptionStack, AnalyticsStack, SettingsStack, WalletStack } from './modules'; +// HomeTab / SubscriptionStack is the landing tab — load it eagerly so the first +// frame renders without a Suspense boundary flash. +import { SubscriptionStack } from './modules'; + +// All other stacks are loaded on-demand the first time the user navigates to +// their tab (or prefetched after the first frame via prefetchModule below). +// This keeps analytics, wallet, and settings JS out of the initial bundle. +const AnalyticsStack = lazyStack( + () => import('./modules/AnalyticsStack').then((m) => ({ default: m.AnalyticsStack })), + { displayName: 'LazyStack(Analytics)' } +); +const WalletStack = lazyStack( + () => import('./modules/WalletStack').then((m) => ({ default: m.WalletStack })), + { displayName: 'LazyStack(Wallet)' } +); +const SettingsStack = lazyStack( + () => import('./modules/SettingsStack').then((m) => ({ default: m.SettingsStack })), + { displayName: 'LazyStack(Settings)' } +); const Tab = createBottomTabNavigator(); const Stack = createNativeStackNavigator(); diff --git a/src/navigation/__tests__/AppNavigator.lazy.test.tsx b/src/navigation/__tests__/AppNavigator.lazy.test.tsx index e58bdab7..7655b0cc 100644 --- a/src/navigation/__tests__/AppNavigator.lazy.test.tsx +++ b/src/navigation/__tests__/AppNavigator.lazy.test.tsx @@ -10,6 +10,7 @@ import { prefetchedModules, prefetchModule, SuspenseLoadingFallback, + lazyStack, } from '../../utils/lazyLoading'; // Mock react-native completely with pass-through elements so testID is fully discoverable by testing-library @@ -268,3 +269,54 @@ describe('Lazy Loading Utilities & Error Boundaries', () => { } }); }); + +// ─── lazyStack — route-level dynamic stack loading (issue #2212) ───────────── + +describe('lazyStack', () => { + const StackComponent = () => Stack Loaded; + + it('applies a custom displayName', () => { + const LazySettingsStack = lazyStack( + () => Promise.resolve({ default: StackComponent }), + { displayName: 'LazyStack(Settings)' } + ); + expect(LazySettingsStack.displayName).toBe('LazyStack(Settings)'); + }); + + it('derives a displayName when one is not provided', () => { + function importStack() { + return Promise.resolve({ default: StackComponent }); + } + const LazyDynStack = lazyStack(importStack); + expect(LazyDynStack.displayName).toContain('lazyStack('); + }); + + it('resolves a module with a default export', async () => { + const importFn = jest.fn().mockResolvedValue({ default: StackComponent }); + const LazyTestStack = lazyStack(importFn); + const mod = await importFn(); + expect(mod.default).toBe(StackComponent); + expect(LazyTestStack.displayName).toBeTruthy(); + }); + + it('resolves a module via a named export when exportName is provided', async () => { + const importFn = jest.fn().mockResolvedValue({ WalletStack: StackComponent }); + const LazyWalletStack = lazyStack(importFn, { + exportName: 'WalletStack', + displayName: 'LazyStack(Wallet)', + }); + expect(LazyWalletStack.displayName).toBe('LazyStack(Wallet)'); + }); + + it('renders with a Suspense fallback while the import resolves', () => { + let resolveFn!: (v: { default: typeof StackComponent }) => void; + const neverSettles = new Promise<{ default: typeof StackComponent }>( + (resolve) => { resolveFn = resolve; } + ); + const LazyNeverStack = lazyStack(() => neverSettles, { displayName: 'LazyStack(Pending)' }); + const { getByTestId } = render(); + expect(getByTestId('lazy-loading-fallback')).toBeTruthy(); + // Resolve to avoid dangling async operations in the test runner. + resolveFn({ default: StackComponent }); + }); +}); diff --git a/src/utils/lazyLoading.tsx b/src/utils/lazyLoading.tsx index 385c969a..22313f24 100644 --- a/src/utils/lazyLoading.tsx +++ b/src/utils/lazyLoading.tsx @@ -145,6 +145,55 @@ export function prefetchModule(name: string, importFn: () => Promise) { } export { prefetchedModules }; +// ─── Route-level dynamic stack loading (issue #2212) ───────────────────────── +// +// Unlike lazyScreen (which lazy-loads individual screen components), lazyStack +// lazy-loads an entire navigator stack. This keeps the initial JS bundle lean: +// only the HomeTab stack loads at startup; every other stack is fetched on +// first navigation to its tab, or prefetched after the first frame. +// +// Usage: +// const SettingsStack = lazyStack( +// () => import('./modules/SettingsStack').then(m => ({ default: m.SettingsStack })), +// { displayName: 'LazyStack(Settings)' } +// ); + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function lazyStack>( + importFn: () => Promise<{ default: T } | Record>, + options: { displayName?: string; exportName?: string } = {} +) { + const resolvedImport = (): Promise<{ default: T }> => + importFn().then((mod) => { + if ('default' in mod && mod.default) { + return mod as { default: T }; + } + if (options.exportName && options.exportName in mod) { + return { default: (mod as Record)[options.exportName] }; + } + const first = Object.values(mod).find( + (v): v is T => typeof v === 'function' || (typeof v === 'object' && v !== null) + ); + if (first) return { default: first }; + throw new Error('[lazyStack] Module has no usable component export'); + }); + + const LazyStackComponent = lazyWithRetry(resolvedImport as () => Promise<{ default: T }>); + + const WrappedStack = (props: React.ComponentPropsWithRef) => ( + + }> + + + + ); + + WrappedStack.displayName = + options.displayName ?? `lazyStack(${importFn.toString().replace(/\s+/g, ' ')})`; + + return WrappedStack; +} + const styles = StyleSheet.create({ loadingContainer: { flex: 1,