# Development Environment & Repository Standards

This document defines the coding standards, file organization, and workflow conventions for this Next.js repository.

---

## Table of Contents

1. [Repository Structure](#repository-structure)
2. [File Naming Conventions](#file-naming-conventions)
3. [Import Conventions](#import-conventions)
4. [Code Organization](#code-organization)
5. [Testing Standards](#testing-standards)
6. [Git Workflow](#git-workflow)
7. [Pull Request Guidelines](#pull-request-guidelines)
8. [Code Review Guidelines](#code-review-guidelines)
9. [Dependencies Management](#dependencies-management)
10. [Environment Variables](#environment-variables)
11. [Adding New Files](#adding-new-files)

---

## Repository Structure

### Root Directory Organization

```
/xur/xdr/home/jf/Arbeit/Websiten-Programmieren/Jomblo/
├── actions/              # Next.js Server Actions (use server)
├── app/                  # Next.js App Router
├── components/           # React Components
│   ├── ui/              # shadcn/ui base components (kebab-case)
│   ├── auth/            # Authentication components (PascalCase)
│   ├── cart/            # Shopping cart components (PascalCase)
│   ├── dashboard/       # Admin dashboard components
│   ├── entities/        # Entity detail components
│   └── shared/          # Shared components
├── docs/                # Documentation
│   ├── testing/         # Testing documentation
│   ├── integrations/    # Integration guides
│   └── github/          # GitHub workflows documentation
├── e2e/                 # Playwright E2E tests
├── hooks/               # Custom React hooks & Zustand stores
├── lib/                 # Utilities, database, auth logic
│   ├── action-mappers.ts
│   ├── cart.ts          # Cart utilities (moved from actions/)
│   ├── db.ts            # Database connection
│   ├── pagination.ts    # Pagination utilities (moved from actions/)
│   └── ...
├── migrations/          # Database migrations
├── public/              # Static assets
├── python/              # Python backend (or backend/)
├── reference-designs/   # Design templates (renamed from Potentielle_Vorlagen)
├── schemas/             # Zod validation schemas
├── tests/               # Test suite organized by type
│   ├── components/      # Component tests
│   ├── integration/     # Integration tests
│   ├── security/        # Security tests
│   ├── unit/           # Unit tests
│   ├── factories/       # Test data factories
│   ├── mocks/          # Test mocks
│   └── setup/          # Test setup files
├── types/               # TypeScript type definitions
└── [config files]       # Root-level configuration
```

### What Belongs at Root Level

**Keep at Root:**
- `README.md` - Project entry point
- `CONTRIBUTING.md` - Contribution guidelines
- `package.json`, `pnpm-lock.yaml` - Package management
- `next.config.ts`, `tsconfig.json` - Framework configuration
- `middleware.ts` - Next.js middleware (required at root)
- `auth.ts`, `auth.config.ts` - NextAuth configuration
- Configuration files: `.eslintrc.json`, `tailwind.config.ts`, `postcss.config.mjs`
- `playwright.config.ts`, `vitest.config.ts` - Test configuration
- `.env.local` - Environment variables (gitignored)

**Never at Root:**
- Test files (move to `tests/` or colocate)
- Documentation (move to `docs/`)
- Utility files (move to `lib/`)
- Temporary/experimental files
- Duplicate folders (e.g., `frontend/`, `shared/`)

---

## File Naming Conventions

### Next.js Official Standards

Following Next.js conventions:

| File Type | Convention | Example | Location |
|-----------|-----------|---------|----------|
| **React Components** | PascalCase | `UserForm.tsx`, `CartButton.tsx` | `components/**` |
| **UI Components (shadcn)** | kebab-case | `button.tsx`, `dialog.tsx` | `components/ui/` |
| **Next.js Pages** | kebab-case | `page.tsx`, `layout.tsx` | `app/**` |
| **Server Actions** | kebab-case | `checkout.ts`, `customer.ts` | `actions/` |
| **Utilities** | kebab-case | `pagination.ts`, `format.ts` | `lib/` |
| **Hooks** | camelCase | `useCartStore.ts`, `useMobile.ts` | `hooks/` |
| **Tests** | `[name].test.ts` | `checkout.test.ts` | colocated or `tests/` |
| **Types** | camelCase or lowercase | `cart.ts`, `db.ts` | `types/` |
| **Config files** | kebab-case | `next.config.ts` | root |

### Naming Examples

**Correct:**
```
components/
  UserForm.tsx
  CartDetails.tsx
  auth/
    LoginForm.tsx
    RegisterForm.tsx
  ui/
    button.tsx
    card.tsx

actions/
  checkout.ts
  customer-address.ts
  customers.ts

lib/
  pagination.ts
  action-mappers.ts
  format.ts
```

**Incorrect (to be renamed):**
```
components/
  login-form.tsx      → LoginForm.tsx
  userMenu.tsx        → UserMenu.tsx
  categoryTabs.tsx    → CategoryTabs.tsx

actions/
  checkOut.ts         → checkout.ts
  customerAddress.ts  → customer-address.ts
  orderItems.ts       → order-items.ts
  fulfillCheckout.ts  → fulfill-checkout.ts
  sales_auth.test.ts  → sales-auth.test.ts
```

---

## Import Conventions

### Always Use @/ Aliases

**Rule:** Always use `@/` path aliases instead of relative imports (`../`, `../../`).

**Correct:**
```typescript
// Components
import { Button } from "@/components/ui/button";
import { UserForm } from "@/components/auth/UserForm";

// Actions
import { createCustomer } from "@/actions/customers";

// Utilities
import { executePaginatedQuery } from "@/lib/pagination";
import { formatCurrency } from "@/lib/format";

// Types
import { CartItem } from "@/types/cart";

// Hooks
import { useCartStore } from "@/hooks/useCartStore";
```

**Incorrect:**
```typescript
// Don't use relative paths for cross-directory imports
import { Button } from "../ui/button";
import { createCustomer } from "../../actions/customer";
import { executePaginatedQuery } from "../utils";
```

### Exception: Same Directory

Relative imports are allowed **only** for files in the same directory:

```typescript
// OK - same directory
import { helper } from "./utils";
import { config } from "./config";
```

---

## Code Organization

### Server Actions (`actions/`)

- All server actions must use `"use server"` directive
- Keep actions focused on single responsibility
- Export both the action and its types
- Place shared utilities in `lib/`, not `actions/`

**Example:**
```typescript
"use server";

import { db } from "@/lib/db";

export async function createCustomer(data: CustomerInput) {
  // Implementation
}
```

### Components (`components/`)

- Use function components with TypeScript
- Props interfaces should be defined in the same file
- Shared components go in `components/shared/`
- Feature-specific components go in feature folders

### Utilities (`lib/`)

- Database connection: `lib/db.ts`
- Authentication logic: `lib/auth-*.ts`
- Formatting utilities: `lib/format.ts`
- Shared utilities: `lib/utils.ts`
- Pagination: `lib/pagination.ts`

---

## Testing Standards

### Test File Organization

**Colocation Pattern (Preferred):**
- Place test files next to source files they test
- Name: `[source-file].test.ts`

```
lib/
  db.ts
  db.test.ts
  pagination.ts
  pagination.test.ts

components/cart/
  CartItemList.tsx
  CartItemList.test.tsx
```

**Centralized Pattern (for special tests):**
```
tests/
  security/
    headers.test.ts        # Security-related tests
  integration/
    stripe.test.ts         # Integration tests
  unit/
    stripe-loading.test.ts # Unit tests
```

### Never at Root

Move these root-level test files:
- `auth.config.test.ts` → keep colocated (already at root with source)
- `csp.test.ts` → `tests/security/headers.test.ts`
- `express-checkout.test.tsx` → `components/cart/ExpressCheckout.test.tsx`
- `middleware.test.ts` → keep colocated (Next.js convention)
- `routes.test.ts` → keep colocated
- `security-headers.test.ts` → merge into `tests/security/headers.test.ts`
- `stripe-integration.test.ts` → `tests/integration/stripe.test.ts`
- `stripe-loading.test.ts` → merge into `tests/integration/stripe.test.ts`

### Test Quality Standards

1. **Test real implementations, not mocks**
   - Bad: Testing hardcoded strings instead of actual config
   - Good: Import and test the actual configuration

2. **Meaningful test names**
   ```typescript
   it("should calculate total with tax", () => { ... });
   ```

3. **100% coverage required**
   - All code must be tested
   - Coverage thresholds enforced in CI/CD

---

## Git Workflow

### Branch Naming Convention

Format: `<type>/<description>`

**Types:**
- `feature/` - New features
- `bugfix/` - Bug fixes
- `hotfix/` - Critical production fixes
- `refactor/` - Code refactoring
- `docs/` - Documentation changes
- `test/` - Test-related changes
- `chore/` - Maintenance tasks

**Examples:**
```
feature/user-authentication
bugfix/cart-calculation-error
hotfix/security-vulnerability
refactor/entity-forms
```

### Commit Message Convention

Use **Conventional Commits** format:

```
<type>(<scope>): <description>

[optional body]

[optional footer]
```

**Types:**
- `feat:` - New feature
- `fix:` - Bug fix
- `docs:` - Documentation
- `style:` - Formatting (no code change)
- `refactor:` - Code restructuring
- `test:` - Adding tests
- `chore:` - Maintenance

**Examples:**
```
feat(auth): add Google OAuth provider

fix(cart): resolve calculation error with discounts

refactor(entities): consolidate form components

docs(readme): update installation instructions

test(stripe): add integration tests for checkout
```

### Commit Best Practices

1. **One logical change per commit**
2. **Write clear, descriptive messages**
3. **Use present tense**: "Add feature" not "Added feature"
4. **Reference issues**: `feat: add login (fixes #123)`
5. **Keep commits atomic and revertible**

---

## Pull Request Guidelines

### PR Template

```markdown
## Description
Brief description of changes

## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation
- [ ] Refactoring

## Checklist
- [ ] Code follows style guidelines
- [ ] Self-review completed
- [ ] Comments added for complex logic
- [ ] Tests added/updated
- [ ] All tests pass (100% coverage)
- [ ] Documentation updated
- [ ] No console errors
- [ ] TypeScript strict mode passes

## Related Issues
Fixes #(issue number)

## Screenshots (if UI changes)
[Add screenshots]
```

### PR Best Practices

1. **Keep PRs focused and small**
   - Ideally < 500 lines changed
   - One feature/fix per PR

2. **Clear title and description**
   - Title follows commit convention
   - Description explains what and why

3. **All checks must pass**
   - Linting
   - Type checking
   - Tests (100% required)
   - Build

4. **Require reviews**
   - At least 1 approval required
   - Address all review comments
   - Resolve conversations before merge

---

## Code Review Guidelines

### For Reviewers

**What to Review:**
1. **Functionality** - Does it work as intended?
2. **Code Quality** - Clean, readable, maintainable?
3. **Testing** - Adequate test coverage?
4. **Performance** - Any performance concerns?
5. **Security** - Any security issues?

**Review Checklist:**
- [ ] Code follows naming conventions
- [ ] Uses @/ aliases for imports
- [ ] Proper TypeScript types
- [ ] No `any` types without justification
- [ ] Error handling implemented
- [ ] No console.log statements
- [ ] No hardcoded secrets/values
- [ ] Tests cover edge cases
- [ ] Documentation updated

**Review Tone:**
- Be constructive and professional
- Ask questions rather than demand changes
- Explain the "why" behind suggestions
- Acknowledge good code

### For Authors

**Responding to Reviews:**
1. Address all comments
2. Explain reasoning if disagreeing
3. Make requested changes promptly
4. Resolve conversations after fixing
5. Re-request review when ready

---

## Dependencies Management

### Adding Dependencies

1. **Use pnpm**
   ```bash
   pnpm add <package>
   pnpm add -D <package>  # dev dependency
   ```

2. **Check necessity**
   - Is it actively maintained?
   - Is there a lighter alternative?
   - Does it duplicate existing functionality?

3. **Update lockfile**
   - Always commit `pnpm-lock.yaml`

### Removing Dependencies

Remove unused packages immediately:

```bash
pnpm remove @redis/search date-fns dompurify isomorphic-dompurify
```

**Current unused packages:**
- `@redis/search` - Not imported anywhere
- `date-fns` - Using native Intl instead
- `dompurify` - Not used
- `isomorphic-dompurify` - Not used

### Dependency Updates

1. **Regular updates**
   ```bash
   pnpm update
   ```

2. **Major version updates**
   - Test thoroughly after major updates
   - Check for breaking changes
   - Update one major package at a time

3. **Security updates**
   - Priority: High
   - Update immediately when security alerts appear

---

## Environment Variables

### Required Variables

```env
# Auth
AUTH_SECRET="your-secret-key"
GOOGLE_CLIENT_ID="your-client-id"
GOOGLE_CLIENT_SECRET="your-client-secret"

# Database
DATABASE_HOST="127.0.0.1"
DATABASE_NAME="JombloDev"
DATABASE_USER="postgres"
DATABASE_PASSWORD="your-password"

# Stripe
STRIPE_SECRET_KEY="sk_test_..."
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY="pk_test_..."
STRIPE_WEBHOOK_SECRET="whsec_..."

# App
NEXT_PUBLIC_BASE_URL="http://localhost:3001"

# Python (optional)
VIDAXL_EMAIL="your@email.com"
VIDAXL_TOKEN="your-token"
```

### Security Rules

1. **Never commit .env.local**
   - Already in `.gitignore`
   - If accidentally committed, rotate secrets immediately

2. **Create .env.local.example**
   - Template for new developers
   - No real values, only placeholders

3. **Separate environments**
   - `.env.development` - Development defaults
   - `.env.production` - Production (deployment only)
   - `.env.test` - Test environment

---

## Adding New Files

### Decision Tree

**Q: What type of file?**

1. **React Component**
   - UI primitive → `components/ui/[name].tsx` (kebab-case)
   - Feature component → `components/[feature]/[Name].tsx` (PascalCase)
   - Shared component → `components/shared/[Name].tsx` (PascalCase)

2. **Server Action**
   - Business logic → `actions/[name].ts` (kebab-case)
   - Related to existing → Add to existing action file
   - Utility function → `lib/[name].ts` (NOT in actions/)

3. **Utility Function**
   - Database-related → `lib/db.ts` or `lib/db/[name].ts`
   - Auth-related → `lib/auth-[name].ts`
   - General utility → `lib/[name].ts`
   - Formatting → `lib/format.ts`

4. **Type Definition**
   - Database types → `types/db.ts`
   - API types → `types/api.ts`
   - Domain-specific → `types/[domain].ts`

5. **Test File**
   - Unit test → Colocate with source or `tests/unit/`
   - Integration test → `tests/integration/`
   - Security test → `tests/security/`
   - Component test → Colocate with component

6. **Configuration**
   - App config → Root level (next.config.ts, etc.)
   - Tool config → Root level (vitest.config.ts, etc.)
   - Feature config → `components/[feature]/config.ts`

7. **Documentation**
   - Technical docs → `docs/[topic].md`
   - API docs → `docs/API.md`
   - Setup guide → `docs/DEVELOPMENT.md`

### Examples

**Adding a new payment action:**
```typescript
// actions/payment.ts
"use server";

export async function processPayment(data: PaymentData) {
  // Implementation
}
```

**Adding a new dashboard component:**
```typescript
// components/dashboard/RevenueChart.tsx
export function RevenueChart({ data }: RevenueChartProps) {
  // Implementation
}
```

**Adding a new utility:**
```typescript
// lib/date-utils.ts
export function formatRelativeDate(date: Date): string {
  // Implementation
}
```

---

## Setup

### Prerequisites
- Node.js 18.x or 20.x
- pnpm
- Docker (required for database)

### Installation
```bash
pnpm install
```

### Environment Variables
Create `.env.local` (see Environment Variables section above).

### Database Setup
```bash
# Start Docker services
pnpm run docker:up

# Setup database schema
pnpm run setup:schema

# Verify setup
pnpm run test:setup
```

### Development Server
```bash
pnpm run dev
```

## Docker Environment

The Docker setup provides a one-click development environment with the following services:

### Services Status
- **PostgreSQL**: Running on port 5435 (container: jomblo-postgres)
- **Redis**: Running on port 6380 (container: jomblo-redis) 
- **pgAdmin**: Running on port 5050 (container: jomblo-pgadmin)

### Management Tools
- **pgAdmin**: http://localhost:5050 (admin@jomblo.de / admin123)
- **PostgreSQL**: localhost:5435 (database: jomblo_dev)

### Docker Commands
```bash
pnpm run docker:up      # Start all services
pnpm run docker:down    # Stop all services
pnpm run docker:ps      # Check service status
pnpm run docker:logs    # View service logs
pnpm run docker:clean    # Reset environment (deletes volumes)
```

## Testing

### Unit Tests
```bash
pnpm test
```

### E2E Tests
```bash
pnpm test:e2e
```

### Coverage
```bash
pnpm test -- --coverage
```

## Workflows

- **Linting**: `pnpm run lint`
- **Build**: `pnpm run build`
- **Type Check**: `pnpm run typecheck`
- **CI/CD**: GitHub Actions with Node 18/20, ESLint, TypeScript.

## Code Style

- TypeScript strict
- JSDoc for exported functions
- ESLint rules enforced
- 100% Test Coverage required

---

*Last updated: 2026 - Repository standards for Jomblo Next.js project*
