feat(yonetim): üyeleri görme ve elle kredi tanımlama paneli (S-017)
All checks were successful
Deploy / deploy (push) Successful in 11m10s
All checks were successful
Deploy / deploy (push) Successful in 11m10s
/yonetim yalnız ADMIN_EMAILS'teki hesaba açılır (varsayılan yok; tanımsızsa kimseye açılmaz). Üye listesi, arama, özet şeridi ve kredi ekle/düş çekmecesi. Hareket credit_ledger'a admin_grant nedeniyle, ref_id'de yönetici kimliğiyle yazılır; bakiye sıfırın altına inmez, çift gönderim UNIQUE(reason, ref_id) ile durur. Sayfa Rybbit'ten çıkarıldı (arama e-postası analitiğe gitmesin). Öğrenciye görünmediği için sürüm artmadı. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
34
src/app/yonetim/page.tsx
Normal file
34
src/app/yonetim/page.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Suspense } from "react";
|
||||
import type { Metadata } from "next";
|
||||
import {
|
||||
YonetimIcerik,
|
||||
YonetimIcerikSkeleton,
|
||||
} from "@/features/yonetim/components/yonetim-icerik";
|
||||
|
||||
// Yönetim paneli (S-017). Yalnız ADMIN_EMAILS'teki hesaba açılır; diğer
|
||||
// herkes 404 görür. Arama motoruna kapalı. Başlık bilerek yok: 404 gören
|
||||
// ziyaretçinin sekmesinde "Yönetim" yazıp sayfanın varlığını ele vermesin.
|
||||
export const metadata: Metadata = {
|
||||
robots: { index: false, follow: false },
|
||||
};
|
||||
|
||||
export default function YonetimPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ ara?: string | string[]; sayfa?: string | string[] }>;
|
||||
}) {
|
||||
return (
|
||||
<Suspense fallback={<YonetimIcerikSkeleton />}>
|
||||
{searchParams.then(({ ara, sayfa }) => {
|
||||
const araTek = (Array.isArray(ara) ? ara[0] : ara)?.trim().slice(0, 100);
|
||||
const n = Number(Array.isArray(sayfa) ? sayfa[0] : sayfa);
|
||||
return (
|
||||
<YonetimIcerik
|
||||
ara={araTek || undefined}
|
||||
sayfa={Number.isInteger(n) && n > 0 ? n : 1}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -33,6 +33,9 @@ export function RybbitYukleyici() {
|
||||
src="https://rybbit.kolaytercih.com/api/script.js"
|
||||
data-site-id="f2cb042c657e"
|
||||
data-mask-patterns='["/sonuc", "/odeme/sonuc"]'
|
||||
// Yönetim paneli (S-017) hiç ölçülmez: üye araması adres çubuğuna
|
||||
// e-posta yazar, analitiğe gitmemeli (gizlilik metni).
|
||||
data-skip-patterns='["/yonetim", "/yonetim/**"]'
|
||||
strategy="afterInteractive"
|
||||
/>
|
||||
);
|
||||
|
||||
15
src/features/yonetim/components/eposta-metni.tsx
Normal file
15
src/features/yonetim/components/eposta-metni.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* E-postayı satıra sığmazsa "@" işaretinden böler ("ad.soyad" / "@alan.com");
|
||||
* yine sığmazsa herhangi bir yerden (overflow-wrap: anywhere).
|
||||
*/
|
||||
export function EpostaMetni({ eposta }: { eposta: string }) {
|
||||
const i = eposta.lastIndexOf("@");
|
||||
if (i <= 0) return <>{eposta}</>;
|
||||
return (
|
||||
<>
|
||||
{eposta.slice(0, i)}
|
||||
<wbr />
|
||||
{eposta.slice(i)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
194
src/features/yonetim/components/kredi-cekmecesi.tsx
Normal file
194
src/features/yonetim/components/kredi-cekmecesi.tsx
Normal file
@@ -0,0 +1,194 @@
|
||||
"use client";
|
||||
|
||||
// Yönetim paneli (S-017): bir üyeye kredi ekleme/düşme çekmecesi. Kabuk ve
|
||||
// çarpı DESIGN.md §4.10 / §4.3 (cta-sira-form.tsx'teki çekmeceyle birebir).
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { X } from "lucide-react";
|
||||
import {
|
||||
AltSayfa,
|
||||
AltSayfaAciklama,
|
||||
AltSayfaBaslik,
|
||||
AltSayfaGovde,
|
||||
AltSayfaIcerik,
|
||||
AltSayfaKapat,
|
||||
} from "@/components/ui/alt-sayfa";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { SecimHaplari } from "@/components/ui/secim-haplari";
|
||||
import { toast } from "@/components/ui/bildirim";
|
||||
import { krediTanimla } from "../yonetim-actions";
|
||||
import { EpostaMetni } from "./eposta-metni";
|
||||
|
||||
type Yon = "ekle" | "dus";
|
||||
|
||||
const YONLER = [
|
||||
{ deger: "ekle", etiket: "Ekle" },
|
||||
{ deger: "dus", etiket: "Düş" },
|
||||
] as const;
|
||||
|
||||
const HAZIR = [
|
||||
{ deger: "3", etiket: "3" },
|
||||
{ deger: "5", etiket: "5" },
|
||||
{ deger: "10", etiket: "10" },
|
||||
{ deger: "30", etiket: "30" },
|
||||
{ deger: "60", etiket: "60" },
|
||||
] as const;
|
||||
|
||||
export function KrediCekmecesi({
|
||||
userId,
|
||||
email,
|
||||
bakiye,
|
||||
}: {
|
||||
userId: string;
|
||||
email: string;
|
||||
bakiye: number;
|
||||
}) {
|
||||
const [acik, setAcik] = useState(false);
|
||||
const [yon, setYon] = useState<Yon>("ekle");
|
||||
const [miktarMetni, setMiktarMetni] = useState("5");
|
||||
const [hata, setHata] = useState<string | null>(null);
|
||||
// Her açılışta yeni istek kimliği: aynı form iki kez gönderilse de deftere
|
||||
// bir kez yazılır (sunucuda UNIQUE(reason, ref_id)).
|
||||
const [istekId, setIstekId] = useState(() => crypto.randomUUID());
|
||||
const [bekliyor, startTransition] = useTransition();
|
||||
|
||||
const miktar = Number(miktarMetni);
|
||||
const gecerli = Number.isInteger(miktar) && miktar > 0 && miktar <= 1000;
|
||||
const yeniBakiye = gecerli ? bakiye + (yon === "ekle" ? miktar : -miktar) : bakiye;
|
||||
const eksiyeDuser = yeniBakiye < 0;
|
||||
|
||||
function acikDegisti(a: boolean) {
|
||||
setAcik(a);
|
||||
if (a) {
|
||||
setYon("ekle");
|
||||
setMiktarMetni("5");
|
||||
setHata(null);
|
||||
setIstekId(crypto.randomUUID());
|
||||
}
|
||||
}
|
||||
|
||||
function gonder(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!gecerli) {
|
||||
setHata("1 ile 1000 arasında bir tam sayı yaz.");
|
||||
return;
|
||||
}
|
||||
if (eksiyeDuser) {
|
||||
setHata(`Bakiye ${bakiye}; en çok ${bakiye} kredi düşebilirsin.`);
|
||||
return;
|
||||
}
|
||||
setHata(null);
|
||||
const delta = yon === "ekle" ? miktar : -miktar;
|
||||
startTransition(async () => {
|
||||
const sonuc = await krediTanimla(userId, delta, istekId);
|
||||
if (!sonuc.ok) {
|
||||
setHata(sonuc.hata);
|
||||
return;
|
||||
}
|
||||
toast.success(
|
||||
yon === "ekle" ? `${miktar} kredi eklendi` : `${miktar} kredi düşüldü`,
|
||||
{ description: `${email} · yeni bakiye ${sonuc.yeniBakiye}` },
|
||||
);
|
||||
setAcik(false);
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ikincil"
|
||||
onClick={() => acikDegisti(true)}
|
||||
aria-label={`${email} için kredi tanımla`}
|
||||
>
|
||||
Kredi
|
||||
</Button>
|
||||
<AltSayfa open={acik} onOpenChange={acikDegisti}>
|
||||
<AltSayfaIcerik>
|
||||
<AltSayfaKapat className="absolute top-3 right-3 z-10 flex size-9 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-popover text-slate-500 transition-[background-color,transform] duration-150 hover:bg-slate-100 hover:text-slate-800 active:scale-[0.96]">
|
||||
<X className="size-4" aria-hidden />
|
||||
<span className="sr-only">Kapat</span>
|
||||
</AltSayfaKapat>
|
||||
|
||||
<AltSayfaGovde className="px-4 pt-3 pb-[max(1.25rem,env(safe-area-inset-bottom))] sm:px-6">
|
||||
<AltSayfaBaslik className="px-10 text-center font-heading text-2xl font-bold text-slate-900 [overflow-wrap:anywhere]">
|
||||
<EpostaMetni eposta={email} />
|
||||
</AltSayfaBaslik>
|
||||
<AltSayfaAciklama className="mx-auto mt-1 max-w-md px-4 text-center text-sm text-slate-500">
|
||||
Şu anki bakiye {bakiye} kredi. Hareket deftere yazılır.
|
||||
</AltSayfaAciklama>
|
||||
|
||||
<form onSubmit={gonder} className="mx-auto mt-6 flex max-w-md flex-col gap-6">
|
||||
<SecimHaplari
|
||||
secenekler={YONLER}
|
||||
deger={yon}
|
||||
onChange={(d) => setYon(d)}
|
||||
ariaLabel="Kredi ekle ya da düş"
|
||||
varyant="ayrik"
|
||||
className="justify-center"
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<SecimHaplari
|
||||
secenekler={HAZIR}
|
||||
deger={HAZIR.some((h) => h.deger === miktarMetni) ? (miktarMetni as (typeof HAZIR)[number]["deger"]) : null}
|
||||
onChange={(d) => setMiktarMetni(d)}
|
||||
ariaLabel="Hazır miktar"
|
||||
varyant="ayrik"
|
||||
boyut="sm"
|
||||
className="justify-center"
|
||||
/>
|
||||
<label htmlFor={`miktar-${userId}`} className="sr-only">
|
||||
Miktar
|
||||
</label>
|
||||
<Input
|
||||
id={`miktar-${userId}`}
|
||||
inputMode="numeric"
|
||||
pattern="[0-9]*"
|
||||
value={miktarMetni}
|
||||
onChange={(e) => setMiktarMetni(e.target.value.replace(/\D/g, ""))}
|
||||
aria-invalid={hata ? true : undefined}
|
||||
aria-describedby={hata ? `miktar-hata-${userId}` : undefined}
|
||||
className="text-center"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p className="text-center text-sm text-slate-500">
|
||||
Yeni bakiye{" "}
|
||||
<span className={eksiyeDuser ? "font-semibold text-red-600" : "font-semibold text-slate-900"}>
|
||||
{yeniBakiye}
|
||||
</span>{" "}
|
||||
kredi
|
||||
</p>
|
||||
|
||||
{hata ? (
|
||||
<p
|
||||
id={`miktar-hata-${userId}`}
|
||||
role="alert"
|
||||
className="text-center text-sm font-medium text-red-600"
|
||||
>
|
||||
{hata}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
size="lg"
|
||||
variant="cta"
|
||||
disabled={bekliyor || !gecerli || eksiyeDuser}
|
||||
className="w-full"
|
||||
>
|
||||
{bekliyor
|
||||
? "Kaydediliyor…"
|
||||
: yon === "ekle"
|
||||
? `${gecerli ? miktar : ""} kredi ekle`
|
||||
: `${gecerli ? miktar : ""} kredi düş`}
|
||||
</Button>
|
||||
</form>
|
||||
</AltSayfaGovde>
|
||||
</AltSayfaIcerik>
|
||||
</AltSayfa>
|
||||
</>
|
||||
);
|
||||
}
|
||||
32
src/features/yonetim/components/uye-sayfalama.tsx
Normal file
32
src/features/yonetim/components/uye-sayfalama.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Sayfalama } from "@/components/ui/sayfalama";
|
||||
|
||||
/** Üye listesinin sayfalaması: arama sorgusunu koruyarak ?sayfa=N'e gider. */
|
||||
export function UyeSayfalama({
|
||||
sayfa,
|
||||
toplamSayfa,
|
||||
ara,
|
||||
}: {
|
||||
sayfa: number;
|
||||
toplamSayfa: number;
|
||||
ara?: string;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
return (
|
||||
<Sayfalama
|
||||
tabanYol="/yonetim"
|
||||
sayfa={sayfa}
|
||||
toplamSayfa={toplamSayfa}
|
||||
onSayfa={(n) => {
|
||||
const q = new URLSearchParams();
|
||||
if (ara) q.set("ara", ara);
|
||||
if (n > 1) q.set("sayfa", String(n));
|
||||
const s = q.toString();
|
||||
router.push(s ? `/yonetim?${s}` : "/yonetim");
|
||||
}}
|
||||
className="mt-8 justify-center"
|
||||
/>
|
||||
);
|
||||
}
|
||||
133
src/features/yonetim/components/yonetim-icerik.tsx
Normal file
133
src/features/yonetim/components/yonetim-icerik.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { Search } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { OzetHucre, OzetSerit } from "@/components/ozet-kart";
|
||||
import { SATIR_AD_DUZ, SATIR_CIP, SATIR_META } from "@/components/liste-satiri";
|
||||
import { yoneticiyiAl } from "@/lib/yonetici";
|
||||
import { UYE_SAYFA_BOYU, uyeOzeti, uyeleriListele } from "../yonetim-queries";
|
||||
import { EpostaMetni } from "./eposta-metni";
|
||||
import { KrediCekmecesi } from "./kredi-cekmecesi";
|
||||
import { UyeSayfalama } from "./uye-sayfalama";
|
||||
|
||||
const sayi = new Intl.NumberFormat("tr-TR");
|
||||
const tarih = new Intl.DateTimeFormat("tr-TR", {
|
||||
day: "numeric",
|
||||
month: "short",
|
||||
year: "numeric",
|
||||
timeZone: "Europe/Istanbul",
|
||||
});
|
||||
|
||||
export async function YonetimIcerik({
|
||||
ara,
|
||||
sayfa,
|
||||
}: {
|
||||
ara?: string;
|
||||
sayfa: number;
|
||||
}) {
|
||||
// Yönetici değilse sayfanın varlığı da belli olmasın
|
||||
const yonetici = await yoneticiyiAl();
|
||||
if (!yonetici) notFound();
|
||||
|
||||
const [ozet, liste] = await Promise.all([
|
||||
uyeOzeti(),
|
||||
uyeleriListele({ ara, sayfa }),
|
||||
]);
|
||||
const toplamSayfa = Math.max(1, Math.ceil(liste.toplam / UYE_SAYFA_BOYU));
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-6xl px-4 py-12 sm:py-16">
|
||||
<h1 className="text-center font-heading text-3xl font-bold leading-tight text-slate-900 sm:text-5xl lg:text-left">
|
||||
Üyeler
|
||||
</h1>
|
||||
<p className="mx-auto mt-4 max-w-xl text-center text-base leading-relaxed text-slate-600 sm:text-lg lg:mx-0 lg:text-left">
|
||||
Kayıtlı hesaplar ve kredi bakiyeleri. Eklediğin ya da düştüğün her
|
||||
kredi deftere yazılır.
|
||||
</p>
|
||||
|
||||
<OzetSerit className="mt-10">
|
||||
<OzetHucre etiket="Toplam üye" deger={sayi.format(ozet.toplam)} alt="Tüm zamanlar" />
|
||||
<OzetHucre etiket="Paketli" deger={sayi.format(ozet.paketli)} alt="Tercih Dönemi Paketi alan" />
|
||||
<OzetHucre etiket="Son 7 gün" deger={sayi.format(ozet.yeni)} alt="Yeni kayıt" />
|
||||
</OzetSerit>
|
||||
|
||||
<form action="/yonetim" className="mt-12 flex flex-col gap-3 sm:flex-row">
|
||||
<label htmlFor="uye-ara" className="sr-only">
|
||||
E-posta ya da ad ara
|
||||
</label>
|
||||
<div className="relative sm:flex-1">
|
||||
<Search
|
||||
className="pointer-events-none absolute left-5 top-1/2 size-4 -translate-y-1/2 text-slate-400"
|
||||
aria-hidden
|
||||
/>
|
||||
<Input
|
||||
id="uye-ara"
|
||||
name="ara"
|
||||
type="search"
|
||||
defaultValue={ara}
|
||||
placeholder="E-posta ya da ad"
|
||||
autoComplete="off"
|
||||
className="pl-12"
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" size="lg" variant="ikincil">
|
||||
Ara
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<h2 className="mt-12 font-heading text-2xl font-bold text-slate-900 sm:text-3xl">
|
||||
{ara ? `"${ara}" için ${sayi.format(liste.toplam)} üye` : `${sayi.format(liste.toplam)} üye`}
|
||||
</h2>
|
||||
|
||||
{liste.satirlar.length === 0 ? (
|
||||
<p className="mt-6 text-base text-slate-600">
|
||||
{ara ? "Bu aramayla eşleşen üye yok." : "Henüz kayıtlı üye yok."}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="mt-6 divide-y divide-slate-200 border-y border-slate-200">
|
||||
{liste.satirlar.map((u) => (
|
||||
<li key={u.id} className="flex items-center gap-4 py-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className={`${SATIR_AD_DUZ} [overflow-wrap:anywhere]`}>
|
||||
<EpostaMetni eposta={u.email} />
|
||||
</span>
|
||||
<div className={`mt-1 ${SATIR_META}`}>
|
||||
{u.ad ? <span className="[overflow-wrap:anywhere]">{u.ad}</span> : null}
|
||||
<span>{tarih.format(u.kayit)}</span>
|
||||
{u.hasPaket ? <span className={SATIR_CIP}>Paketli</span> : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-col items-end">
|
||||
<span className="font-heading text-2xl font-bold leading-none text-slate-900">
|
||||
{sayi.format(u.bakiye)}
|
||||
</span>
|
||||
<span className="mt-1 text-xs font-semibold text-slate-400">kredi</span>
|
||||
</div>
|
||||
<KrediCekmecesi userId={u.id} email={u.email} bakiye={u.bakiye} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{toplamSayfa > 1 ? (
|
||||
<UyeSayfalama sayfa={sayfa} toplamSayfa={toplamSayfa} ara={ara} />
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function YonetimIcerikSkeleton() {
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-6xl px-4 py-12 sm:py-16" aria-busy>
|
||||
<Skeleton className="mx-auto h-12 w-48 lg:mx-0" />
|
||||
<Skeleton className="mt-10 h-28 w-full" />
|
||||
<Skeleton className="mt-12 h-12 w-full rounded-full" />
|
||||
<div className="mt-12 space-y-4">
|
||||
{Array.from({ length: 6 }, (_, i) => (
|
||||
<Skeleton key={i} className="h-16 w-full" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
68
src/features/yonetim/yonetim-actions.ts
Normal file
68
src/features/yonetim/yonetim-actions.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
"use server";
|
||||
|
||||
import { refresh } from "next/cache";
|
||||
import { yoneticiKrediAyarla } from "@/lib/credits";
|
||||
import { yoneticiyiAl } from "@/lib/yonetici";
|
||||
|
||||
export type KrediTanimlaSonucu =
|
||||
| { ok: true; yeniBakiye: number }
|
||||
| { ok: false; hata: string };
|
||||
|
||||
/** Tek seferde en çok bu kadar kredi eklenir/düşülür (yanlış tuşa karşı). */
|
||||
const AZAMI = 1000;
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
/**
|
||||
* Yönetim paneli (S-017): üyeye kredi ekler ya da düşer. Yetki her çağrıda
|
||||
* sunucuda yeniden doğrulanır; argümanlar istemciden geldiği için tipine
|
||||
* güvenilmez. `istekId` formun açılışta ürettiği UUID'dir — çift gönderim
|
||||
* deftere iki kez yazılmaz.
|
||||
*/
|
||||
export async function krediTanimla(
|
||||
userId: unknown,
|
||||
miktar: unknown,
|
||||
istekId: unknown,
|
||||
): Promise<KrediTanimlaSonucu> {
|
||||
const yonetici = await yoneticiyiAl();
|
||||
if (!yonetici) {
|
||||
console.warn("[yonetim] yetkisiz kredi tanımlama denemesi");
|
||||
return { ok: false, hata: "Bu işlem için yetkin yok." };
|
||||
}
|
||||
|
||||
if (typeof userId !== "string" || userId.length === 0 || userId.length > 100) {
|
||||
return { ok: false, hata: "Üye bulunamadı." };
|
||||
}
|
||||
if (
|
||||
typeof miktar !== "number" ||
|
||||
!Number.isInteger(miktar) ||
|
||||
miktar === 0 ||
|
||||
Math.abs(miktar) > AZAMI
|
||||
) {
|
||||
return { ok: false, hata: `Miktar 0 olmayan, en çok ${AZAMI} olan bir tam sayı olmalı.` };
|
||||
}
|
||||
if (typeof istekId !== "string" || !UUID.test(istekId)) {
|
||||
return { ok: false, hata: "Form bayatlamış; sayfayı yenileyip tekrar dene." };
|
||||
}
|
||||
|
||||
const sonuc = await yoneticiKrediAyarla({
|
||||
userId,
|
||||
delta: miktar,
|
||||
// Denetim izi deftere de düşer: hangi yönetici yaptı (göç gerektirmez)
|
||||
refId: `yonetim:${yonetici.id}:${istekId}`,
|
||||
});
|
||||
|
||||
if (!sonuc.ok) {
|
||||
if (sonuc.error === "YETERSIZ") {
|
||||
return { ok: false, hata: "Bakiye bu kadar düşmeye yetmiyor." };
|
||||
}
|
||||
if (sonuc.error === "KULLANICI_YOK") return { ok: false, hata: "Üye bulunamadı." };
|
||||
return { ok: false, hata: "Bu istek zaten işlendi." };
|
||||
}
|
||||
|
||||
// Denetim izi: kim, kime, ne kadar (e-posta değil kimlik yazılır)
|
||||
console.info(
|
||||
`[yonetim] ${yonetici.id} → ${userId}: ${miktar > 0 ? "+" : ""}${miktar} kredi (bakiye ${sonuc.yeniBakiye})`,
|
||||
);
|
||||
refresh();
|
||||
return { ok: true, yeniBakiye: sonuc.yeniBakiye };
|
||||
}
|
||||
65
src/features/yonetim/yonetim-queries.ts
Normal file
65
src/features/yonetim/yonetim-queries.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import "server-only";
|
||||
import { count, desc, eq, gte, sql } from "drizzle-orm";
|
||||
import { appDb, schema } from "@/lib/appdb";
|
||||
|
||||
const { user } = schema;
|
||||
|
||||
export const UYE_SAYFA_BOYU = 50;
|
||||
|
||||
export type UyeSatiri = {
|
||||
id: string;
|
||||
email: string;
|
||||
ad: string;
|
||||
kayit: Date;
|
||||
hasPaket: boolean;
|
||||
bakiye: number;
|
||||
};
|
||||
|
||||
/** LIKE joker karakterlerini kaçır: "%" yazan arama tüm tabloyu getirmesin. */
|
||||
function likeKacis(s: string): string {
|
||||
return s.replace(/[\\%_]/g, (m) => `\\${m}`);
|
||||
}
|
||||
|
||||
/** En yeni üye önce; `ara` e-posta ya da adın içinde geçen metin. */
|
||||
export async function uyeleriListele(opts: { ara?: string; sayfa: number }) {
|
||||
const ara = opts.ara?.trim().toLowerCase();
|
||||
const kosul = ara
|
||||
? sql`(lower(${user.email}) like ${`%${likeKacis(ara)}%`} escape '\\' or lower(${user.name}) like ${`%${likeKacis(ara)}%`} escape '\\')`
|
||||
: undefined;
|
||||
|
||||
const [satirlar, toplam] = await Promise.all([
|
||||
appDb
|
||||
.select({
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
ad: user.name,
|
||||
kayit: user.createdAt,
|
||||
hasPaket: user.hasPaket,
|
||||
bakiye: user.creditBalance,
|
||||
})
|
||||
.from(user)
|
||||
.where(kosul)
|
||||
.orderBy(desc(user.createdAt))
|
||||
.limit(UYE_SAYFA_BOYU)
|
||||
.offset((opts.sayfa - 1) * UYE_SAYFA_BOYU),
|
||||
appDb.select({ n: count() }).from(user).where(kosul),
|
||||
]);
|
||||
|
||||
return { satirlar: satirlar as UyeSatiri[], toplam: toplam[0]?.n ?? 0 };
|
||||
}
|
||||
|
||||
/** Üst şerit: toplam üye, paketli üye, son 7 günde gelen. */
|
||||
export async function uyeOzeti() {
|
||||
const yediGunOnce = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
||||
const [toplam, paketli, yeni] = await Promise.all([
|
||||
appDb.select({ n: count() }).from(user),
|
||||
appDb.select({ n: count() }).from(user).where(eq(user.hasPaket, true)),
|
||||
appDb.select({ n: count() }).from(user).where(gte(user.createdAt, yediGunOnce)),
|
||||
]);
|
||||
return {
|
||||
toplam: toplam[0]?.n ?? 0,
|
||||
paketli: paketli[0]?.n ?? 0,
|
||||
yeni: yeni[0]?.n ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -125,6 +125,8 @@ export const creditLedger = sqliteTable(
|
||||
"refund",
|
||||
"report_generate",
|
||||
"report_revision",
|
||||
// Yönetim panelinden elle ekleme/düşme (S-017); delta iki yönlü
|
||||
"admin_grant",
|
||||
],
|
||||
}).notNull(),
|
||||
refId: text("ref_id"),
|
||||
|
||||
@@ -263,3 +263,70 @@ export async function krediBittiIsaretle(userId: string): Promise<void> {
|
||||
console.error(`[kredi] kredi-bitti işaretlenemedi (${userId}):`, err);
|
||||
}
|
||||
}
|
||||
|
||||
export type YoneticiKrediSonucu =
|
||||
| { ok: true; yeniBakiye: number }
|
||||
| { ok: false; error: "KULLANICI_YOK" | "YETERSIZ" | "TEKRAR" };
|
||||
|
||||
/**
|
||||
* Yönetim panelinden elle kredi ekler (delta > 0) ya da düşer (delta < 0) —
|
||||
* S-017. Defter satırı ve bakiye tek transaction'da yazılır. refId istemcinin
|
||||
* ürettiği istek kimliğidir: aynı form iki kez gönderilirse UNIQUE(reason,
|
||||
* ref_id) ikinciyi durdurur (TEKRAR). Düşme bakiyeyi sıfırın altına indirmez.
|
||||
*/
|
||||
export async function yoneticiKrediAyarla(opts: {
|
||||
userId: string;
|
||||
delta: number;
|
||||
refId: string;
|
||||
}): Promise<YoneticiKrediSonucu> {
|
||||
try {
|
||||
const yeniBakiye = await appDb.transaction(async (tx) => {
|
||||
// Önce bakiye: kullanıcı yoksa ya da bakiye yetmiyorsa defter satırı
|
||||
// hiç denenmez (yabancı anahtar hatası yerine anlamlı sonuç). Defter
|
||||
// insert'i UNIQUE'e takılırsa transaction bakiye güncellemesini de geri alır.
|
||||
const res = await tx
|
||||
.update(user)
|
||||
.set({
|
||||
creditBalance: sql`${user.creditBalance} + ${opts.delta}`,
|
||||
// Kredi eklenince bekleyen kredi-bitti hatırlatması iptal olur
|
||||
...(opts.delta > 0 ? { krediBittiAt: null } : {}),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(
|
||||
opts.delta < 0
|
||||
? and(eq(user.id, opts.userId), gte(user.creditBalance, -opts.delta))
|
||||
: eq(user.id, opts.userId),
|
||||
);
|
||||
if (res.rowsAffected === 0) {
|
||||
const var_ = await tx
|
||||
.select({ id: user.id })
|
||||
.from(user)
|
||||
.where(eq(user.id, opts.userId))
|
||||
.limit(1);
|
||||
throw new Error(var_.length ? "YETERSIZ" : "KULLANICI_YOK");
|
||||
}
|
||||
await tx.insert(creditLedger).values({
|
||||
id: newId(),
|
||||
userId: opts.userId,
|
||||
delta: opts.delta,
|
||||
reason: "admin_grant",
|
||||
refId: opts.refId,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
const satir = await tx
|
||||
.select({ bakiye: user.creditBalance })
|
||||
.from(user)
|
||||
.where(eq(user.id, opts.userId))
|
||||
.limit(1);
|
||||
return satir[0]?.bakiye ?? 0;
|
||||
});
|
||||
return { ok: true, yeniBakiye };
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
if (msg === "YETERSIZ" || msg === "KULLANICI_YOK") {
|
||||
return { ok: false, error: msg };
|
||||
}
|
||||
if (uniqueIhlaliMi(err)) return { ok: false, error: "TEKRAR" };
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
30
src/lib/yonetici.ts
Normal file
30
src/lib/yonetici.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import "server-only";
|
||||
import { getCurrentUser } from "./session";
|
||||
|
||||
/**
|
||||
* Yönetim paneline (S-017) girebilen e-postalar. Liste sunucudadır:
|
||||
* `ADMIN_EMAILS` (virgülle ayrılmış). Varsayılan yok: değişken tanımlı
|
||||
* değilse panel kimseye açılmaz (dev'deki "anında giriş" herhangi bir
|
||||
* e-postayla oturum açtırabildiği için de varsayılan e-posta konmadı).
|
||||
*/
|
||||
function yoneticiEpostalari(): Set<string> {
|
||||
const ham = process.env.ADMIN_EMAILS ?? "";
|
||||
return new Set(
|
||||
ham
|
||||
.split(",")
|
||||
.map((e) => e.trim().toLowerCase())
|
||||
.filter(Boolean),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Oturumdaki kullanıcı yöneticiyse satırını, değilse null döner. E-postası
|
||||
* doğrulanmamış hesap yönetici sayılmaz (magic link girişi zaten doğrular).
|
||||
*/
|
||||
export async function yoneticiyiAl() {
|
||||
const kullanici = await getCurrentUser();
|
||||
if (!kullanici || !kullanici.emailVerified) return null;
|
||||
return yoneticiEpostalari().has(kullanici.email.toLowerCase())
|
||||
? kullanici
|
||||
: null;
|
||||
}
|
||||
Reference in New Issue
Block a user