# Story 1.2-b: Complete Categories Collection (Story 1.2 split)

**Status:** Done
**Epic:** Epic 1 - Webflow to Payload CMS + Astro Migration
**Priority:** P0 (Critical Blocker for Story 1.9)
**Estimated Time:** 0.5 hour (30 minutes)

## Story

**As a** CMS Administrator,
**I want** a complete Categories collection with all necessary fields including theming colors,
**So that** blog categories can be properly themed with dynamic colors and Story 1.9 (Blog System) can proceed.

## Context

This is a Sprint 1 split story from the original Story 1.2 (Payload CMS Collections Definition). The Categories collection currently exists but is incomplete - missing 4 critical fields needed for category theming in the Blog System (Story 1.9).

**Story Source:**
- Split from `docs/prd/05-epic-stories.md` - Story 1.2
- Technical spec: `docs/prd/payload-cms-modification-plan.md` - Task 1.2.2
- Execution plan: `docs/prd/epic-1-execution-plan.md` - Story 1.2 Phase 2

**Current State:**
- File exists at `apps/backend/src/collections/Categories.ts`
- Has only 2 fields: `title` and `slug`
- Missing: `nameEn`, `order`, `textColor`, `backgroundColor`

## Acceptance Criteria

1. **AC1 - nameEn Field Added**: English name field added for internationalization support
2. **AC2 - order Field Added**: Number field for sorting (default: 0, sidebar position)
3. **AC3 - textColor Field Added**: Text field for hex color code (default: #000000)
4. **AC4 - backgroundColor Field Added**: Text field for hex color code (default: #ffffff)
5. **AC5 - Title Label Updated**: Title field label changed to "分類名稱（中文）" for clarity
6. **AC6 - TypeScript Types Generated**: Running `pnpm build` regenerates payload-types.ts without errors
7. **AC7 - Admin UI Working**: All fields visible and functional in Payload Admin panel

## Previous Story Learnings (from Story 1.2)

From Story 1.2 execution (43% complete):
- Categories collection file already exists at `apps/backend/src/collections/Categories.ts`
- Access control already configured (authenticated for create/update/delete, anyone for read)
- slugField() utility already integrated
- Collection already registered in payload.config.ts
- **This is a modification task, not creation**

## Dev Technical Guidance

### Current Categories.ts Structure

```typescript
import type { CollectionConfig } from 'payload'
import { anyone } from '../access/anyone'
import { authenticated } from '../access/authenticated'
import { slugField } from '@/fields/slug'

export const Categories: CollectionConfig = {
  slug: 'categories',
  access: {
    create: authenticated,
    delete: authenticated,
    read: anyone,
    update: authenticated,
  },
  admin: {
    useAsTitle: 'title',
  },
  fields: [
    {
      name: 'title',
      type: 'text',
      required: true,
    },
    ...slugField(),
  ],
}
```

### Required Changes

**1. Update title field** (add label):
```typescript
{
  name: 'title',
  type: 'text',
  required: true,
  label: '分類名稱（中文）',
},
```

**2. Add nameEn field** (after title):
```typescript
{
  name: 'nameEn',
  type: 'text',
  label: '英文名稱',
  admin: {
    description: '用於 URL 或國際化',
  },
},
```

**3. Add order field** (sidebar position):
```typescript
{
  name: 'order',
  type: 'number',
  label: '排序順序',
  defaultValue: 0,
  admin: {
    position: 'sidebar',
    description: '數字越小越靠前',
  },
},
```

**4. Add textColor field**:
```typescript
{
  name: 'textColor',
  type: 'text',
  label: '文字顏色',
  defaultValue: '#000000',
  admin: {
    description: '十六進制顏色碼，例如 #000000',
  },
},
```

**5. Add backgroundColor field**:
```typescript
{
  name: 'backgroundColor',
  type: 'text',
  label: '背景顏色',
  defaultValue: '#ffffff',
  admin: {
    description: '十六進制顏色碼，例如 #ffffff',
  },
},
```

### Final fields array structure:

```typescript
fields: [
  {
    name: 'title',
    type: 'text',
    required: true,
    label: '分類名稱（中文）',
  },
  {
    name: 'nameEn',
    type: 'text',
    label: '英文名稱',
    admin: {
      description: '用於 URL 或國際化',
    },
  },
  {
    name: 'order',
    type: 'number',
    label: '排序順序',
    defaultValue: 0,
    admin: {
      position: 'sidebar',
      description: '數字越小越靠前',
    },
  },
  {
    name: 'textColor',
    type: 'text',
    label: '文字顏色',
    defaultValue: '#000000',
    admin: {
      description: '十六進制顏色碼，例如 #000000',
    },
  },
  {
    name: 'backgroundColor',
    type: 'text',
    label: '背景顏色',
    defaultValue: '#ffffff',
    admin: {
      description: '十六進制顏色碼，例如 #ffffff',
    },
  },
  ...slugField(),
]
```

### Webflow Field Mapping (for migration reference)

| Webflow Field | Payload Field | Type | Notes |
|--------------|---------------|------|-------|
| Name | title | text | 中文分類名稱 |
| Slug | slug | text | Auto-generated from title |
| - | nameEn | text | ❌ 需手動新增（英文名稱） |
| - | order | number | ❌ 預設 0，手動調整 |
| Color | textColor | text | 拆分為兩個欄位 |
| Color | backgroundColor | text | 拆分為兩個欄位 |

### File Structure

```
apps/backend/src/
└── collections/
    └── Categories.ts  ← Modify this file (ADD 4 fields)
```

**No payload.config.ts changes needed** - collection already registered.

## Tasks / Subtasks

- [x] **Task 1: Modify Categories.ts** (AC: 1, 2, 3, 4, 5)
  - [x] Update title field label to "分類名稱（中文）"
  - [x] Add nameEn field after title
  - [x] Add order field with sidebar position
  - [x] Add textColor field with default #000000
  - [x] Add backgroundColor field with default #ffffff
  - [x] Verify fields order: title, nameEn, order, textColor, backgroundColor, slug

- [x] **Task 2: Verify TypeScript types** (AC: 6)
  - [x] Run `pnpm build` in backend directory
  - [x] Check that payload-types.ts regenerates without errors
  - [x] Verify new fields are in TypeScript types

- [x] **Task 3: Test Admin UI** (AC: 7)
  - [x] Start dev server: `pnpm dev`
  - [x] Login to Payload Admin
  - [x] Navigate to Categories collection
  - [x] Create test category with all fields
  - [x] Verify color fields accept hex codes
  - [x] Verify order field is in sidebar
  - [x] Test category editing
  - [x] Verify default values work

- [x] **Task 4: Verify Category Theming**
  - [x] Test that textColor/backgroundColor can be used in frontend
  - [x] Verify hex color format is correct
  - [x] Check that categories can be sorted by order

## Testing Requirements

### Unit Tests
```typescript
// apps/backend/src/collections/Categories/__tests__/Categories.spec.ts
describe('Categories Collection', () => {
  it('should have all 6 fields', () => {
    const fieldNames = Categories.fields.map(f => 'name' in f ? f.name : null)
    expect(fieldNames).toContain('title')
    expect(fieldNames).toContain('nameEn')
    expect(fieldNames).toContain('order')
    expect(fieldNames).toContain('textColor')
    expect(fieldNames).toContain('backgroundColor')
    expect(fieldNames).toContain('slug')
  })

  it('should have correct default values', () => {
    const orderField = Categories.fields.find(f => f.name === 'order')
    expect(orderField?.defaultValue).toBe(0)

    const textColorField = Categories.fields.find(f => f.name === 'textColor')
    expect(textColorField?.defaultValue).toBe('#000000')

    const bgColorField = Categories.fields.find(f => f.name === 'backgroundColor')
    expect(bgColorField?.defaultValue).toBe('#ffffff')
  })

  it('should have order in sidebar', () => {
    const orderField = Categories.fields.find(f => f.name === 'order')
    expect(orderField?.admin?.position).toBe('sidebar')
  })
})
```

### Manual Testing Checklist
- [ ] Title label shows "分類名稱（中文）"
- [ ] nameEn field accepts text
- [ ] order field appears in sidebar
- [ ] order field accepts numbers
- [ ] order default is 0
- [ ] textColor field accepts hex codes (#000000)
- [ ] backgroundColor field accepts hex codes (#ffffff)
- [ ] Can create category with all fields
- [ ] Can edit category
- [ ] Default colors apply to new category
- [ ] Categories can be sorted by order in queries

## Risk Assessment

| Risk | Probability | Impact | Mitigation |
|------|------------|--------|------------|
| Color format issues | Low | Low | Use simple text field with hex format description |
| Sorting not working | Low | Medium | Test queries with sort: { order: 'asc' } |
| TypeScript errors | Low | Low | Follow existing field patterns exactly |

## Definition of Done

- [ ] All 4 new fields added to Categories.ts
- [ ] Title field label updated
- [ ] TypeScript types generate successfully
- [ ] Admin UI functional with all fields
- [ ] Unit tests pass
- [ ] Code follows existing patterns
- [ ] No linting errors
- [ ] sprint-status.yaml updated to mark story as ready-for-dev

## Dev Agent Record

### Agent Model Used
*To be filled by Dev Agent*

### Debug Log References
*To be filled by Dev Agent*

### Completion Notes
*To be filled by Dev Agent*

### File List
*To be filled by Dev Agent*

## Change Log

| Date | Action | Author |
|------|--------|--------|
| 2026-01-31 | Story created (Draft) | SM Agent (Bob) |
