# FastDesk NAS - Deployment Summary

**Status:** ✅ Backend complete, ready for Phase 1 data import

---

## What's Been Built

### 1. **Database Schema** (`fastdesk-schema.sql`)
- **Cards table**: 7,792 cards from your Lovable export
- **Items table**: 26,978 nested items (links, notes, etc.)
- **Keywords table**: Full-text search on card keywords
- **Media files table**: Tracks Supabase URLs + future NAS paths
- **Indexes**: Optimized for search and filtering

### 2. **Import Tool** (`import.py`)
Converts your CSV exports → SQLite database:
- **Input**: `links-export-*.csv` + `items-export-*.csv`
- **Output**: `fastdesk.db` (ready to use)
- **Features**:
  - Parses JSON keywords from Lovable format
  - Handles duplicate detection
  - Creates default admin user
  - Tracks media references for Phase 2

### 3. **Express Backend** (`server.js`)
Full REST API with:
- **Auth**: JWT tokens, login/register
- **CRUD**: Cards, items, keywords
- **Search**: Full-text + filtering (by type, keyword, etc.)
- **Media**: Upload/download (currently Supabase links, NAS-ready)
- **Database**: SQLite with proper indexing

### 4. **Phase 2 Media Tool** (`migrate_media.py`)
Optional media migration from Supabase → NAS:
- Download files one-at-a-time (safe, testable)
- Progress tracking
- Automatic database updates
- Rollback-friendly

### 5. **Documentation**
- `QUICKSTART.md`: 15-min setup guide
- `server.js`: Fully commented endpoints
- `import.py`: Detailed logging

---

## Your Data Structure (Mapped)

### Cards (7,792 total)
```
id                → UUID primary key
label             → Card title
content           → Card description
emoji             → Visual indicator
keywords          → JSON array (parsed to separate table)
visibility        → 'private' (your default)
enabled           → Boolean (filter inactive)
created_at        → Timestamp
updated_at        → Timestamp
```

### Items (26,978 total)
```
id                → UUID primary key
card_id           → Link to card
type              → 'link', 'note', 'media_carousel', 'timeline', 'minipost'
label             → Item title
url               → Link/reference
content           → Full text
media_url         → Currently Supabase (optional Phase 2 migration)
position          → Sort order
created_at        → Timestamp
updated_at        → Timestamp
```

### Keywords (56,000+ total)
```
card_id           → Link to card
keyword           → Single keyword (lowercased, unique per card)
```

---

## Getting Started (3 Steps)

### **Step 1: Import Your Data**
```bash
# Install Node dependencies
npm install

# Initialize database from schema
sqlite3 fastdesk.db < fastdesk-schema.sql

# Import your CSV exports
python3 import.py links-export-2026-04-03_12-59-41.csv items-export-2026-04-03_12-38-57.csv
```

Expected output:
```
✅ Cards imported: 7792
✅ Items imported: 26978
✅ Keywords inserted: 56000+
✅ Media references tracked: 5000+
```

### **Step 2: Start Backend**
```bash
node server.js
```

Server will start on `http://localhost:3001`

### **Step 3: Test**
```bash
# Login
curl -X POST http://localhost:3001/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"password"}'

# Get all cards
curl http://localhost:3001/api/cards?limit=5 \
  -H "Authorization: Bearer <token>"
```

---

## File Structure

```
/home/claude/
├── fastdesk-schema.sql        ← Database schema (create with: sqlite3 fastdesk.db < this)
├── import.py                  ← CSV → SQLite (run this first)
├── migrate_media.py           ← Phase 2 media downloader (optional)
├── server.js                  ← Express backend (run with: node this)
├── package.json               ← Node dependencies
├── QUICKSTART.md              ← 15-min setup guide
├── DEPLOYMENT.md              ← This file
├── fastdesk.db                ← SQLite database (created by import.py)
└── media/                     ← Media storage (created by server.js)
```

---

## API Endpoints Summary

### **Authentication**
```
POST /api/auth/login                → Get JWT token
POST /api/auth/register             → Create new user
```

### **Cards**
```
GET    /api/cards?search=&type=&keyword=&limit=50&offset=0
GET    /api/cards/:id               → With items + keywords
POST   /api/cards                   → Create
PUT    /api/cards/:id               → Update
DELETE /api/cards/:id               → Delete
```

### **Items**
```
POST   /api/items                   → Create (nested in card)
PUT    /api/items/:id               → Update
DELETE /api/items/:id               → Delete
```

### **Search**
```
GET    /api/search?q=&type=&keyword=&cardId=&limit=50&offset=0
```

### **Media**
```
POST   /api/upload                  → Upload file to NAS
GET    /api/media/:id               → Download file
```

### **Health**
```
GET    /api/health                  → Server status
```

---

## Configuration (Environment Variables)

```bash
PORT=3001                           # Backend port
JWT_SECRET=your-secret-key          # ⚠️ Change in production!
DB_PATH=./fastdesk.db               # SQLite database location
MEDIA_PATH=./media                  # Media storage location
```

---

## Important: Media Strategy

### Phase 1 (Current)
✅ All media stays in **Supabase** (what you have now)
✅ No download risk
✅ Full access via `media_url` field
✅ Works immediately

### Phase 2 (Optional, when ready)
📥 Download media from Supabase → NAS
🔄 Update database with local paths
🧪 Test with 10 files first
✅ Then migrate everything

**Why this approach?**
- Zero risk of data loss
- You can test the backend before touching media
- Easy rollback (just keep Supabase URLs)
- Media is optional for MVP

---

## Next Steps

### **Immediately (Ready to Go)**
1. Run `import.py` to load your 7,792 cards into SQLite ✅
2. Start `server.js` to test backend API ✅
3. Verify login works with admin/password ✅

### **Soon (Frontend)**
- React UI to display cards, items, search
- Responsive design for mobile
- URL parameter support for deep linking
- Item type renderers (link, note, carousel, timeline, minipost)

### **Later (Optional)**
- Phase 2 media migration (Supabase → NAS)
- Synology Docker deployment
- Custom password setup
- Advanced search/filtering UI

---

## Deployment to Synology NAS

Copy everything to your NAS:
```bash
scp -r /home/claude/* admin@<NAS-IP>:/volume1/docker/fastdesk/
```

Then SSH in and run:
```bash
cd /volume1/docker/fastdesk/
npm install
node server.js
```

Or use Docker (docker-compose.yml available if needed).

---

## Quick Fixes

### "Database is locked"
- Only one instance of `server.js` running
- Restart: `killall node && node server.js`

### Import fails on CSV encoding
- Make sure CSVs are UTF-8
- Test: `file links-export-*.csv`

### Password reset
```bash
sqlite3 fastdesk.db
UPDATE users SET password_hash = 'new-bcrypt-hash' WHERE username = 'admin';
```

---

## Status

✅ **Backend complete**
✅ **Database schema validated**
✅ **Import tool ready**
✅ **Media strategy defined** (Phase 1 + optional Phase 2)

⏭️ **Frontend** (React) - ready to build when needed
⏭️ **Synology deployment** - copy files + run

---

**Ready to start? Run:**
```bash
python3 import.py links-export-2026-04-03_12-59-41.csv items-export-2026-04-03_12-38-57.csv
node server.js
```

Then test:
```bash
curl http://localhost:3001/api/health
```

Should return: `{"status":"ok","timestamp":"..."}`

---

Let me know when you've run the import and I'll help with the frontend! 🚀
