Files
gruperly/apps/backend/src/modules/mp/features/callback/use-case.ts
Jose Selesan 21a4c69f38 feat(mp): add Mercado Pago reauthorization notice and status card components
- Implemented MpReauthNotice component to notify users when reauthorization is needed.
- Created MpStatusCard component to display the current status of the Mercado Pago account.
- Added utility functions and constants for handling Mercado Pago status and messages.
- Introduced hooks for managing the connection and disconnection of Mercado Pago accounts.
- Developed a disconnect confirmation modal for user actions.
- Added tests for the new functionality and utility functions.
- Defined schemas for Mercado Pago account status and callback reasons in shared package.
2026-10-07 12:00:38 -03:00

146 lines
4.8 KiB
TypeScript

import type { PrismaClient } from '@generated/prisma/client';
import type { MpCallbackReason, MpReturnTo, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import {
mpAccountInUseProblem,
mpNotConfiguredProblem,
mpProviderErrorProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import {
exchangeAuthorizationCode,
getMpOAuthConfig,
type MpTokenResponse,
sealToken,
} from '../../lib';
type CompleteMpAuthorizationDeps = {
db?: Pick<PrismaClient, 'mpOAuthState' | 'mpAccount'>;
/** Swapped in tests; defaults to the real Mercado Pago exchange. */
exchange?: typeof exchangeAuthorizationCode;
};
export type MpCallbackResult = {
returnTo: MpReturnTo;
outcome: { kind: 'success' } | { kind: 'error'; reason: MpCallbackReason };
};
/** Prisma's unique-constraint violation on `mp_accounts_mpUserId_key`. */
const UNIQUE_VIOLATION = 'P2002';
/** Where we land if the state is gone and there is nothing to recover. */
const DEFAULT_RETURN_TO: MpReturnTo = 'settings';
export class CompleteMpAuthorization {
constructor(private readonly deps: CompleteMpAuthorizationDeps = {}) {}
async execute(input: {
code?: string;
state?: string;
error?: string;
}): Promise<Result<MpCallbackResult, ProblemDetails>> {
let config: ReturnType<typeof getMpOAuthConfig>;
try {
config = getMpOAuthConfig();
} catch (configError) {
logger.error({ err: configError }, 'Mercado Pago is not configured');
return err(mpNotConfiguredProblem());
}
const db = this.deps.db ?? prisma;
// The teacher closed the consent screen. There is nothing to exchange, but
// the state is still burned so it cannot be replayed later.
if (input.error) {
if (input.state) {
await db.mpOAuthState.deleteMany({ where: { state: input.state } });
}
return failure('mp_denied');
}
if (!input.code || !input.state) {
return failure('invalid_state');
}
const stored = await db.mpOAuthState.findUnique({ where: { state: input.state } });
if (!stored || stored.expiresAt.getTime() <= Date.now()) {
return failure('invalid_state');
}
const returnTo: MpReturnTo = stored.returnTo === 'onboarding' ? 'onboarding' : DEFAULT_RETURN_TO;
// Single use, and burned *before* we talk to Mercado Pago: a `count` of zero
// means someone replayed a state we already consumed.
const consumed = await db.mpOAuthState.deleteMany({ where: { state: input.state } });
if (consumed.count === 0) {
return failure('invalid_state', returnTo);
}
const exchange = this.deps.exchange ?? exchangeAuthorizationCode;
let tokens: MpTokenResponse;
try {
tokens = await exchange({
clientId: config.clientId,
clientSecret: config.clientSecret,
redirectUri: config.redirectUri,
code: input.code,
codeVerifier: stored.codeVerifier,
});
} catch (exchangeError) {
// `MpApiError` already logged the status and MP's own error code. Nothing
// added here mentions the authorization code or the verifier.
logger.error({ err: exchangeError }, 'Mercado Pago authorization could not be completed');
return err(mpProviderErrorProblem());
}
const claimed = await db.mpAccount.findUnique({ where: { mpUserId: tokens.mpUserId } });
if (claimed && claimed.ownerId !== stored.ownerId) {
return err(mpAccountInUseProblem());
}
const encrypted = {
accessTokenEnc: sealToken(tokens.accessToken),
refreshTokenEnc: sealToken(tokens.refreshToken),
expiresAt: new Date(Date.now() + tokens.expiresInSeconds * 1000),
scope: tokens.scope,
liveMode: tokens.liveMode,
status: 'ACTIVE' as const,
};
try {
await db.mpAccount.upsert({
where: { ownerId: stored.ownerId },
create: { ownerId: stored.ownerId, mpUserId: tokens.mpUserId, ...encrypted },
// Re-linking renews the credentials and clears a `requires_reauth`.
update: { mpUserId: tokens.mpUserId, ...encrypted, connectedAt: new Date() },
});
} catch (writeError) {
// Two teachers linked the same Mercado Pago id at the same time: the
// unique index is the real arbiter, not the read above.
if (isUniqueViolation(writeError)) {
return err(mpAccountInUseProblem());
}
throw writeError;
}
return ok({ returnTo, outcome: { kind: 'success' } });
}
}
function failure(
reason: MpCallbackReason,
returnTo: MpReturnTo = DEFAULT_RETURN_TO,
): Result<MpCallbackResult, ProblemDetails> {
return ok({ returnTo, outcome: { kind: 'error', reason } });
}
function isUniqueViolation(error: unknown): boolean {
return (
typeof error === 'object' &&
error !== null &&
'code' in error &&
(error as { code?: unknown }).code === UNIQUE_VIOLATION
);
}