# คู่มือการทำ Week 7: D2

**D2** ประกอบด้วยภารกิจ 3 งาน:

- **ภารกิจ 7.1**: มาตรฐานการเขียนโค้ด + ตั้งค่า Git
- **ภารกิจ 7.2**: วางแผนสปริ้นท์ 1 + ตั้งค่าสภาพแวดล้อม
- **ภารกิจ 7.3**: Code Review Training

**เวลาประมาณ:** 20-30 ชั่วโมง

---

## สารบัญ

- [บทนำ](#บทนำ)
- [ตารางการวางแผน](#ตารางการวางแผน)
- [ภารกิจ 7.1: Coding Standards + Git Setup](#ภารกิจ-71-coding-standards--git-setup-2-จุด)
  - [ขั้นตอนที่ 1: สร้างเอกสาร Coding Standards](#ขั้นตอนที่-1-สร้างเอกสาร-coding-standards)
  - [ขั้นตอนที่ 2: ตั้งค่า Git Repository](#ขั้นตอนที่-2-ตั้งค่า-git-repository)
  - [ขั้นตอนที่ 3: สร้าง Code Skeleton](#ขั้นตอนที่-3-สร้าง-code-skeleton)
  - [ขั้นตอนที่ 4: สร้างเอกสาร GitHub](#ขั้นตอนที่-4-สร้างเอกสาร-github)
- [ภารกิจ 7.2: Sprint 1 Planning + Development Setup](#ภารกิจ-72-sprint-1-planning--development-setup-25-จุด)
  - [ขั้นตอนที่ 1: วางแผน Sprint 1](#ขั้นตอนที่-1-วางแผน-sprint-1)
  - [ขั้นตอนที่ 2: สร้าง Database Setup Scripts](#ขั้นตอนที่-2-สร้าง-database-setup-scripts)
  - [ขั้นตอนที่ 3: สร้าง Development Environment Guide](#ขั้นตอนที่-3-สร้าง-development-environment-guide)
- [ภารกิจ 7.3: Code Review Training](#ภารกิจ-73-code-review-training-โบนัส-1-จุด)
  - [ขั้นตอนที่ 1: สร้าง Code Review Checklist](#ขั้นตอนที่-1-สร้าง-code-review-checklist)
  - [ขั้นตอนที่ 2: ทำการฝึก Code Review](#ขั้นตอนที่-2-ทำการฝึก-code-review)
  - [ขั้นตอนที่ 3: ตั้งค่า Automated Code Review](#ขั้นตอนที่-3-ตั้งค่า-automated-code-review)
- [Deliverables Checklist](#deliverables-checklist-ก่อนส่ง)
- [File Structure](#file-structure-เมื่อเสร็จ)
- [วิธีส่ง](#วิธีส่ง)
- [Tips & Best Practices](#tips--best-practices)
- [หากติดปัญหา](#หากติดปัญหา)
- [Final Checklist](#final-checklist)

---

## ตารางการวางแผน

```
วันจันทร์: ศึกษา + เริ่มภารกิจ 7.1
วันอังคาร: ทำภารกิจ 7.1 (Coding Standards) ต่อ
วันพุธ: ทำภารกิจ 7.1 (Git Setup) + ริเริ่มภารกิจ 7.2
วันพฤหัสบดี: ภารกิจ 7.2 (Sprint Planning)
วันศุกร์: ภารกิจ 7.2 (Development Setup) + ภารกิจ 7.3 (optional)
วันเสาร์-อาทิตย์: ทบทวน + ส่งงาน
```

---

## ภารกิจ 7.1: Coding Standards + Git Setup

### ขั้นตอนที่ 1: สร้างเอกสาร Coding Standards

**เป้าหมาย:** เขียน Coding Standards Document ที่ครอบคลุม

#### Step 1.1: สร้างไฟล์

```bash
# ที่ repository root
touch Coding_Standards.md
```

#### Step 1.2: เขียนโครงสร้าง

```markdown
# Coding Standards

## 1. Naming Conventions

### Classes/Objects

### Methods/Functions

### Variables

### Constants

### Database

## 2. Code Organization

### Folder Structure

### File Naming

## 3. Code Style

### Indentation

### Line Length

### Braces & Spacing

## 4. Comments & Documentation

### Class Comments

### Method Comments

### Inline Comments

## 5. Error Handling

### Exception Types

### Logging

## 6. Testing Standards

### Unit Test Naming

### Code Coverage

## 7. Code Review Guidelines
```

#### Step 1.3: ปรับแต่งตามเทคโนโลยีของคุณ

**สำหรับ Java:**

```markdown
### Classes - PascalCase

❌ userService
✅ UserService

### Methods - camelCase

❌ getUserByID
✅ getUserById

### Variables - camelCase

❌ user_name
✅ userName

### Constants - UPPER_SNAKE_CASE

MAX_RETRY_COUNT
DB_TIMEOUT

### Folder Structure

src/main/java/com/project/
├── controllers/
├── services/
├── models/
├── repositories/
├── middleware/
└── utils/
```

**สำหรับ JavaScript/Node:**

```markdown
### Classes - PascalCase

class UserService {}

### Functions - camelCase

function getUserById() {}

### Constants - UPPER_SNAKE_CASE

const MAX_RETRY = 3;

### Folder Structure

src/
├── controllers/
├── services/
├── models/
├── middleware/
├── utils/
└── config/
```

**สำหรับ Python:**

```markdown
### Class Names - PascalCase

class UserService:

### Function Names - snake_case

def get_user_by_id():

### Constants - UPPER_SNAKE_CASE

MAX_RETRY_COUNT = 3

### Folder Structure

src/
├── controllers/
├── services/
├── models/
├── middleware/
├── utils/
└── config/
```

#### Step 1.4: เพิ่มตัวอย่างชัดเจน

```markdown
## Code Style Examples

### ✓ Good Examples

[ใส่โค้ดตัวอย่างที่ดี]

### ✗ Bad Examples

[ใส่โค้ดตัวอย่างที่ไม่ดี]

### Why This Matters

[อธิบายเหตุผล]
```

#### Step 1.5: เพิ่มความเห็นและ Documentation

```markdown
### Comments for Classes

/\*\*

- [ไทย/English] คำอธิบายว่าคลาสนี้ทำอะไร
-
- @usage
- [ตัวอย่างการใช้]
  \*/
  public class UserService {
```

#### Step 1.6: Error Handling Standards

```markdown
## 5. Error Handling

### Exception Types

- ✅ Specific exceptions (e.g., UserNotFoundException)
- ❌ Generic Exception or RuntimeException

### Logging

- Log when: creating, updating, deleting
- Log level: ERROR for failures, INFO for major actions
- Include: timestamp, user, action, result

Example:
```

logger.error("Failed to create user: {}", error);
logger.info("User {} logged in", userId);

```

```

#### Step 1.7: ขอความเห็นจากทีม

```markdown
## Team Review & Approval

✅ Team members who reviewed:

- [ ] Developer 1: Date
- [ ] Developer 2: Date
- [ ] Tech Lead: Date

✅ Approved by: [Name], Date

Comments/Suggestions:
[ใส่ข้อเสนอแนะ]
```

✅ **Checklist ส่วนนี้:**

- [ ] Coding_Standards.md สร้าง
- [ ] ครอบคลุม: naming, organization, style, comments, errors, testing
- [ ] ตัวอย่างชัดเจนสำหรับแต่ละส่วน
- [ ] ทีมทั้งหมดอ่าน + ลงนาม

---

### ขั้นตอนที่ 2: ตั้งค่า Git Repository

**เป้าหมาย:** Setup Repository ให้พร้อมพัฒนา

#### Step 2.1: สร้าง .gitignore

```bash
# ที่ repository root สร้าง .gitignore

# For Java
echo "*.class
*.jar
target/
.DS_Store
.idea/
*.iml
.vscode/
.env
.env.local" > .gitignore

# For Node.js
echo "node_modules/
npm-debug.log
yarn-error.log
.env
.env.local
.DS_Store
.idea/
.vscode/" > .gitignore

# For Python
echo "__pycache__/
*.py[cod]
*$py.class
*.so
.Python
venv/
ENV/
.vscode/
.idea/
.env
.env.local" > .gitignore
```

#### Step 2.2: ตั้งค่า Branch Protection Rules

```
ที่ GitHub Repository:

1. ไปที่ Settings → Branches
2. เลือก main branch
3. Enable "Require pull request reviews before merging"
   - Required number of reviews: 2
4. Enable "Dismiss stale pull request approvals"
5. Enable "Require status checks to pass before merging"
   - Status checks: CI/CD pipeline
```

#### Step 2.3: สร้าง README.md

```markdown
# [Project Name]

## Description

[คำอธิบายโครงการ 2-3 ประโยค]

## Tech Stack

- Language: Java/Node.js/Python
- Framework: Spring Boot/Express/Flask
- Database: MySQL/PostgreSQL/MongoDB

## Prerequisites

- Java 11+ (or Node 14+, Python 3.8+)
- Maven/npm/pip
- MySQL/PostgreSQL

## Setup

### 1. Clone Repository

\`\`\`bash
git clone [repo-url]
cd [project-name]
\`\`\`

### 2. Install Dependencies

\`\`\`bash

# Java

mvn clean install

# Node.js

npm install

# Python

pip install -r requirements.txt
\`\`\`

### 3. Configure Database

\`\`\`bash

# Create database

mysql -u root -p < database/schema.sql

# Or use migrations

./mvn flyway:migrate
\`\`\`

### 4. Configure Environment

\`\`\`bash
cp .env.example .env

# Edit .env with your settings

\`\`\`

### 5. Run Application

\`\`\`bash

# Java

mvn spring-boot:run

# Node.js

npm start

# Python

python app.py
\`\`\`

Application runs at: http://localhost:8080

## Build & Test

\`\`\`bash

# Build

mvn clean package

# Test

mvn test

# Coverage

mvn jacoco:report
\`\`\`

## Git Workflow

1. Create branch: \`git checkout -b feature/feature-name\`
2. Make changes
3. Commit: \`git commit -m "feat: description"\`
4. Push: \`git push origin feature/feature-name\`
5. Create PR on GitHub
6. Request review (2+ reviewers)
7. Merge after approval

## Coding Standards

See [Coding_Standards.md](Coding_Standards.md)

## Contact

[Your Email/Slack]
```

#### Step 2.4: สร้าง PR Template

```bash
# สร้าง .github/pull_request_template.md

mkdir -p .github
cat > .github/pull_request_template.md << 'EOF'
## Description
[คำอธิบายสั้น ๆ ของการเปลี่ยนแปลง]

## Related Issue
Closes #[issue-number]

## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update

## How to Test
[ขั้นตอนการทดสอบ]

## Checklist
- [ ] Code follows Coding Standards
- [ ] Added tests for new features
- [ ] All tests pass locally
- [ ] No console errors/warnings
- [ ] Updated documentation
- [ ] No hardcoded secrets/passwords

## Screenshots (if applicable)
[ใส่รูปภาพถ้าจำเป็น]
EOF
```

#### Step 2.5: ตั้งค่า GitHub Actions (Basic CI)

```bash
# สร้าง .github/workflows/ci.yml

mkdir -p .github/workflows
cat > .github/workflows/ci.yml << 'EOF'
name: CI Pipeline

on:
  push:
    branches: [develop, main]
  pull_request:
    branches: [develop, main]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2

    # For Java
    - name: Set up Java
      uses: actions/setup-java@v2
      with:
        java-version: '11'

    - name: Build with Maven
      run: mvn clean package

    - name: Run tests
      run: mvn test

    # For Node.js
    # - name: Set up Node.js
    #   uses: actions/setup-node@v2
    #   with:
    #     node-version: '14'
    #
    # - name: Install dependencies
    #   run: npm ci
    #
    # - name: Run tests
    #   run: npm test

    # For Python
    # - name: Set up Python
    #   uses: actions/setup-python@v2
    #   with:
    #     python-version: '3.8'
    #
    # - name: Install dependencies
    #   run: pip install -r requirements.txt
    #
    # - name: Run tests
    #   run: pytest
EOF
```

#### Step 2.6: Commit & Push

```bash
git add .gitignore README.md .github/
git commit -m "docs: add repository configuration"
git push origin main
```

✅ **Checklist ส่วนนี้:**

- [ ] .gitignore สร้างเสร็จ
- [ ] Branch protection rules ตั้งค่า
- [ ] README.md เขียนเสร็จ
- [ ] PR template สร้าง
- [ ] GitHub Actions CI ตั้งค่าเบื้องต้น
- [ ] Repository push สำเร็จ

---

### ขั้นตอนที่ 3: สร้าง Code Skeleton

**เป้าหมาย:** สร้างโครงสร้างโปรเจกต์พื้นฐาน

#### Step 3.1: สร้างโครงสร้างโฟลเดอร์

```bash
# Java Project Structure
mkdir -p src/main/java/com/project/{controllers,services,models,repositories,middleware,utils,config,exceptions}
mkdir -p src/test/java/com/project/{controllers,services,models,repositories}
mkdir -p database/migrations
mkdir -p database/seeds
mkdir -p docs/Sprint_Plans
mkdir -p docs/Setup

# Node.js Project Structure
mkdir -p src/{controllers,services,models,middleware,utils,config,routes,exceptions}
mkdir -p tests/{controllers,services,models}
mkdir -p database/migrations
mkdir -p database/seeds
mkdir -p docs/Sprint_Plans
mkdir -p docs/Setup

# Python Project Structure
mkdir -p src/{controllers,services,models,middleware,utils,config,exceptions}
mkdir -p tests/{controllers,services,models}
mkdir -p database/migrations
mkdir -p database/seeds
mkdir -p docs/Sprint_Plans
mkdir -p docs/Setup
```

#### Step 3.2: สร้าง Main Application Class

**สำหรับ Java (Spring Boot):**

```java
// src/main/java/com/project/Application.java

package com.project;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
```

**สำหรับ Node.js (Express):**

```javascript
// src/index.js

const express = require("express");
const app = express();

app.use(express.json());

// Health check
app.get("/api/health", (req, res) => {
  res.json({ status: "UP" });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

module.exports = app;
```

**สำหรับ Python (Flask):**

```python
# src/app.py

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/health', methods=['GET'])
def health():
    return jsonify({"status": "UP"})

if __name__ == '__main__':
    app.run(debug=True, port=5000)
```

#### Step 3.3: สร้าง Config Classes

**สำหรับ Java:**

```java
// src/main/java/com/project/config/ApplicationConfig.java

package com.project.config;

import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationConfig {
    // Database beans
    // Service beans
    // Repository beans
}
```

**สำหรับ Node.js:**

```javascript
// src/config/config.js

module.exports = {
  database: {
    host: process.env.DB_HOST || "localhost",
    port: process.env.DB_PORT || 3306,
    name: process.env.DB_NAME || "project_db",
    user: process.env.DB_USER || "root",
    password: process.env.DB_PASSWORD || "",
  },
  server: {
    port: process.env.PORT || 3000,
  },
  jwt: {
    secret: process.env.JWT_SECRET || "secret-key",
  },
};
```

#### Step 3.4: สร้าง Base Model/Entity

**สำหรับ Java:**

```java
// src/main/java/com/project/models/BaseEntity.java

package com.project.models;

import javax.persistence.*;
import java.time.LocalDateTime;

@MappedSuperclass
public class BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "created_at")
    private LocalDateTime createdAt = LocalDateTime.now();

    @Column(name = "updated_at")
    private LocalDateTime updatedAt = LocalDateTime.now();

    // Getters & Setters
}
```

**สำหรับ Node.js:**

```javascript
// src/models/BaseModel.js

module.exports = class BaseModel {
  constructor(id, createdAt, updatedAt) {
    this.id = id;
    this.createdAt = createdAt || new Date();
    this.updatedAt = updatedAt || new Date();
  }
};
```

#### Step 3.5: สร้าง Build Scripts

**สำหรับ Java (pom.xml):**

```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.project</groupId>
    <artifactId>project-api</artifactId>
    <version>1.0.0</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- Spring Boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.7.0</version>
        </dependency>

        <!-- Database -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>
    </dependencies>
</project>
```

**สำหรับ Node.js (package.json):**

```json
{
  "name": "project-api",
  "version": "1.0.0",
  "main": "src/index.js",
  "scripts": {
    "start": "node src/index.js",
    "dev": "nodemon src/index.js",
    "test": "jest",
    "lint": "eslint src/",
    "build": "echo 'Building...'"
  },
  "dependencies": {
    "express": "^4.18.1",
    "mysql2": "^2.3.3",
    "dotenv": "^16.0.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.16",
    "jest": "^27.5.1",
    "eslint": "^8.15.0"
  }
}
```

#### Step 3.6: ทดสอบ Build

```bash
# Java
mvn clean compile

# Node.js
npm install
npm start

# Python
pip install flask
python src/app.py
```

✅ **Checklist ส่วนนี้:**

- [ ] Folder structure สร้างเสร็จ
- [ ] Main application class เขียนเสร็จ
- [ ] Config files ตั้งค่าเสร็จ
- [ ] Base model/entity สร้าง
- [ ] Build script ทำงาน
- [ ] Application compile/run สำเร็จ

---

### ขั้นตอนที่ 4: สร้างเอกสาร GitHub

#### Step 4.1: สร้าง docs/ folder

```bash
mkdir -p docs/Sprint_Plans
mkdir -p docs/Setup
```

#### Step 4.2: สร้าง DEVELOPMENT.md (Development Environment)

```markdown
# Development Environment Setup

## System Requirements

- OS: Windows/Mac/Linux
- Memory: 8GB RAM (minimum)
- Disk: 500MB free space

## Installation

### Step 1: Install Java

[ขั้นตอนการติดตั้ง]

### Step 2: Install Maven/npm/pip

[ขั้นตอนการติดตั้ง]

### Step 3: Install Database

[ขั้นตอนการติดตั้ง MySQL]

### Step 4: Clone & Setup

[ขั้นตอนการ clone]

## Verification

[วิธีตรวจสอบว่าติดตั้งเสร็จแล้ว]
```

#### Step 4.3: สร้าง ARCHITECTURE.md

```markdown
# Project Architecture

## System Design

[แสดงแผนระบบ]

## Component Overview

[อธิบายส่วนประกอบ]

## Data Flow

[วิธีการไหลของข้อมูล]
```

✅ **Checklist ส่วนที่ 7.1:**

- [ ] Coding_Standards.md เขียนเสร็จ + ทีมอนุมัติ
- [ ] .gitignore ตั้งค่า
- [ ] Branch protection rules ตั้งค่า
- [ ] README.md เขียนเสร็จ
- [ ] PR template สร้าง
- [ ] GitHub Actions CI ตั้งค่า
- [ ] Code skeleton สร้างเสร็จ
- [ ] Build script ทำงาน
- [ ] Repository push เสร็จ

---

## ภารกิจ 7.2: Sprint 1 Planning + Development Setup

### ขั้นตอนที่ 1: วางแผน Sprint 1

**เป้าหมาย:** สร้าง Sprint 1 Backlog ที่สมจริง

#### Step 1.1: สร้างเอกสาร Sprint_1_Backlog.md

```markdown
# Sprint 1 Backlog

## Sprint Duration

- Start Date: [วันที่เริ่ม]
- End Date: [วันที่สิ้นสุด]
- Duration: 2 weeks (10 working days)

## Sprint Goal

[เขียนเป้าหมายที่ชัดเจน เช่น:
"ให้ผู้ใช้สามารถสมัครสมาชิก เข้าสู่ระบบ และดูรายการผลิตภัณฑ์ได้"]

## Team Capacity

- Team Size: [จำนวนสมาชิก]
- Available Hours: [ชั่วโมงทั้งหมด]
- Estimated Capacity: 30-35 story points

## User Stories Selected

### Story 1: [ชื่อเรื่องราว]

- Story Points: [ประมาณ]
- Priority: High/Medium/Low
- Assigned To: [ชื่อคน]
- Tasks:
  - Task 1.1: [รายละเอียด]
  - Task 1.2: [รายละเอียด]
  - Task 1.3: [รายละเอียด]
- Definition of Done:
  - [ ] Code review passed
  - [ ] Unit tests written
  - [ ] Integration tested
  - [ ] Documentation updated

[ทำซ้ำสำหรับเรื่องราวอื่น ๆ]

## Sprint Schedule

- Daily Standup: 09:00 - 09:15
- Development: 10:00 - 17:00
- Sprint Review: [วันและเวลา]
- Sprint Retrospective: [วันและเวลา]

## Risk Register

[ดูขั้นตอนถัดไป]
```

#### Step 1.2: สร้าง Risk_Register.md

```markdown
# Risk Register - Sprint 1

## Risk #1: [ชื่อความเสี่ยง]

- Probability: Low/Medium/High
- Impact: Low/Medium/High
- Description: [คำอธิบาย]
- Mitigation Strategy: [วิธีบรรเทา]
- Owner: [ผู้รับผิดชอบ]
- Status: Identified/Monitoring/Mitigated

## Risk #2: [Database Connection Issues]

- Probability: Medium
- Impact: High (blocks development)
- Description: MySQL server may not start properly
- Mitigation Strategy:
  - Have Docker setup as alternative
  - Create setup troubleshooting guide
- Owner: Tech Lead
- Status: Identified

## Risk #3: [Scope Creep]

- Probability: High
- Impact: High (miss deadline)
- Description: PO may request additional features
- Mitigation Strategy:
  - Clear scope definition
  - Scrum Master protects sprint
  - Use change control process
- Owner: Scrum Master
- Status: Identified

[เพิ่มเติม 5-7 risks]
```

#### Step 1.3: สร้าง Team_Communication_Plan.md

```markdown
# Team Communication Plan

## Communication Channels

- Primary: [Slack/Discord/Teams]
- Secondary: Email
- Escalation: [ชื่อ Scrum Master/Tech Lead]

## Meeting Schedule

### Daily Standup

- **When:** 09:00 AM
- **Duration:** 15 minutes
- **Format:** In-person/Video call
- **Attendees:** All team members
- **Agenda:**
  1. What did I do yesterday?
  2. What will I do today?
  3. Any blockers?

### Code Review

- **When:** Every morning 09:15 - 10:00
- **Process:** Pull requests reviewed by 2+ reviewers
- **Turnaround:** 24 hours

### Sprint Review

- **When:** [วันและเวลา]
- **Duration:** 30 minutes
- **Attendees:** Team + PO + Stakeholders

### Sprint Retrospective

- **When:** [วันและเวลา]
- **Duration:** 30 minutes
- **Attendees:** Team only

## Escalation Matrix

| Issue    | Contact      | Response Time |
| -------- | ------------ | ------------- |
| Blocker  | Tech Lead    | 1 hour        |
| Critical | Scrum Master | 2 hours       |
| High     | Team Lead    | 4 hours       |
| Medium   | Assigned Dev | 24 hours      |

## Working Hours

- Core Hours: 10:00 - 15:00
- Flexible: 08:00 - 18:00
- Timezone: [เขตเวลา]
```

#### Step 1.4: เพิ่มรายละเอียด Story Points

```
วิธีประมาณ Story Points:

1 Point = ~2 ชั่วโมง
2 Points = ~4 ชั่วโมง
3 Points = ~6 ชั่วโมง
5 Points = ~10 ชั่วโมง
8 Points = ~16 ชั่วโมง
13 Points = ~26 ชั่วโมง

Capacity Example:
- Team: 5 people
- Days: 10 working days
- Hours/day: 8
- Total: 400 hours
- Minus overhead (standup, review, interruptions): ~50 hours
- Available: 350 hours
- Average: 10 hours/point
- Capacity: 35 points
- Conservative: 30-32 points (20% buffer)
```

✅ **Checklist ส่วนนี้:**

- [ ] Sprint_1_Backlog.md เขียนเสร็จ (8-12 stories)
- [ ] Task breakdown ชัดเจน (3-5 tasks per story)
- [ ] Story points realistic
- [ ] Team assignments ชัดเจน
- [ ] Risk_Register.md ระบุความเสี่ยง 5+ รายการ
- [ ] Team_Communication_Plan.md เขียนเสร็จ

---

### ขั้นตอนที่ 2: สร้าง Database Setup Scripts

**เป้าหมาย:** เตรียม Database schema + data

#### Step 2.1: สร้าง Database Schema

```bash
# database/schema.sql

CREATE DATABASE IF NOT EXISTS project_db;
USE project_db;

CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE products (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    price DECIMAL(10, 2),
    stock INT DEFAULT 0,
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE orders (
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT NOT NULL,
    total_amount DECIMAL(10, 2),
    status VARCHAR(50) DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_orders_user_id ON orders(user_id);
CREATE INDEX idx_products_active ON products(is_active);
```

#### Step 2.2: สร้าง Seed Data

```bash
# database/seeds.sql

USE project_db;

-- Sample Users
INSERT INTO users (email, password_hash, first_name, last_name) VALUES
('john@example.com', '$2b$10$...', 'John', 'Doe'),
('jane@example.com', '$2b$10$...', 'Jane', 'Smith');

-- Sample Products
INSERT INTO products (name, description, price, stock) VALUES
('Laptop', 'High performance laptop', 999.99, 10),
('Mouse', 'Wireless mouse', 29.99, 50),
('Keyboard', 'Mechanical keyboard', 79.99, 30);
```

#### Step 2.3: สร้าง Setup Script

```bash
# setup.sh

#!/bin/bash

echo "Setting up project..."

# 1. Install dependencies
echo "Installing dependencies..."
if [ "$1" = "java" ]; then
    mvn clean install
elif [ "$1" = "node" ]; then
    npm install
elif [ "$1" = "python" ]; then
    pip install -r requirements.txt
fi

# 2. Setup Database
echo "Setting up database..."
mysql -u root -p < database/schema.sql
mysql -u root -p < database/seeds.sql

# 3. Create environment file
if [ ! -f .env ]; then
    cp .env.example .env
    echo ".env file created. Please update with your settings."
fi

# 4. Build application
echo "Building application..."
if [ "$1" = "java" ]; then
    mvn clean package
elif [ "$1" = "node" ]; then
    npm run build
fi

echo "✅ Setup complete!"
echo "Run: npm start (or mvn spring-boot:run for Java)"
```

#### Step 2.4: สร้าง Environment Template

```bash
# .env.example

# Database
DB_HOST=localhost
DB_PORT=3306
DB_NAME=project_db
DB_USER=root
DB_PASSWORD=

# Server
PORT=3000
NODE_ENV=development

# JWT
JWT_SECRET=your-secret-key-here
JWT_EXPIRY=24h

# API
API_URL=http://localhost:3000
API_VERSION=v1

# Logging
LOG_LEVEL=debug
```

✅ **Checklist ส่วนนี้:**

- [ ] Database schema SQL สร้าง
- [ ] Sample data seeds สร้าง
- [ ] setup.sh script สร้าง
- [ ] .env.example template สร้าง
- [ ] Database setup ทดสอบและ work

---

### ขั้นตอนที่ 3: สร้าง Development Environment Guide

#### Step 3.1: สร้าง docs/Setup/DEVELOPMENT.md

```markdown
# Development Environment Setup Guide

## System Requirements

- OS: Windows 10/Mac OS 10.15+/Ubuntu 18.04+
- RAM: 8GB minimum
- Disk: 500MB free

## Installation Steps

### For Java Developers

1. **Install Java**
   \`\`\`bash

   # Mac: brew install openjdk@11

   # Windows: Download from oracle.com

   java -version # Verify
   \`\`\`

2. **Install Maven**
   \`\`\`bash
   brew install maven
   mvn -version # Verify
   \`\`\`

3. **Install MySQL**
   \`\`\`bash
   brew install mysql
   mysql --version
   \`\`\`

4. **Clone Repository**
   \`\`\`bash
   git clone https://github.com/yourrepo/project.git
   cd project
   \`\`\`

5. **Build Project**
   \`\`\`bash
   mvn clean install
   \`\`\`

6. **Setup Database**
   \`\`\`bash
   ./setup.sh java
   \`\`\`

7. **Run Application**
   \`\`\`bash
   mvn spring-boot:run
   \`\`\`

### For Node.js Developers

1. **Install Node.js**
   \`\`\`bash
   brew install node
   node --version && npm --version
   \`\`\`

2. **Install Dependencies**
   \`\`\`bash
   npm install
   \`\`\`

3. **Setup Database**
   \`\`\`bash
   npm run setup
   \`\`\`

4. **Run Development Server**
   \`\`\`bash
   npm run dev
   \`\`\`

### For Python Developers

1. **Install Python**
   \`\`\`bash
   python --version # Should be 3.8+
   \`\`\`

2. **Create Virtual Environment**
   \`\`\`bash
   python -m venv venv
   source venv/bin/activate # Mac/Linux
   venv\\Scripts\\activate # Windows
   \`\`\`

3. **Install Dependencies**
   \`\`\`bash
   pip install -r requirements.txt
   \`\`\`

4. **Setup Database**
   \`\`\`bash
   python setup.py
   \`\`\`

5. **Run Application**
   \`\`\`bash
   python app.py
   \`\`\`

## Verification

After setup, verify:

- [ ] Application runs: http://localhost:3000 (or 8080/5000)
- [ ] Health check: http://localhost:3000/api/health → {"status":"UP"}
- [ ] Database connected: Check logs for success message
- [ ] All tests pass: \`npm test\` or \`mvn test\`

## Troubleshooting

### Port Already in Use

\`\`\`bash

# Find process using port 3000

lsof -i :3000

# Kill process

kill -9 <PID>
\`\`\`

### Database Connection Failed

- Check MySQL is running: \`mysql -u root -p\`
- Verify .env file has correct credentials
- Check database exists: \`show databases;\`

### Dependencies not installing

- Clear cache: \`npm cache clean --force\`
- Delete node_modules: \`rm -rf node_modules\`
- Reinstall: \`npm install\`

## IDE Setup

### VS Code

- Extensions: Rest Client, ESLint, Prettier
- Settings: Format on save enabled

### IntelliJ (Java)

- Plugins: Spring Boot, CheckStyle, Sonarqube
- Code Style: Match Coding_Standards.md

### PyCharm (Python)

- Interpreter: Select venv
- Style: Match Coding_Standards.md
```

✅ **Checklist ส่วน 7.2:**

- [ ] Sprint_1_Backlog.md ชัดเจน
- [ ] Risk_Register.md ระบุความเสี่ยง
- [ ] Team_Communication_Plan.md เสร็จ
- [ ] Database schema SQL เขียน
- [ ] Seed data เตรียม
- [ ] setup.sh script ทำงาน
- [ ] .env.example สร้าง
- [ ] Development guide เขียนเสร็จ
- [ ] Team members ทั้งหมด setup สำเร็จ

---

## ภารกิจ 7.3: Code Review Training

### ขั้นตอนที่ 1: สร้าง Code Review Checklist

#### Step 1.1: สร้าง Code_Review_Checklist.md

```markdown
# Code Review Checklist

## Before Reviewing

- [ ] Understand the PR context (issue #xxx)
- [ ] Read the test cases first
- [ ] Check if changes match the acceptance criteria

## Functionality & Logic

- [ ] Code does what it's supposed to do
- [ ] Edge cases handled (null, empty, negative values)
- [ ] No hardcoded values (use constants)
- [ ] Error messages are clear and helpful
- [ ] Logging is appropriate

## Code Quality

- [ ] Follows Coding Standards
- [ ] Variable names are descriptive
- [ ] Methods are small (< 30 lines)
- [ ] No code duplication
- [ ] Proper indentation & formatting

## Testing

- [ ] Unit tests provided
- [ ] Tests cover positive & negative cases
- [ ] Test coverage > 80%
- [ ] No skipped/commented tests
- [ ] Tests are meaningful (not just stubs)

## Security

- [ ] No hardcoded passwords/secrets
- [ ] Input validation present
- [ ] SQL injection prevented
- [ ] XSS protection (if frontend)
- [ ] Authentication/authorization checks

## Performance

- [ ] No N+1 query problems
- [ ] No excessive loops
- [ ] Appropriate data structures used
- [ ] No memory leaks
- [ ] Reasonable time complexity

## Documentation

- [ ] Code comments for complex logic
- [ ] Method/function documentation
- [ ] README updated if needed
- [ ] API documentation updated

## Database (if applicable)

- [ ] Schema changes included
- [ ] Migrations written
- [ ] Indexes added where needed
- [ ] Backward compatible

## Reviewing Tips

- ✅ Be constructive & kind
- ✅ Ask questions instead of demanding
- ✅ Suggest, don't command
- ✅ Praise good code
- ✅ Focus on important issues first

## Review Comments Template

### For Issues:

"I'm concerned about [issue]. Consider [suggestion] because [reason]."

### For Questions:

"What's the reason for [code]? Have you considered [alternative]?"

### For Praise:

"Great implementation of [feature]! I like how you [specific thing]."
```

### ขั้นตอนที่ 2: ทำการฝึก Code Review

#### Step 2.1: สร้าง Sample Code (intentionally with issues)

```java
// Sample code with 10 intentional issues

public class UserService {

    // Issue 1: No error handling
    public User login(String email, String password) {
        User user = database.findByEmail(email);
        if (user.password.equals(password)) {
            return user;
        }
        return null;
    }

    // Issue 2: Method too long, hardcoded values
    public void processOrder(String userId) {
        User user = getUser(userId);
        List<Product> products = getCart(userId);

        double total = 0;
        for (Product p : products) {
            total += p.price;
        }

        // Issue 3: No tax/shipping, hardcoded logic
        double finalTotal = total * 1.1; // 10% hardcoded

        // Issue 4: SQL injection vulnerable
        String query = "UPDATE orders SET total = " + finalTotal;
        database.execute(query);

        // Issue 5: No logging
        // ... more code
    }

    // Issue 6: Poor naming
    public boolean check(User u) {
        return u.status == 1 && u.type == 2;
    }

    // Issue 7: Duplicated code
    public User createUser(String email, String name) {
        if (email == null || email.isEmpty()) {
            return null;
        }
        User u = new User();
        u.email = email;
        u.name = name;
        return u;
    }

    // Issue 8: No documentation
    public void syncWithExternalAPI() {
        // ...
    }
}
```

#### Step 2.2: ขอให้ทีมทำ Code Review

```markdown
# Code Review Training Exercise

## Exercise 1: Review the Sample Code

1. Read the code in Sample_UserService.java
2. Use Code_Review_Checklist.md
3. Identify all issues
4. Write constructive comments
5. Suggest improvements

## Exercise 2: Pair Review

- Dev A & Dev B: Review code together
- Discuss & align on standards
- Record key insights

## Exercise 3: Review Actual PR

- Use first real PR in sprint
- Apply what learned
- Document process
```

#### Step 2.3: บันทึก Training Results

```markdown
# Code Review Training Report

## Date: [วันที่]

## Facilitator: [ชื่อ]

## Attendees: [รายชื่อ]

## Learning Outcomes

### Key Lessons

1. [บทเรียนที่ 1]
2. [บทเรียนที่ 2]
   ...

### Common Issues Found

- [ประเภทปัญหา]
- [ประเภทปัญหา]

### Team Agreements

- [ตกลงร่วมกัน]
- [ตกลงร่วมกัน]

### Action Items

- [ ] [งานติดตาม]
- [ ] [งานติดตาม]

## Next Steps

1. Apply checklist on all PRs
2. Weekly code review sync
3. Review and update standards
```

### ขั้นตอนที่ 3: ตั้งค่า Automated Code Review

#### Step 3.1: ตั้งค่า GitHub Actions Linting

```bash
# .github/workflows/code-quality.yml

name: Code Quality

on: [push, pull_request]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2

    # For Node.js
    - name: ESLint
      run: npx eslint src/ --format json > report.json
      continue-on-error: true

    # For Java
    - name: CheckStyle
      run: mvn checkstyle:check

    # For Python
    - name: Pylint
      run: pylint src/ --exit-zero
```

#### Step 3.2: ตั้งค่า Code Coverage

```bash
# .github/workflows/coverage.yml

name: Code Coverage

on: [pull_request]

jobs:
  coverage:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Run Tests with Coverage
      run: mvn clean test jacoco:report

    - name: Upload Coverage
      uses: codecov/codecov-action@v2
      with:
        file: ./target/site/jacoco/jacoco.xml
```

✅ **Checklist ส่วน 7.3 (โบนัส):**

- [ ] Code_Review_Checklist.md เขียนเสร็จ
- [ ] Sample code สร้าง (พร้อมปัญหา)
- [ ] Team ทำ review exercise
- [ ] Code_Review_Training_Report.md เขียน
- [ ] Linting automation ตั้งค่า
- [ ] Code coverage tracking ตั้งค่า
- [ ] Team aligned on review process

---

## Deliverables Checklist (ก่อนส่ง)

ก่อนส่ง D2 ตรวจสอบให้แน่ใจว่า:

### ภารกิจ 7.1

- [ ] Coding_Standards.md ครบถ้วน (8+ sections)
- [ ] ตัวอย่างชัดเจนสำหรับแต่ละส่วน
- [ ] ทีมทั้งหมด signed off
- [ ] Repository ตั้งค่าเสร็จ:
  - [ ] .gitignore
  - [ ] Branch protection rules
  - [ ] PR template
  - [ ] README.md
  - [ ] GitHub Actions CI
- [ ] Code Skeleton compile & run ได้
- [ ] All files push to GitHub

### ภารกิจ 7.2

- [ ] Sprint_1_Backlog.md:
  - [ ] 8-12 user stories
  - [ ] Story points assigned
  - [ ] Tasks breakdown (3-5 per story)
  - [ ] Clear assignments
  - [ ] Dependencies marked
- [ ] Risk_Register.md (5+ risks identified)
- [ ] Team_Communication_Plan.md
- [ ] Database setup:
  - [ ] schema.sql ระบุฐานข้อมูล
  - [ ] seeds.sql เตรียมข้อมูล
  - [ ] setup.sh ทำงาน
  - [ ] Database verified
- [ ] Development guide (DEVELOPMENT.md)
- [ ] .env.example template
- [ ] All developers ✅ local setup work

### ภารกิจ 7.3

- [ ] Code_Review_Checklist.md
- [ ] Code_Review_Training_Report.md
- [ ] GitHub Actions linting ตั้งค่า
- [ ] Code coverage reporting ตั้งค่า

---

## File Structure เมื่อเสร็จ

```
project-root/
├── Coding_Standards.md          ✅ ภารกิจ 7.1
├── README.md                    ✅ ภารกิจ 7.1
├── .gitignore                   ✅ ภารกิจ 7.1
├── .env.example                 ✅ ภารกิจ 7.2
├── pom.xml (or package.json)    ✅ ภารกิจ 7.1
├── setup.sh                     ✅ ภารกิจ 7.2
│
├── src/                         ✅ Code Skeleton
│   ├── main/java/...
│   ├── controllers/
│   ├── services/
│   ├── models/
│   └── config/
│
├── database/
│   ├── schema.sql               ✅ ภารกิจ 7.2
│   ├── seeds.sql                ✅ ภารกิจ 7.2
│   └── migrations/
│
├── tests/
│   └── ...
│
├── docs/
│   ├── Sprint_Plans/
│   │   └── Sprint_1_Backlog.md  ✅ ภารกิจ 7.2
│   ├── Setup/
│   │   └── DEVELOPMENT.md       ✅ ภารกิจ 7.2
│   ├── Risk_Register.md         ✅ ภารกิจ 7.2
│   ├── Team_Communication_Plan.md ✅ ภารกิจ 7.2
│   ├── Code_Review_Checklist.md ✅ ภารกิจ 7.3
│   └── Code_Review_Training_Report.md ✅ ภารกิจ 7.3
│
├── .github/
│   ├── pull_request_template.md ✅ ภารกิจ 7.1
│   └── workflows/
│       ├── ci.yml               ✅ ภารกิจ 7.1
│       ├── code-quality.yml     ✅ ภารกิจ 7.3
│       └── coverage.yml         ✅ ภารกิจ 7.3
│
└── [other project files]
```

---

## วิธีส่ง

### Step 1: ตรวจสอบ Checklist

```bash
# ตรวจสอบว่าทั้งหมด push ไปแล้ว
git status  # Should be clean
```

### Step 2: สร้าง Release Tag

```bash
git tag -a v1.0.0-D2-ready -m "D2 Deliverable Ready"
git push origin v1.0.0-D2-ready
```

### Step 3: ส่ง GitHub Link

```
ส่งไปยัง [ที่ส่งงาน]:
- GitHub Repository: [link]
- Branch: main
- Tag: v1.0.0-D2-ready
- Submission Date: [วันที่]
```

### Step 4: เตรียม Presentation (ถ้าจำเป็น)

```
Slide presentation (5-10 นาที):
1. Project Overview (1 slide)
2. Architecture (1 slide)
3. Development Environment (1 slide)
4. Sprint 1 Plan (2 slides)
5. Team & Communication (1 slide)
6. Risks & Mitigation (1 slide)
7. Timeline (1 slide)
```

---

## Tips & Best Practices

### สิ่งที่ควรทำ

- **Start Early:** ห้ามรอถึงวันส่ง!
- **Collaborate:** ทีมควรทำงานร่วมกัน
- **Iterate:** ได้ feedback จากผู้สอน แล้วแก้ไข
- **Test Everything:** ตรวจสอบว่า setup ทำงานจริง
- **Document Well:** เอกสารต้องชัดเจน
- **Version Control:** Commit บ่อย ๆ
- **Code Review:** ทำ review ก่อน merge

### สิ่งที่ต้องหลีกเลี่ยง

- ❌ เขียนมาตรฐาน แต่ไม่ปฏิบัติตามเอง
- ❌ ประมาณ story points เกินความเป็นจริง
- ❌ ไม่มี risk management
- ❌ เอกสาร incomplete/unclear
- ❌ Code skeleton ไม่ compile
- ❌ ไม่ได้ test setup ของตัวเอง

---

## หากติดปัญหา

### ปัญหา: ไม่รู้เขียน Coding Standards ยังไง

→ ดู Google Java Style Guide + อัปแบบให้เหมาะกับโปรเจกต์

### ปัญหา: Story points ยากต้อง estimate

→ ประมาณตามชั่วโมง แล้วแปลงเป็น points

### ปัญหา: Setup ไม่ทำงาน

→ ตรวจสอบ: Java version, MySQL running, Port available

### ปัญหา: ไม่รู้ Risk ไหนต้องจด

→ คิดถึง: technical, resource, schedule, scope risks

---

## Final Checklist

ก่อน submit สุดท้าย:

- [ ] ทั้ง 3 ภารกิจ ทำเสร็จ
- [ ] เอกสารทั้งหมด push ไปแล้ว
- [ ] Code ทั้งหมด compile/run ได้
- [ ] Database setup ทำงาน
- [ ] Team members ทั้งหมด aligned
- [ ] GitHub Actions passing
- [ ] ไม่มี hardcoded secrets
- [ ] README ชัดเจน
- [ ] ตรวจสอบ spelling & grammar

---
