minor update

This commit is contained in:
2025-12-10 07:05:37 -07:00
parent 95e80bf03d
commit 39f484ee05
4 changed files with 321 additions and 830 deletions

View File

@@ -1,521 +0,0 @@
# RepairDesk Backend Implementation TODO
This document outlines the backend implementation tasks needed to transform the scaffold into a fully functional repair shop helpdesk system.
## Directory Structure
```
flexsupport/
├── cmd/
│ └── repairdesk/
│ └── main.go # Application entry point
├── internal/
│ ├── handlers/
│ │ └── handlers.go # HTTP request handlers
│ ├── models/
│ │ └── ticket.go # Data models
│ ├── middleware/ # Custom middleware (auth, logging, etc.)
│ ├── database/ # Database connection and queries
│ │ ├── db.go # Connection management
│ │ ├── migrations/ # SQL migration files
│ │ └── queries/ # SQL query implementations
│ ├── services/ # Business logic layer
│ │ ├── ticket_service.go
│ │ ├── customer_service.go
│ │ └── notification_service.go
│ └── config/ # Configuration management
│ └── config.go
├── templates/
│ ├── layouts/
│ │ └── base.tmpl ✅ Created
│ ├── pages/
│ │ ├── dashboard.tmpl ✅ Created
│ │ ├── ticket-form.tmpl ✅ Created
│ │ └── technician-view.tmpl ✅ Created
│ └── partials/ # Reusable template components
│ ├── status-badge.tmpl
│ └── notification.tmpl
├── static/
│ ├── css/
│ │ └── styles.css ✅ Created
│ ├── js/
│ │ └── app.js # Optional JavaScript enhancements
│ └── images/
├── migrations/ # Database migration files
├── go.mod ✅ Created
├── go.sum
├── .env.example # Environment variable template
└── README.md # Project documentation
```
---
## Core Tasks
### 1. Database Setup
#### 1.1 Choose Database Solution
- [ ] **PostgreSQL** (recommended for production)
- Robust, feature-rich, excellent for structured data
- Go driver: `github.com/lib/pq` or use with `database/sql`
- [ ] **SQLite** (good for getting started)
- Zero-config, file-based, perfect for prototyping
- Go driver: `github.com/mattn/go-sqlite3`
- [ ] **MySQL/MariaDB** (alternative)
- Widely used, good tooling
- Go driver: `github.com/go-sql-driver/mysql`
#### 1.2 Create Database Schema
Create migration files in `internal/database/migrations/`:
**001_initial_schema.sql:**
```sql
-- Customers table
CREATE TABLE customers (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
phone VARCHAR(50) NOT NULL,
email VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(phone)
);
-- Technicians table
CREATE TABLE technicians (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
is_available BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Tickets table
CREATE TABLE tickets (
id SERIAL PRIMARY KEY,
status VARCHAR(50) DEFAULT 'new',
priority VARCHAR(50) DEFAULT 'normal',
customer_id INT REFERENCES customers(id),
customer_name VARCHAR(255) NOT NULL,
customer_phone VARCHAR(50) NOT NULL,
customer_email VARCHAR(255),
device_type VARCHAR(100) NOT NULL,
device_brand VARCHAR(100),
device_model VARCHAR(100),
serial_number VARCHAR(255),
issue_description TEXT NOT NULL,
internal_notes TEXT,
estimated_cost DECIMAL(10,2) DEFAULT 0,
assigned_to INT REFERENCES technicians(id),
due_date TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
created_by VARCHAR(255),
CHECK (status IN ('new', 'in_progress', 'waiting_parts', 'ready', 'completed', 'cancelled')),
CHECK (priority IN ('low', 'normal', 'high', 'urgent'))
);
-- Parts table
CREATE TABLE parts (
id SERIAL PRIMARY KEY,
ticket_id INT REFERENCES tickets(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
quantity INT NOT NULL DEFAULT 1,
cost DECIMAL(10,2) NOT NULL,
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
added_by VARCHAR(255)
);
-- Work notes table
CREATE TABLE work_notes (
id SERIAL PRIMARY KEY,
ticket_id INT REFERENCES tickets(id) ON DELETE CASCADE,
content TEXT NOT NULL,
author VARCHAR(255) NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Create indexes for performance
CREATE INDEX idx_tickets_status ON tickets(status);
CREATE INDEX idx_tickets_assigned ON tickets(assigned_to);
CREATE INDEX idx_tickets_created ON tickets(created_at);
CREATE INDEX idx_tickets_customer ON tickets(customer_phone);
CREATE INDEX idx_parts_ticket ON parts(ticket_id);
CREATE INDEX idx_notes_ticket ON work_notes(ticket_id);
```
#### 1.3 Database Connection Management
Create `internal/database/db.go`:
```go
package database
import (
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq" // or your chosen driver
)
type DB struct {
*sql.DB
}
func New(dataSourceName string) (*DB, error) {
db, err := sql.Open("postgres", dataSourceName)
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
if err := db.Ping(); err != nil {
return nil, fmt.Errorf("pinging database: %w", err)
}
// Set connection pool settings
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(5)
log.Println("Database connection established")
return &DB{db}, nil
}
```
#### 1.4 Migration Runner
- [ ] Implement migration runner or use tool like `golang-migrate/migrate`
- [ ] Create up/down migrations for schema changes
- [ ] Add migration command to application
---
### 2. Data Access Layer
#### 2.1 Ticket Repository
Create `internal/database/ticket_repo.go`:
- [ ] `GetTicketByID(id int) (*models.Ticket, error)`
- [ ] `ListTickets(filters TicketFilters) ([]models.Ticket, error)`
- [ ] `CreateTicket(ticket *models.Ticket) error`
- [ ] `UpdateTicket(ticket *models.Ticket) error`
- [ ] `DeleteTicket(id int) error`
- [ ] `UpdateTicketStatus(id int, status string) error`
- [ ] `SearchTickets(query string) ([]models.Ticket, error)`
- [ ] `GetTicketStats() (*models.TicketStats, error)`
- [ ] `GetTicketsByTechnician(techID int) ([]models.Ticket, error)`
#### 2.2 Parts Repository
Create `internal/database/part_repo.go`:
- [ ] `AddPart(part *models.Part) error`
- [ ] `GetPartsByTicket(ticketID int) ([]models.Part, error)`
- [ ] `DeletePart(id int) error`
- [ ] `GetTotalPartsCost(ticketID int) (float64, error)`
#### 2.3 Work Notes Repository
Create `internal/database/note_repo.go`:
- [ ] `AddNote(note *models.WorkNote) error`
- [ ] `GetNotesByTicket(ticketID int) ([]models.WorkNote, error)`
- [ ] `DeleteNote(id int) error`
#### 2.4 Customer Repository
Create `internal/database/customer_repo.go`:
- [ ] `GetOrCreateCustomer(phone string, name string, email string) (*models.Customer, error)`
- [ ] `GetCustomerByPhone(phone string) (*models.Customer, error)`
- [ ] `GetCustomerHistory(customerID int) ([]models.Ticket, error)`
#### 2.5 Technician Repository
Create `internal/database/technician_repo.go`:
- [ ] `GetTechnicians() ([]models.Technician, error)`
- [ ] `GetTechnicianByID(id int) (*models.Technician, error)`
- [ ] `UpdateTechnicianAvailability(id int, available bool) error`
- [ ] `GetTechnicianWorkload(id int) (int, error)`
---
### 3. Business Logic Layer
Create service layer in `internal/services/`:
#### 3.1 Ticket Service
`internal/services/ticket_service.go`:
- [ ] Wrap database operations with business logic
- [ ] Validate ticket data before saving
- [ ] Calculate total costs (labor + parts)
- [ ] Auto-assign tickets to available technicians
- [ ] Handle status transitions with validation
- [ ] Generate ticket numbers/IDs
#### 3.2 Customer Service
`internal/services/customer_service.go`:
- [ ] Deduplicate customers by phone
- [ ] Track customer history
- [ ] Calculate customer lifetime value
#### 3.3 Notification Service
`internal/services/notification_service.go`:
- [ ] Send SMS notifications (integrate Twilio or similar)
- [ ] Send email notifications (integrate SendGrid or SMTP)
- [ ] Notify customer when ticket status changes
- [ ] Notify customer when repair is ready
- [ ] Send reminder notifications
---
### 4. Complete Handler Implementation
Update `internal/handlers/handlers.go`:
#### 4.1 Replace Mock Data
- [ ] Remove all `getMock*()` functions
- [ ] Inject database repositories into Handler struct
- [ ] Update all handlers to use real database queries
#### 4.2 Form Validation
- [ ] Add input validation for all forms
- [ ] Sanitize user input to prevent XSS
- [ ] Return helpful error messages
#### 4.3 Error Handling
- [ ] Implement consistent error responses
- [ ] Log errors properly
- [ ] Show user-friendly error pages
#### 4.4 HTMX Response Handling
- [ ] Return proper HTML fragments for htmx requests
- [ ] Use appropriate htmx headers (HX-Trigger, HX-Redirect, etc.)
- [ ] Implement loading states
---
### 5. Authentication & Authorization
Create `internal/middleware/auth.go`:
#### 5.1 User Authentication
- [ ] Implement session management (use `gorilla/sessions`)
- [ ] Create login/logout handlers
- [ ] Password hashing with bcrypt
- [ ] Login form template
#### 5.2 Role-Based Access Control
- [ ] Define roles: Admin, Front Desk, Technician
- [ ] Middleware to check user permissions
- [ ] Restrict routes based on roles
- [ ] Show/hide UI elements based on permissions
#### 5.3 Session Management
- [ ] Store user info in session
- [ ] Add CSRF protection
- [ ] Implement "remember me" functionality
---
### 6. Configuration Management
Create `internal/config/config.go`:
#### 6.1 Environment Variables
Create `.env.example`:
```env
# Database
DATABASE_URL=postgres://user:pass@localhost:5432/repairdesk?sslmode=disable
# Server
PORT=8080
ENV=development
# Session
SESSION_SECRET=your-secret-key-change-in-production
# Email (optional)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@example.com
SMTP_PASS=your-password
# SMS (optional)
TWILIO_ACCOUNT_SID=your-account-sid
TWILIO_AUTH_TOKEN=your-auth-token
TWILIO_PHONE_NUMBER=+1234567890
```
#### 6.2 Config Loader
- [ ] Use `godotenv` to load .env files
- [ ] Parse and validate configuration
- [ ] Provide sensible defaults
- [ ] Make config available to handlers/services
---
### 7. Additional Features
#### 7.1 Search Functionality
- [ ] Full-text search across tickets
- [ ] Search by customer name, phone, device
- [ ] Search by ticket ID
- [ ] Filter by date range
#### 7.2 Reporting
- [ ] Daily/weekly/monthly ticket reports
- [ ] Technician performance metrics
- [ ] Revenue reports
- [ ] Export to CSV/PDF
#### 7.3 File Uploads
- [ ] Allow uploading photos of damaged devices
- [ ] Store files in `static/uploads/`
- [ ] Display photos in ticket view
- [ ] Security: validate file types, limit sizes
#### 7.4 Print Functionality
- [ ] Printable ticket receipts
- [ ] Work order printouts for technicians
- [ ] Customer invoices
#### 7.5 Notifications
- [ ] Email notifications on status changes
- [ ] SMS reminders for pickups
- [ ] In-app notifications
#### 7.6 Dashboard Enhancements
- [ ] Real-time updates with WebSocket or SSE
- [ ] Charts and graphs for metrics
- [ ] Quick filters and saved views
---
### 8. Testing
#### 8.1 Unit Tests
- [ ] Test database repositories
- [ ] Test business logic in services
- [ ] Test utility functions
- [ ] Aim for >70% coverage
#### 8.2 Integration Tests
- [ ] Test HTTP handlers end-to-end
- [ ] Use test database
- [ ] Test htmx interactions
#### 8.3 Manual Testing
- [ ] Create test tickets
- [ ] Test all workflows
- [ ] Test on different browsers
- [ ] Test responsive design on mobile
---
### 9. Deployment Preparation
#### 9.1 Production Readiness
- [ ] Add rate limiting middleware
- [ ] Implement proper logging (structured logs)
- [ ] Add health check endpoint (`/health`)
- [ ] Configure CORS if needed
- [ ] Enable HTTPS/TLS
- [ ] Add request ID middleware
#### 9.2 Database Backups
- [ ] Set up automated backups
- [ ] Test restore process
- [ ] Document backup procedures
#### 9.3 Deployment
- [ ] Create Dockerfile
- [ ] Set up CI/CD pipeline
- [ ] Deploy to chosen platform (Fly.io, Railway, DigitalOcean, etc.)
- [ ] Set up monitoring (uptime, errors)
- [ ] Configure domain and SSL
#### 9.4 Documentation
- [ ] Write README with setup instructions
- [ ] Document API endpoints
- [ ] Create user guide
- [ ] Document deployment process
---
## Suggested Implementation Order
### Phase 1: Core Functionality (MVP)
1. Set up database (SQLite for quick start)
2. Implement basic ticket CRUD operations
3. Replace mock data with real database queries
4. Get create/read/update working end-to-end
### Phase 2: Enhanced Features
5. Add parts and work notes functionality
6. Implement search and filtering
7. Add basic authentication (single admin user)
8. Polish the UI and fix bugs
### Phase 3: Production Features
9. Add role-based access control
10. Implement notifications
11. Add reporting and analytics
12. Testing and bug fixes
### Phase 4: Polish & Deploy
13. Performance optimization
14. Security hardening
15. Documentation
16. Deploy to production
---
## Useful Go Libraries
### Core
- **Router**: `github.com/go-chi/chi/v5` ✅ Already included
- **Database**: `github.com/lib/pq` (PostgreSQL) or `github.com/mattn/go-sqlite3` (SQLite)
- **Migrations**: `github.com/golang-migrate/migrate/v4`
- **Environment**: `github.com/joho/godotenv`
### Authentication
- **Sessions**: `github.com/gorilla/sessions`
- **Password**: `golang.org/x/crypto/bcrypt` (standard library)
- **CSRF**: `github.com/gorilla/csrf`
### Utilities
- **Validation**: `github.com/go-playground/validator/v10`
- **UUID**: `github.com/google/uuid`
- **Logging**: `github.com/sirupsen/logrus` or `log/slog` (Go 1.21+)
### External Services
- **Email**: `github.com/sendgrid/sendgrid-go` or standard `net/smtp`
- **SMS**: `github.com/twilio/twilio-go`
### Optional Enhancements
- **Query Builder**: `github.com/Masterminds/squirrel`
- **ORM Alternative**: `github.com/jmoiron/sqlx` (lighter than full ORM)
- **Testing**: `github.com/stretchr/testify`
---
## Notes
- Start simple, iterate based on actual usage
- Focus on the repair shop workflow first
- Keep templates clean and maintainable
- Use htmx for all dynamic interactions to minimize JavaScript
- Prioritize data integrity and reliability
- Make it easy to backup and restore data
- Consider multi-tenancy if planning to serve multiple shops
---
## Questions to Answer Before Building
1. **Single shop or multi-tenant?** (affects database schema)
2. **What payment processing is needed?** (Stripe, Square, etc.)
3. **Inventory management?** (track parts stock levels)
4. **Customer portal?** (let customers check ticket status)
5. **Barcode/QR scanning?** (for device tracking)
6. **Email/SMS budget?** (affects notification strategy)
---
This TODO provides a roadmap from the current scaffold to a production-ready repair shop helpdesk system. Start with Phase 1 to get core functionality working, then iterate based on real-world needs.

406
CLAUDE.md
View File

@@ -1,100 +1,320 @@
# AI PROJECT SCAFFOLDING PARAMETERS
# FlexSupport - Project Documentation for Claude
## Project Overview
You are helping scaffold a new web application called **RepairDesk** — a lightweight helpdesk/ticketing system tailored initially for a **repair shop** workflow.
There are two primary user roles:
1. **Employee / Front Desk Staff** — creates, edits, and manages tickets and customer info.
2. **Repair Technician** — manages active repair jobs, tracks status, parts, costs, and deadlines.
FlexSupport is a lightweight helpdesk and ticketing system specifically tailored for **repair shop workflows**. It's designed to manage repair tickets for items like boots, shoes, bags, and other goods, tracking customer information, repair status, parts, and work notes.
The goal is to provide a **clear, functional frontend scaffold** and a **well-organized backend plan**, not necessarily a complete production implementation.
**Primary Use Case**: Repair shops that need to track customer repairs from intake through completion, including parts management and technician assignment.
## Technology Stack
### Backend
- **Go 1.25** - Primary language
- **Chi (v5)** - HTTP router and middleware
- **Templ** - Type-safe Go templating (generates `*_templ.go` files)
- **Shopify Integration** - Customer/order integration via `go-shopify` SDK
### Frontend
- **htmx** - Dynamic HTML interactions without heavy JavaScript
- **Alpine.js** - Lightweight JavaScript framework for interactivity
- **Tailwind CSS** - Utility-first CSS framework
- **TemplUI** - Custom component library (see `ui/components/`)
### Development Tools
- **Air** - Hot reloading for Go server (`.air.toml`)
- **Task** - Task runner (Taskfile.yml) for build automation
- **godotenv** - Environment variable management
## Project Structure
```
FlexSupport/
├── main.go # Entry point, runs App()
├── app.go # Main application logic and server setup
├── .env # Environment variables (not committed)
├── go.mod # Go dependencies
├── Taskfile.yml # Task definitions for dev workflow
├── .air.toml # Air hot reload configuration
├── cmd/ # Command-line tools (if any)
├── internal/
│ ├── config/ # Application configuration
│ │ └── config.go # Config struct and env var loading
│ │
│ ├── models/ # Data models
│ │ └── ticket.go # Ticket, Part, WorkNote, Customer, Technician, TicketStats
│ │
│ ├── handlers/ # HTTP request handlers (stub/interface level)
│ │ ├── handlers.go # Handler struct with methods for endpoints
│ │ └── getHome.go # Home page handler
│ │
│ ├── routes/ # Feature-specific route handlers
│ │ ├── dashboard/ # Dashboard page and logic
│ │ │ ├── dashboard.templ # Templ template
│ │ │ ├── dashboard_templ.go # Generated Go code
│ │ │ └── handler.go
│ │ └── tickets/ # Ticket management routes
│ │ ├── tickets.go
│ │ ├── ticket-form.templ
│ │ └── ticket-page.templ
│ │
│ ├── router/ # Route registration and middleware setup
│ │ └── router.go # Chi router configuration
│ │
│ ├── server/ # HTTP server configuration
│ │ └── server.go
│ │
│ ├── middleware/ # Custom middleware
│ │ ├── middleware.go
│ │ ├── logging.go # Request logging
│ │ └── noonce.go # Security nonce handling
│ │
│ ├── layout/ # Page layouts and common UI
│ │ ├── base.templ # Base HTML layout
│ │ ├── base_templ.go
│ │ └── layout.go
│ │
│ ├── lib/ # Utility libraries
│ │ └── logger/ # Structured logging setup
│ │
│ ├── shopify/ # Shopify integration code
│ │ └── shopify.go
│ │
│ ├── utils/ # General utilities
│ │ └── templui.go # TemplUI component helpers
│ │
│ └── ports/ # Interface definitions (ports pattern)
│ └── ports.go
├── static/ # Static assets
│ ├── assets/
│ │ ├── css/
│ │ │ ├── input.css # Tailwind source
│ │ │ └── output.min.css # Compiled CSS
│ │ ├── js/ # JavaScript files
│ │ ├── icons/ # Icon assets
│ │ └── public/ # Public assets
│ └── assets.go # Go embed for static files
├── ui/ # Templ components
│ ├── components/ # Reusable UI components
│ │ ├── button/
│ │ ├── card/
│ │ ├── form/
│ │ ├── input/
│ │ ├── table/
│ │ └── ... (many more)
│ └── modules/ # Larger UI modules
│ └── navbar.templ
└── tmp/ # Build artifacts (Air output)
└── main # Compiled binary
```
## Core Data Models
### Ticket
The central entity representing a repair job. Key fields:
- **Status**: `new`, `in_progress`, `waiting_parts`, `ready`, `completed`
- **Priority**: `low`, `normal`, `high`, `urgent`
- **Customer Info**: Name, phone, email
- **Item Info**: Type (boot/shoe/bag/other), brand, model, serial number
- **Repair Details**: Issue description, internal notes, estimated cost
- **Assignment**: Assigned technician, due date
- **Relations**: Parts (replacement parts used), WorkNotes (log entries)
### Part
Replacement parts/materials used in repairs (quantity, cost)
### WorkNote
Log entries and notes added to tickets by technicians
### Customer & Technician
User entities (planned for future expansion)
## Routing Structure
**Main Router**: `internal/router/router.go`
### Routes
- `GET /` - Dashboard (home page)
- `GET /assets/*` - Static assets
- `POST /tickets` - Create new ticket
- `GET /tickets/search` - Search tickets
- `POST /tickets/{id}` - Update ticket
- `POST /tickets/{id}/status` - Update ticket status
- `POST /tickets/{id}/parts` - Add part to ticket
- `DELETE /tickets/{id}/parts/{partId}` - Remove part
- `POST /tickets/{id}/notes` - Add work note
- `GET /api/stats/open` - Get open ticket count (API endpoint for htmx)
## Development Workflow
### Starting Development
```bash
# Option 1: Full development mode (recommended)
task gen # Generates Templ files + Tailwind CSS
task dev # Starts Air hot-reload server
# Option 2: Individual tasks
task templ # Generate Templ files only
task tailwind # Build Tailwind CSS only
go run . # Run server directly
```
**Server runs on**: `http://localhost:8080`
### File Generation
**Templ Files**: `*.templ``*_templ.go` (auto-generated, DON'T edit)
- Templ is a templating language that compiles to Go code
- Edit `.templ` files, never edit `_templ.go` files
- Run `task templ` to regenerate
**Tailwind CSS**: `static/assets/css/input.css``output.min.css`
- Run `task tailwind` to rebuild CSS
- Minified output for production
### Hot Reloading
**Air** watches for changes to:
- `*.go` files (except `*_templ.go`)
- `*.templ` files
- `*.html` files
**Important**: Air excludes `_templ.go` from watch list to prevent rebuild loops. You must manually run `task templ` when editing `.templ` files, or use `task gen` which runs both templ and tailwind in watch mode.
## Key Patterns and Conventions
### 1. Handler Pattern
- `internal/handlers/handlers.go` - Handler struct with all endpoint methods
- Route-specific handlers in `internal/routes/*/handler.go`
- Handlers receive `*slog.Logger` for structured logging
### 2. Templ Components
- Type-safe Go templating
- Components are Go functions returning `templ.Component`
- Call components from other components or HTTP handlers
- Example: `dashboard.Show()` returns a component to render
### 3. htmx Integration
- Partial page updates without full page reloads
- Server returns HTML fragments
- Use `hx-*` attributes in Templ templates
### 4. Middleware Stack
- Logger, Recoverer (panic recovery)
- Custom logging middleware
- Content-Type enforcement (`text/html`)
- CSP (Content Security Policy) - currently commented out
### 5. Environment Configuration
- `development` vs `production` mode
- Config loaded from environment variables via `.env`
- Config struct in `internal/config/config.go`
## Common Tasks
### Adding a New Route
1. Add handler method to `internal/handlers/handlers.go`
2. Register route in `internal/router/router.go`
3. Create Templ template if needed in `internal/routes/*/`
4. Run `task templ` to generate Go code
### Creating a New Templ Component
1. Create `component.templ` in appropriate directory
2. Write templ code using `templ` syntax
3. Run `task templ` to generate `component_templ.go`
4. Import and use in handlers or other components
### Adding Tailwind Classes
1. Use classes in Templ files
2. Tailwind will auto-detect and include them
3. Run `task tailwind` to rebuild CSS
### Working with Models
- Models are in `internal/models/`
- Use struct tags for JSON/DB serialization
- Add helper methods for display logic (e.g., `StatusClass()`, `StatusDisplay()`)
## Important Files
- **`main.go`**: Entry point, loads env vars, calls `App()`
- **`app.go`**: Creates config, logger, handlers, router, starts HTTP server
- **`internal/router/router.go`**: All route definitions
- **`internal/models/ticket.go`**: Core data structures
- **`.air.toml`**: Hot reload configuration (watch patterns, build commands)
- **`Taskfile.yml`**: Development tasks (templ, tailwind, dev server)
- **`.env`**: Environment variables (LOG_LEVEL, ENVIRONMENT, etc.)
## Environment Variables
Default values in `internal/config/config.go`:
- `LOG_LEVEL`: `debug` (development), `info` (production)
- `VERBOSE_LOGGING`: `false`
- `ENVIRONMENT`: `development` | `production`
- `DOMAIN`: `http://localhost:8080`
## Database / Persistence
**Currently**: No database implementation visible in codebase
**Likely**: Using in-memory data or planning to add database layer via `internal/ports/` (ports/adapters pattern)
If implementing database:
- Add repository interfaces in `internal/ports/`
- Create implementations (e.g., PostgreSQL, SQLite)
- Inject into handlers via dependency injection
## Tips for Working with This Codebase
1. **Always regenerate Templ files** after editing `.templ` files
2. **Don't edit `_templ.go` files** - they're auto-generated
3. **Use `task gen`** for concurrent Templ + Tailwind watching during development
4. **Check Air logs** in `tmp/build-errors.log` if builds fail
5. **Use structured logging** via `slog.Logger` passed to handlers
6. **Follow Chi router patterns** - use `r.Group()` for middleware scoping
7. **Templ components are type-safe** - leverage Go's type system
8. **htmx expects HTML fragments** - return partial templates for AJAX endpoints
9. **Static assets are embedded** via `static/assets.go` (Go 1.16+ embed)
10. **Middleware order matters** - logger before recoverer, auth after logging
## Testing Notes
- No test files currently visible in the repository
- Consider adding tests in `*_test.go` files alongside code
- Integration tests for handlers
- Unit tests for models and utilities
## Future Enhancements / TODOs
Based on commented-out code in `router.go`:
- Ticket list view (`GET /tickets`)
- New ticket form (`GET /tickets/new`)
- View single ticket (`GET /tickets/{id}`)
- Edit ticket form (`GET /tickets/{id}/edit`)
- Content Security Policy middleware (currently disabled)
- Right now the system is focused on a cobler repair shop workflow as they are the first clients I'm working with. The end goal is to make this more generic and adaptable to different workflows such as car repair or an IT team ticket system.
## Shopify Integration
- Located in `internal/shopify/shopify.go`
- Uses `github.com/bold-commerce/go-shopify/v4`
- Likely for importing customer/order data
- Integration details to be explored
## Quick Reference
**Start dev server**: `task gen && task dev`
**Build only**: `go build -o ./tmp/main .`
**Generate Templ**: `task templ` or `go tool templ generate`
**Build CSS**: `task tailwind`
**Server port**: `:8080`
**Logs**: Structured JSON (prod) or text (dev) via `slog`
---
## Tech Stack & Frameworks
- **Language:** Go (Golang)
- **Templating:** `html/template`
- **Frontend Interactivity:** `htmx` for dynamic updates, `Alpine.js` for interactive components when needed
- **UI Library Support:** allowed to use [`rotmh/shadcn-templ`](https://github.com/rotmh/shadcn-templ) for UI components
- **Storage/DB:** not yet implemented — just produce TODO items and planning guidance
- **Routing:** Go HTTP or `chi` router (you may suggest)
- **Build Goal:** Produce well-organized, human-readable code structure, focusing on layout and extensibility
---
## Primary Deliverables
### 1. Frontend Scaffold
Generate well-structured templates and page scaffolding that includes:
- `base.tmpl` or equivalent for shared layout (nav, title, etc.)
- Templates for:
- Ticket listing / dashboard (employee view)
- Ticket entry form / parts input form
- Technician's detail view with job progress and actions
- htmx components for dynamic sections like:
- “Mark as completed”
- “Update status” dropdowns
- “Add part” inline updates
- Example use of `shadcn-templ` components (buttons, modals, tables)
- Optionally, Alpine snippets for simple UI logic (e.g., modal toggles)
### 2. Backend TODO / Planning Document
Provide a clear high-level TODO list describing:
- Proposed directory structure (`/cmd`, `/internal`, `/templates`, `/static`, etc.)
- Core data models/entities:
- Customer
- RepairTicket (status, cost, dueDate, assignedTo)
- Parts
- Suggested Go route/handler design
- Integration points for frontend templates
- Example endpoint definitions (stub form handlers, update routes)
- Suggestions for extending later (authentication, email, reporting, etc.)
---
## Design & UX Focus
The design should be:
- Clean, minimal, functional
- Favor tables and cards for organizing ticket info
- Emphasize legibility and usability for repair techs
- Responsive layout (works well on desktop/tablet)
---
## Agent Behavior & Output Style
- Start by summarizing the structure youll generate.
- Then output Go template and example Go code inline in fenced blocks.
- Use helpful comments to explain file purposes.
- Be practical rather than exhaustive; focus on a functional starting point.
- Reference but do not duplicate external component code unless vital.
---
## Example Interaction Flow
1. The user (Ellie) requests the scaffold.
2. The agent outputs:
- A project overview summary
- Suggested directory layout
- Example template files (`base.tmpl`, `dashboard.tmpl`, etc.)
- A TODO checklist for the backend
3. Ellie reviews and requests deeper code generation or iteration.
---
## Constraints
- Do not generate sensitive or copyrighted material.
- Focus on functionality and clarity, not lorem-ipsum-heavy mock data.
- Keep Go code idiomatic and templates minimal but extendable.
- Use plain Markdown fenced code blocks for all code output (no HTML formatting).
---
## Goals
Deliver a **ready-to-expand** scaffold that gives Ellie:
- A visual, usable starting frontend
- A solid understanding of what needs to be built next
- A foundation for iterative development of a helpdesk/ticket app
---
*End of parameter specification.*
**Last Updated**: 2025-12-10
**Go Version**: 1.25
**Main Branch**: `main`

211
README.md
View File

@@ -1,212 +1,3 @@
# FlexSupport
A lightweight helpdesk and ticketing system tailored for repair shop workflows. Built with Go, html/template, htmx, and Alpine.js.
## Overview
FlexSupport provides a clean, functional interface for managing repair tickets with two primary user roles:
1. **Employee / Front Desk Staff** — Creates, edits, and manages tickets and customer information
2. **Repair Technician** — Manages active repair jobs, tracks status, parts, costs, and deadlines
## Current Status
**🚧 This is a functional scaffold with mock data.** The frontend UI is complete and interactive, but the backend uses placeholder data. See [BACKEND_TODO.md](BACKEND_TODO.md) for the complete implementation roadmap.
### What's Included
**Frontend Scaffold:**
- Base layout with navigation (`templates/layouts/base.tmpl`)
- Dashboard with ticket listing (`templates/pages/dashboard.tmpl`)
- Ticket entry/edit form (`templates/pages/ticket-form.tmpl`)
- Technician detail view with job progress (`templates/pages/technician-view.tmpl`)
- htmx integration for dynamic updates
- Alpine.js for interactive components
- Tailwind CSS for styling
**Backend Structure:**
- Go HTTP server with chi router (`cmd/repairdesk/main.go`)
- Handler stubs for all routes (`internal/handlers/handlers.go`)
- Data models for tickets, parts, notes, etc. (`internal/models/ticket.go`)
- Organized directory structure ready for expansion
## Quick Start
### Prerequisites
- Go 1.21 or later
- Basic familiarity with Go and HTML templates
### Installation
1. Clone the repository:
```bash
git clone <repository-url>
cd flexsupport
```
2. Install dependencies:
```bash
go mod download
```
3. Run the application:
```bash
go run cmd/repairdesk/main.go
```
4. Open your browser to `http://localhost:8080`
## Project Structure
```
flexsupport/
├── cmd/repairdesk/ # Application entry point
├── internal/
│ ├── handlers/ # HTTP request handlers
│ ├── models/ # Data models
│ ├── middleware/ # Custom middleware (TODO)
│ ├── database/ # Database layer (TODO)
│ ├── services/ # Business logic (TODO)
│ └── config/ # Configuration (TODO)
├── templates/
│ ├── layouts/ # Base layout templates
│ └── pages/ # Page templates
├── static/
│ ├── css/ # Stylesheets
│ ├── js/ # JavaScript (optional)
│ └── images/ # Static images
├── go.mod # Go module definition
├── BACKEND_TODO.md # Implementation roadmap
└── README.md # This file
```
## Available Routes
### Employee/Front Desk Routes
- `GET /` - Dashboard with ticket overview
- `GET /tickets` - List all tickets (with filtering)
- `GET /tickets/new` - New ticket form
- `POST /tickets` - Create ticket
- `GET /tickets/{id}` - View ticket details
- `GET /tickets/{id}/edit` - Edit ticket form
- `POST /tickets/{id}` - Update ticket
### Technician Routes
- `GET /technician` - Technician work queue
- `GET /technician/{id}` - Detailed ticket view with actions
- `POST /tickets/{id}/status` - Update ticket status (htmx)
- `POST /tickets/{id}/parts` - Add parts (htmx)
- `DELETE /tickets/{id}/parts/{partId}` - Remove parts (htmx)
- `POST /tickets/{id}/notes` - Add work notes (htmx)
### API Endpoints (for htmx)
- `GET /api/stats/open` - Get open ticket count
- `GET /tickets/search` - Search tickets
## Features
### Current (with Mock Data)
- ✅ Ticket creation and management
- ✅ Customer information tracking
- ✅ Device details and serial numbers
- ✅ Status tracking (New, In Progress, Waiting for Parts, Ready, Completed)
- ✅ Priority levels (Low, Normal, High, Urgent)
- ✅ Parts and materials tracking
- ✅ Work notes/logs
- ✅ Assignment to technicians
- ✅ Due date tracking
- ✅ Dashboard statistics
- ✅ Real-time updates with htmx
- ✅ Responsive design
### Planned (See BACKEND_TODO.md)
- [ ] Database persistence
- [ ] User authentication
- [ ] Role-based access control
- [ ] Search functionality
- [ ] Email/SMS notifications
- [ ] Reporting and analytics
- [ ] File uploads (device photos)
- [ ] Printable receipts/invoices
- [ ] Customer history tracking
## Next Steps
To transform this scaffold into a production application:
1. **Read [BACKEND_TODO.md](BACKEND_TODO.md)** for the complete implementation roadmap
2. **Set up a database** (SQLite for quick start, PostgreSQL for production)
3. **Implement data persistence** by replacing mock data with real database queries
4. **Add authentication** to secure the application
5. **Test thoroughly** with real repair shop workflows
6. **Deploy** to your chosen hosting platform
## Technology Stack
- **Backend:** Go 1.21+ with `html/template`
- **Router:** chi v5
- **Frontend:** htmx for dynamic updates, Alpine.js for interactivity
- **Styling:** Tailwind CSS (via CDN, can be customized)
- **Database:** Not yet implemented (PostgreSQL/SQLite recommended)
## Development
### Adding New Templates
Templates are organized in three locations:
- `templates/layouts/` - Base layouts (navigation, structure)
- `templates/pages/` - Full page templates
- `templates/partials/` - Reusable components (TODO)
All page templates should extend the base layout:
```html
{{define "title"}}Page Title{{end}}
{{define "content"}}
<!-- Your content here -->
{{end}}
```
### Adding New Routes
1. Add route definition in `cmd/repairdesk/main.go` in the `setupRoutes` function
2. Implement handler in `internal/handlers/handlers.go`
3. Create or update templates as needed
### Using htmx
htmx attributes are already integrated for dynamic updates:
- `hx-get`, `hx-post`, `hx-delete` - Make requests
- `hx-target` - Specify where to inject response
- `hx-swap` - Control how content is swapped
- `hx-trigger` - Define when requests fire
Example:
```html
<button hx-post="/tickets/123/status"
hx-vals='{"status": "completed"}'
hx-target="#status-badge">
Mark Complete
</button>
```
## Contributing
This is a scaffold project. Contributions welcome for:
- Database implementation
- Authentication system
- Additional features
- Bug fixes
- Documentation improvements
## License
[Your chosen license]
## Support
For questions about implementation, see [BACKEND_TODO.md](BACKEND_TODO.md) or open an issue.
---
Built with Go, htmx, Alpine.js, and Tailwind CSS.
A lightweight helpdesk and ticketing system tailored for repair shop workflows. Built with Go, Templ, htmx, and Alpine.js.

View File

@@ -62,9 +62,9 @@ func getMockTickets() []models.Ticket {
Priority: "high",
CustomerName: "John Doe",
CustomerPhone: "(555) 123-4567",
ItemType: "Smartphone",
ItemModel: "iPhone 13 Pro",
IssueDescription: "Cracked screen, needs replacement",
ItemType: models.Bag,
ItemModel: "Backpack",
IssueDescription: "Broken strap, needs replacement",
AssignedTo: "Mike Tech",
DueDate: time.Now().Add(48 * time.Hour),
},
@@ -74,10 +74,11 @@ func getMockTickets() []models.Ticket {
Priority: "normal",
CustomerName: "Jane Smith",
CustomerPhone: "(555) 987-6543",
ItemType: "Laptop",
ItemModel: "MacBook Pro 2020",
IssueDescription: "Battery not charging",
ItemType: models.Boot,
ItemModel: "Keen",
IssueDescription: "Sole needs replaced",
AssignedTo: "Sarah Tech",
DueDate: time.Now().Add(72 * time.Hour),
},
}
}