Compare commits

...

12 Commits

Author SHA1 Message Date
kertenkerem
cd542259a9 feat: implement lesson creation directly on the schedule calendar via a new API endpoint and database updates. 2026-01-08 02:57:38 +03:00
kertenkerem
721e003253 feat: Introduce a dark-themed, time-grid calendar with hall support, updating page styling and lesson data model. 2026-01-08 02:39:18 +03:00
kertenkerem
cd29713bca chore: Update development database. 2026-01-08 02:13:48 +03:00
kertenkerem
255ec6fd25 refactor: improve branch update logic with explicit field selection and robust hallCount parsing, and enhance error handling in branch API endpoints 2026-01-08 02:09:34 +03:00
kertenkerem
dbca26f3ad feat: add in-place editing functionality for classes and instructors with dedicated API routes. 2026-01-08 02:03:26 +03:00
kertenkerem
091435c8b4 feat: Implement a weekly schedule calendar on the homepage and extend branch management with hall count and phone fields. 2026-01-08 01:57:54 +03:00
kertenkerem
6880c738f9 feat: Implement student CRUD operations in admin panel with dedicated API routes and updated Prisma schema. 2026-01-08 01:52:00 +03:00
kertenkerem
b7f98ed3ad style: Redesign the admin registration page, relocating the title to the page component and updating all form element styles. 2026-01-08 01:33:02 +03:00
kertenkerem
9bb5ec46ce Move Registration to Admin Panel 2026-01-08 01:25:06 +03:00
kertenkerem
8fa560cd5e Student Registeration CRUD & Listing 2026-01-08 01:14:35 +03:00
kertenkerem
d5de503f86 proje dosyaları hazırlandı 2026-01-08 01:03:58 +03:00
kertenkerem
260dea0713 Initial commit of Dance School App 2026-01-08 00:51:13 +03:00
56 changed files with 9153 additions and 1 deletions

43
.gitignore vendored Normal file
View File

@@ -0,0 +1,43 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
/src/generated/prisma

View File

@@ -1,2 +1,36 @@
# dance_school This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

BIN
dev.db Normal file

Binary file not shown.

18
eslint.config.mjs Normal file
View File

@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;

7
next.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

6558
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

31
package.json Normal file
View File

@@ -0,0 +1,31 @@
{
"name": "temp_app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@prisma/client": "^5.22.0",
"bcryptjs": "^3.0.3",
"jose": "^6.1.3",
"next": "16.1.1",
"prisma": "^5.22.0",
"react": "19.2.3",
"react-dom": "19.2.3"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"dotenv": "^17.2.3",
"eslint": "^9",
"eslint-config-next": "16.1.1",
"tsx": "^4.21.0",
"typescript": "^5"
}
}

BIN
prisma/dev.db Normal file

Binary file not shown.

96
prisma/schema.prisma Normal file
View File

@@ -0,0 +1,96 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
model User {
id String @id @default(uuid())
username String @unique
password String
createdAt DateTime @default(now())
}
model Branch {
id String @id @default(uuid())
name String
address String?
phone String?
hallCount Int? @default(1)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
classes DanceClass[]
lessons Lesson[]
students Student[]
instructors Instructor[] @relation("BranchToInstructor")
}
model Instructor {
id String @id @default(uuid())
name String
bio String?
phone String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
classes DanceClass[]
lessons Lesson[]
branches Branch[] @relation("BranchToInstructor")
}
model DanceClass {
id String @id @default(uuid())
name String
description String?
branchId String
instructorId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
instructor Instructor? @relation(fields: [instructorId], references: [id])
branch Branch @relation(fields: [branchId], references: [id])
fees Fee[]
lessons Lesson[]
}
model Lesson {
id String @id @default(uuid())
name String?
startTime DateTime
endTime DateTime
type String
hallNumber Int @default(1)
branchId String
instructorId String
classId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
class DanceClass? @relation(fields: [classId], references: [id])
instructor Instructor @relation(fields: [instructorId], references: [id])
branch Branch @relation(fields: [branchId], references: [id])
}
model Fee {
id String @id @default(uuid())
name String
amount Float
currency String @default("TRY")
type String
classId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
class DanceClass? @relation(fields: [classId], references: [id])
}
model Student {
id String @id @default(uuid())
name String
email String?
phone String
birthDate DateTime
branchId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
branch Branch? @relation(fields: [branchId], references: [id])
}

1
public/file.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

1
public/globe.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

1
public/next.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
public/vercel.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

1
public/window.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

29
scripts/seed.ts Normal file
View File

@@ -0,0 +1,29 @@
import 'dotenv/config';
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
// Manually read .env if needed, but dotenv/config should handle it
const prisma = new PrismaClient();
async function main() {
const password = await bcrypt.hash('admin123', 10);
const user = await prisma.user.upsert({
where: { username: 'admin' },
update: {},
create: {
username: 'admin',
password,
},
});
console.log('Admin user created:', user);
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});

View File

@@ -0,0 +1,67 @@
.layout {
display: flex;
min-height: 100vh;
}
.sidebar {
width: 250px;
background-color: #1a1a1a;
color: white;
padding: 2rem;
display: flex;
flex-direction: column;
}
.brand {
font-size: 1.5rem;
font-weight: bold;
margin-bottom: 2rem;
color: #fff;
text-decoration: none;
}
.nav {
display: flex;
flex-direction: column;
gap: 1rem;
flex: 1;
}
.navLink {
color: #aaa;
text-decoration: none;
font-size: 1.1rem;
padding: 0.5rem 0;
transition: color 0.2s;
}
.navLink:hover {
color: white;
}
.active {
color: white;
font-weight: bold;
}
.main {
flex: 1;
background-color: #f9f9f9;
padding: 2rem;
overflow-y: auto;
}
.logoutBtn {
margin-top: auto;
background: none;
border: 1px solid #333;
color: #999;
padding: 0.5rem;
cursor: pointer;
border-radius: 4px;
}
.logoutBtn:hover {
color: white;
border-color: white;
}

View File

@@ -0,0 +1,47 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import styles from './branches.module.css';
export function AddBranchForm() {
const [name, setName] = useState('');
const [address, setAddress] = useState('');
const [phone, setPhone] = useState('');
const [hallCount, setHallCount] = useState('1');
const router = useRouter();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
await fetch('/api/branches', {
method: 'POST',
body: JSON.stringify({ name, address, phone, hallCount: parseInt(hallCount) }),
});
setName('');
setAddress('');
setPhone('');
setHallCount('1');
router.refresh();
};
return (
<form onSubmit={handleSubmit} className={styles.form}>
<div className={styles.inputGroup}>
<label>Şube Adı</label>
<input value={name} onChange={e => setName(e.target.value)} className={styles.input} required />
</div>
<div className={styles.inputGroup}>
<label>Telefon</label>
<input value={phone} onChange={e => setPhone(e.target.value)} className={styles.input} />
</div>
<div className={styles.inputGroup}>
<label>Adres</label>
<input value={address} onChange={e => setAddress(e.target.value)} className={styles.input} />
</div>
<div className={styles.inputGroup}>
<label>Salon Sayısı</label>
<input type="number" min="1" value={hallCount} onChange={e => setHallCount(e.target.value)} className={styles.input} />
</div>
<button type="submit" className={styles.btn}>Ekle</button>
</form>
);
}

View File

@@ -0,0 +1,106 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import styles from './branches.module.css';
export function BranchList({ branches }: { branches: any[] }) {
const router = useRouter();
const [editingId, setEditingId] = useState<string | null>(null);
const [editForm, setEditForm] = useState<any>(null);
const handleDelete = async (id: string) => {
if (!confirm('Silmek istediğinize emin misiniz?')) return;
await fetch(`/api/branches/${id}`, { method: 'DELETE' });
router.refresh();
};
const startEdit = (branch: any) => {
setEditingId(branch.id);
setEditForm({
name: branch.name,
phone: branch.phone || '',
address: branch.address || '',
hallCount: branch.hallCount?.toString() || '1'
});
};
const handleUpdate = async (e: React.FormEvent) => {
e.preventDefault();
const res = await fetch(`/api/branches/${editingId}`, {
method: 'PUT',
body: JSON.stringify(editForm),
headers: { 'Content-Type': 'application/json' }
});
if (res.ok) {
setEditingId(null);
router.refresh();
} else {
alert('Güncelleme başarısız oldu.');
}
};
return (
<div className={styles.list}>
{branches.map(b => (
<div key={b.id} className={styles.card}>
{editingId === b.id ? (
<form onSubmit={handleUpdate} style={{ width: '100%', display: 'flex', gap: '1rem', flexWrap: 'wrap', alignItems: 'flex-end' }}>
<div className={styles.inputGroup}>
<label>Şube Adı</label>
<input
value={editForm.name}
onChange={e => setEditForm({ ...editForm, name: e.target.value })}
className={styles.input}
required
/>
</div>
<div className={styles.inputGroup}>
<label>Telefon</label>
<input
value={editForm.phone}
onChange={e => setEditForm({ ...editForm, phone: e.target.value })}
className={styles.input}
/>
</div>
<div className={styles.inputGroup}>
<label>Adres</label>
<input
value={editForm.address}
onChange={e => setEditForm({ ...editForm, address: e.target.value })}
className={styles.input}
/>
</div>
<div className={styles.inputGroup}>
<label>Salon Sayısı</label>
<input
type="number"
min="1"
value={editForm.hallCount}
onChange={e => setEditForm({ ...editForm, hallCount: e.target.value })}
className={styles.input}
/>
</div>
<div style={{ display: 'flex', gap: '0.5rem' }}>
<button type="submit" className={styles.btn} style={{ background: '#2e7d32' }}>Kaydet</button>
<button type="button" onClick={() => setEditingId(null)} className={styles.btn}>İptal</button>
</div>
</form>
) : (
<>
<div>
<h3>{b.name}</h3>
<p>{b.phone ? `Tel: ${b.phone}` : 'Telefon yok'} | {b.address || 'Adres yok'}</p>
<small>Salon Sayısı: {b.hallCount || 1}</small>
</div>
<div style={{ display: 'flex', gap: '0.5rem' }}>
<button onClick={() => startEdit(b)} className={styles.btn} style={{ background: '#ffa000' }}>Düzenle</button>
<button onClick={() => handleDelete(b.id)} className={`${styles.btn} ${styles.btnDelete}`}>Sil</button>
</div>
</>
)}
</div>
))}
</div>
);
}

View File

@@ -0,0 +1,62 @@
.container {
padding: 1rem;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
}
.form {
background: white;
padding: 1.5rem;
border-radius: 8px;
margin-bottom: 2rem;
display: flex;
gap: 1rem;
align-items: flex-end;
flex-wrap: wrap;
}
.inputGroup {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.input {
padding: 0.5rem;
border: 1px solid #ccc;
border-radius: 4px;
min-width: 200px;
}
.btn {
padding: 0.6rem 1.2rem;
background: #333;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.btnDelete {
background: #d32f2f;
}
.list {
display: grid;
gap: 1rem;
}
.card {
background: white;
padding: 1.5rem;
border-radius: 8px;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

View File

@@ -0,0 +1,17 @@
import { prisma } from '@/infrastructure/db/prisma';
import { AddBranchForm } from './AddBranchForm';
import { BranchList } from './BranchList';
import styles from './branches.module.css';
export default async function Page() {
const branches = await prisma.branch.findMany({ orderBy: { createdAt: 'desc' } });
return (
<div className={styles.container}>
<div className={styles.header}>
<h1>Şubeler</h1>
</div>
<AddBranchForm />
<BranchList branches={branches} />
</div>
);
}

View File

@@ -0,0 +1,49 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import styles from '../branches/branches.module.css';
export function AddClassForm({ branches, instructors }: { branches: any[], instructors: any[] }) {
const [name, setName] = useState('');
const [branchId, setBranchId] = useState('');
const [instructorId, setInstructorId] = useState(''); // Optional
const router = useRouter();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!branchId) return alert('Şube seçiniz');
await fetch('/api/classes', {
method: 'POST',
body: JSON.stringify({ name, branchId, instructorId: instructorId || null }),
});
setName('');
setBranchId('');
setInstructorId('');
router.refresh();
};
return (
<form onSubmit={handleSubmit} className={styles.form}>
<div className={styles.inputGroup}>
<label>Sınıf Adı</label>
<input value={name} onChange={e => setName(e.target.value)} className={styles.input} required />
</div>
<div className={styles.inputGroup}>
<label>Şube</label>
<select value={branchId} onChange={e => setBranchId(e.target.value)} className={styles.input} required>
<option value="">Seçiniz</option>
{branches.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
</select>
</div>
<div className={styles.inputGroup}>
<label>Varsayılan Hoca (Opsiyonel)</label>
<select value={instructorId} onChange={e => setInstructorId(e.target.value)} className={styles.input}>
<option value="">Seçiniz</option>
{instructors.map(i => <option key={i.id} value={i.id}>{i.name}</option>)}
</select>
</div>
<button type="submit" className={styles.btn}>Ekle</button>
</form>
);
}

View File

@@ -0,0 +1,124 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import styles from '../branches/branches.module.css';
export function ClassList({
classes,
branches,
instructors
}: {
classes: any[],
branches: any[],
instructors: any[]
}) {
const router = useRouter();
const [editingId, setEditingId] = useState<string | null>(null);
const [editForm, setEditForm] = useState<any>(null);
const handleDelete = async (id: string) => {
if (!confirm('Silmek istediğinize emin misiniz?')) return;
await fetch(`/api/classes/${id}`, { method: 'DELETE' });
router.refresh();
};
const startEdit = (c: any) => {
setEditingId(c.id);
setEditForm({
name: c.name,
description: c.description || '',
branchId: c.branchId,
instructorId: c.instructorId || ''
});
};
const handleUpdate = async (e: React.FormEvent) => {
e.preventDefault();
const res = await fetch(`/api/classes/${editingId}`, {
method: 'PATCH',
body: JSON.stringify(editForm),
headers: { 'Content-Type': 'application/json' }
});
if (res.ok) {
setEditingId(null);
router.refresh();
} else {
alert('Güncelleme başarısız oldu.');
}
};
return (
<div className={styles.list}>
{classes.map(c => (
<div key={c.id} className={styles.card}>
{editingId === c.id ? (
<form onSubmit={handleUpdate} style={{ width: '100%', display: 'flex', gap: '1rem', flexWrap: 'wrap', alignItems: 'flex-end' }}>
<div className={styles.inputGroup}>
<label>Sınıf Adı</label>
<input
value={editForm.name}
onChange={e => setEditForm({ ...editForm, name: e.target.value })}
className={styles.input}
required
/>
</div>
<div className={styles.inputGroup}>
<label>ıklama</label>
<input
value={editForm.description}
onChange={e => setEditForm({ ...editForm, description: e.target.value })}
className={styles.input}
/>
</div>
<div className={styles.inputGroup}>
<label>Şube</label>
<select
value={editForm.branchId}
onChange={e => setEditForm({ ...editForm, branchId: e.target.value })}
className={styles.input}
required
>
<option value="">Şube Seçiniz</option>
{branches.map(b => (
<option key={b.id} value={b.id}>{b.name}</option>
))}
</select>
</div>
<div className={styles.inputGroup}>
<label>Eğitmen</label>
<select
value={editForm.instructorId}
onChange={e => setEditForm({ ...editForm, instructorId: e.target.value })}
className={styles.input}
>
<option value="">Eğitmen Seçiniz</option>
{instructors.map(i => (
<option key={i.id} value={i.id}>{i.name}</option>
))}
</select>
</div>
<div style={{ display: 'flex', gap: '0.5rem' }}>
<button type="submit" className={styles.btn} style={{ background: '#2e7d32' }}>Kaydet</button>
<button type="button" onClick={() => setEditingId(null)} className={styles.btn}>İptal</button>
</div>
</form>
) : (
<>
<div>
<h3>{c.name}</h3>
<p>Şube: {c.branch?.name}</p>
{c.instructor && <p>Hoca: {c.instructor.name}</p>}
<small>{c.description}</small>
</div>
<div style={{ display: 'flex', gap: '0.5rem' }}>
<button onClick={() => startEdit(c)} className={styles.btn} style={{ background: '#ffa000' }}>Düzenle</button>
<button onClick={() => handleDelete(c.id)} className={`${styles.btn} ${styles.btnDelete}`}>Sil</button>
</div>
</>
)}
</div>
))}
</div>
);
}

View File

@@ -0,0 +1,22 @@
import { prisma } from '@/infrastructure/db/prisma';
import { AddClassForm } from './AddClassForm';
import { ClassList } from './ClassList';
import styles from '../branches/branches.module.css';
export default async function Page() {
const [classes, branches, instructors] = await Promise.all([
prisma.danceClass.findMany({ include: { branch: true, instructor: true }, orderBy: { createdAt: 'desc' } }),
prisma.branch.findMany({ select: { id: true, name: true } }),
prisma.instructor.findMany({ select: { id: true, name: true } })
]);
return (
<div className={styles.container}>
<div className={styles.header}>
<h1>Sınıflar</h1>
</div>
<AddClassForm branches={branches} instructors={instructors} />
<ClassList classes={classes} branches={branches} instructors={instructors} />
</div>
);
}

View File

@@ -0,0 +1,3 @@
.container {
padding: 2rem;
}

View File

@@ -0,0 +1,10 @@
import styles from './dashboard.module.css';
export default function Dashboard() {
return (
<div className={styles.container}>
<h1>Dashboard</h1>
<p>Welcome to the Admin Panel</p>
</div>
);
}

View File

@@ -0,0 +1,35 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import styles from '../branches/branches.module.css'; // Reuse styles
export function AddInstructorForm() {
const [name, setName] = useState('');
const [bio, setBio] = useState('');
const router = useRouter();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
await fetch('/api/instructors', {
method: 'POST',
body: JSON.stringify({ name, bio }),
});
setName('');
setBio('');
router.refresh();
};
return (
<form onSubmit={handleSubmit} className={styles.form}>
<div className={styles.inputGroup}>
<label>Hoca Adı</label>
<input value={name} onChange={e => setName(e.target.value)} className={styles.input} required />
</div>
<div className={styles.inputGroup}>
<label>Biyografi / Uzmanlık</label>
<input value={bio} onChange={e => setBio(e.target.value)} className={styles.input} />
</div>
<button type="submit" className={styles.btn}>Ekle</button>
</form>
);
}

View File

@@ -0,0 +1,94 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import styles from '../branches/branches.module.css';
export function InstructorList({ instructors }: { instructors: any[] }) {
const router = useRouter();
const [editingId, setEditingId] = useState<string | null>(null);
const [editForm, setEditForm] = useState<any>(null);
const handleDelete = async (id: string) => {
if (!confirm('Silmek istediğinize emin misiniz?')) return;
await fetch(`/api/instructors/${id}`, { method: 'DELETE' });
router.refresh();
};
const startEdit = (instructor: any) => {
setEditingId(instructor.id);
setEditForm({
name: instructor.name,
phone: instructor.phone || '',
bio: instructor.bio || ''
});
};
const handleUpdate = async (e: React.FormEvent) => {
e.preventDefault();
const res = await fetch(`/api/instructors/${editingId}`, {
method: 'PATCH',
body: JSON.stringify(editForm),
headers: { 'Content-Type': 'application/json' }
});
if (res.ok) {
setEditingId(null);
router.refresh();
} else {
alert('Güncelleme başarısız oldu.');
}
};
return (
<div className={styles.list}>
{instructors.map(i => (
<div key={i.id} className={styles.card}>
{editingId === i.id ? (
<form onSubmit={handleUpdate} style={{ width: '100%', display: 'flex', gap: '1rem', flexWrap: 'wrap', alignItems: 'flex-end' }}>
<div className={styles.inputGroup}>
<label>Hoca Adı</label>
<input
value={editForm.name}
onChange={e => setEditForm({ ...editForm, name: e.target.value })}
className={styles.input}
required
/>
</div>
<div className={styles.inputGroup}>
<label>Telefon</label>
<input
value={editForm.phone}
onChange={e => setEditForm({ ...editForm, phone: e.target.value })}
className={styles.input}
/>
</div>
<div className={styles.inputGroup}>
<label>Biyo</label>
<input
value={editForm.bio}
onChange={e => setEditForm({ ...editForm, bio: e.target.value })}
className={styles.input}
/>
</div>
<div style={{ display: 'flex', gap: '0.5rem' }}>
<button type="submit" className={styles.btn} style={{ background: '#2e7d32' }}>Kaydet</button>
<button type="button" onClick={() => setEditingId(null)} className={styles.btn}>İptal</button>
</div>
</form>
) : (
<>
<div>
<h3>{i.name} {i.phone && <small>({i.phone})</small>}</h3>
<p>{i.bio || 'Biyografi bulunmuyor'}</p>
</div>
<div style={{ display: 'flex', gap: '0.5rem' }}>
<button onClick={() => startEdit(i)} className={styles.btn} style={{ background: '#ffa000' }}>Düzenle</button>
<button onClick={() => handleDelete(i.id)} className={`${styles.btn} ${styles.btnDelete}`}>Sil</button>
</div>
</>
)}
</div>
))}
</div>
);
}

View File

@@ -0,0 +1,17 @@
import { prisma } from '@/infrastructure/db/prisma';
import { AddInstructorForm } from './AddInstructorForm';
import { InstructorList } from './InstructorList';
import styles from '../branches/branches.module.css';
export default async function Page() {
const instructors = await prisma.instructor.findMany({ orderBy: { createdAt: 'desc' } });
return (
<div className={styles.container}>
<div className={styles.header}>
<h1>Hocalar</h1>
</div>
<AddInstructorForm />
<InstructorList instructors={instructors} />
</div>
);
}

15
src/app/admin/layout.tsx Normal file
View File

@@ -0,0 +1,15 @@
import { Sidebar } from '@/presentation/components/Sidebar';
import styles from './admin.module.css';
export default function AdminLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className={styles.layout}>
<Sidebar />
<main className={styles.main}>{children}</main>
</div>
);
}

View File

@@ -0,0 +1,69 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import styles from '../branches/branches.module.css';
export function RegisterForm({ branches }: { branches: any[] }) {
const [formData, setFormData] = useState({
name: '',
email: '',
phone: '',
birthDate: '',
branchId: ''
});
const router = useRouter();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const res = await fetch('/api/register', {
method: 'POST',
body: JSON.stringify(formData),
headers: { 'Content-Type': 'application/json' }
});
if (res.ok) {
setFormData({ name: '', email: '', phone: '', birthDate: '', branchId: '' });
router.refresh();
}
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
return (
<form onSubmit={handleSubmit} className={styles.form}>
<div className={styles.inputGroup}>
<label>Ad Soyad</label>
<input name="name" value={formData.name} onChange={handleChange} className={styles.input} required placeholder="Adınız" />
</div>
<div className={styles.inputGroup}>
<label>Email</label>
<input name="email" type="email" value={formData.email} onChange={handleChange} className={styles.input} placeholder="ornek@email.com" />
</div>
<div className={styles.inputGroup}>
<label>Telefon</label>
<input name="phone" type="tel" value={formData.phone} onChange={handleChange} className={styles.input} required placeholder="5XX XXX XX XX" />
</div>
<div className={styles.inputGroup}>
<label>Doğum Tarihi</label>
<input name="birthDate" type="date" value={formData.birthDate} onChange={handleChange} className={styles.input} required />
</div>
<div className={styles.inputGroup}>
<label>Şube</label>
<select name="branchId" value={formData.branchId} onChange={handleChange} className={styles.input}>
<option value="">Seçiniz</option>
{branches.map(b => (
<option key={b.id} value={b.id}>{b.name}</option>
))}
</select>
</div>
<button type="submit" className={styles.btn}>Kaydet</button>
</form>
);
}

View File

@@ -0,0 +1,134 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import styles from '../branches/branches.module.css';
export function StudentList({ students, branches }: { students: any[], branches: any[] }) {
const router = useRouter();
const [showSensitive, setShowSensitive] = useState(false);
const [editingId, setEditingId] = useState<string | null>(null);
const [editForm, setEditForm] = useState<any>(null);
const handleDelete = async (id: string) => {
if (!confirm('Kaydı silmek istediğinize emin misiniz?')) return;
const res = await fetch(`/api/students/${id}`, { method: 'DELETE' });
if (res.ok) {
router.refresh();
} else {
alert('Silme işlemi başarısız oldu.');
}
};
const startEdit = (student: any) => {
setEditingId(student.id);
setEditForm({
name: student.name,
email: student.email || '',
phone: student.phone,
branchId: student.branchId || '',
birthDate: student.birthDate ? new Date(student.birthDate).toISOString().split('T')[0] : ''
});
};
const handleUpdate = async (e: React.FormEvent) => {
e.preventDefault();
const res = await fetch(`/api/students/${editingId}`, {
method: 'PATCH',
body: JSON.stringify(editForm),
headers: { 'Content-Type': 'application/json' }
});
if (res.ok) {
setEditingId(null);
router.refresh();
} else {
alert('Güncelleme başarısız oldu.');
}
};
const maskInfo = (text: string) => {
if (!text) return 'Yok';
if (showSensitive) return text;
return text.replace(/.(?=.{4})/g, '*');
};
return (
<div className={styles.list}>
<div style={{ marginBottom: '1rem', display: 'flex', justifyContent: 'flex-end' }}>
<button
onClick={() => setShowSensitive(!showSensitive)}
className={styles.btn}
style={{ background: showSensitive ? '#666' : '#0056b3' }}
>
{showSensitive ? 'Bilgileri Gizle' : 'Bilgileri Göster'}
</button>
</div>
{students.map(s => (
<div key={s.id} className={styles.card}>
{editingId === s.id ? (
<form onSubmit={handleUpdate} style={{ width: '100%', display: 'flex', gap: '1rem', flexWrap: 'wrap', alignItems: 'flex-end' }}>
<div className={styles.inputGroup}>
<label>Ad Soyad</label>
<input
value={editForm.name}
onChange={e => setEditForm({ ...editForm, name: e.target.value })}
className={styles.input}
required
/>
</div>
<div className={styles.inputGroup}>
<label>Telefon</label>
<input
value={editForm.phone}
onChange={e => setEditForm({ ...editForm, phone: e.target.value })}
className={styles.input}
required
/>
</div>
<div className={styles.inputGroup}>
<label>Email</label>
<input
value={editForm.email}
onChange={e => setEditForm({ ...editForm, email: e.target.value })}
className={styles.input}
/>
</div>
<div className={styles.inputGroup}>
<label>Şube</label>
<select
value={editForm.branchId}
onChange={e => setEditForm({ ...editForm, branchId: e.target.value })}
className={styles.input}
>
<option value="">Seçiniz</option>
{branches.map(b => (
<option key={b.id} value={b.id}>{b.name}</option>
))}
</select>
</div>
<div style={{ display: 'flex', gap: '0.5rem' }}>
<button type="submit" className={styles.btn} style={{ background: '#2e7d32' }}>Kaydet</button>
<button type="button" onClick={() => setEditingId(null)} className={styles.btn}>İptal</button>
</div>
</form>
) : (
<>
<div>
<h3>{s.name}</h3>
<p>
<strong>Tel:</strong> {maskInfo(s.phone)} |
<strong> Email:</strong> {maskInfo(s.email)}
</p>
<small>{s.branch?.name || 'Şube seçilmemiş'}</small>
</div>
<div style={{ display: 'flex', gap: '0.5rem' }}>
<button onClick={() => startEdit(s)} className={styles.btn} style={{ background: '#ffa000' }}>Düzenle</button>
<button onClick={() => handleDelete(s.id)} className={`${styles.btn} ${styles.btnDelete}`}>Sil</button>
</div>
</>
)}
</div>
))}
</div>
);
}

View File

@@ -0,0 +1,27 @@
import { prisma } from '@/infrastructure/db/prisma';
import { RegisterForm } from './RegisterForm';
import { StudentList } from './StudentList';
import styles from '../branches/branches.module.css';
export default async function Page() {
const [branches, students] = await Promise.all([
prisma.branch.findMany({ select: { id: true, name: true } }),
prisma.student.findMany({
include: { branch: true },
orderBy: { createdAt: 'desc' }
})
]);
return (
<div className={styles.container}>
<div className={styles.header}>
<h1>Öğrenci Kayıt İşlemleri</h1>
</div>
<RegisterForm branches={branches} />
<div className={styles.header} style={{ marginTop: '2rem' }}>
<h2>Kayıtlı Öğrenciler</h2>
</div>
<StudentList students={students} branches={branches} />
</div>
);
}

View File

@@ -0,0 +1,42 @@
import { NextResponse } from 'next/server';
import { prisma } from '@/infrastructure/db/prisma';
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
await prisma.branch.delete({
where: { id },
});
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json({ error: 'Failed' }, { status: 500 });
}
}
export async function PUT(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
const json = await request.json();
// Explicitly selecting fields to update to avoid spreading unwanted fields (like id)
const branch = await prisma.branch.update({
where: { id },
data: {
name: json.name,
address: json.address,
phone: json.phone,
hallCount: (json.hallCount !== undefined && json.hallCount !== '') ? parseInt(json.hallCount.toString()) : undefined
},
});
return NextResponse.json(branch);
} catch (error: any) {
console.error('Branch update error:', error);
return NextResponse.json({ error: 'Failed to update branch', details: error.message }, { status: 500 });
}
}

View File

@@ -0,0 +1,27 @@
import { NextResponse } from 'next/server';
import { prisma } from '@/infrastructure/db/prisma';
export async function GET() {
const branches = await prisma.branch.findMany({
orderBy: { createdAt: 'desc' }
});
return NextResponse.json(branches);
}
export async function POST(request: Request) {
try {
const json = await request.json();
// Validate?
const branch = await prisma.branch.create({
data: {
name: json.name,
address: json.address,
phone: json.phone,
hallCount: json.hallCount ? parseInt(json.hallCount) : undefined
}
});
return NextResponse.json(branch);
} catch (error: any) {
return NextResponse.json({ error: 'Failed to create branch', details: error.message }, { status: 500 });
}
}

View File

@@ -0,0 +1,39 @@
import { NextResponse } from 'next/server';
import { prisma } from '@/infrastructure/db/prisma';
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
const json = await request.json();
const danceClass = await prisma.danceClass.update({
where: { id },
data: {
name: json.name,
description: json.description,
branchId: json.branchId,
instructorId: json.instructorId
},
});
return NextResponse.json({ success: true, danceClass });
} catch (error) {
return NextResponse.json({ error: 'Failed to update class' }, { status: 500 });
}
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
await prisma.danceClass.delete({
where: { id },
});
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json({ error: 'Failed' }, { status: 500 });
}
}

View File

@@ -0,0 +1,27 @@
import { NextResponse } from 'next/server';
import { prisma } from '@/infrastructure/db/prisma';
export async function GET() {
const classes = await prisma.danceClass.findMany({
include: { branch: true, instructor: true },
orderBy: { createdAt: 'desc' }
});
return NextResponse.json(classes);
}
export async function POST(request: Request) {
try {
const json = await request.json();
const cls = await prisma.danceClass.create({
data: {
name: json.name,
branchId: json.branchId, // required
instructorId: json.instructorId || undefined, // optional?
},
});
return NextResponse.json(cls);
} catch (error) {
console.error(error);
return NextResponse.json({ error: 'Failed' }, { status: 500 });
}
}

View File

@@ -0,0 +1,38 @@
import { NextResponse } from 'next/server';
import { prisma } from '@/infrastructure/db/prisma';
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
const json = await request.json();
const instructor = await prisma.instructor.update({
where: { id },
data: {
name: json.name,
bio: json.bio,
phone: json.phone
},
});
return NextResponse.json({ success: true, instructor });
} catch (error) {
return NextResponse.json({ error: 'Failed to update instructor' }, { status: 500 });
}
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
await prisma.instructor.delete({
where: { id },
});
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json({ error: 'Failed' }, { status: 500 });
}
}

View File

@@ -0,0 +1,22 @@
import { NextResponse } from 'next/server';
import { prisma } from '@/infrastructure/db/prisma';
export async function GET() {
const instructors = await prisma.instructor.findMany({ orderBy: { createdAt: 'desc' } });
return NextResponse.json(instructors);
}
export async function POST(request: Request) {
try {
const json = await request.json();
const instructor = await prisma.instructor.create({
data: {
name: json.name,
bio: json.bio,
},
});
return NextResponse.json(instructor);
} catch (error) {
return NextResponse.json({ error: 'Failed' }, { status: 500 });
}
}

View File

@@ -0,0 +1,65 @@
import { prisma } from "@/infrastructure/db/prisma";
import { NextResponse } from "next/server";
export async function GET() {
try {
const lessons = await prisma.lesson.findMany({
include: {
instructor: true,
branch: true,
class: true,
},
});
return NextResponse.json(lessons);
} catch (error) {
return NextResponse.json({ error: "Dersler yüklenemedi" }, { status: 500 });
}
}
export async function POST(request: Request) {
try {
const json = await request.json();
const { startTime, endTime, instructorId, branchId, classId, type, hallNumber, occurrenceCount = 1, period = 'NONE' } = json;
const start = new Date(startTime);
const end = new Date(endTime);
const lessons = [];
for (let i = 0; i < occurrenceCount; i++) {
const currentStart = new Date(start);
const currentEnd = new Date(end);
if (period === 'DAILY') {
currentStart.setDate(start.getDate() + i);
currentEnd.setDate(end.getDate() + i);
} else if (period === 'WEEKLY') {
currentStart.setDate(start.getDate() + (i * 7));
currentEnd.setDate(end.getDate() + (i * 7));
} else if (period === 'MONTHLY') {
currentStart.setMonth(start.getMonth() + i);
currentEnd.setMonth(end.getMonth() + i);
} else if (period === 'SIX_MONTHLY') {
currentStart.setMonth(start.getMonth() + (i * 6));
currentEnd.setMonth(end.getMonth() + (i * 6));
}
const lesson = await prisma.lesson.create({
data: {
startTime: currentStart,
endTime: currentEnd,
type,
hallNumber: parseInt(hallNumber),
branchId,
instructorId,
classId: classId || null,
}
});
lessons.push(lesson);
}
return NextResponse.json({ message: `${lessons.length} ders başarıyla oluşturuldu`, lessons });
} catch (error: any) {
console.error('Lesson creation error:', error);
return NextResponse.json({ error: "Ders oluşturulamadı", details: error.message }, { status: 500 });
}
}

View File

@@ -0,0 +1,44 @@
import { NextResponse } from 'next/server';
import { prisma } from '@/infrastructure/db/prisma';
import { comparePassword, encrypt } from '@/lib/auth';
import { cookies } from 'next/headers';
export async function POST(request: Request) {
try {
const body = await request.json();
const { username, password } = body;
if (!username || !password) {
return NextResponse.json({ error: 'Missing fields' }, { status: 400 });
}
const user = await prisma.user.findUnique({ where: { username } });
if (!user) {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
}
const isValid = await comparePassword(password, user.password);
if (!isValid) {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
}
const expires = new Date(Date.now() + 24 * 60 * 60 * 1000); // 1 day
const token = await encrypt({ userId: user.id, username: user.username, expires });
// Set cookie
const cookieStore = await cookies();
cookieStore.set('admin_session', token, {
expires,
httpOnly: true,
path: '/',
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax'
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('Login error:', error);
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}
}

View File

@@ -0,0 +1,28 @@
import { NextResponse } from 'next/server';
import { prisma } from '@/infrastructure/db/prisma';
export async function POST(request: Request) {
try {
const json = await request.json();
// Basic validation
if (!json.name || !json.phone || !json.birthDate) {
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
}
const student = await prisma.student.create({
data: {
name: json.name,
email: json.email || null,
phone: json.phone,
birthDate: new Date(json.birthDate), // Ensure date format
branchId: json.branchId || null
},
});
return NextResponse.json({ success: true, student });
} catch (error) {
console.error('Registration error:', error);
return NextResponse.json({ error: 'Failed to register' }, { status: 500 });
}
}

View File

@@ -0,0 +1,42 @@
import { NextResponse } from 'next/server';
import { prisma } from '@/infrastructure/db/prisma';
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
const json = await request.json();
const student = await prisma.student.update({
where: { id },
data: {
name: json.name,
email: json.email || null,
phone: json.phone,
birthDate: json.birthDate ? new Date(json.birthDate) : undefined,
branchId: json.branchId || null
},
});
return NextResponse.json({ success: true, student });
} catch (error: any) {
console.error('Update error:', error);
return NextResponse.json({ error: 'Failed to update student', details: error.message }, { status: 500 });
}
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
await prisma.student.delete({
where: { id },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('Delete error:', error);
return NextResponse.json({ error: 'Failed to delete student' }, { status: 500 });
}
}

BIN
src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

16
src/app/globals.css Normal file
View File

@@ -0,0 +1,16 @@
body {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
background-color: #f5f5f5;
color: #333;
}
a {
text-decoration: none;
color: inherit;
}
* {
box-sizing: border-box;
}

32
src/app/layout.tsx Normal file
View File

@@ -0,0 +1,32 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={`${geistSans.variable} ${geistMono.variable}`}>
{children}
</body>
</html>
);
}

View File

@@ -0,0 +1,63 @@
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f5f5f5;
}
.card {
background: white;
padding: 2rem;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
width: 100%;
max-width: 400px;
}
.title {
text-align: center;
margin-bottom: 2rem;
color: #333;
}
.formGroup {
margin-bottom: 1.5rem;
}
.label {
display: block;
margin-bottom: 0.5rem;
color: #555;
font-weight: 500;
}
.input {
width: 100%;
padding: 0.75rem;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 1rem;
}
.button {
width: 100%;
padding: 0.75rem;
background-color: #0070f3;
color: white;
border: none;
border-radius: 6px;
font-size: 1rem;
cursor: pointer;
transition: background 0.2s;
}
.button:hover {
background-color: #005bb5;
}
.error {
color: red;
margin-bottom: 1rem;
text-align: center;
}

57
src/app/login/page.tsx Normal file
View File

@@ -0,0 +1,57 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import styles from './login.module.css';
export default function LoginPage() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const router = useRouter();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
if (res.ok) {
router.push('/admin/dashboard');
} else {
const data = await res.json();
setError(data.error || 'Login failed');
}
};
return (
<div className={styles.container}>
<form onSubmit={handleSubmit} className={styles.card}>
<h1 className={styles.title}>Admin Login</h1>
{error && <div className={styles.error}>{error}</div>}
<div className={styles.formGroup}>
<label className={styles.label}>Username</label>
<input
className={styles.input}
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className={styles.formGroup}>
<label className={styles.label}>Password</label>
<input
className={styles.input}
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button type="submit" className={styles.button}>Login</button>
</form>
</div>
);
}

90
src/app/page.module.css Normal file
View File

@@ -0,0 +1,90 @@
.page {
--primary: #8ab4f8;
--secondary: #202124;
--accent: #f28b82;
--bg: #000000;
--white: #ffffff;
--text: #e8eaed;
--text-muted: #9aa0a6;
min-height: 100vh;
display: flex;
flex-direction: column;
background: var(--bg);
font-family: var(--font-outfit, 'Outfit', sans-serif);
color: var(--text);
}
.nav {
padding: 0.75rem 2rem;
display: flex;
justify-content: space-between;
align-items: center;
background: #000000;
border-bottom: 1px solid #3c4043;
position: sticky;
top: 0;
z-index: 1000;
}
.logo {
font-size: 1.2rem;
font-weight: 700;
color: #e8eaed;
letter-spacing: -0.5px;
}
.adminLink {
padding: 0.6rem 1.2rem;
background: var(--secondary);
color: white;
border-radius: 8px;
text-decoration: none;
font-weight: 600;
transition: all 0.3s;
}
.adminLink:hover {
background: var(--primary);
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.main {
flex: 1;
display: flex;
flex-direction: column;
}
.hero {
text-align: center;
max-width: 800px;
margin: 0 auto;
}
.hero h1 {
font-size: 3.5rem;
font-weight: 900;
margin-bottom: 1rem;
color: #111;
letter-spacing: -2px;
}
.hero p {
font-size: 1.25rem;
color: var(--text-muted);
}
.footer {
display: none;
}
@media (max-width: 768px) {
.nav {
padding: 1rem 2rem;
}
.hero h1 {
font-size: 2.5rem;
}
}

57
src/app/page.tsx Normal file
View File

@@ -0,0 +1,57 @@
import { prisma } from "@/infrastructure/db/prisma";
import { ScheduleCalendar } from "@/components/ScheduleCalendar";
import Link from "next/link";
import styles from "./page.module.css";
export default async function Home() {
// Calculate start and end of current week
const now = new Date();
const dayOfWeek = now.getDay(); // 0 is Sunday
const diff = now.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1); // Adjust to Monday
const startOfWeek = new Date(now.setDate(diff));
startOfWeek.setHours(0, 0, 0, 0);
const endOfWeek = new Date(startOfWeek);
endOfWeek.setDate(endOfWeek.getDate() + 7);
// Get the first branch to determine hallCount (or you could add a selector)
const branch = await prisma.branch.findFirst();
const hallCount = branch?.hallCount || 1;
const lessons = await prisma.lesson.findMany({
where: {
startTime: {
gte: startOfWeek,
lt: endOfWeek,
},
},
include: {
instructor: true,
branch: true,
class: true,
},
orderBy: {
startTime: 'asc',
},
});
return (
<div className={styles.page}>
<nav className={styles.nav}>
<div className={styles.logo}>{branch?.name || "Dance School"}</div>
<Link href="/admin/dashboard" className={styles.adminLink}>
Yönetici Paneli
</Link>
</nav>
<main className={styles.main}>
<ScheduleCalendar lessons={lessons} hallCount={hallCount} branchId={branch?.id} />
</main>
<footer className={styles.footer}>
<p>&copy; {new Date().getFullYear()} Dance School Yönetim Sistemi. Tüm hakları saklıdır.</p>
</footer>
</div>
);
}

View File

@@ -0,0 +1,213 @@
.container {
width: 100%;
height: 100vh;
background-color: #000000;
color: #e8eaed;
font-family: var(--font-outfit, 'Outfit', -apple-system, sans-serif);
display: flex;
flex-direction: column;
overflow: hidden;
}
.title {
text-align: center;
padding: 0.75rem 0;
margin: 0;
font-size: 1.25rem;
font-weight: 500;
border-bottom: 1px solid #3c4043;
}
.calendarWrapper {
flex: 1;
overflow: auto;
position: relative;
display: flex;
flex-direction: column;
}
.stickyHeader {
position: sticky;
top: 0;
z-index: 100;
background: #000;
border-bottom: 1px solid #3c4043;
}
.headerRow {
display: flex;
margin-left: 60px;
/* Space for time axis */
}
.dayHeader {
flex: 1;
min-width: 120px;
text-align: center;
padding: 0.5rem 0;
border-right: 1px solid #3c4043;
font-size: 0.75rem;
color: #9aa0a6;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.dayHeader:last-child {
border-right: none;
}
.today .dayHeader {
color: #8ab4f8;
font-weight: 700;
}
.hallLabelsRow {
display: flex;
margin-left: 60px;
border-top: 1px solid rgba(60, 64, 67, 0.3);
}
.hallLabel {
flex: 1;
min-width: calc(120px / var(--hall-count, 1));
text-align: center;
font-size: 0.65rem;
color: #5f6368;
padding: 2px 0;
border-right: 1px solid rgba(60, 64, 67, 0.3);
}
.gridContainer {
position: relative;
display: flex;
min-height: 1440px;
/* 24 hours * 60px */
}
.timeAxis {
width: 60px;
background: #000;
border-right: 1px solid #3c4043;
position: sticky;
left: 0;
z-index: 50;
/* Ensure time axis fills the height */
height: 1440px;
}
.timeLabel {
height: 60px;
display: flex;
align-items: flex-start;
justify-content: flex-end;
padding-right: 8px;
font-size: 0.7rem;
color: #9aa0a6;
/* Center the text vertically at the hour mark */
position: relative;
top: -8px;
}
.mainGrid {
flex: 1;
display: flex;
background-image: linear-gradient(#3c4043 1px, transparent 1px);
background-size: 100% 60px;
position: relative;
}
.dayColumn {
flex: 1;
min-width: 120px;
border-right: 1px solid #3c4043;
display: flex;
position: relative;
}
.dayColumn:last-child {
border-right: none;
}
.hallColumn {
flex: 1;
position: relative;
border-right: 1px solid rgba(60, 64, 67, 0.2);
}
.hallColumn:last-child {
border-right: none;
}
.nowLine {
position: absolute;
left: 0;
right: 0;
height: 2px;
background: #ea4335;
z-index: 10;
pointer-events: none;
}
.nowLine::before {
content: '';
position: absolute;
left: -4px;
top: -4px;
width: 10px;
height: 10px;
background: #ea4335;
border-radius: 50%;
}
.lessonCard {
position: absolute;
left: 3px;
right: 3px;
background: rgba(138, 180, 248, 0.2);
border: 1px solid #8ab4f8;
border-radius: 4px;
padding: 4px;
font-size: 0.7rem;
overflow: hidden;
cursor: pointer;
z-index: 1;
display: flex;
flex-direction: column;
gap: 1px;
}
.lessonCard:hover {
background: rgba(138, 180, 248, 0.3);
z-index: 5;
}
.lessonCard[data-type="Individual"] {
background: rgba(242, 139, 130, 0.2);
border-color: #f28b82;
}
.lessonTime {
color: #8ab4f8;
font-weight: 500;
font-size: 0.65rem;
}
.lessonCard[data-type="Individual"] .lessonTime {
color: #f28b82;
}
.lessonTitle {
font-weight: 600;
color: #fff;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.lessonMeta {
color: #9aa0a6;
font-size: 0.6rem;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}

View File

@@ -0,0 +1,380 @@
'use client';
import { useMemo, useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
interface Lesson {
id: string;
name?: string | null;
startTime: Date | string;
endTime: Date | string;
type: string;
class?: { name: string } | null;
instructor: { name: string };
branch: { name: string; hallCount?: number | null };
hallNumber?: number | null;
}
export function ScheduleCalendar({ lessons, hallCount = 1, branchId }: { lessons: Lesson[], hallCount?: number, branchId?: string }) {
const router = useRouter();
const days = ['Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi', 'Pazar'];
const hours = Array.from({ length: 24 }, (_, i) => i);
const scrollRef = useRef<HTMLDivElement>(null);
const [now, setNow] = useState(new Date());
// Modal State
const [isModalOpen, setIsModalOpen] = useState(false);
const [selectedSlot, setSelectedSlot] = useState<{ dayIdx: number, hour: number, hNum: number } | null>(null);
const [instructors, setInstructors] = useState<any[]>([]);
const [classes, setClasses] = useState<any[]>([]);
const [formData, setFormData] = useState({
instructorId: '',
classId: '',
type: 'Group',
period: 'NONE',
occurrenceCount: 1,
duration: 60
});
useEffect(() => {
const timer = setInterval(() => setNow(new Date()), 60000);
if (scrollRef.current) {
const currentHour = now.getHours();
const scrollHour = Math.max(0, currentHour - 2);
scrollRef.current.scrollTop = scrollHour * 60;
}
return () => clearInterval(timer);
}, []);
const fetchFormData = async () => {
const [instRes, classRes] = await Promise.all([
fetch('/api/instructors'),
fetch('/api/classes')
]);
const instData = await instRes.json();
const classData = await classRes.json();
setInstructors(instData);
setClasses(classData);
};
const handleSlotClick = (dayIdx: number, hour: number, hNum: number) => {
if (!branchId) return;
setSelectedSlot({ dayIdx, hour, hNum });
setIsModalOpen(true);
fetchFormData();
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!selectedSlot || !branchId) return;
// Calculate actual date for the selected slot in the current week
const now = new Date();
const dayOfWeek = now.getDay();
const diff = now.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1);
const startOfWeek = new Date(now.setDate(diff));
const startTime = new Date(startOfWeek);
startTime.setDate(startOfWeek.getDate() + selectedSlot.dayIdx);
startTime.setHours(selectedSlot.hour, 0, 0, 0);
const endTime = new Date(startTime);
endTime.setMinutes(startTime.getMinutes() + parseInt(formData.duration.toString()));
try {
const res = await fetch('/api/lessons', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...formData,
branchId,
hallNumber: selectedSlot.hNum,
startTime,
endTime
})
});
if (res.ok) {
setIsModalOpen(false);
router.refresh();
} else {
const errData = await res.json();
alert(`Ders oluşturulamadı: ${errData.details || errData.error || 'Bilinmeyen hata'}`);
}
} catch (error) {
console.error(error);
}
};
const nowTop = (now.getHours() * 60) + now.getMinutes();
const groupedLessons = useMemo(() => {
const groups: Record<number, Record<number, any[]>> = {};
lessons.forEach(lesson => {
const start = new Date(lesson.startTime);
const end = new Date(lesson.endTime);
let dayIndex = start.getDay() - 1;
if (dayIndex === -1) dayIndex = 6;
const hallNum = lesson.hallNumber || 1;
const top = (start.getHours() * 60) + start.getMinutes();
const bottom = (end.getHours() * 60) + end.getMinutes();
if (!groups[dayIndex]) groups[dayIndex] = {};
if (!groups[dayIndex][hallNum]) groups[dayIndex][hallNum] = [];
groups[dayIndex][hallNum].push({
...lesson,
top,
height: Math.max(bottom - top, 20),
startTimeStr: start.toLocaleTimeString('tr-TR', { hour: '2-digit', minute: '2-digit' })
});
});
return groups;
}, [lessons]);
const timeWidth = 60;
const dayMinWidth = 180;
return (
<div style={{
width: '100%',
height: '100vh',
backgroundColor: '#000',
color: '#fff',
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
fontFamily: 'sans-serif'
}}>
<h1 style={{ textAlign: 'center', padding: '10px', margin: 0, fontSize: '1.2rem', borderBottom: '1px solid #333' }}>
Haftalık Ders Programı
</h1>
<div ref={scrollRef} style={{ flex: 1, overflow: 'auto', position: 'relative' }}>
<div style={{ position: 'sticky', top: 0, zIndex: 100, backgroundColor: '#000', borderBottom: '1px solid #333' }}>
<div style={{ display: 'flex', marginLeft: timeWidth }}>
{days.map((day, idx) => {
const isToday = ((new Date().getDay() - 1 + 7) % 7) === idx;
return (
<div key={day} style={{
flex: 1,
minWidth: dayMinWidth,
textAlign: 'center',
padding: '8px 0',
borderRight: '1px solid #333',
fontSize: '0.8rem',
color: isToday ? '#8ab4f8' : '#9aa0a6',
fontWeight: isToday ? 'bold' : 'normal'
}}>
{day}
</div>
);
})}
</div>
{hallCount > 1 && (
<div style={{ display: 'flex', marginLeft: timeWidth, borderTop: '1px solid #222' }}>
{days.map((_, dIdx) => (
<div key={dIdx} style={{ flex: 1, minWidth: dayMinWidth, display: 'flex' }}>
{Array.from({ length: hallCount }).map((_, hIdx) => (
<div key={hIdx} style={{
flex: 1,
textAlign: 'center',
fontSize: '0.6rem',
color: '#666',
borderRight: hIdx === hallCount - 1 ? '1px solid #333' : '1px solid #222',
padding: '4px 0',
backgroundColor: '#050505'
}}>
S{hIdx + 1}
</div>
))}
</div>
))}
</div>
)}
</div>
<div style={{ display: 'flex', minHeight: '1440px', position: 'relative' }}>
<div style={{ width: timeWidth, position: 'sticky', left: 0, zIndex: 50, backgroundColor: '#000', borderRight: '1px solid #333' }}>
{hours.map(h => (
<div key={h} style={{ height: '60px', paddingRight: '5px', textAlign: 'right', fontSize: '0.7rem', color: '#666', paddingTop: '2px' }}>
{h === 0 ? '12 AM' : h === 12 ? '12 PM' : h > 12 ? `${h - 12} PM` : `${h} AM`}
</div>
))}
</div>
<div style={{ flex: 1, position: 'relative', display: 'flex', backgroundImage: 'linear-gradient(#222 1px, transparent 1px)', backgroundSize: '100% 60px' }}>
<div style={{ position: 'absolute', top: nowTop, left: 0, right: 0, height: '2px', backgroundColor: 'red', zIndex: 40, pointerEvents: 'none' }}>
<div style={{ position: 'absolute', left: '-5px', top: '-4px', width: '10px', height: '10px', borderRadius: '50%', backgroundColor: 'red' }} />
</div>
{days.map((_, dIdx) => (
<div key={dIdx} style={{ flex: 1, minWidth: dayMinWidth, borderRight: '1px solid #333', position: 'relative', display: 'flex' }}>
{Array.from({ length: hallCount }).map((_, hIdx) => {
const hNum = hIdx + 1;
return (
<div key={hIdx} style={{ flex: 1, position: 'relative', borderRight: hallCount > 1 ? '1px solid #111' : 'none' }}>
{/* Hoverable Slots */}
{hours.map(h => (
<div
key={h}
onClick={() => handleSlotClick(dIdx, h, hNum)}
style={{ height: '60px', position: 'relative', cursor: 'pointer' }}
className="slot-hover"
>
<div className="plus-btn" style={{
position: 'absolute',
right: '5px',
top: '5px',
width: '20px',
height: '20px',
backgroundColor: 'rgba(255,255,255,0.1)',
borderRadius: '50%',
display: 'none',
alignItems: 'center',
justifyContent: 'center',
fontSize: '12px'
}}>+</div>
</div>
))}
{groupedLessons[dIdx]?.[hNum]?.map(lesson => (
<div key={lesson.id} style={{
position: 'absolute',
top: lesson.top,
height: lesson.height,
left: '2px',
right: '2px',
backgroundColor: lesson.type === 'Individual' ? 'rgba(242, 139, 130, 0.2)' : 'rgba(138, 180, 248, 0.2)',
borderLeft: `3px solid ${lesson.type === 'Individual' ? '#f28b82' : '#8ab4f8'}`,
borderRadius: '4px',
padding: '4px',
fontSize: '0.7rem',
overflow: 'hidden',
zIndex: 10
}}>
<div style={{ fontWeight: 'bold', fontSize: '0.6rem', opacity: 0.8 }}>{lesson.startTimeStr}</div>
<div style={{ fontWeight: 'bold', margin: '2px 0' }}>{lesson.class?.name || lesson.name}</div>
<div style={{ opacity: 0.6 }}>{lesson.instructor.name}</div>
</div>
))}
</div>
);
})}
</div>
))}
</div>
</div>
</div>
{/* Reservation Modal */}
{isModalOpen && (
<div style={{
position: 'fixed',
top: 0, left: 0, right: 0, bottom: 0,
backgroundColor: 'rgba(0,0,0,0.8)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: 200
}}>
<form onSubmit={handleSubmit} style={{
backgroundColor: '#1e1e1e',
padding: '2rem',
borderRadius: '8px',
width: '400px',
border: '1px solid #333',
display: 'flex',
flexDirection: 'column',
gap: '1rem'
}}>
<h3>Yeni Ders Rezervasyonu</h3>
<p style={{ fontSize: '0.8rem', color: '#9aa0a6' }}>
{days[selectedSlot!.dayIdx]} - Saat: {selectedSlot!.hour}:00 - Salon: {selectedSlot!.hNum}
</p>
<label>Eğitmen</label>
<select
required
value={formData.instructorId}
onChange={(e) => setFormData({ ...formData, instructorId: e.target.value })}
style={{ padding: '8px', backgroundColor: '#2b2b2b', color: '#fff', border: '1px solid #444' }}
>
<option value="">Seçiniz</option>
{instructors.map(i => <option key={i.id} value={i.id}>{i.name}</option>)}
</select>
<label>Sınıf (Opsiyonel)</label>
<select
value={formData.classId}
onChange={(e) => setFormData({ ...formData, classId: e.target.value })}
style={{ padding: '8px', backgroundColor: '#2b2b2b', color: '#fff', border: '1px solid #444' }}
>
<option value="">Seçiniz</option>
{classes.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
<label>Ders Türü</label>
<select
value={formData.type}
onChange={(e) => setFormData({ ...formData, type: e.target.value })}
style={{ padding: '8px', backgroundColor: '#2b2b2b', color: '#fff', border: '1px solid #444' }}
>
<option value="Group">Grup Dersi</option>
<option value="Individual">Özel Ders</option>
</select>
<label>Süre (Dakika)</label>
<input
type="number"
value={formData.duration}
onChange={(e) => setFormData({ ...formData, duration: parseInt(e.target.value) })}
style={{ padding: '8px', backgroundColor: '#2b2b2b', color: '#fff', border: '1px solid #444' }}
/>
<label>Tekrar</label>
<select
value={formData.period}
onChange={(e) => setFormData({ ...formData, period: e.target.value })}
style={{ padding: '8px', backgroundColor: '#2b2b2b', color: '#fff', border: '1px solid #444' }}
>
<option value="NONE">Tek Seferlik</option>
<option value="DAILY">Günlük</option>
<option value="WEEKLY">Haftalık</option>
<option value="MONTHLY">Aylık</option>
<option value="SIX_MONTHLY">6 Aylık</option>
</select>
{formData.period !== 'NONE' && (
<>
<label>Tekrar Sayısı</label>
<input
type="number"
value={formData.occurrenceCount}
onChange={(e) => setFormData({ ...formData, occurrenceCount: parseInt(e.target.value) })}
style={{ padding: '8px', backgroundColor: '#2b2b2b', color: '#fff', border: '1px solid #444' }}
/>
</>
)}
<div style={{ display: 'flex', gap: '10px', marginTop: '10px' }}>
<button type="submit" style={{ flex: 1, padding: '10px', backgroundColor: '#8ab4f8', color: '#000', border: 'none', borderRadius: '4px', fontWeight: 'bold', cursor: 'pointer' }}>
Kaydet
</button>
<button type="button" onClick={() => setIsModalOpen(false)} style={{ flex: 1, padding: '10px', backgroundColor: 'transparent', color: '#fff', border: '1px solid #444', borderRadius: '4px', cursor: 'pointer' }}>
İptal
</button>
</div>
</form>
</div>
)}
<style jsx>{`
.slot-hover:hover .plus-btn {
display: flex !important;
}
.slot-hover:hover {
background-color: rgba(255,255,255,0.05);
}
`}</style>
</div>
);
}

View File

@@ -0,0 +1,14 @@
import { PrismaClient } from '@prisma/client';
const globalForPrisma = global as unknown as { prisma: PrismaClient };
const prismaInstance = globalForPrisma.prisma || new PrismaClient();
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prismaInstance;
// Log models to verify generation
const models = Object.keys(prismaInstance).filter(k => !k.startsWith('_') && !k.startsWith('$'));
console.log('Prisma models available:', models);
}
export const prisma = prismaInstance;

32
src/lib/auth.ts Normal file
View File

@@ -0,0 +1,32 @@
import { SignJWT, jwtVerify } from 'jose';
import bcrypt from 'bcryptjs';
const secretKey = process.env.JWT_SECRET || 'super-secret-key-dance-school';
const key = new TextEncoder().encode(secretKey);
export async function encrypt(payload: any) {
return await new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('24h')
.sign(key);
}
export async function decrypt(input: string): Promise<any> {
try {
const { payload } = await jwtVerify(input, key, {
algorithms: ['HS256'],
});
return payload;
} catch (error) {
return null;
}
}
export async function hashPassword(password: string) {
return await bcrypt.hash(password, 10);
}
export async function comparePassword(plain: string, hashed: string) {
return await bcrypt.compare(plain, hashed);
}

29
src/middleware.ts Normal file
View File

@@ -0,0 +1,29 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { decrypt } from '@/lib/auth';
export async function middleware(request: NextRequest) {
const path = request.nextUrl.pathname;
// Check for session cookie
const cookie = request.cookies.get('admin_session')?.value;
const session = cookie ? await decrypt(cookie) : null;
// Protect /admin routes
if (path.startsWith('/admin')) {
if (!session) {
return NextResponse.redirect(new URL('/login', request.nextUrl));
}
}
// Redirect already logged in users from /login to /admin/dashboard
if (path === '/login' && session) {
return NextResponse.redirect(new URL('/admin/dashboard', request.nextUrl));
}
return NextResponse.next();
}
export const config = {
matcher: ['/admin/:path*', '/login'],
};

View File

@@ -0,0 +1,42 @@
'use client';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import styles from '@/app/admin/admin.module.css';
export function Sidebar() {
const pathname = usePathname();
const router = useRouter();
const navItems = [
{ name: 'Takvime Git 🗓️', href: '/' },
{ name: 'Dashboard', href: '/admin/dashboard' },
{ name: 'Şubeler', href: '/admin/branches' },
{ name: 'Hocalar', href: '/admin/instructors' },
{ name: 'Sınıflar', href: '/admin/classes' },
{ name: 'Kayıt', href: '/admin/register' },
];
const handleLogout = () => {
document.cookie = 'admin_session=; Max-Age=0; path=/;';
router.push('/login');
router.refresh();
};
return (
<aside className={styles.sidebar}>
<div className={styles.brand}>Dance School</div>
<nav className={styles.nav}>
{navItems.map((item) => (
<Link
key={item.href}
href={item.href}
className={`${styles.navLink} ${pathname.startsWith(item.href) ? styles.active : ''}`}
>
{item.name}
</Link>
))}
</nav>
<button onClick={handleLogout} className={styles.logoutBtn}>Çıkış Yap</button>
</aside>
);
}

34
tsconfig.json Normal file
View File

@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}