feat: abonelik iptal ekranı (ayrılma nedeni + açıklama) & gerçek abonelik rozeti (yönetici erişimi aboneliği gizlemesin)

This commit is contained in:
2026-08-29 21:47:58 +03:00
parent 5d502c8ae4
commit 65997055fe
8 changed files with 261 additions and 7 deletions
+42
View File
@@ -187,3 +187,45 @@ export async function createCheckoutSession({ planId, email, periyot = 'yillik'
if (!res.ok) throw new Error(data?.error?.message || `Stripe hatası: HTTP ${res.status}`); if (!res.ok) throw new Error(data?.error?.message || `Stripe hatası: HTTP ${res.status}`);
return { url: data.url, id: data.id }; return { url: data.url, id: data.id };
} }
/** Ayrılma nedeni seçenekleri — arayüz ve Stripe aynı listeyi kullanır. */
export const IPTAL_NEDENLERI = [
{ id: 'too_expensive', label: 'Fiyat bütçemize uygun değil' },
{ id: 'missing_features', label: 'İhtiyacım olan özellik yok' },
{ id: 'switched_service', label: 'Başka bir hizmete geçtim' },
{ id: 'unused', label: 'Yeterince kullanmıyorum' },
{ id: 'too_complex', label: 'Kullanımı karmaşık geldi' },
{ id: 'low_quality', label: 'Veri/sonuç kalitesi beklentimi karşılamadı' },
{ id: 'customer_service', label: 'Destekten memnun kalmadım' },
{ id: 'other', label: 'Diğer' },
];
/**
* Aboneliği dönem sonunda iptal eder (erişim ödenen sürenin sonuna kadar sürer)
* ve ayrılma nedenini Stripe'a işler.
*/
export async function cancelSubscription({ subId, neden, aciklama }) {
const key = process.env.STRIPE_SECRET_KEY;
if (!key) throw new Error('Ödeme yapılandırılmamış (STRIPE_SECRET_KEY yok)');
if (!subId) throw new Error('İptal edilecek abonelik bulunamadı');
const govde = { cancel_at_period_end: 'true' };
if (IPTAL_NEDENLERI.some((n) => n.id === neden)) {
govde['cancellation_details[feedback]'] = neden;
}
const not = String(aciklama || '').trim().slice(0, 500);
if (not) govde['cancellation_details[comment]'] = not;
const res = await fetch(`https://api.stripe.com/v1/subscriptions/${encodeURIComponent(subId)}`, {
method: 'POST',
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/x-www-form-urlencoded' },
body: formEncode(govde),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data?.error?.message || `Stripe hatası: HTTP ${res.status}`);
return {
id: data.id,
donemSonunda: Boolean(data.cancel_at_period_end),
bitis: data.cancel_at ? new Date(data.cancel_at * 1000).toISOString() : null,
};
}
+10
View File
@@ -62,9 +62,19 @@ export function kullanim(email, opts) {
const belge = documentUsage(email); const belge = documentUsage(email);
const ekip = (getData(email, 'ekip') || []).length; const ekip = (getData(email, 'ekip') || []).length;
const takip = (getData(email, 'kanban') || []).filter?.((t) => t?.takipte)?.length ?? null; const takip = (getData(email, 'kanban') || []).filter?.((t) => t?.takipte)?.length ?? null;
// Yönetici hesapları her zaman tam erişimlidir; bu, satın alınan aboneliği
// GİZLEMEMELİ — arayüz ikisini ayrı gösterebilsin diye ikisini de döndürüyoruz.
const u = getUser(email);
const abonelik = u && PLAN_HAKLARI[u.plan] && !(u.plan_bitis && new Date(u.plan_bitis) < new Date())
? u.plan : 'ucretsiz';
return { return {
plan: planOf(email, opts), plan: planOf(email, opts),
planAdi: h.ad, planAdi: h.ad,
yonetici: Boolean(opts?.isAdmin),
abonelik, // gerçekten satın alınan plan
abonelikAdi: PLAN_HAKLARI[abonelik]?.ad || 'Ücretsiz',
abonelikVar: abonelik !== 'ucretsiz',
iptalEdilebilir: Boolean(u?.stripe_sub_id) && abonelik !== 'ucretsiz',
haklar: h, haklar: h,
kullanilan: { kullanilan: {
belgeAdet: belge.adet, belgeAdet: belge.adet,
+24 -2
View File
@@ -20,7 +20,7 @@ import { readDtTenders } from './dt-store.mjs';
import { loginWithGoogle, userFromAuthHeader } from './auth.mjs'; import { loginWithGoogle, userFromAuthHeader } from './auth.mjs';
import { emailConfigured, sendEmail, tenderDigestHtml, emailFrom } from './email.mjs'; import { emailConfigured, sendEmail, tenderDigestHtml, emailFrom } from './email.mjs';
import { aiConfigured, availableProviders, analyzeSpec } from './ai.mjs'; import { aiConfigured, availableProviders, analyzeSpec } from './ai.mjs';
import { billingConfigured, webhookConfigured, planCatalog, createCheckoutSession, verifyWebhook, planForPrice } from './billing.mjs'; import { billingConfigured, webhookConfigured, planCatalog, createCheckoutSession, verifyWebhook, planForPrice, cancelSubscription, IPTAL_NEDENLERI } from './billing.mjs';
import * as store from './user-store.mjs'; import * as store from './user-store.mjs';
import { planOf, haklar, kullanim, kotaKontrol, ozellikVar } from './entitlements.mjs'; import { planOf, haklar, kullanim, kotaKontrol, ozellikVar } from './entitlements.mjs';
import { searchTed } from './ted.mjs'; import { searchTed } from './ted.mjs';
@@ -679,6 +679,28 @@ const server = http.createServer(async (req, res) => {
// --- Stripe webhook (imza doğrulamalı) --- // --- Stripe webhook (imza doğrulamalı) ---
// NOT: Bu uç kimlik doğrulaması İSTEMEZ; güvenlik imza doğrulamasıyla sağlanır. // NOT: Bu uç kimlik doğrulaması İSTEMEZ; güvenlik imza doğrulamasıyla sağlanır.
if (url.pathname === '/api/billing/cancel' && req.method === 'POST') {
const user = userFromAuthHeader(req.headers['authorization']);
if (!user) return json(res, 401, { success: false, error: 'oturum yok' });
const kayit = store.getUser(user.email);
const subId = kayit?.stripe_sub_id;
if (!subId) return json(res, 400, { success: false, error: 'Aktif bir aboneliğiniz görünmüyor.' });
const body = await readJson(req);
try {
const out = await cancelSubscription({ subId, neden: body.neden, aciklama: body.aciklama });
// Neden kaydı: ürün kararları için kendi tarafımızda da tutulur.
store.setData(user.email, 'iptal_geri_bildirim', {
neden: body.neden || null,
aciklama: String(body.aciklama || '').slice(0, 500),
tarih: new Date().toISOString(),
});
console.log(`[billing] ${user.email} aboneliğini iptal etti (neden: ${body.neden || 'belirtilmedi'})`);
return json(res, 200, { success: true, ...out });
} catch (e) {
return json(res, 502, { success: false, error: e.message });
}
}
if (url.pathname === '/api/billing/webhook' && req.method === 'POST') { if (url.pathname === '/api/billing/webhook' && req.method === 'POST') {
if (!webhookConfigured()) { if (!webhookConfigured()) {
return json(res, 503, { success: false, error: 'STRIPE_WEBHOOK_SECRET tanımlı değil' }); return json(res, 503, { success: false, error: 'STRIPE_WEBHOOK_SECRET tanımlı değil' });
@@ -750,7 +772,7 @@ const server = http.createServer(async (req, res) => {
// --- Abonelik / ödeme --- // --- Abonelik / ödeme ---
if (url.pathname === '/api/billing/plans') { if (url.pathname === '/api/billing/plans') {
return json(res, 200, { configured: billingConfigured(), webhookHazir: webhookConfigured(), plans: planCatalog() }); return json(res, 200, { configured: billingConfigured(), webhookHazir: webhookConfigured(), plans: planCatalog(), iptalNedenleri: IPTAL_NEDENLERI });
} }
if (url.pathname === '/api/billing/checkout' && req.method === 'POST') { if (url.pathname === '/api/billing/checkout' && req.method === 'POST') {
const user = userFromAuthHeader(req.headers['authorization']); const user = userFromAuthHeader(req.headers['authorization']);
+1
View File
@@ -142,6 +142,7 @@ export function findByStripe({ customerId, subId }) {
const IZINLI_ANAHTARLAR = new Set([ const IZINLI_ANAHTARLAR = new Set([
'favori_kurumlar', 'ekip', 'saved_filters', 'reminder', 'favori_kurumlar', 'ekip', 'saved_filters', 'reminder',
'rakip_izleme', 'ciro_hedefi', 'ai_model_config', 'kanban', 'rakip_izleme', 'ciro_hedefi', 'ai_model_config', 'kanban',
'iptal_geri_bildirim',
]); ]);
export function getData(email, anahtar) { export function getData(email, anahtar) {
+119
View File
@@ -0,0 +1,119 @@
import React, { useState } from 'react';
import { X, AlertTriangle, Loader2 } from 'lucide-react';
import { cancelSubscription } from '../services/account';
/**
* Abonelik iptali — nedeni sorar, dönem sonunda iptal eder.
* Erişim ödenen sürenin sonuna kadar sürer; anında kesilmez.
*/
export const CancelSubscriptionModal = ({ planAdi, nedenler = [], onKapat, onIptalEdildi }) => {
const [neden, setNeden] = useState('');
const [aciklama, setAciklama] = useState('');
const [busy, setBusy] = useState(false);
const [hata, setHata] = useState(null);
// "Diğer" seçildiyse açıklama zorunlu — yoksa geri bildirim işe yaramaz.
const digerSecili = neden === 'other';
const gonderilebilir = Boolean(neden) && (!digerSecili || aciklama.trim().length >= 3);
const gonder = async () => {
setBusy(true);
setHata(null);
try {
const out = await cancelSubscription(neden, aciklama.trim());
onIptalEdildi(out);
} catch (e) {
setHata(e.message || 'İptal edilemedi');
} finally {
setBusy(false);
}
};
return (
<div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4">
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
<div className="flex items-start justify-between gap-3 p-5 border-b border-slate-100">
<div className="flex gap-3">
<div className="w-10 h-10 rounded-xl bg-amber-100 flex items-center justify-center shrink-0">
<AlertTriangle className="w-5 h-5 text-amber-700" />
</div>
<div>
<h3 className="font-black text-slate-900">Aboneliği iptal et</h3>
<p className="text-xs text-slate-500 mt-0.5">
{planAdi} planınız <strong>dönem sonunda</strong> sona erer. Ödediğiniz sürenin sonuna
kadar tüm özellikler açık kalır, yenileme yapılmaz.
</p>
</div>
</div>
<button onClick={onKapat} className="text-slate-400 hover:text-slate-700 shrink-0" aria-label="Kapat">
<X className="w-5 h-5" />
</button>
</div>
<div className="p-5 space-y-4">
<div>
<p className="text-xs font-bold text-slate-700 mb-2">Ayrılma nedeniniz nedir? <span className="text-red-500">*</span></p>
<div className="space-y-1.5">
{nedenler.map((n) => (
<label
key={n.id}
className={`flex items-center gap-2.5 px-3 py-2 rounded-lg border cursor-pointer text-xs transition-colors ${
neden === n.id
? 'border-blue-500 bg-blue-50 text-blue-900 font-semibold'
: 'border-slate-200 hover:bg-slate-50 text-slate-700'
}`}
>
<input
type="radio"
name="iptal-neden"
value={n.id}
checked={neden === n.id}
onChange={() => setNeden(n.id)}
className="accent-blue-600"
/>
<span>{n.label}</span>
</label>
))}
</div>
</div>
<div>
<label className="text-xs font-bold text-slate-700 block mb-1.5">
Biraz daha anlatır mısınız? {digerSecili ? <span className="text-red-500">*</span> : <span className="font-normal text-slate-400">(isteğe bağlı)</span>}
</label>
<textarea
rows={3}
value={aciklama}
maxLength={500}
onChange={(e) => setAciklama(e.target.value)}
placeholder="Neyi eksik bulduğunuzu yazarsanız düzeltiriz."
className="w-full border border-slate-200 rounded-lg px-3 py-2 text-xs focus:outline-hidden focus:ring-2 focus:ring-blue-500/30 focus:border-blue-400"
/>
<p className="text-[10px] text-slate-400 mt-1 text-right">{aciklama.length}/500</p>
</div>
{hata && (
<div className="bg-red-50 border border-red-200 rounded-lg p-3 text-xs text-red-800">{hata}</div>
)}
</div>
<div className="flex gap-2 p-5 border-t border-slate-100">
<button
onClick={onKapat}
className="flex-1 py-2.5 rounded-xl text-xs font-bold text-slate-700 bg-slate-100 hover:bg-slate-200 transition-colors"
>
Vazgeç, kalıyorum
</button>
<button
onClick={gonder}
disabled={!gonderilebilir || busy}
className="flex-1 py-2.5 rounded-xl text-xs font-extrabold text-white bg-red-600 hover:bg-red-500 transition-colors disabled:opacity-40 disabled:cursor-not-allowed flex items-center justify-center gap-2"
>
{busy && <Loader2 className="w-4 h-4 animate-spin" />}
{busy ? 'İptal ediliyor…' : 'Aboneliği iptal et'}
</button>
</div>
</div>
</div>
);
};
+3 -3
View File
@@ -21,9 +21,9 @@ export const Header = () => {
handleLogout handleLogout
} = useApp(); } = useApp();
// Plan rozeti gerçek /api/me/plan yanıtından gelir (uydurma "7 gün kalan" değil). // Rozet SATIN ALINAN aboneliği gösterir. Yönetici hesapları her özelliğe
const PLAN_ADLARI = { ucretsiz: 'Ücretsiz', pro: 'Pro', kurumsal: 'Kurumsal' }; // erişir ama bu bir abonelik değildir; ikisini karıştırmamak için ayrı yazılır.
const planAdi = PLAN_ADLARI[plan?.plan] || 'Ücretsiz'; const planAdi = plan?.abonelikVar ? plan.abonelikAdi : (plan?.yonetici ? 'Yönetici' : 'Ücretsiz');
const [showNotifications, setShowNotifications] = useState(false); const [showNotifications, setShowNotifications] = useState(false);
const [showUserMenu, setShowUserMenu] = useState(false); const [showUserMenu, setShowUserMenu] = useState(false);
+58 -2
View File
@@ -1,14 +1,17 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { useApp } from '../../context/AppContext'; import { useApp } from '../../context/AppContext';
import { getToken } from '../../services/auth'; import { getToken } from '../../services/auth';
import { Check, Sparkles, CreditCard, Loader2, Info } from 'lucide-react'; import { Check, Sparkles, CreditCard, Loader2, Info, ShieldCheck, XCircle } from 'lucide-react';
import { CancelSubscriptionModal } from '../CancelSubscriptionModal';
export const Pricing = () => { export const Pricing = () => {
const { authUser } = useApp(); const { authUser, plan, planYenile } = useApp();
const [data, setData] = useState(null); const [data, setData] = useState(null);
const [busy, setBusy] = useState(null); const [busy, setBusy] = useState(null);
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [yillik, setYillik] = useState(true); // yıllık varsayılan (indirimli) const [yillik, setYillik] = useState(true); // yıllık varsayılan (indirimli)
const [iptalAcik, setIptalAcik] = useState(false);
const [iptalSonuc, setIptalSonuc] = useState(null);
useEffect(() => { useEffect(() => {
fetch('/api/billing/plans') fetch('/api/billing/plans')
@@ -83,6 +86,50 @@ export const Pricing = () => {
</div> </div>
)} )}
{/* Mevcut abonelik — gerçek /api/me/plan verisi */}
{plan && (
<div className="bg-white border border-slate-200 rounded-2xl p-5 shadow-xs">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-emerald-50 border border-emerald-200 flex items-center justify-center">
<ShieldCheck className="w-5 h-5 text-emerald-600" />
</div>
<div>
<p className="text-xs text-slate-500">Mevcut aboneliğiniz</p>
<p className="font-black text-slate-900">
{plan.abonelikVar ? plan.abonelikAdi : 'Ücretsiz'}
{plan.yonetici && (
<span className="ml-2 text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-indigo-50 text-indigo-700 border border-indigo-200">
yönetici erişimi: {plan.planAdi}
</span>
)}
</p>
</div>
</div>
{plan.iptalEdilebilir && (
<button
onClick={() => setIptalAcik(true)}
className="text-xs font-bold text-red-600 hover:text-red-700 hover:bg-red-50 border border-red-200 px-3 py-2 rounded-xl flex items-center gap-1.5 transition-colors"
>
<XCircle className="w-4 h-4" /> Aboneliği iptal et
</button>
)}
</div>
{plan.yonetici && (
<p className="text-[11px] text-slate-400 mt-2 leading-relaxed">
Yönetici hesapları tüm özelliklere erişir; bu, satın aldığınız aboneliğin yerine geçmez.
</p>
)}
{iptalSonuc && (
<div className="mt-3 bg-amber-50 border border-amber-200 rounded-xl p-3 text-xs text-amber-900">
Aboneliğiniz iptal edildi. Erişiminiz{' '}
<strong>{iptalSonuc.bitis ? new Date(iptalSonuc.bitis).toLocaleDateString('tr-TR') : 'dönem sonuna'}</strong>{' '}
kadar açık kalacak, sonrasında yenileme yapılmayacak.
</div>
)}
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-3 gap-5"> <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
{plans.map((p) => ( {plans.map((p) => (
<div <div
@@ -152,6 +199,15 @@ export const Pricing = () => {
))} ))}
</div> </div>
{iptalAcik && (
<CancelSubscriptionModal
planAdi={plan?.abonelikAdi || 'Mevcut'}
nedenler={data?.iptalNedenleri || []}
onKapat={() => setIptalAcik(false)}
onIptalEdildi={(out) => { setIptalAcik(false); setIptalSonuc(out); planYenile(); }}
/>
)}
<p className="text-[11px] text-slate-400 text-center leading-relaxed max-w-2xl mx-auto"> <p className="text-[11px] text-slate-400 text-center leading-relaxed max-w-2xl mx-auto">
Ödemeler Stripe üzerinden güvenli şekilde alınır; kart bilgileriniz İhaleist sunucularında saklanmaz. Ödemeler Stripe üzerinden güvenli şekilde alınır; kart bilgileriniz İhaleist sunucularında saklanmaz.
Aboneliğinizi istediğiniz zaman iptal edebilirsiniz. Aboneliğinizi istediğiniz zaman iptal edebilirsiniz.
+4
View File
@@ -74,3 +74,7 @@ export function formatBayt(b) {
if (b < 1024 * 1024 * 1024) return `${(b / 1024 / 1024).toFixed(1)} MB`; if (b < 1024 * 1024 * 1024) return `${(b / 1024 / 1024).toFixed(1)} MB`;
return `${(b / 1024 / 1024 / 1024).toFixed(2)} GB`; return `${(b / 1024 / 1024 / 1024).toFixed(2)} GB`;
} }
// --- Abonelik iptali ---
export const cancelSubscription = (neden, aciklama) =>
iste('/api/billing/cancel', { method: 'POST', body: JSON.stringify({ neden, aciklama }) });