quantictech-subscription-components
Version:
Biblioteca de componentes reutilizáveis para sistema de assinatura com Stripe - Arquitetura Service-to-Service
278 lines (277 loc) • 13 kB
JavaScript
;
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 __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatDate = exports.formatPrice = exports.verifySubscriptionStatusWithStripe = exports.reactivateSubscription = exports.cancelSubscriptionBackend = exports.cancelMySubscription = exports.apiEndpoints = void 0;
var axios_1 = __importDefault(require("axios"));
// Configuração base do axios
var api = axios_1.default.create({
timeout: 30000,
headers: {
'Content-Type': 'application/json',
},
});
// Função para obter token de autorização
var getAuthToken = function () {
if (typeof window !== 'undefined') {
return localStorage.getItem('token') || sessionStorage.getItem('token');
}
return null;
};
// Interceptor para adicionar token de autorização
api.interceptors.request.use(function (config) {
var token = getAuthToken();
if (token) {
config.headers.Authorization = "Bearer ".concat(token);
}
return config;
});
// API Endpoints
exports.apiEndpoints = {
// Assinatura
getUserSubscription: function () {
return api.get('/api/user-subscription').then(function (response) { return response.data; });
},
getPaymentHistory: function () {
return api.get('/api/payment-history').then(function (response) { return response.data; });
},
createSubscription: function (data) {
return api.post('/api/create-subscription', data).then(function (response) { return response.data; });
},
createPaymentIntent: function (data) {
return api.post('/api/create-payment-intent', data).then(function (response) { return response.data; });
},
createCheckout: function (data) {
return api.post('/api/create-checkout', data).then(function (response) { return response.data; });
},
// Status
stripeStatusCheck: function (subscriptionId) {
return api.get("/api/stripe-status-check?subscriptionId=".concat(subscriptionId)).then(function (response) { return response.data; });
},
};
// Funções de pagamento
var cancelMySubscription = function (subscriptionId_1) {
var args_1 = [];
for (var _i = 1; _i < arguments.length; _i++) {
args_1[_i - 1] = arguments[_i];
}
return __awaiter(void 0, __spreadArray([subscriptionId_1], args_1, true), void 0, function (subscriptionId, cancelAtPeriodEnd, cancellationReason, feedback) {
var response, error_1, apiError;
var _a, _b;
if (cancelAtPeriodEnd === void 0) { cancelAtPeriodEnd = true; }
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_c.trys.push([0, 2, , 3]);
console.log('🔄 Iniciando cancelamento da assinatura:', {
subscriptionId: subscriptionId,
cancelAtPeriodEnd: cancelAtPeriodEnd,
cancellationReason: cancellationReason,
feedback: feedback
});
return [4 /*yield*/, api.post('/api/cancel-subscription', {
subscriptionId: subscriptionId,
cancelAtPeriodEnd: cancelAtPeriodEnd,
cancellationReason: cancellationReason,
feedback: feedback
})];
case 1:
response = _c.sent();
console.log('✅ Resposta do cancelamento:', response.data);
return [2 /*return*/, response.data];
case 2:
error_1 = _c.sent();
apiError = error_1;
console.error('❌ Erro no cancelamento:', error_1);
return [2 /*return*/, {
success: false,
error: ((_b = (_a = apiError.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) || apiError.message || 'Erro desconhecido'
}];
case 3: return [2 /*return*/];
}
});
});
};
exports.cancelMySubscription = cancelMySubscription;
var cancelSubscriptionBackend = function (subscriptionId, cancellationReason, feedback) { return __awaiter(void 0, void 0, void 0, function () {
var response, error_2, apiError;
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_c.trys.push([0, 2, , 3]);
return [4 /*yield*/, api.post('/api/cancel-subscription', {
subscriptionId: subscriptionId,
cancelAtPeriodEnd: false, // Cancelamento imediato
cancellationReason: cancellationReason,
feedback: feedback
})];
case 1:
response = _c.sent();
return [2 /*return*/, response.data];
case 2:
error_2 = _c.sent();
apiError = error_2;
console.error('❌ Erro no cancelamento backend:', error_2);
return [2 /*return*/, {
success: false,
error: ((_b = (_a = apiError.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) || apiError.message || 'Erro desconhecido'
}];
case 3: return [2 /*return*/];
}
});
}); };
exports.cancelSubscriptionBackend = cancelSubscriptionBackend;
var reactivateSubscription = function (subscriptionId) { return __awaiter(void 0, void 0, void 0, function () {
var response, error_3, apiError;
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_c.trys.push([0, 2, , 3]);
console.log('🔄 Reativando assinatura:', subscriptionId);
return [4 /*yield*/, api.post('/api/reactivate-subscription', {
subscriptionId: subscriptionId
})];
case 1:
response = _c.sent();
console.log('✅ Resposta da reativação:', response.data);
return [2 /*return*/, response.data];
case 2:
error_3 = _c.sent();
apiError = error_3;
console.error('❌ Erro na reativação:', error_3);
return [2 /*return*/, {
success: false,
error: ((_b = (_a = apiError.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) || apiError.message || 'Erro desconhecido'
}];
case 3: return [2 /*return*/];
}
});
}); };
exports.reactivateSubscription = reactivateSubscription;
var verifySubscriptionStatusWithStripe = function (subscriptionId) { return __awaiter(void 0, void 0, void 0, function () {
var response, error_4, apiError;
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_c.trys.push([0, 2, , 3]);
console.log('🔄 Verificando status no Stripe:', subscriptionId);
return [4 /*yield*/, api.get("/api/stripe-status-check?subscriptionId=".concat(subscriptionId))];
case 1:
response = _c.sent();
console.log('✅ Status verificado:', response.data);
return [2 /*return*/, response.data];
case 2:
error_4 = _c.sent();
apiError = error_4;
console.error('❌ Erro na verificação de status:', error_4);
return [2 /*return*/, {
success: false,
error: ((_b = (_a = apiError.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) || apiError.message || 'Erro desconhecido'
}];
case 3: return [2 /*return*/];
}
});
}); };
exports.verifySubscriptionStatusWithStripe = verifySubscriptionStatusWithStripe;
// Função auxiliar para formatação de preços
var formatPrice = function (price, currency) {
if (currency === void 0) { currency = 'BRL'; }
return new Intl.NumberFormat('pt-BR', {
style: 'currency',
currency: currency.toUpperCase(),
}).format(price);
};
exports.formatPrice = formatPrice;
// Função auxiliar para formatação de datas
var formatDate = function (dateString) {
if (!dateString ||
(typeof dateString === 'object' &&
!(dateString instanceof Date) &&
Object.keys(dateString).length === 0)) {
return 'Data não disponível';
}
try {
var date = void 0;
if (dateString instanceof Date) {
date = dateString;
}
else if (typeof dateString === 'number') {
date = new Date(dateString * 1000); // Assumir timestamp Unix
}
else if (typeof dateString === 'string') {
if (dateString.includes('T') || dateString.includes('Z')) {
date = new Date(dateString);
}
else {
date = new Date(dateString);
}
}
else {
return 'Data inválida';
}
if (isNaN(date.getTime())) {
return 'Data inválida';
}
return date.toLocaleDateString('pt-BR', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
}
catch (error) {
console.error('Erro ao formatar data:', error);
return 'Data inválida';
}
};
exports.formatDate = formatDate;