UNPKG

quantictech-subscription-components

Version:

Biblioteca de componentes reutilizáveis para sistema de assinatura com Stripe - Arquitetura Service-to-Service

259 lines (258 loc) 23.5 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var jsx_runtime_1 = require("react/jsx-runtime"); var Warning_1 = __importDefault(require("@mui/icons-material/Warning")); var material_1 = require("@mui/material"); var react_1 = __importStar(require("react")); var usePayment_1 = __importDefault(require("../hooks/usePayment")); var useSubscription_1 = __importDefault(require("../hooks/useSubscription")); var paymentApi_1 = require("../utils/paymentApi"); var SubscriptionSummary = function (_a) { var _b = _a.showDetailedHistory, showDetailedHistory = _b === void 0 ? false : _b, onSubscriptionChange = _a.onSubscriptionChange; var _c = (0, useSubscription_1.default)(), subscription = _c.subscription, loading = _c.loading, error = _c.error, refetch = _c.refetch; var _d = (0, usePayment_1.default)(), payments = _d.payments, fetchPayments = _d.fetchPayments; var _e = (0, react_1.useState)(false), cancellingSubscription = _e[0], setCancellingSubscription = _e[1]; var _f = (0, react_1.useState)(false), showCancelDialog = _f[0], setShowCancelDialog = _f[1]; var _g = (0, react_1.useState)(true), cancelAtPeriodEnd = _g[0], setCancelAtPeriodEnd = _g[1]; var _h = (0, react_1.useState)(''), cancellationReason = _h[0], setCancellationReason = _h[1]; var _j = (0, react_1.useState)(''), cancellationFeedback = _j[0], setCancellationFeedback = _j[1]; var _k = (0, react_1.useState)(false), snackbarOpen = _k[0], setSnackbarOpen = _k[1]; var _l = (0, react_1.useState)(''), snackbarMessage = _l[0], setSnackbarMessage = _l[1]; var _m = (0, react_1.useState)(false), reactivatingSubscription = _m[0], setReactivatingSubscription = _m[1]; // Carregar histórico de pagamentos se necessário react_1.default.useEffect(function () { if (showDetailedHistory) { fetchPayments(); } }, [showDetailedHistory, fetchPayments]); // Função para verificar se a assinatura foi cancelada mas ainda está ativa var isScheduledForCancellation = function (subscription) { var hasCancelAt = subscription.cancelAt !== undefined && subscription.cancelAt !== null; var hasNotBeenCanceled = !subscription.canceledAt; var isActive = subscription.status === 'active'; return hasCancelAt && hasNotBeenCanceled && isActive; }; // Função para detectar cancelamento definitivo var isDefinitivelyCanceled = function (subscription) { return subscription.canceledAt !== undefined && subscription.canceledAt !== null; }; // Função para obter data de cancelamento programado var getCancellationDate = function (subscription) { if (subscription.cancelAt) { return (0, paymentApi_1.formatDate)(subscription.cancelAt); } return 'Data não disponível'; }; // Traduzir status var translateStatus = function (status) { var statusMap = { active: { label: 'Ativa', color: 'success' }, cancelled: { label: 'Cancelada', color: 'error' }, expired: { label: 'Expirada', color: 'error' }, pending: { label: 'Pendente', color: 'warning' }, authorized: { label: 'Autorizada', color: 'primary' } }; return statusMap[status] || { label: status, color: 'default' }; }; // Traduzir método de pagamento var translatePaymentMethod = function (method) { var methodMap = { credit_card: 'Cartão de Crédito', debit_card: 'Cartão de Débito', pix: 'PIX', boleto: 'Boleto Bancário', paypal: 'PayPal' }; return methodMap[method] || method; }; // Função para cancelar assinatura var handleCancelSubscription = function () { setShowCancelDialog(true); }; // Confirmar cancelamento var handleConfirmCancellation = function () { return __awaiter(void 0, void 0, void 0, function () { var result, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!(subscription === null || subscription === void 0 ? void 0 : subscription.stripeSubscriptionId)) { setSnackbarMessage('❌ ID da assinatura não encontrado'); setSnackbarOpen(true); return [2 /*return*/]; } _a.label = 1; case 1: _a.trys.push([1, 6, 7, 8]); setCancellingSubscription(true); return [4 /*yield*/, (0, paymentApi_1.cancelMySubscription)(subscription.stripeSubscriptionId, cancelAtPeriodEnd, cancellationReason, cancellationFeedback)]; case 2: result = _a.sent(); if (!result.success) return [3 /*break*/, 4]; return [4 /*yield*/, refetch()]; case 3: _a.sent(); if (onSubscriptionChange) { onSubscriptionChange(); } setSnackbarMessage('✅ ' + result.message); setSnackbarOpen(true); setShowCancelDialog(false); return [3 /*break*/, 5]; case 4: setSnackbarMessage('❌ ' + result.error); setSnackbarOpen(true); _a.label = 5; case 5: return [3 /*break*/, 8]; case 6: error_1 = _a.sent(); console.error('Erro ao cancelar assinatura:', error_1); setSnackbarMessage('❌ Erro ao cancelar assinatura'); setSnackbarOpen(true); return [3 /*break*/, 8]; case 7: setCancellingSubscription(false); return [7 /*endfinally*/]; case 8: return [2 /*return*/]; } }); }); }; // Função para reativar assinatura var handleReactivateSubscription = function () { return __awaiter(void 0, void 0, void 0, function () { var result, error_2; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!(subscription === null || subscription === void 0 ? void 0 : subscription.stripeSubscriptionId)) { setSnackbarMessage('❌ ID da assinatura não encontrado'); setSnackbarOpen(true); return [2 /*return*/]; } _a.label = 1; case 1: _a.trys.push([1, 6, 7, 8]); setReactivatingSubscription(true); return [4 /*yield*/, (0, paymentApi_1.reactivateSubscription)(subscription.stripeSubscriptionId)]; case 2: result = _a.sent(); if (!result.success) return [3 /*break*/, 4]; return [4 /*yield*/, refetch()]; case 3: _a.sent(); if (onSubscriptionChange) { onSubscriptionChange(); } setSnackbarMessage('✅ ' + result.message); setSnackbarOpen(true); return [3 /*break*/, 5]; case 4: setSnackbarMessage('❌ ' + result.error); setSnackbarOpen(true); _a.label = 5; case 5: return [3 /*break*/, 8]; case 6: error_2 = _a.sent(); console.error('Erro ao reativar assinatura:', error_2); setSnackbarMessage('❌ Erro ao reativar assinatura'); setSnackbarOpen(true); return [3 /*break*/, 8]; case 7: setReactivatingSubscription(false); return [7 /*endfinally*/]; case 8: return [2 /*return*/]; } }); }); }; if (loading) { return ((0, jsx_runtime_1.jsx)(material_1.Card, { children: (0, jsx_runtime_1.jsxs)(material_1.CardContent, { children: [(0, jsx_runtime_1.jsx)(material_1.Skeleton, { variant: "text", height: 24, width: "80%", sx: { mb: 2 } }), (0, jsx_runtime_1.jsx)(material_1.Skeleton, { variant: "text", height: 24, width: "60%", sx: { mb: 2 } }), (0, jsx_runtime_1.jsx)(material_1.Skeleton, { variant: "text", height: 24, width: "70%", sx: { mb: 2 } }), (0, jsx_runtime_1.jsx)(material_1.Skeleton, { variant: "text", height: 24, width: "50%" })] }) })); } if (error) { return ((0, jsx_runtime_1.jsxs)(material_1.Alert, { severity: "error", children: [(0, jsx_runtime_1.jsx)(material_1.AlertTitle, { children: "Erro!" }), error] })); } if (!subscription) { return ((0, jsx_runtime_1.jsx)(material_1.Card, { children: (0, jsx_runtime_1.jsx)(material_1.CardContent, { children: (0, jsx_runtime_1.jsxs)(material_1.Alert, { severity: "info", children: [(0, jsx_runtime_1.jsx)(material_1.AlertTitle, { children: "Sem assinatura ativa" }), (0, jsx_runtime_1.jsx)(material_1.Typography, { children: "Voc\u00EA ainda n\u00E3o possui uma assinatura. Assine um plano para aproveitar todos os benef\u00EDcios premium." })] }) }) })); } return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(material_1.Card, { children: (0, jsx_runtime_1.jsx)(material_1.CardContent, { children: (0, jsx_runtime_1.jsxs)(material_1.Stack, { spacing: 2, children: [(0, jsx_runtime_1.jsxs)(material_1.Box, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "h6", sx: { fontWeight: 'bold' }, children: "Sua Assinatura" }), isScheduledForCancellation(subscription) ? ((0, jsx_runtime_1.jsxs)(material_1.Box, { sx: { mt: 1 }, children: [(0, jsx_runtime_1.jsx)(material_1.Chip, { label: "Cancelada - Ativa at\u00E9 o fim do per\u00EDodo", color: "warning", size: "small", icon: (0, jsx_runtime_1.jsx)(Warning_1.default, {}), sx: { mb: 1 } }), (0, jsx_runtime_1.jsx)(material_1.Alert, { severity: "warning", sx: { mt: 1 }, children: (0, jsx_runtime_1.jsxs)(material_1.Typography, { variant: "body2", children: [(0, jsx_runtime_1.jsx)("strong", { children: "Sua assinatura ser\u00E1 cancelada" }), " em", ' ', (0, jsx_runtime_1.jsx)("strong", { children: getCancellationDate(subscription) }), ". Voc\u00EA continuar\u00E1 com acesso completo at\u00E9 esta data."] }) }), (0, jsx_runtime_1.jsx)(material_1.Box, { sx: { mt: 2 }, children: (0, jsx_runtime_1.jsx)(material_1.Button, { variant: "contained", color: "success", onClick: handleReactivateSubscription, disabled: reactivatingSubscription, startIcon: reactivatingSubscription ? (0, jsx_runtime_1.jsx)(material_1.CircularProgress, { size: 16 }) : null, sx: { mr: 1 }, children: reactivatingSubscription ? 'Reativando...' : 'Reativar Assinatura' }) })] })) : isDefinitivelyCanceled(subscription) ? ((0, jsx_runtime_1.jsxs)(material_1.Box, { sx: { mt: 1 }, children: [(0, jsx_runtime_1.jsx)(material_1.Chip, { label: "Assinatura Cancelada", color: "error", size: "small", icon: (0, jsx_runtime_1.jsx)(Warning_1.default, {}), sx: { mb: 1 } }), (0, jsx_runtime_1.jsx)(material_1.Alert, { severity: "error", sx: { mt: 1 }, children: (0, jsx_runtime_1.jsxs)(material_1.Typography, { variant: "body2", children: [(0, jsx_runtime_1.jsx)("strong", { children: "Sua assinatura foi cancelada definitivamente" }), " em", ' ', (0, jsx_runtime_1.jsx)("strong", { children: (0, paymentApi_1.formatDate)(subscription.canceledAt) }), ". Para continuar usando nossos servi\u00E7os, voc\u00EA precisa criar uma nova assinatura."] }) })] })) : ((0, jsx_runtime_1.jsx)(material_1.Chip, { label: translateStatus(subscription.status).label, color: translateStatus(subscription.status).color, size: "small", sx: { mt: 1 } }))] }), (0, jsx_runtime_1.jsx)(material_1.Divider, {}), (0, jsx_runtime_1.jsxs)(material_1.Box, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "subtitle2", sx: { fontWeight: 'medium' }, children: "Plano:" }), (0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "body1", sx: { fontWeight: 'bold' }, children: subscription.planId.name }), (0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "body2", color: "text.secondary", children: subscription.planId.description })] }), (0, jsx_runtime_1.jsxs)(material_1.Box, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "subtitle2", sx: { fontWeight: 'medium' }, children: "Valor:" }), (0, jsx_runtime_1.jsxs)(material_1.Typography, { variant: "body1", sx: { fontWeight: 'bold' }, children: [subscription.auto_recurring ? (0, paymentApi_1.formatPrice)(subscription.auto_recurring.transaction_amount, subscription.auto_recurring.currency_id) : (0, paymentApi_1.formatPrice)(subscription.planId.price, subscription.planId.currency), (0, jsx_runtime_1.jsxs)(material_1.Typography, { component: "span", variant: "body2", color: "text.secondary", children: ["/", subscription.auto_recurring ? (subscription.auto_recurring.frequency_type === 'months' ? 'mês' : 'ano') : (subscription.planId.interval === 'monthly' ? 'mês' : subscription.planId.interval === 'annual' ? 'ano' : 'único')] })] })] }), (0, jsx_runtime_1.jsxs)(material_1.Box, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "subtitle2", sx: { fontWeight: 'medium' }, children: "M\u00E9todo de Pagamento:" }), (0, jsx_runtime_1.jsxs)(material_1.Typography, { variant: "body1", children: [translatePaymentMethod(subscription.paymentMethod), subscription.cardDetails && subscription.paymentMethod === 'credit_card' && ((0, jsx_runtime_1.jsxs)(material_1.Typography, { component: "span", variant: "body2", color: "text.secondary", sx: { ml: 1 }, children: ["\u2022\u2022\u2022\u2022 ", subscription.cardDetails.lastFourDigits || '****', subscription.cardDetails.brand && " (".concat(subscription.cardDetails.brand, ")")] }))] })] }), (0, jsx_runtime_1.jsxs)(material_1.Box, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "subtitle2", sx: { fontWeight: 'medium' }, children: "Data de In\u00EDcio:" }), (0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "body1", children: subscription.startDate ? (0, paymentApi_1.formatDate)(subscription.startDate) : 'Data não disponível' })] }), (0, jsx_runtime_1.jsxs)(material_1.Box, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "subtitle2", sx: { fontWeight: 'medium' }, children: "Data de T\u00E9rmino:" }), (0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "body1", children: subscription.endDate ? (0, paymentApi_1.formatDate)(subscription.endDate) : 'Data não disponível' })] }), showDetailedHistory && payments.length > 0 && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(material_1.Divider, { sx: { my: 1 } }), (0, jsx_runtime_1.jsxs)(material_1.Box, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "h6", sx: { fontWeight: 'bold', mb: 1 }, children: "Hist\u00F3rico de Pagamentos" }), (0, jsx_runtime_1.jsx)(material_1.Stack, { spacing: 2, children: payments.map(function (payment) { return ((0, jsx_runtime_1.jsxs)(material_1.Box, { sx: { p: 2, border: '1px solid', borderColor: 'divider', borderRadius: 1, position: 'relative' }, children: [(0, jsx_runtime_1.jsx)(material_1.Chip, { label: translateStatus(payment.status).label, color: translateStatus(payment.status).color, size: "small", sx: { position: 'absolute', top: 8, right: 8 } }), (0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "body1", sx: { fontWeight: 'medium', mt: 1 }, children: (0, paymentApi_1.formatPrice)(payment.amount, payment.currency) }), (0, jsx_runtime_1.jsxs)(material_1.Typography, { variant: "body2", color: "text.secondary", children: [translatePaymentMethod(payment.paymentMethod), " \u2022 ", (0, paymentApi_1.formatDate)(payment.createdAt)] })] }, payment._id)); }) })] })] })), subscription.status === 'active' && !isScheduledForCancellation(subscription) && ((0, jsx_runtime_1.jsx)(material_1.Box, { sx: { display: 'flex', gap: 2, mt: 2 }, children: (0, jsx_runtime_1.jsx)(material_1.Button, { variant: "outlined", color: "error", onClick: handleCancelSubscription, disabled: cancellingSubscription, children: cancellingSubscription ? 'Cancelando...' : 'Cancelar Assinatura' }) }))] }) }) }), (0, jsx_runtime_1.jsxs)(material_1.Dialog, { open: showCancelDialog, onClose: function () { return setShowCancelDialog(false); }, maxWidth: "md", fullWidth: true, children: [(0, jsx_runtime_1.jsx)(material_1.DialogTitle, { children: "Cancelar Assinatura" }), (0, jsx_runtime_1.jsx)(material_1.DialogContent, { children: (0, jsx_runtime_1.jsxs)(material_1.Stack, { spacing: 3, sx: { mt: 1 }, children: [(0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "body1", children: "Sentimos muito que voc\u00EA queira cancelar sua assinatura. Escolha como gostaria de cancelar:" }), (0, jsx_runtime_1.jsxs)(material_1.FormControl, { component: "fieldset", children: [(0, jsx_runtime_1.jsx)(material_1.FormLabel, { component: "legend", sx: { fontWeight: 'bold', mb: 2 }, children: "Tipo de Cancelamento" }), (0, jsx_runtime_1.jsxs)(material_1.RadioGroup, { value: cancelAtPeriodEnd ? 'period_end' : 'immediately', onChange: function (e) { return setCancelAtPeriodEnd(e.target.value === 'period_end'); }, children: [(0, jsx_runtime_1.jsx)(material_1.FormControlLabel, { value: "period_end", control: (0, jsx_runtime_1.jsx)(material_1.Radio, { color: "success" }), label: "Cancelar no final do per\u00EDodo (Recomendado)" }), (0, jsx_runtime_1.jsx)(material_1.FormControlLabel, { value: "immediately", control: (0, jsx_runtime_1.jsx)(material_1.Radio, { color: "error" }), label: "Cancelar imediatamente" })] })] }), (0, jsx_runtime_1.jsx)(material_1.TextField, { label: "Motivo do cancelamento (opcional)", multiline: true, rows: 3, value: cancellationFeedback, onChange: function (e) { return setCancellationFeedback(e.target.value); }, fullWidth: true })] }) }), (0, jsx_runtime_1.jsxs)(material_1.DialogActions, { children: [(0, jsx_runtime_1.jsx)(material_1.Button, { onClick: function () { return setShowCancelDialog(false); }, children: "Manter Assinatura" }), (0, jsx_runtime_1.jsx)(material_1.Button, { onClick: handleConfirmCancellation, color: "error", disabled: cancellingSubscription, children: cancellingSubscription ? 'Cancelando...' : 'Confirmar Cancelamento' })] })] }), (0, jsx_runtime_1.jsx)(material_1.Snackbar, { open: snackbarOpen, autoHideDuration: 6000, onClose: function () { return setSnackbarOpen(false); }, message: snackbarMessage })] })); }; exports.default = SubscriptionSummary;