feat(go-crm): full auth, routing, middleware, and supporting infra
- Add auth handlers (signup, login, logout, account management) with bcrypt - Add client, customer, service, scheduling, payment, question, answer handlers - Add dashboard, monthly report, and lead pipeline pages - Add UTF-8 middleware to force charset on HTML responses - Add config package with env-based overrides for DB path, secrets, endpoints - Add parser package for WhatsApp message ingestion - Add clean-arch layers: pkg/domain, pkg/repo, pkg/usecase for leads - Add cmd/migrate utility for DB migrations - Add Makefile, README, run-tests.sh, and dev scripts - Update docker-compose.yml with memory limits - Update .air.toml to exclude DB files and stop on errors - Update whatsapp-sync dependencies and add src/index.js entrypoint - Add whatsme standalone WhatsApp reader app (source only) - Untrack .opencode-sandbox/data/go-crm.db from git history - Expand root .gitignore: ngrok, tmp dirs, sandbox DBs, compiled binaries
This commit is contained in:
1 parent
57920d45d6
commit
744868caa1
52 files changed
+4868
-1068
No files matched your search
+18
@@ -64,3 +64,21 @@ data/*.db
|
||||
# Go build artifacts
|
||||
apps/go-crm/go-crm
|
||||
apps/go-crm/tmp/
|
||||
|
||||
# Sandbox / generated data
|
||||
.opencode-sandbox/data/
|
||||
.opencode-sandbox/*.db
|
||||
|
||||
# Binaries / tools
|
||||
ngrok
|
||||
apps/go-crm/go-crm
|
||||
apps/go-crm/main
|
||||
apps/go-crm/migrate
|
||||
|
||||
# Temporary build dirs
|
||||
tmp/
|
||||
apps/tmp/
|
||||
|
||||
# WhatsApp compiled binaries
|
||||
apps/whatsme/whatsme
|
||||
*.log
|
||||
Binary file not shown.
@@ -0,0 +1,36 @@
|
||||
---
|
||||
name: backend-driven-ui
|
||||
description: Create distinctive, production-grade frontend interfaces using Golang and Hypermedia (HTMX/Templ). Use this skill to build reactive web components and pages that prioritize performance and maintainability without the complexity of modern JavaScript frameworks.
|
||||
---
|
||||
|
||||
This skill guides the creation of high-end, "vibe-coded" interfaces using a **Golang-centric stack**. It avoids the maintenance burden of React/JS frameworks by leveraging **HTMX** and **Templ**, focusing on server-side logic that delivers rich, interactive client experiences.
|
||||
|
||||
## Design Thinking & "Vibe Coding"
|
||||
|
||||
Before coding, commit to a BOLD aesthetic direction that feels "hand-crafted" rather than "framework-default":
|
||||
- **Hypermedia First**: Architecture relies on HTML fragments. Every interaction is a server-side transition, making the app feel incredibly fast and robust.
|
||||
- **Tone**: Since we are avoiding the "React look," lean into distinctive styles: **High-Tech Industrial**, **Neo-Brutalist**, **Swiss International**, or **Terminal-Core**.
|
||||
- **The "Vibe"**: Aim for the "vibe coding" energy—fast feedback loops, visible data flowing through the terminal, and interfaces that feel like specialized tools rather than generic SaaS dashboards.
|
||||
|
||||
## Frontend Aesthetics Guidelines
|
||||
|
||||
Focus on:
|
||||
- **Typography**: Use characterful fonts that reflect the precision of Go. Lean towards high-quality Monospace (e.g., JetBrains Mono, Berkeley Graphics) for a "tooling" feel, or sophisticated Serifs paired with tight Grotesks for an editorial look.
|
||||
- **Color & Theme**: Use high-contrast themes. Since this is built with **Tailwind CSS**, use specific color scales (e.g., Zinc, Slate, or custom olive/amber palettes) to avoid the "Tailwind default" blue.
|
||||
- **Motion (CSS-Only)**: Prioritize CSS transitions and HTMX swapping animations (`htmx-settling`, `htmx-requesting`). Use staggered reveals and smooth opacity fades to mask the server-side round trip, making it feel "instant."
|
||||
- **Interaction**: Use **HTMX attributes** (`hx-get`, `hx-post`, `hx-target`) to create "Active Search," "Infinite Scroll," and "Inline Editing" patterns that surprise users who expect a heavy JS bundle.
|
||||
|
||||
## Technical Implementation (The Go Stack)
|
||||
|
||||
- **Templ over HTML**: All components must be written in `.templ` files. This ensures type safety and allows you to pass Go structs directly into your UI components.
|
||||
- **HTMX over JavaScript**: Replace `useState` and `useEffect` with `hx-trigger` and `hx-swap`. Maintain application state in the Go backend or the URL, not in a complex client-side store.
|
||||
- **Tailwind for Styling**: Use utility classes to keep styles local to the HTML. Avoid external CSS files to maintain the "Locality of Behavior" principle.
|
||||
- **Zero-JS Interactivity**: If client-side logic is strictly necessary (modals, toggles), use **Alpine.js** for its minimal footprint, keeping the code readable within the HTML.
|
||||
|
||||
## What to Avoid
|
||||
- **No Heavy Frameworks**: Strictly avoid React, Vue, or Angular.
|
||||
- **No JS "Glue Code"**: Avoid writing custom vanilla JavaScript for things HTMX can handle natively.
|
||||
- **No "AI Slop" Aesthetics**: Avoid the "Inter font + purple gradient + rounded card" combo.
|
||||
- **No JSON APIs for the UI**: Do not build internal JSON endpoints for your own frontend; return HTML fragments instead.
|
||||
|
||||
**IMPORTANT**: The beauty of this approach lies in its **mechanical elegance**. The code should be as clean and performant as the Go binary itself. Show that a "Vibe" can be achieved through clever hypermedia patterns and rock-solid backend engineering.
|
||||
@@ -1,206 +1,111 @@
|
||||
# AGENTS.md - Agent Coding Guidelines
|
||||
|
||||
Monorepo: data engineering projects + WhatsApp CRM apps.
|
||||
|
||||
---
|
||||
# AGENTS.md
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
workspace/
|
||||
├── apps/
|
||||
│ ├── go-crm/ # Go CRM, Chi router (primary)
|
||||
│ ├── whatsapp-crm/ # Next.js CRM, Kanban board
|
||||
│ ├── whatsapp-sync/ # WhatsApp message sync
|
||||
│ ├── whatsapp-reader/ # WhatsApp message reader
|
||||
│ └── timesfm-forecast/ # Time series forecast (Python/uv)
|
||||
├── data/ # SQLite files
|
||||
│ ├── go-crm.db
|
||||
│ └── whatsapp.db
|
||||
├── data-engineering/ # Udacity DE portfolio
|
||||
│ ├── go-crm/ # Go server (Chi), HTML templates, hot-reload via air
|
||||
│ ├── whatsapp-crm/ # Next.js 14 App Router, sql.js (browser SQLite), Kanban
|
||||
│ ├── whatsapp-sync/ # Node.js WhatsApp sync service
|
||||
│ ├── whatsapp-reader/ # Standalone message reader
|
||||
│ └── timesfm-forecast/ # Streamlit + TimesFM (Python/uv)
|
||||
├── data/ # SQLite DBs: go-crm.db, whatsapp.db
|
||||
├── data-engineering/ # Udacity DE portfolio (standalone, no unified build)
|
||||
└── skills/ # dbt reference templates
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Build / Lint / Test Commands
|
||||
## Developer Commands
|
||||
|
||||
### go-crm (primary)
|
||||
```bash
|
||||
cd apps/go-crm
|
||||
go run main.go # plain dev (no hot-reload)
|
||||
air # hot-reload dev (uses .air.toml)
|
||||
go build -o go-crm main.go # binary
|
||||
./go-crm # run binary
|
||||
|
||||
go run main.go # dev
|
||||
go build -o go-crm main.go # build binary
|
||||
./go-crm # run binary
|
||||
go mod tidy # clean go.mod/go.sum
|
||||
|
||||
go mod download # deps
|
||||
go mod tidy # clean go.mod/go.sum
|
||||
|
||||
# DB: /workspace/data/go-crm.db
|
||||
# DB: /workspace/data/go-crm.db (hardcoded path — do not change)
|
||||
# WhatsApp session: /workspace/data/whatsapp.db (hardcoded path)
|
||||
```
|
||||
|
||||
### whatsapp-crm (Next.js)
|
||||
### whatsapp-crm
|
||||
```bash
|
||||
cd apps/whatsapp-crm
|
||||
|
||||
npm run dev # dev server 0.0.0.0:3000
|
||||
npm run build # production build
|
||||
npm run start # production server
|
||||
|
||||
npm run lint # ESLint
|
||||
|
||||
npm run test # all Jest tests
|
||||
npm run test:watch # watch mode
|
||||
npm run test:coverage # coverage
|
||||
|
||||
npm run test -- tests/kanban.test.ts
|
||||
npm run test -- --testPathPattern=kanban
|
||||
npm run dev # Next.js dev server 0.0.0.0:3000
|
||||
npm run build # production build
|
||||
npm run lint # ESLint
|
||||
npm run test # Jest (uses tests/setup.ts)
|
||||
```
|
||||
|
||||
### whatsapp-sync
|
||||
```bash
|
||||
cd apps/whatsapp-sync
|
||||
|
||||
npm run start # node src/index.js
|
||||
npm run dev # node --watch src/index.js
|
||||
npm run sync # node src/sync.js
|
||||
npm run test # Jest
|
||||
npm run test:watch
|
||||
npm run test:coverage
|
||||
npm run start # node src/index.js
|
||||
npm run dev # node --watch src/index.js
|
||||
npm run sync # node src/sync.js
|
||||
npm run test # Jest (mocks qrcode-terminal + whatsapp-web.js)
|
||||
```
|
||||
|
||||
### whatsapp-reader
|
||||
```bash
|
||||
cd apps/whatsapp-reader
|
||||
|
||||
node index.js # main script
|
||||
node sync.js # sync script
|
||||
node index.js # main script
|
||||
node sync.js # sync script
|
||||
# no test script
|
||||
```
|
||||
|
||||
### timesfm-forecast
|
||||
```bash
|
||||
cd apps/timesfm-forecast
|
||||
uv venv && source .venv/bin/activate
|
||||
uv pip install -e .
|
||||
ruff check . # lint (dev dep)
|
||||
timesfm-app # run Streamlit app
|
||||
|
||||
uv venv && source .venv/bin/activate # create + activate venv
|
||||
uv pip install -e . # install package
|
||||
timesfm-app # run Streamlit app
|
||||
# See apps/timesfm-forecast/README.md for CUDA/CPU wheel guidance
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Code Style Guidelines
|
||||
## Important Quirks
|
||||
|
||||
### TypeScript
|
||||
### WhatsApp auth sessions
|
||||
- `.wwebjs_auth/` directories store session state — do not commit these
|
||||
- `whatsapp-sync` uses `better-sqlite3` for persistence
|
||||
- `whatsapp-crm` browser-side uses `sql.js` (WebAssembly, no native deps)
|
||||
|
||||
### go-crm auth
|
||||
- `X-Internal-Secret` header required on requests (value: `internal-secret`)
|
||||
- WhatsApp connector init URL: `http://localhost:8080`
|
||||
|
||||
### Docker
|
||||
```bash
|
||||
docker compose up whatsapp-crm # CRM only
|
||||
docker compose --profile sync up # CRM + sync
|
||||
docker compose --profile test up # test runner
|
||||
```
|
||||
|
||||
### go-crm hot-reload
|
||||
- Uses `air` (not `go run`) — configured in `.air.toml`
|
||||
- Build excludes `_test.go` and `vendor/`, `tmp/`, `assets/`
|
||||
|
||||
### TypeScript config (whatsapp-crm, whatsapp-sync)
|
||||
- `strict: true` in tsconfig.json
|
||||
- Explicit types for params + return values
|
||||
- `interface` for objects, `type` for unions/aliases
|
||||
- Path alias `@/*` maps to `src/*`
|
||||
|
||||
```typescript
|
||||
interface Contact {
|
||||
id: number
|
||||
name: string
|
||||
stage: Stage
|
||||
}
|
||||
|
||||
function getContactById(id: number): Contact | null
|
||||
```
|
||||
|
||||
### Imports
|
||||
- Path alias `@/*` (tsconfig.json)
|
||||
- Order: external → internal → relative
|
||||
- Group: React imports → other imports → types → components
|
||||
|
||||
```typescript
|
||||
import { useState, useMemo } from 'react'
|
||||
import { Stage, STAGES, Contact } from '@/lib/types'
|
||||
import { ContactCard } from '@/components/ContactCard'
|
||||
```
|
||||
|
||||
### Naming
|
||||
- **Components**: PascalCase (`KanbanBoard`, `ContactCard`)
|
||||
- **Files**: PascalCase (`.tsx`), camelCase (`.ts`)
|
||||
- **Interfaces/Types**: PascalCase
|
||||
- **Constants**: UPPER_SNAKE_CASE
|
||||
- **Hooks**: camelCase + `use` prefix
|
||||
- **Booleans**: `is`/`has`/`should` prefix
|
||||
|
||||
### Error Handling
|
||||
- Zod for input validation + react-hook-form
|
||||
- Wrap async in try/catch
|
||||
- Return proper HTTP status codes
|
||||
|
||||
```typescript
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = await request.json()
|
||||
const validated = CreateContactInput.parse(body)
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
return Response.json({ error: error.errors }, { status: 400 })
|
||||
}
|
||||
return Response.json({ error: 'Internal server error' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Component Structure
|
||||
- `'use client'` directive for client-side
|
||||
- Destructure props, explicit typing
|
||||
- Keep components focused, small
|
||||
- Extract reusable logic to custom hooks
|
||||
|
||||
```typescript
|
||||
'use client'
|
||||
|
||||
interface Props {
|
||||
contacts: Contact[]
|
||||
onContactClick: (contact: Contact) => void
|
||||
}
|
||||
|
||||
export default function ComponentName({ contacts, onContactClick }: Props) {
|
||||
const [state, setState] = useState(false)
|
||||
|
||||
return <div>{/* JSX */}</div>
|
||||
}
|
||||
```
|
||||
|
||||
### Database (sql.js)
|
||||
- Zod schemas for table definitions
|
||||
- Validate data before insert/update
|
||||
- Use transactions for multi-step ops
|
||||
|
||||
### Testing
|
||||
- Test files: `tests/*.test.ts` or `*.test.tsx`
|
||||
- `@testing-library/react` for component tests
|
||||
- `@testing-library/user-event` for interactions
|
||||
- AAA pattern: Arrange, Act, Assert
|
||||
|
||||
```typescript
|
||||
test('should update contact stage', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<KanbanBoard {...props} />)
|
||||
|
||||
await user.click(screen.getByText('Move to Next Stage'))
|
||||
expect(onStageChange).toHaveBeenCalledWith(1, 'DECIDINDO')
|
||||
})
|
||||
```
|
||||
|
||||
### CSS / Styling
|
||||
- CSS modules or global CSS
|
||||
- BEM-like: `block-element--modifier`
|
||||
- Co-locate styles when possible
|
||||
|
||||
### Git
|
||||
- Meaningful commit messages
|
||||
- Branch naming: `feature/description` or `fix/description`
|
||||
- Run `npm run lint` + `npm run test` before commit
|
||||
### Testing mocks
|
||||
- `whatsapp-sync` has manual mocks for `qrcode-terminal` and `whatsapp-web.js` in `tests/__mocks__/`
|
||||
|
||||
---
|
||||
|
||||
## Important Notes
|
||||
## What to Avoid
|
||||
|
||||
- whatsapp-crm: Next.js 14 App Router
|
||||
- Database: sql.js (WebAssembly SQLite), runs in browser
|
||||
- Auth: WhatsApp Web.js QR code scanning
|
||||
- STAGES constant: Kanban pipeline (defined in `src/lib/types.ts`)
|
||||
- Do not use `go run main.go` for development — use `air`
|
||||
- Do not commit `.wwebjs_auth/` or `.wwebjs_cache/` directories
|
||||
- Do not change hardcoded DB paths in `main.go`
|
||||
- The `data-engineering/` projects are standalone — no shared build or test commands
|
||||
@@ -4,20 +4,20 @@ tmp_dir = "tmp"
|
||||
[build]
|
||||
bin = "./tmp/main"
|
||||
cmd = "go build -buildvcs=false -o ./tmp/main ."
|
||||
delay = 1000
|
||||
exclude_dir = ["assets", "tmp", "vendor"]
|
||||
delay = 2000
|
||||
exclude_dir = ["assets", "tmp", "vendor", "data", "node_modules", ".git"]
|
||||
exclude_file = []
|
||||
exclude_regex = ["_test.go"]
|
||||
exclude_unchanged = false
|
||||
exclude_regex = ["_test.go", "\\.db$", "\\.db-journal$", "\\.db-shm$", "\\.db-wal$"]
|
||||
exclude_unchanged = true
|
||||
follow_symlink = false
|
||||
full_screen = false
|
||||
include_dir = []
|
||||
include_dir = ["internal"]
|
||||
include_ext = ["go", "templ"]
|
||||
kill_delay = "0s"
|
||||
kill_delay = "2s"
|
||||
log = "build-errors.toml"
|
||||
send_exit = false
|
||||
send_user = false
|
||||
stop_on_error = false
|
||||
stop_on_error = true
|
||||
|
||||
[log]
|
||||
main_only = false
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
.PHONY: test test-watch build clean dev migrate
|
||||
|
||||
test:
|
||||
go test ./... -v
|
||||
|
||||
test-watch:
|
||||
while true; do \
|
||||
inotifywait -q -e modify -e create -e delete -r internal/ 2>/dev/null || sleep 2; \
|
||||
go test ./... -v; \
|
||||
done
|
||||
|
||||
build:
|
||||
go build -o go-crm .
|
||||
|
||||
clean:
|
||||
rm -f go-crm
|
||||
|
||||
dev:
|
||||
./scripts/dev.sh
|
||||
|
||||
migrate:
|
||||
go build -o migrate cmd/migrate/main.go
|
||||
./migrate
|
||||
rm -f migrate
|
||||
@@ -0,0 +1,125 @@
|
||||
# go-crm (lightweight local dev)
|
||||
|
||||
This service is intentionally small so junior Go developers can understand it end-to-end without Docker, hot reloads, or other heavy tooling. The goal: `go run main.go` with a single SQLite file in `.dev-data/`.
|
||||
|
||||
## Local development (junior-friendly)
|
||||
|
||||
1. Ensure Go 1.25+ is installed and `go` is in your `PATH`.
|
||||
2. Run the helper script (no Docker):
|
||||
```bash
|
||||
./scripts/dev.sh
|
||||
```
|
||||
3. The server boots on [http://localhost:8080](http://localhost:8080).
|
||||
4. The database and WhatsApp store live under `.dev-data/` (auto-created).
|
||||
|
||||
There are no file watchers or `air` hot reloads—just the plain Go toolchain so newcomers can focus on code, not tooling.
|
||||
|
||||
## Project layout (modern, clean layers)
|
||||
|
||||
```
|
||||
go-crm/
|
||||
├── cmd/ # optional commands (e.g. migrations)
|
||||
│ └── migrate/ # lightweight migration CLI (future)
|
||||
├── config/ # templated configs (kept simple)
|
||||
├── data/ # production data path (gitignored)
|
||||
├── internal/ # HTTP handlers (usecases wired to HTTP)
|
||||
│ ├── handlers/
|
||||
│ ├── middleware/
|
||||
│ └── templates/
|
||||
├── pkg/ # reusable application packages
|
||||
│ ├── domain/ # entities + repository interfaces
|
||||
│ ├── usecase/ # application services / business logic
|
||||
│ └── repo/ # persistence adapters (SQLite, etc.)
|
||||
├── scripts/ # helper scripts (dev runner, migrations)
|
||||
├── main.go # application entrypoint (wire handlers → usecases)
|
||||
├── go.mod
|
||||
└── go.sum
|
||||
```
|
||||
|
||||
## Recommended architecture / interfaces
|
||||
|
||||
### `pkg/domain/lead.go`
|
||||
```go
|
||||
package domain
|
||||
|
||||
// Lead is the core business entity.
|
||||
type Lead struct {
|
||||
LeadID int64
|
||||
ClientID int64
|
||||
Name string
|
||||
PhoneRaw string
|
||||
PhoneNormalized string
|
||||
ServiceInterest string
|
||||
Status string
|
||||
PaymentStatus string
|
||||
}
|
||||
|
||||
// LeadRepository abstracts persistence.
|
||||
type LeadRepository interface {
|
||||
FindAll(ctx context.Context, clientID int64) ([]Lead, error)
|
||||
FindByID(ctx context.Context, clientID, leadID int64) (*Lead, error)
|
||||
Update(ctx context.Context, lead Lead) error
|
||||
}
|
||||
```
|
||||
|
||||
### `pkg/usecase/lead_service.go`
|
||||
```go
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go-crm/pkg/domain"
|
||||
)
|
||||
|
||||
// LeadService orchestrates business logic.
|
||||
type LeadService struct {
|
||||
Repo domain.LeadRepository
|
||||
}
|
||||
|
||||
func (s *LeadService) ListAll(ctx context.Context, clientID int64) ([]domain.Lead, error) {
|
||||
return s.Repo.FindAll(ctx, clientID)
|
||||
}
|
||||
```
|
||||
|
||||
### `pkg/repo/sqlite_lead_repo.go`
|
||||
```go
|
||||
package repo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"go-crm/pkg/domain"
|
||||
)
|
||||
|
||||
// SQLiteLeadRepository implements LeadRepository using sqlite.
|
||||
type SQLiteLeadRepository struct {
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
func (r *SQLiteLeadRepository) FindAll(ctx context.Context, clientID int64) ([]domain.Lead, error) {
|
||||
// query leads table, scan rows, return []domain.Lead
|
||||
}
|
||||
```
|
||||
|
||||
Handlers in `internal/handlers` should accept a clear service layer (`usecase.LeadService`), not raw DB logic. Keep controllers thin: parse request, call service, write HTML/JSON.
|
||||
|
||||
## Migration strategy
|
||||
|
||||
- Do not scan/clean the entire `leads` table on every startup (that was causing RAM blowups).
|
||||
- Run the lightweight CLI with `make migrate` (which builds and runs the migration binary) whenever you need to refresh the schema or re-decode legacy Latin-1 data. To target non-default files, run the migration binary directly:
|
||||
```bash
|
||||
go build -o migrate cmd/migrate/main.go && ./migrate --db /path/to/go-crm.db
|
||||
```
|
||||
|
||||
## Running tests
|
||||
|
||||
```bash
|
||||
go test ./...
|
||||
```
|
||||
|
||||
## Summary
|
||||
|
||||
- No Docker or `air` watchers—just `go run main.go`.
|
||||
- Clean package boundaries (domain/usecase/repo) improve readability and testability.
|
||||
- Scripts under `scripts/` orchestrate database setup or helper tasks.
|
||||
- Use the architecture sketch above to guide future refactors.
|
||||
@@ -0,0 +1,28 @@
|
||||
// Command migrate applies schema changes and sanitizes legacy data.
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"go-crm/config"
|
||||
"go-crm/internal/db"
|
||||
)
|
||||
|
||||
func main() {
|
||||
dbPath := flag.String("db", config.DatabasePath(), "path to SQLite database file")
|
||||
flag.Parse()
|
||||
|
||||
database, err := db.Init(*dbPath)
|
||||
if err != nil {
|
||||
log.Fatalf("migration failed: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := database.Close(); err != nil {
|
||||
log.Printf("warning: closing database: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
fmt.Println("Migration complete. Schema ensured and legacy encodings for lead_statuses & service_keywords fixed.")
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultWorkspaceRoot = "/workspace"
|
||||
defaultDataDirName = "data"
|
||||
defaultDatabaseFile = "go-crm.db"
|
||||
defaultWhatsAppStore = "whatsapp.db"
|
||||
defaultHTTPEndpoint = "http://localhost:8080"
|
||||
defaultInternalSecret = "internal-secret"
|
||||
)
|
||||
|
||||
// WorkspaceRoot returns the path to the shared workspace. CRM_WORKSPACE_PATH overrides it.
|
||||
// When no override is provided, we try to detect the workspace by walking up from the current
|
||||
// working directory and looking for the typical monorepo layout. If that fails, we fall back
|
||||
// to `../..` relative to the current directory and ultimately to `/workspace`.
|
||||
func WorkspaceRoot() string {
|
||||
if v := os.Getenv("CRM_WORKSPACE_PATH"); v != "" {
|
||||
return filepath.Clean(v)
|
||||
}
|
||||
if candidate := detectWorkspaceRoot(); candidate != "" {
|
||||
return candidate
|
||||
}
|
||||
if fallback := fallbackWorkspaceRoot(); fallback != "" {
|
||||
return fallback
|
||||
}
|
||||
return defaultWorkspaceRoot
|
||||
}
|
||||
|
||||
func detectWorkspaceRoot() string {
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for dir := wd; ; {
|
||||
if hasDir(dir, "data") && hasDir(dir, "apps") {
|
||||
return filepath.Clean(dir)
|
||||
}
|
||||
parent := filepath.Dir(dir)
|
||||
if parent == dir {
|
||||
break
|
||||
}
|
||||
dir = parent
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func fallbackWorkspaceRoot() string {
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Clean(filepath.Join(wd, "..", ".."))
|
||||
}
|
||||
|
||||
func hasDir(dir, name string) bool {
|
||||
info, err := os.Stat(filepath.Join(dir, name))
|
||||
return err == nil && info.IsDir()
|
||||
}
|
||||
|
||||
// DataDir returns the directory that stores SQLite files and related state. CRM_DATA_DIR overrides it.
|
||||
// If a local ".dev-data" directory exists (for junior-friendly dev), it is preferred.
|
||||
func DataDir() string {
|
||||
if v := os.Getenv("CRM_DATA_DIR"); v != "" {
|
||||
return filepath.Clean(v)
|
||||
}
|
||||
// prefer local .dev-data directory if present
|
||||
if cwd, err := os.Getwd(); err == nil {
|
||||
if info, err := os.Stat(filepath.Join(cwd, ".dev-data")); err == nil && info.IsDir() {
|
||||
return filepath.Join(cwd, ".dev-data")
|
||||
}
|
||||
}
|
||||
return filepath.Join(WorkspaceRoot(), defaultDataDirName)
|
||||
}
|
||||
|
||||
// DatabasePath returns the path to the Go CRM SQLite database. CRM_DATABASE_PATH overrides it.
|
||||
func DatabasePath() string {
|
||||
if v := os.Getenv("CRM_DATABASE_PATH"); v != "" {
|
||||
return filepath.Clean(v)
|
||||
}
|
||||
return filepath.Join(DataDir(), defaultDatabaseFile)
|
||||
}
|
||||
|
||||
// WhatsAppStorePath returns the path where the Whatsmeow session DB is stored. CRM_WHATSAPP_STORE_PATH overrides it.
|
||||
func WhatsAppStorePath() string {
|
||||
if v := os.Getenv("CRM_WHATSAPP_STORE_PATH"); v != "" {
|
||||
return filepath.Clean(v)
|
||||
}
|
||||
return filepath.Join(DataDir(), defaultWhatsAppStore)
|
||||
}
|
||||
|
||||
// HTTPServerEndpoint returns the HTTP endpoint used when WhatsApp events need to call back to the Go server.
|
||||
func HTTPServerEndpoint() string {
|
||||
if v := os.Getenv("CRM_HTTP_ENDPOINT"); v != "" {
|
||||
return v
|
||||
}
|
||||
return defaultHTTPEndpoint
|
||||
}
|
||||
|
||||
// InternalSecret returns the internal secret required by the WhatsApp connector.
|
||||
func InternalSecret() string {
|
||||
if v := os.Getenv("CRM_INTERNAL_SECRET"); v != "" {
|
||||
return v
|
||||
}
|
||||
return defaultInternalSecret
|
||||
}
|
||||
Binary file not shown.
@@ -12,6 +12,10 @@ services:
|
||||
working_dir: /workspace/apps/go-crm
|
||||
command: air
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 2G
|
||||
|
||||
networks:
|
||||
crm-network:
|
||||
|
||||
+1
-1
@@ -9,6 +9,7 @@ require (
|
||||
github.com/go-chi/cors v1.2.2
|
||||
go.mau.fi/whatsmeow v0.0.0-20260427122815-7514259253a7
|
||||
golang.org/x/crypto v0.50.0
|
||||
golang.org/x/text v0.37.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -32,7 +33,6 @@ require (
|
||||
golang.org/x/net v0.53.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.43.0 // indirect
|
||||
golang.org/x/text v0.36.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gorm.io/gorm v1.25.7 // indirect
|
||||
modernc.org/libc v1.22.5 // indirect
|
||||
|
||||
+2
-2
@@ -72,8 +72,8 @@ golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
|
||||
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
||||
@@ -9,8 +9,11 @@ import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func SignupPage(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
// package-level globals kept for existing tests; App methods use a.DB directly.
|
||||
var DB *sql.DB
|
||||
|
||||
func (a *App) SignupPage(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
@@ -30,7 +33,7 @@ func SignupPage(w http.ResponseWriter, r *http.Request) {
|
||||
</html>`))
|
||||
}
|
||||
|
||||
func Signup(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *App) Signup(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
email := r.FormValue("email")
|
||||
name := r.FormValue("name")
|
||||
@@ -47,21 +50,17 @@ func Signup(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
account := struct {
|
||||
Email string
|
||||
Name string
|
||||
Password string
|
||||
CreatedAt int64
|
||||
}{
|
||||
Email: email,
|
||||
Name: name,
|
||||
Password: string(hashedPassword),
|
||||
CreatedAt: time.Now().Unix(),
|
||||
// Use a transaction so account + client + session are atomic.
|
||||
tx, err := a.DB.Begin()
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to start transaction", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
_, err = DB.Exec(
|
||||
_, err = tx.Exec(
|
||||
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||
account.Email, account.Name, account.Password, account.CreatedAt,
|
||||
email, name, string(hashedPassword), time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
http.Error(w, "Email already exists", http.StatusBadRequest)
|
||||
@@ -69,45 +68,40 @@ func Signup(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
var accountID int64
|
||||
err = DB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", email).Scan(&accountID)
|
||||
if err != nil {
|
||||
if err = tx.QueryRow("SELECT account_id FROM accounts WHERE email = ?", email).Scan(&accountID); err != nil {
|
||||
http.Error(w, "Failed to create account", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
client := struct {
|
||||
AccountID int64
|
||||
Name string
|
||||
CreatedAt int64
|
||||
}{
|
||||
AccountID: accountID,
|
||||
Name: name,
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}
|
||||
_, err = DB.Exec(
|
||||
if _, err = tx.Exec(
|
||||
"INSERT INTO clients (account_id, name, created_at) VALUES (?, ?, ?)",
|
||||
client.AccountID, client.Name, client.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
accountID, name, time.Now().Unix(),
|
||||
); err != nil {
|
||||
http.Error(w, "Failed to create client", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
sessionID := generateSessionID()
|
||||
expires := time.Now().Add(24 * time.Hour).Unix()
|
||||
|
||||
_, err = DB.Exec("INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)", sessionID, accountID, expires)
|
||||
if err != nil {
|
||||
if _, err = tx.Exec(
|
||||
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
|
||||
sessionID, accountID, expires,
|
||||
); err != nil {
|
||||
http.Error(w, "Failed to create session", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if err = tx.Commit(); err != nil {
|
||||
http.Error(w, "Failed to commit signup", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.SetCookie(w, &http.Cookie{Name: "session", Value: sessionID, Path: "/"})
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
||||
func LoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
func (a *App) LoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
@@ -126,16 +120,14 @@ func LoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
</html>`))
|
||||
}
|
||||
|
||||
var DB *sql.DB
|
||||
|
||||
func Login(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *App) Login(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
email := r.FormValue("email")
|
||||
password := r.FormValue("password")
|
||||
|
||||
var accountID int64
|
||||
var hashedPassword string
|
||||
err := DB.QueryRow("SELECT account_id, password FROM accounts WHERE email = ?", email).Scan(&accountID, &hashedPassword)
|
||||
err := a.DB.QueryRow("SELECT account_id, password FROM accounts WHERE email = ?", email).Scan(&accountID, &hashedPassword)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
|
||||
return
|
||||
@@ -149,7 +141,7 @@ func Login(w http.ResponseWriter, r *http.Request) {
|
||||
sessionID := generateSessionID()
|
||||
expires := time.Now().Add(24 * time.Hour).Unix()
|
||||
|
||||
_, err = DB.Exec("INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)", sessionID, accountID, expires)
|
||||
_, err = a.DB.Exec("INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)", sessionID, accountID, expires)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to create session", http.StatusInternalServerError)
|
||||
return
|
||||
@@ -159,16 +151,152 @@ func Login(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
||||
func Logout(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *App) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie("session")
|
||||
if err == nil {
|
||||
DB.Exec("DELETE FROM sessions WHERE session_id = ?", cookie.Value)
|
||||
a.DB.Exec("DELETE FROM sessions WHERE session_id = ?", cookie.Value)
|
||||
}
|
||||
|
||||
http.SetCookie(w, &http.Cookie{Name: "session", Value: "", Path: "/", MaxAge: -1})
|
||||
http.Redirect(w, r, "/auth/login", http.StatusFound)
|
||||
}
|
||||
|
||||
func (a *App) AccountPage(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var name, email string
|
||||
err := a.DB.QueryRow("SELECT name, email FROM accounts WHERE account_id = ?", accountID).Scan(&name, &email)
|
||||
if err != nil {
|
||||
http.Error(w, "Account not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html><html><head><title>Account</title></head><body><h1>Account Settings</h1><form method="POST" action="/auth/account">
|
||||
<p>Name: <input type="text" name="name" value="` + name + `"></p>
|
||||
<p>Email: <input type="email" value="` + email + `" disabled></p>
|
||||
<p>New Password: <input type="password" name="password" placeholder="Leave blank to keep current"></p>
|
||||
<button type="submit">Update</button>
|
||||
</form>
|
||||
<a href="/">Back to Dashboard</a></body></html>`))
|
||||
}
|
||||
|
||||
func (a *App) UpdateAccount(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
r.ParseForm()
|
||||
name := r.FormValue("name")
|
||||
password := r.FormValue("password")
|
||||
|
||||
if name != "" {
|
||||
a.DB.Exec("UPDATE accounts SET name = ? WHERE account_id = ?", name, accountID)
|
||||
}
|
||||
|
||||
if password != "" {
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err == nil {
|
||||
a.DB.Exec("UPDATE accounts SET password = ? WHERE account_id = ?", string(hashedPassword), accountID)
|
||||
}
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/auth/account", http.StatusFound)
|
||||
}
|
||||
|
||||
// --- session helpers on App --------------------------------------------------
|
||||
|
||||
func (a *App) getSession(r *http.Request) (int64, error) {
|
||||
cookie, err := r.Cookie("session")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var accountID int64
|
||||
err = a.DB.QueryRow(
|
||||
"SELECT account_id FROM sessions WHERE session_id = ? AND expires > ?",
|
||||
cookie.Value, time.Now().Unix(),
|
||||
).Scan(&accountID)
|
||||
return accountID, err
|
||||
}
|
||||
|
||||
func (a *App) GetAccountID(r *http.Request) (int64, error) {
|
||||
return a.getSession(r)
|
||||
}
|
||||
|
||||
func (a *App) requireAuth(w http.ResponseWriter, r *http.Request) (int64, bool) {
|
||||
accountID, err := a.getSession(r)
|
||||
if err != nil {
|
||||
if isAPIRequest(r) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Write([]byte(`{"error":"unauthorized"}`))
|
||||
} else {
|
||||
http.Redirect(w, r, "/auth/login", http.StatusFound)
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
return accountID, true
|
||||
}
|
||||
|
||||
func (a *App) clientIDForAccount(accountID int64) int64 {
|
||||
var clientID int64
|
||||
a.DB.QueryRow("SELECT client_id FROM clients WHERE account_id = ? LIMIT 1", accountID).Scan(&clientID)
|
||||
return clientID
|
||||
}
|
||||
|
||||
// --- package-level shims kept for existing tests that set the global DB ------
|
||||
|
||||
func GetAccountID(r *http.Request) (int64, error) {
|
||||
return getSession(r)
|
||||
}
|
||||
|
||||
func getSession(r *http.Request) (int64, error) {
|
||||
cookie, err := r.Cookie("session")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var accountID int64
|
||||
err = DB.QueryRow(
|
||||
"SELECT account_id FROM sessions WHERE session_id = ? AND expires > ?",
|
||||
cookie.Value, time.Now().Unix(),
|
||||
).Scan(&accountID)
|
||||
return accountID, err
|
||||
}
|
||||
|
||||
func requireAuth(w http.ResponseWriter, r *http.Request) (int64, bool) {
|
||||
accountID, err := getSession(r)
|
||||
if err != nil {
|
||||
if isAPIRequest(r) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Write([]byte(`{"error":"unauthorized"}`))
|
||||
} else {
|
||||
http.Redirect(w, r, "/auth/login", http.StatusFound)
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
return accountID, true
|
||||
}
|
||||
|
||||
func clientIDForAccount(accountID int64) int64 {
|
||||
var clientID int64
|
||||
DB.QueryRow("SELECT client_id FROM clients WHERE account_id = ? LIMIT 1", accountID).Scan(&clientID)
|
||||
return clientID
|
||||
}
|
||||
|
||||
func isAPIRequest(r *http.Request) bool {
|
||||
accept := r.Header.Get("Accept")
|
||||
return accept == "application/json" || r.URL.Path == "/leads/qr"
|
||||
}
|
||||
|
||||
func SetupAuthHandlers(db *sql.DB) {
|
||||
DB = db
|
||||
chi.RegisterMethod("GET")
|
||||
}
|
||||
|
||||
// --- session ID generation ---------------------------------------------------
|
||||
|
||||
func generateSessionID() string {
|
||||
return time.Now().Format("20060102150405") + "-" + randomString(32)
|
||||
}
|
||||
@@ -182,88 +310,41 @@ func randomString(n int) string {
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func getSession(r *http.Request) (int64, error) {
|
||||
cookie, err := r.Cookie("session")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// SignupPage, Signup, LoginPage, Login, Logout, AccountPage, UpdateAccount
|
||||
// are also kept as package-level functions for backward compat with test
|
||||
// setups that call handlers.Signup directly. They delegate to the globals.
|
||||
|
||||
var accountID int64
|
||||
err = DB.QueryRow("SELECT account_id FROM sessions WHERE session_id = ? AND expires > ?", cookie.Value, time.Now().Unix()).Scan(&accountID)
|
||||
return accountID, err
|
||||
func SignupPage(w http.ResponseWriter, r *http.Request) {
|
||||
a := &App{DB: DB, WAConnector: WAConnector}
|
||||
a.SignupPage(w, r)
|
||||
}
|
||||
|
||||
func GetAccountID(r *http.Request) (int64, error) {
|
||||
return getSession(r)
|
||||
func Signup(w http.ResponseWriter, r *http.Request) {
|
||||
a := &App{DB: DB, WAConnector: WAConnector}
|
||||
a.Signup(w, r)
|
||||
}
|
||||
|
||||
func requireAuth(w http.ResponseWriter, r *http.Request) (int64, bool) {
|
||||
accountID, err := getSession(r)
|
||||
if err != nil {
|
||||
if isAPIRequest(r) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"error":"unauthorized"}`))
|
||||
} else {
|
||||
http.Redirect(w, r, "/auth/login", http.StatusFound)
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
return accountID, true
|
||||
func LoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
a := &App{DB: DB, WAConnector: WAConnector}
|
||||
a.LoginPage(w, r)
|
||||
}
|
||||
|
||||
func isAPIRequest(r *http.Request) bool {
|
||||
accept := r.Header.Get("Accept")
|
||||
return accept == "application/json" || r.URL.Path == "/leads/qr"
|
||||
func Login(w http.ResponseWriter, r *http.Request) {
|
||||
a := &App{DB: DB, WAConnector: WAConnector}
|
||||
a.Login(w, r)
|
||||
}
|
||||
|
||||
func SetupAuthHandlers(db *sql.DB) {
|
||||
DB = db
|
||||
chi.RegisterMethod("GET")
|
||||
func Logout(w http.ResponseWriter, r *http.Request) {
|
||||
a := &App{DB: DB, WAConnector: WAConnector}
|
||||
a.Logout(w, r)
|
||||
}
|
||||
|
||||
func AccountPage(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var name, email string
|
||||
err := DB.QueryRow("SELECT name, email FROM accounts WHERE account_id = ?", accountID).Scan(&name, &email)
|
||||
if err != nil {
|
||||
http.Error(w, "Account not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Write([]byte(`<!DOCTYPE html><html><head><title>Account</title></head><body><h1>Account Settings</h1><form method="POST" action="/auth/account">
|
||||
<p>Name: <input type="text" name="name" value="` + name + `"></p>
|
||||
<p>Email: <input type="email" value="` + email + `" disabled></p>
|
||||
<p>New Password: <input type="password" name="password" placeholder="Leave blank to keep current"></p>
|
||||
<button type="submit">Update</button>
|
||||
</form>
|
||||
<a href="/">Back to Dashboard</a></body></html>`))
|
||||
a := &App{DB: DB, WAConnector: WAConnector}
|
||||
a.AccountPage(w, r)
|
||||
}
|
||||
|
||||
func UpdateAccount(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
r.ParseForm()
|
||||
name := r.FormValue("name")
|
||||
password := r.FormValue("password")
|
||||
|
||||
if name != "" {
|
||||
DB.Exec("UPDATE accounts SET name = ? WHERE account_id = ?", name, accountID)
|
||||
}
|
||||
|
||||
if password != "" {
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err == nil {
|
||||
DB.Exec("UPDATE accounts SET password = ? WHERE account_id = ?", string(hashedPassword), accountID)
|
||||
}
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/auth/account", http.StatusFound)
|
||||
}
|
||||
a := &App{DB: DB, WAConnector: WAConnector}
|
||||
a.UpdateAccount(w, r)
|
||||
}
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func ListClients(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) ListClients(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -22,13 +22,13 @@ func ListClients(w http.ResponseWriter, r *http.Request) {
|
||||
limit = 20
|
||||
}
|
||||
|
||||
clients, err := db.ListClients(DB, accountID, limit, offset)
|
||||
clients, err := db.ListClients(a.DB, accountID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
@@ -60,8 +60,14 @@ func ListClients(w http.ResponseWriter, r *http.Request) {
|
||||
`))
|
||||
for _, c := range clients {
|
||||
var whatsappCell string
|
||||
if c.WhatsAppConnected == 1 && c.WhatsAppNumber != "" {
|
||||
whatsappCell = c.WhatsAppNumber
|
||||
connected := false
|
||||
if c.WhatsAppNumber != "" && a.WAConnector != nil {
|
||||
connected, _ = a.WAConnector.IsConnected(r.Context(), c.ClientID)
|
||||
}
|
||||
if connected {
|
||||
whatsappCell = c.WhatsAppNumber + ` <span style="color:#28a745">●</span>`
|
||||
} else if c.WhatsAppConnected == 1 && c.WhatsAppNumber != "" {
|
||||
whatsappCell = c.WhatsAppNumber + ` <span style="color:#dc3545">○</span> <a href="/leads/connect?client_id=` + strconv.FormatInt(c.ClientID, 10) + `">Reconnect</a>`
|
||||
} else {
|
||||
whatsappCell = `<a href="/leads/connect?client_id=` + strconv.FormatInt(c.ClientID, 10) + `">Connect</a>`
|
||||
}
|
||||
@@ -88,11 +94,13 @@ func ListClients(w http.ResponseWriter, r *http.Request) {
|
||||
</td>
|
||||
</tr>`))
|
||||
}
|
||||
w.Write([]byte(`</tbody></table></body></html>`))
|
||||
w.Write([]byte(`</tbody></table>
|
||||
<p><a href="/">Back to Home</a></p>
|
||||
</body></html>`))
|
||||
}
|
||||
|
||||
func CreateClient(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) CreateClient(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -104,33 +112,57 @@ func CreateClient(w http.ResponseWriter, r *http.Request) {
|
||||
Phone: r.FormValue("phone"),
|
||||
Email: r.FormValue("email"),
|
||||
Address: r.FormValue("address"),
|
||||
Notes: r.FormValue("notes"),
|
||||
Notes: r.FormValue("notes"),
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}
|
||||
|
||||
if err := client.Create(DB); err != nil {
|
||||
if err := client.Create(a.DB); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("HX-Refresh", "true")
|
||||
}
|
||||
|
||||
func ViewClient(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) ViewClient(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
client, err := db.GetClientByID(DB, accountID, id)
|
||||
client, err := db.GetClientByID(a.DB, accountID, id)
|
||||
if err != nil {
|
||||
http.Error(w, "Client not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
|
||||
var whatsappSection string
|
||||
if client.WhatsAppNumber != "" {
|
||||
connected := false
|
||||
if a.WAConnector != nil {
|
||||
connected, _ = a.WAConnector.IsConnected(r.Context(), client.ClientID)
|
||||
}
|
||||
status := "Not connected"
|
||||
style := "color:#999"
|
||||
if connected {
|
||||
status = "Connected"
|
||||
style = "color:#28a745"
|
||||
} else if client.WhatsAppConnected == 1 {
|
||||
status = "Disconnected (was connected)"
|
||||
style = "color:#dc3545"
|
||||
}
|
||||
whatsappSection = `
|
||||
<p>WhatsApp: <strong>` + client.WhatsAppNumber + `</strong> <span style="` + style + `">(` + status + `)</span></p>
|
||||
<p><a href="/leads/connect?client_id=` + strconv.FormatInt(client.ClientID, 10) + `">Reconnect WhatsApp</a></p>`
|
||||
} else {
|
||||
whatsappSection = `
|
||||
<p>WhatsApp: Not configured <a href="/leads/connect?client_id=` + strconv.FormatInt(client.ClientID, 10) + `">Connect</a></p>`
|
||||
}
|
||||
|
||||
w.Write([]byte(`<!DOCTYPE html>
|
||||
<html>
|
||||
<head></head>
|
||||
@@ -140,13 +172,13 @@ func ViewClient(w http.ResponseWriter, r *http.Request) {
|
||||
<p>Phone: ` + client.Phone + `</p>
|
||||
<p>Email: ` + client.Email + `</p>
|
||||
<p>Address: ` + client.Address + `</p>
|
||||
<p>Notes: ` + client.Notes + `</p>
|
||||
<p>Notes: ` + client.Notes + `</p>` + whatsappSection + `
|
||||
<a href="/clients">Back</a>
|
||||
</body></html>`))
|
||||
}
|
||||
|
||||
func UpdateClient(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) UpdateClient(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -156,14 +188,14 @@ func UpdateClient(w http.ResponseWriter, r *http.Request) {
|
||||
client := db.Client{
|
||||
ClientID: id,
|
||||
AccountID: accountID,
|
||||
Name: r.FormValue("name"),
|
||||
Phone: r.FormValue("phone"),
|
||||
Email: r.FormValue("email"),
|
||||
Address: r.FormValue("address"),
|
||||
Notes: r.FormValue("notes"),
|
||||
Name: r.FormValue("name"),
|
||||
Phone: r.FormValue("phone"),
|
||||
Email: r.FormValue("email"),
|
||||
Address: r.FormValue("address"),
|
||||
Notes: r.FormValue("notes"),
|
||||
}
|
||||
|
||||
if err := client.Update(DB); err != nil {
|
||||
if err := client.Update(a.DB); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
@@ -171,19 +203,37 @@ func UpdateClient(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("HX-Refresh", "true")
|
||||
}
|
||||
|
||||
func DeleteClient(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) DeleteClient(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
client := &db.Client{ClientID: id, AccountID: accountID}
|
||||
if err := client.Delete(DB); err != nil {
|
||||
if err := client.Delete(a.DB); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte("OK"))
|
||||
}
|
||||
}
|
||||
|
||||
// --- package-level shims kept for existing tests ---
|
||||
|
||||
func ListClients(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).ListClients(w, r)
|
||||
}
|
||||
func CreateClient(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).CreateClient(w, r)
|
||||
}
|
||||
func ViewClient(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).ViewClient(w, r)
|
||||
}
|
||||
func UpdateClient(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).UpdateClient(w, r)
|
||||
}
|
||||
func DeleteClient(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).DeleteClient(w, r)
|
||||
}
|
||||
@@ -210,4 +210,128 @@ func TestLeadsQRPolling(t *testing.T) {
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListClientsHasBackToHomeLink(t *testing.T) {
|
||||
tmpfile, err := os.CreateTemp("", "test_*.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(tmpfile.Name())
|
||||
tmpfile.Close()
|
||||
|
||||
testDB, err := db.Init(tmpfile.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to init db: %v", err)
|
||||
}
|
||||
defer testDB.Close()
|
||||
|
||||
DB = testDB
|
||||
WAConnector = whatsapp.NewFakeConnector()
|
||||
|
||||
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||
"[email protected]", "Test Account", string(hashedPassword), time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create account: %v", err)
|
||||
}
|
||||
|
||||
var accountID int64
|
||||
err = testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "[email protected]").Scan(&accountID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get account id: %v", err)
|
||||
}
|
||||
|
||||
sessionID := "test-session-nav"
|
||||
expires := time.Now().Add(time.Hour).Unix()
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
|
||||
sessionID, accountID, expires,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create session: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/clients", nil)
|
||||
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
ListClients(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
body := w.Body.String()
|
||||
|
||||
if !strings.Contains(body, `href="/"`) {
|
||||
t.Error("expected clients page to have Back to Home link")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListClientsShowsConnectButtonForUnconnectedClients(t *testing.T) {
|
||||
tmpfile, err := os.CreateTemp("", "test_*.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(tmpfile.Name())
|
||||
tmpfile.Close()
|
||||
|
||||
testDB, err := db.Init(tmpfile.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to init db: %v", err)
|
||||
}
|
||||
defer testDB.Close()
|
||||
|
||||
DB = testDB
|
||||
WAConnector = whatsapp.NewFakeConnector()
|
||||
|
||||
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||
"[email protected]", "Test Account", string(hashedPassword), time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create account: %v", err)
|
||||
}
|
||||
|
||||
var accountID int64
|
||||
err = testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "[email protected]").Scan(&accountID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get account id: %v", err)
|
||||
}
|
||||
|
||||
var clientID int64
|
||||
testDB.QueryRow(
|
||||
"INSERT INTO clients (account_id, name, phone, created_at) VALUES (?, ?, ?, ?) RETURNING client_id",
|
||||
accountID, "Unconnected Client", "+5521987654321", time.Now().Unix(),
|
||||
).Scan(&clientID)
|
||||
|
||||
sessionID := "test-session-connect-btn"
|
||||
expires := time.Now().Add(time.Hour).Unix()
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
|
||||
sessionID, accountID, expires,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create session: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/clients", nil)
|
||||
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
ListClients(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
body := w.Body.String()
|
||||
|
||||
if !strings.Contains(body, "leads/connect?client_id=") {
|
||||
t.Error("expected clients page to show Connect link for unconnected clients")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (a *App) Dashboard(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, err := a.getSession(r)
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/auth/login", http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
var clientID int64
|
||||
a.DB.QueryRow("SELECT client_id FROM clients WHERE account_id = ? LIMIT 1", accountID).Scan(&clientID)
|
||||
var reviewCount int
|
||||
if clientID > 0 {
|
||||
a.DB.QueryRow("SELECT COUNT(*) FROM leads WHERE client_id = ? AND needs_review = 1", clientID).Scan(&reviewCount)
|
||||
}
|
||||
|
||||
waStatus := "disconnected"
|
||||
waStyle := "color:#dc3545"
|
||||
connectLink := ""
|
||||
if a.WAConnector != nil {
|
||||
if connected, _ := a.WAConnector.IsConnected(r.Context(), clientID); connected {
|
||||
waStatus = "connected"
|
||||
waStyle = "color:#28a745"
|
||||
} else if clientID > 0 {
|
||||
// Fallback: check DB column when in-memory state not available.
|
||||
var dbConnected int
|
||||
a.DB.QueryRow("SELECT whatsapp_connected FROM clients WHERE client_id = ?", clientID).Scan(&dbConnected)
|
||||
if dbConnected == 1 {
|
||||
waStatus = "connected"
|
||||
waStyle = "color:#28a745"
|
||||
} else {
|
||||
connectLink = fmt.Sprintf(` <a href="/leads/connect?client_id=%d" style="color:#28a745">Connect</a>`, clientID)
|
||||
}
|
||||
} else {
|
||||
connectLink = ` <a href="/clients" style="color:#28a745">Create client to connect</a>`
|
||||
}
|
||||
}
|
||||
|
||||
badge := ""
|
||||
if reviewCount > 0 {
|
||||
badge = fmt.Sprintf(` <span style="background:#dc3545;color:#fff;border-radius:1rem;padding:0.15rem 0.5rem;font-size:0.8rem">%d</span>`, reviewCount)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
fmt.Fprintf(w, `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Dashboard</title>
|
||||
<style>
|
||||
body { font-family: sans-serif; padding: 1.5rem; }
|
||||
nav a { margin-right: 1rem; text-decoration: none; color: #2c7be5; }
|
||||
nav a:hover { text-decoration: underline; }
|
||||
.wa-status { font-size: 0.9rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>CRM Dashboard</h1>
|
||||
<p class="wa-status">WhatsApp: <strong style="%s">%s</strong>%s</p>
|
||||
<nav>
|
||||
<a href="/leads/review">Review Queue%s</a>
|
||||
<a href="/leads/all">All Leads</a>
|
||||
<a href="/report">Monthly Report</a>
|
||||
<a href="/leads/keywords">Keyword Mapping</a>
|
||||
<a href="/clients">Clients</a>
|
||||
<a href="/services">Services</a>
|
||||
<a href="/scheduling">Scheduling</a>
|
||||
<a href="/payments">Payments</a>
|
||||
<a href="/auth/account">Account</a>
|
||||
<form method="POST" action="/auth/logout" style="display:inline">
|
||||
<button type="submit">Logout</button>
|
||||
</form>
|
||||
</nav>
|
||||
</body></html>`, waStyle, waStatus, connectLink, badge)
|
||||
}
|
||||
|
||||
// --- package-level shim kept for existing tests ---
|
||||
|
||||
func Dashboard(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).Dashboard(w, r)
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go-crm/internal/db"
|
||||
"go-crm/internal/whatsapp"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestDashboardHidesConnectLinkWhenDBConnected(t *testing.T) {
|
||||
tmpfile, err := os.CreateTemp("", "test_*.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(tmpfile.Name())
|
||||
tmpfile.Close()
|
||||
|
||||
testDB, err := db.Init(tmpfile.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to init db: %v", err)
|
||||
}
|
||||
defer testDB.Close()
|
||||
|
||||
// FakeConnector NOT marked connected — only DB column is set.
|
||||
DB = testDB
|
||||
WAConnector = whatsapp.NewFakeConnector()
|
||||
|
||||
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||
"[email protected]", "Test Account", string(hashedPassword), time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create account: %v", err)
|
||||
}
|
||||
|
||||
var accountID int64
|
||||
err = testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "[email protected]").Scan(&accountID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get account id: %v", err)
|
||||
}
|
||||
|
||||
var clientID int64
|
||||
testDB.QueryRow(
|
||||
"INSERT INTO clients (account_id, name, phone, whatsapp_connected, created_at) VALUES (?, ?, ?, ?, ?) RETURNING client_id",
|
||||
accountID, "DB Connected Client", "+5521987654321", 1, time.Now().Unix(),
|
||||
).Scan(&clientID)
|
||||
|
||||
sessionID := "test-session-db-connected"
|
||||
expires := time.Now().Add(time.Hour).Unix()
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
|
||||
sessionID, accountID, expires,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create session: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
Dashboard(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
body := w.Body.String()
|
||||
|
||||
if !strings.Contains(body, "connected") {
|
||||
t.Error("expected dashboard to show 'connected' status from DB column")
|
||||
}
|
||||
|
||||
if strings.Contains(body, "/leads/connect") {
|
||||
t.Error("expected dashboard to NOT show Connect link when DB column indicates connected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDashboardShowsConnectLinkWhenDisconnected(t *testing.T) {
|
||||
tmpfile, err := os.CreateTemp("", "test_*.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(tmpfile.Name())
|
||||
tmpfile.Close()
|
||||
|
||||
testDB, err := db.Init(tmpfile.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to init db: %v", err)
|
||||
}
|
||||
defer testDB.Close()
|
||||
|
||||
DB = testDB
|
||||
WAConnector = whatsapp.NewFakeConnector()
|
||||
|
||||
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||
"[email protected]", "Test Account", string(hashedPassword), time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create account: %v", err)
|
||||
}
|
||||
|
||||
var accountID int64
|
||||
err = testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "[email protected]").Scan(&accountID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get account id: %v", err)
|
||||
}
|
||||
|
||||
sessionID := "test-session-dashboard"
|
||||
expires := time.Now().Add(time.Hour).Unix()
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
|
||||
sessionID, accountID, expires,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create session: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
Dashboard(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
body := w.Body.String()
|
||||
|
||||
if !strings.Contains(body, "disconnected") {
|
||||
t.Error("expected dashboard to show 'disconnected' status")
|
||||
}
|
||||
|
||||
if !strings.Contains(body, "/clients") {
|
||||
t.Error("expected dashboard to show link to create client when no client exists")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDashboardShowsConnectedStatus(t *testing.T) {
|
||||
tmpfile, err := os.CreateTemp("", "test_*.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(tmpfile.Name())
|
||||
tmpfile.Close()
|
||||
|
||||
testDB, err := db.Init(tmpfile.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to init db: %v", err)
|
||||
}
|
||||
defer testDB.Close()
|
||||
|
||||
fakeWA := whatsapp.NewFakeConnector()
|
||||
fakeWA.MarkConnected(1)
|
||||
|
||||
DB = testDB
|
||||
WAConnector = fakeWA
|
||||
|
||||
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||
"[email protected]", "Test Account", string(hashedPassword), time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create account: %v", err)
|
||||
}
|
||||
|
||||
var accountID int64
|
||||
err = testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "[email protected]").Scan(&accountID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get account id: %v", err)
|
||||
}
|
||||
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO clients (account_id, name, phone, created_at) VALUES (?, ?, ?, ?)",
|
||||
accountID, "Test Client", "+5521987654321", time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create client: %v", err)
|
||||
}
|
||||
|
||||
sessionID := "test-session-connected"
|
||||
expires := time.Now().Add(time.Hour).Unix()
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
|
||||
sessionID, accountID, expires,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create session: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
Dashboard(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
body := w.Body.String()
|
||||
|
||||
if !strings.Contains(body, "connected") {
|
||||
t.Error("expected dashboard to show 'connected' status")
|
||||
}
|
||||
|
||||
if strings.Contains(body, "/leads/connect") {
|
||||
t.Error("expected dashboard to NOT show Connect link when WhatsApp is connected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDashboardShowsConnectLinkWithClientID(t *testing.T) {
|
||||
tmpfile, err := os.CreateTemp("", "test_*.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(tmpfile.Name())
|
||||
tmpfile.Close()
|
||||
|
||||
testDB, err := db.Init(tmpfile.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to init db: %v", err)
|
||||
}
|
||||
defer testDB.Close()
|
||||
|
||||
DB = testDB
|
||||
WAConnector = whatsapp.NewFakeConnector()
|
||||
|
||||
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||
"[email protected]", "Test Account", string(hashedPassword), time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create account: %v", err)
|
||||
}
|
||||
|
||||
var accountID int64
|
||||
err = testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "[email protected]").Scan(&accountID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get account id: %v", err)
|
||||
}
|
||||
|
||||
var clientID int64
|
||||
testDB.QueryRow(
|
||||
"INSERT INTO clients (account_id, name, phone, created_at) VALUES (?, ?, ?, ?) RETURNING client_id",
|
||||
accountID, "Test Client", "+5521987654321", time.Now().Unix(),
|
||||
).Scan(&clientID)
|
||||
|
||||
sessionID := "test-session-disconnected-client"
|
||||
expires := time.Now().Add(time.Hour).Unix()
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
|
||||
sessionID, accountID, expires,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create session: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
Dashboard(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
body := w.Body.String()
|
||||
|
||||
if !strings.Contains(body, "disconnected") {
|
||||
t.Error("expected dashboard to show 'disconnected' status")
|
||||
}
|
||||
|
||||
if !strings.Contains(body, "/leads/connect?client_id=") {
|
||||
t.Error("expected dashboard to show Connect link with client_id when client exists")
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go-crm/internal/db"
|
||||
@@ -14,8 +15,8 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func ListLeads(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) ListLeads(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -27,7 +28,7 @@ func ListLeads(w http.ResponseWriter, r *http.Request) {
|
||||
limit = 20
|
||||
}
|
||||
|
||||
query := "SELECT customer_id, client_id, name, phone, birth_date, instagram, created_at FROM customers WHERE client_id IN (SELECT client_id FROM clients WHERE account_id = ?)"
|
||||
query := "SELECT cu.customer_id, cu.client_id, cu.name, cu.phone, cu.birth_date, cu.instagram, cu.created_at, COALESCE(cl.whatsapp_connected,0), COALESCE(cl.whatsapp_number,'') FROM customers cu JOIN clients cl ON cu.client_id = cl.client_id WHERE cl.account_id = ?"
|
||||
args := []interface{}{accountID}
|
||||
|
||||
if search != "" {
|
||||
@@ -36,10 +37,10 @@ func ListLeads(w http.ResponseWriter, r *http.Request) {
|
||||
args = append(args, searchPat, searchPat)
|
||||
}
|
||||
|
||||
query += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
|
||||
query += " ORDER BY cu.created_at DESC LIMIT ? OFFSET ?"
|
||||
args = append(args, limit, offset)
|
||||
|
||||
rows, err := DB.Query(query, args...)
|
||||
rows, err := a.DB.Query(query, args...)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -49,13 +50,13 @@ func ListLeads(w http.ResponseWriter, r *http.Request) {
|
||||
var customers []db.Customer
|
||||
for rows.Next() {
|
||||
var c db.Customer
|
||||
if err := rows.Scan(&c.CustomerID, &c.ClientID, &c.Name, &c.Phone, &c.BirthDate, &c.Instagram, &c.CreatedAt); err != nil {
|
||||
if err := rows.Scan(&c.CustomerID, &c.ClientID, &c.Name, &c.Phone, &c.BirthDate, &c.Instagram, &c.CreatedAt, &c.WhatsAppConnected, &c.WhatsAppNumber); err != nil {
|
||||
continue
|
||||
}
|
||||
customers = append(customers, c)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
@@ -80,17 +81,24 @@ func ListLeads(w http.ResponseWriter, r *http.Request) {
|
||||
</div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Name</th><th>Phone</th><th>Birth Date</th><th>Instagram</th><th>Actions</th></tr>
|
||||
<tr><th>Name</th><th>Phone</th><th>Birth Date</th><th>Instagram</th><th>WhatsApp</th><th>Actions</th></tr>
|
||||
</thead>
|
||||
<tbody id="leadList">
|
||||
`))
|
||||
|
||||
for _, c := range customers {
|
||||
waStatus := "Not connected"
|
||||
waStyle := "color: #999;"
|
||||
if c.WhatsAppConnected == 1 && c.WhatsAppNumber != "" {
|
||||
waStatus = c.WhatsAppNumber
|
||||
waStyle = "color: #28a745; font-weight: 600;"
|
||||
}
|
||||
w.Write([]byte(`<tr>
|
||||
<td>` + c.Name + `</td>
|
||||
<td>` + c.Phone + `</td>
|
||||
<td>` + c.BirthDate + `</td>
|
||||
<td>` + c.Instagram + `</td>
|
||||
<td style="` + waStyle + `">` + waStatus + `</td>
|
||||
<td>
|
||||
<button type="button" onclick="document.getElementById('editLead` + strconv.FormatInt(c.CustomerID, 10) + `').style.display='table-row'">Edit</button>
|
||||
<form method="DELETE" style="display:inline" hx-delete="/leads/` + strconv.FormatInt(c.CustomerID, 10) + `" hx-target="closest tr">
|
||||
@@ -99,7 +107,7 @@ func ListLeads(w http.ResponseWriter, r *http.Request) {
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="editLead` + strconv.FormatInt(c.CustomerID, 10) + `" class="edit-row">
|
||||
<td colspan="5">
|
||||
<td colspan="6">
|
||||
<form hx-put="/leads/` + strconv.FormatInt(c.CustomerID, 10) + `" hx-target="#leadList" hx-swap="innerHTML">
|
||||
<input type="text" name="name" value="` + c.Name + `">
|
||||
<input type="tel" name="phone" value="` + c.Phone + `">
|
||||
@@ -112,12 +120,12 @@ func ListLeads(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
w.Write([]byte(`</tbody></table>
|
||||
<p><a href="/clients">Back to Clients</a></p>
|
||||
<p><a href="/">Back to Home</a> | <a href="/clients">Back to Clients</a></p>
|
||||
</body></html>`))
|
||||
}
|
||||
|
||||
func UpdateLead(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) UpdateLead(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -125,7 +133,7 @@ func UpdateLead(w http.ResponseWriter, r *http.Request) {
|
||||
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
r.ParseForm()
|
||||
|
||||
_, err := DB.Exec(
|
||||
_, err := a.DB.Exec(
|
||||
"UPDATE customers SET name = ?, phone = ?, birth_date = ?, instagram = ? WHERE customer_id = ? AND client_id IN (SELECT client_id FROM clients WHERE account_id = ?)",
|
||||
r.FormValue("name"), r.FormValue("phone"), r.FormValue("birth_date"), r.FormValue("instagram"), id, accountID,
|
||||
)
|
||||
@@ -134,18 +142,18 @@ func UpdateLead(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
ListLeads(w, r)
|
||||
a.ListLeads(w, r)
|
||||
}
|
||||
|
||||
func DeleteLead(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) DeleteLead(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
|
||||
_, err := DB.Exec(
|
||||
_, err := a.DB.Exec(
|
||||
"DELETE FROM customers WHERE customer_id = ? AND client_id IN (SELECT client_id FROM clients WHERE account_id = ?)",
|
||||
id, accountID,
|
||||
)
|
||||
@@ -154,24 +162,24 @@ func DeleteLead(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte("OK"))
|
||||
}
|
||||
|
||||
func LeadsConnectPage(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) LeadsConnectPage(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
clientID, _ := strconv.ParseInt(r.URL.Query().Get("client_id"), 10, 64)
|
||||
client, err := db.GetClientByID(DB, accountID, clientID)
|
||||
client, err := db.GetClientByID(a.DB, accountID, clientID)
|
||||
if err != nil {
|
||||
http.Error(w, "Client not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
@@ -196,7 +204,6 @@ func LeadsConnectPage(w http.ResponseWriter, r *http.Request) {
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.qr) {
|
||||
// Only re-render QR if the code actually changed.
|
||||
if (data.qr !== lastQR) {
|
||||
lastQR = data.qr;
|
||||
document.getElementById('qrcode').innerHTML = '';
|
||||
@@ -209,12 +216,29 @@ func LeadsConnectPage(w http.ResponseWriter, r *http.Request) {
|
||||
document.getElementById('status').textContent = 'Scan with WhatsApp';
|
||||
setTimeout(pollQR, 5000);
|
||||
} else if (data.status === 'ready') {
|
||||
document.getElementById('status').textContent = 'Connected!';
|
||||
document.getElementById('status').textContent = 'Connected! Verifying phone...';
|
||||
document.getElementById('qrcode').innerHTML = '✓';
|
||||
// Stop polling — connected.
|
||||
setTimeout(() => {
|
||||
fetch('/leads/verify/` + strconv.FormatInt(client.ClientID, 10) + `')
|
||||
.then(r => r.json())
|
||||
.then(v => {
|
||||
var msg = 'WhatsApp: ' + (v.wa_phone || 'unknown');
|
||||
if (v.match === 'yes') {
|
||||
document.getElementById('status').textContent = msg + ' — matches ' + (v.client_phone || '') + ' ✓';
|
||||
document.getElementById('status').style.color = '#28a745';
|
||||
} else if (v.match === 'no') {
|
||||
document.getElementById('status').textContent = msg + ' — does NOT match client phone ' + (v.client_phone || '') + ' ⚠';
|
||||
document.getElementById('status').style.color = '#dc3545';
|
||||
} else {
|
||||
document.getElementById('status').textContent = msg + ' (client phone unknown — verify manually)';
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
document.getElementById('status').textContent = 'Connected! (could not verify phone)';
|
||||
});
|
||||
}, 1500);
|
||||
} else if (data.status === 'error') {
|
||||
document.getElementById('status').textContent = 'Error: ' + (data.error || 'Unknown') + ' — retrying...';
|
||||
// Back off longer on error to let server recover.
|
||||
setTimeout(pollQR, 8000);
|
||||
} else {
|
||||
document.getElementById('status').textContent = 'Status: ' + data.status;
|
||||
@@ -228,7 +252,7 @@ func LeadsConnectPage(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
pollQR();
|
||||
</script>
|
||||
<p><a href="/clients">Back to Clients</a></p>
|
||||
<p><a href="/">Back to Home</a> | <a href="/clients">Back to Clients</a></p>
|
||||
</body></html>`))
|
||||
}
|
||||
|
||||
@@ -237,46 +261,44 @@ func jsonEscape(s string) string {
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func LeadsQR(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) LeadsQR(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
clientID, _ := strconv.ParseInt(r.URL.Query().Get("client_id"), 10, 64)
|
||||
client, err := db.GetClientByID(DB, accountID, clientID)
|
||||
client, err := db.GetClientByID(a.DB, accountID, clientID)
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
w.Write([]byte(`{"status":"error","error":"client not found"}`))
|
||||
return
|
||||
}
|
||||
|
||||
if WAConnector == nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if a.WAConnector == nil {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
w.Write([]byte(`{"status":"error","error":"WhatsApp not configured - contact admin"}`))
|
||||
return
|
||||
}
|
||||
|
||||
connected, err := WAConnector.IsConnected(r.Context(), clientID)
|
||||
connected, err := a.WAConnector.IsConnected(r.Context(), clientID)
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Write([]byte(`{"client_id":` + strconv.FormatInt(client.ClientID, 10) + `,"status":"error","error":` + jsonEscape(err.Error()) + `}`))
|
||||
return
|
||||
}
|
||||
if connected {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Write([]byte(`{"client_id":` + strconv.FormatInt(client.ClientID, 10) + `,"status":"ready"}`))
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
log.Printf("QR: Starting Connect for client %d", clientID)
|
||||
|
||||
// Use context.Background() so the WA session goroutine outlives this HTTP request.
|
||||
// The handler returns after the first QR frame; subsequent polls reuse the same session.
|
||||
qrChan, err := WAConnector.Connect(context.Background(), clientID)
|
||||
qrChan, err := a.WAConnector.Connect(context.Background(), clientID)
|
||||
if err != nil {
|
||||
log.Printf("QR: Connect returned error for client %d: %v", clientID, err)
|
||||
w.Write([]byte(`{"client_id":` + strconv.FormatInt(client.ClientID, 10) + `,"status":"error","error":` + jsonEscape(err.Error()) + `}`))
|
||||
@@ -311,3 +333,52 @@ func LeadsQR(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) VerifyLead(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
clientID, _ := strconv.ParseInt(chi.URLParam(r, "client_id"), 10, 64)
|
||||
client, err := db.GetClientByID(a.DB, accountID, clientID)
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Write([]byte(`{"status":"error","error":"client not found"}`))
|
||||
return
|
||||
}
|
||||
|
||||
match := "unknown"
|
||||
if client.WhatsAppNumber != "" && client.Phone != "" {
|
||||
cleanWA := strings.TrimPrefix(client.WhatsAppNumber, "+")
|
||||
cleanClient := strings.TrimPrefix(client.Phone, "+")
|
||||
if cleanWA == cleanClient {
|
||||
match = "yes"
|
||||
} else {
|
||||
match = "no"
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Write([]byte(`{"status":"ok","wa_phone":"` + jsonEscape(client.WhatsAppNumber) + `","client_phone":"` + jsonEscape(client.Phone) + `","match":"` + match + `","client_name":"` + jsonEscape(client.Name) + `"}`))
|
||||
}
|
||||
|
||||
// --- package-level shims kept for existing tests ---
|
||||
|
||||
func ListLeads(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).ListLeads(w, r)
|
||||
}
|
||||
func UpdateLead(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).UpdateLead(w, r)
|
||||
}
|
||||
func DeleteLead(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).DeleteLead(w, r)
|
||||
}
|
||||
func LeadsConnectPage(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).LeadsConnectPage(w, r)
|
||||
}
|
||||
func LeadsQR(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).LeadsQR(w, r)
|
||||
}
|
||||
func VerifyLead(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).VerifyLead(w, r)
|
||||
}
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func ListPayments(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) ListPayments(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -23,19 +23,19 @@ func ListPayments(w http.ResponseWriter, r *http.Request) {
|
||||
limit = 20
|
||||
}
|
||||
|
||||
payments, err := db.ListPayments(DB, clientID, limit, offset)
|
||||
payments, err := db.ListPayments(a.DB, clientID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
clients, err := db.ListClients(DB, accountID, limit, offset)
|
||||
clients, err := db.ListClients(a.DB, accountID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
customers, err := db.ListCustomers(DB, accountID, clientID, limit, offset)
|
||||
customers, err := db.ListCustomers(a.DB, accountID, clientID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -53,7 +53,7 @@ func ListPayments(w http.ResponseWriter, r *http.Request) {
|
||||
customerNames[cu.CustomerID] = cu.Name
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html><html><head><script src="https://unpkg.com/[email protected]"></script><style>.edit-row{display:none}</style></head><body><h1>Payments</h1><button class="btn" onclick="document.getElementById('paymentForm').style.display='block'">Add Payment</button><div id="paymentForm" style="display:none; margin-top:1rem;"><form hx-post="/payments" hx-target="#paymentList"><select name="client_id" required><option value="">Select Client</option>` + clientOptions + `</select><select name="customer_id" required><option value="">Select Customer</option>` + customerOptions + `</select><input type="checkbox" name="has_paid"><label>Paid</label><input type="number" name="amount" placeholder="Amount" step="0.01"><input type="date" name="payment_date"><select name="payment_method"><option value="">Select Payment Method</option><option value="PIX">PIX</option><option value="Dinheiro">Dinheiro</option><option value="Débito">Débito</option><option value="Crédito à Vista">Crédito à Vista</option><option value="Parcelado">Parcelado</option><option value="Boleto">Boleto</option><option value="Transferência Bancária">Transferência Bancária</option></select><button type="submit">Add</button></form></div><table><thead><tr><th>Client</th><th>Customer</th><th>Amount</th><th>Paid</th><th>Date</th><th>Method</th><th>Actions</th></tr></thead><tbody id="paymentList">`))
|
||||
for _, p := range payments {
|
||||
paid := "No"
|
||||
@@ -73,8 +73,8 @@ func ListPayments(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`</tbody></table></body></html>`))
|
||||
}
|
||||
|
||||
func CreatePayment(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) CreatePayment(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -97,7 +97,7 @@ func CreatePayment(w http.ResponseWriter, r *http.Request) {
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}
|
||||
|
||||
if err := payment.Create(DB); err != nil {
|
||||
if err := payment.Create(a.DB); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
@@ -105,8 +105,8 @@ func CreatePayment(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("HX-Refresh", "true")
|
||||
}
|
||||
|
||||
func ViewPayment(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) ViewPayment(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -114,19 +114,19 @@ func ViewPayment(w http.ResponseWriter, r *http.Request) {
|
||||
id, _ := strconv.ParseInt(r.URL.Query().Get("id"), 10, 64)
|
||||
var p db.Payment
|
||||
var hasPaid int
|
||||
err := DB.QueryRow("SELECT payment_id, client_id, customer_id, schedule_id, has_paid, amount, payment_date, payment_method, created_at FROM payments WHERE payment_id = ?", id).Scan(&p.PaymentID, &p.ClientID, &p.CustomerID, &p.ScheduleID, &hasPaid, &p.Amount, &p.PaymentDate, &p.PaymentMethod, &p.CreatedAt)
|
||||
err := a.DB.QueryRow("SELECT payment_id, client_id, customer_id, schedule_id, has_paid, amount, payment_date, payment_method, created_at FROM payments WHERE payment_id = ?", id).Scan(&p.PaymentID, &p.ClientID, &p.CustomerID, &p.ScheduleID, &hasPaid, &p.Amount, &p.PaymentDate, &p.PaymentMethod, &p.CreatedAt)
|
||||
if err != nil {
|
||||
http.Error(w, "Payment not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
p.HasPaid = hasPaid == 1
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html><body><h1>Payment</h1><p>Amount: ` + strconv.FormatFloat(p.Amount, 'f', 2, 64) + `</p><p>Paid: ` + strconv.FormatBool(p.HasPaid) + `</p><p>Method: ` + p.PaymentMethod + `</p><a href="/payments">Back</a></body></html>`))
|
||||
}
|
||||
|
||||
func UpdatePayment(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) UpdatePayment(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -137,7 +137,7 @@ func UpdatePayment(w http.ResponseWriter, r *http.Request) {
|
||||
customerID, _ := strconv.ParseInt(r.FormValue("customer_id"), 10, 64)
|
||||
amount, _ := strconv.ParseFloat(r.FormValue("amount"), 64)
|
||||
hasPaid := r.FormValue("has_paid") == "on"
|
||||
_, err := DB.Exec("UPDATE payments SET client_id=?, customer_id=?, has_paid=?, amount=?, payment_date=?, payment_method=? WHERE payment_id=?", clientID, customerID, hasPaid, amount, r.FormValue("payment_date"), r.FormValue("payment_method"), id)
|
||||
_, err := a.DB.Exec("UPDATE payments SET client_id=?, customer_id=?, has_paid=?, amount=?, payment_date=?, payment_method=? WHERE payment_id=?", clientID, customerID, hasPaid, amount, r.FormValue("payment_date"), r.FormValue("payment_method"), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
@@ -145,19 +145,30 @@ func UpdatePayment(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("HX-Refresh", "true")
|
||||
}
|
||||
|
||||
func DeletePayment(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) DeletePayment(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
id, _ := strconv.ParseInt(r.URL.Query().Get("id"), 10, 64)
|
||||
DB.Exec("DELETE FROM payments WHERE payment_id = ?", id)
|
||||
a.DB.Exec("DELETE FROM payments WHERE payment_id = ?", id)
|
||||
}
|
||||
|
||||
func boolToStr(b bool) string {
|
||||
if b {
|
||||
return "Yes"
|
||||
}
|
||||
return "No"
|
||||
}
|
||||
// --- package-level shims kept for existing tests ---
|
||||
|
||||
func ListPayments(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).ListPayments(w, r)
|
||||
}
|
||||
func CreatePayment(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).CreatePayment(w, r)
|
||||
}
|
||||
func ViewPayment(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).ViewPayment(w, r)
|
||||
}
|
||||
func UpdatePayment(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).UpdatePayment(w, r)
|
||||
}
|
||||
func DeletePayment(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).DeletePayment(w, r)
|
||||
}
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func ListQuestions(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) ListQuestions(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -23,19 +23,19 @@ func ListQuestions(w http.ResponseWriter, r *http.Request) {
|
||||
limit = 20
|
||||
}
|
||||
|
||||
questions, err := db.ListQuestions(DB, clientID, limit, offset)
|
||||
questions, err := db.ListQuestions(a.DB, clientID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
clients, err := db.ListClients(DB, accountID, limit, offset)
|
||||
clients, err := db.ListClients(a.DB, accountID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
customers, err := db.ListCustomers(DB, accountID, clientID, limit, offset)
|
||||
customers, err := db.ListCustomers(a.DB, accountID, clientID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -53,7 +53,7 @@ func ListQuestions(w http.ResponseWriter, r *http.Request) {
|
||||
customerNames[cu.CustomerID] = cu.Name
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html><html><head><script src="https://unpkg.com/[email protected]"></script><style>.edit-row{display:none}</style></head><body><h1>Questions</h1><button class="btn" onclick="document.getElementById('questionForm').style.display='block'">Add Question</button><div id="questionForm" style="display:none; margin-top:1rem;"><form hx-post="/questions" hx-target="#questionList"><select name="client_id" required><option value="">Select Client</option>` + clientOptions + `</select><select name="customer_id" required><option value="">Select Customer</option>` + customerOptions + `</select><textarea name="question" placeholder="Question" required></textarea><select name="status"><option value="pending">Pending</option><option value="answered">Answered</option></select><button type="submit">Add</button></form></div><table><thead><tr><th>Client</th><th>Customer</th><th>Question</th><th>Status</th><th>Actions</th></tr></thead><tbody id="questionList">`))
|
||||
for _, q := range questions {
|
||||
clientName := clientNames[q.ClientID]
|
||||
@@ -69,8 +69,8 @@ func ListQuestions(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`</tbody></table></body></html>`))
|
||||
}
|
||||
|
||||
func CreateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) CreateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -81,13 +81,13 @@ func CreateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
question := db.Question{
|
||||
ClientID: clientID,
|
||||
CustomerID: customerID,
|
||||
Question: r.FormValue("question"),
|
||||
Timestamp: time.Now().Unix(),
|
||||
Status: r.FormValue("status"),
|
||||
CreatedAt: time.Now().Unix(),
|
||||
Question: r.FormValue("question"),
|
||||
Timestamp: time.Now().Unix(),
|
||||
Status: r.FormValue("status"),
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}
|
||||
|
||||
if err := question.Create(DB); err != nil {
|
||||
if err := question.Create(a.DB); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
@@ -95,26 +95,26 @@ func CreateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("HX-Refresh", "true")
|
||||
}
|
||||
|
||||
func ViewQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) ViewQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
var q db.Question
|
||||
err := DB.QueryRow("SELECT question_id, client_id, customer_id, question, timestamp, status, created_at FROM questions WHERE question_id = ?", id).Scan(&q.QuestionID, &q.ClientID, &q.CustomerID, &q.Question, &q.Timestamp, &q.Status, &q.CreatedAt)
|
||||
err := a.DB.QueryRow("SELECT question_id, client_id, customer_id, question, timestamp, status, created_at FROM questions WHERE question_id = ?", id).Scan(&q.QuestionID, &q.ClientID, &q.CustomerID, &q.Question, &q.Timestamp, &q.Status, &q.CreatedAt)
|
||||
if err != nil {
|
||||
http.Error(w, "Question not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html><body><h1>Question</h1><p>Client ID: ` + strconv.FormatInt(q.ClientID, 10) + `</p><p>Customer ID: ` + strconv.FormatInt(q.CustomerID, 10) + `</p><p>Question: ` + q.Question + `</p><p>Status: ` + q.Status + `</p><a href="/questions">Back</a></body></html>`))
|
||||
}
|
||||
|
||||
func UpdateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) UpdateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -123,7 +123,7 @@ func UpdateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||
customerID, _ := strconv.ParseInt(r.FormValue("customer_id"), 10, 64)
|
||||
_, err := DB.Exec("UPDATE questions SET client_id=?, customer_id=?, question=?, status=? WHERE question_id=?", clientID, customerID, r.FormValue("question"), r.FormValue("status"), id)
|
||||
_, err := a.DB.Exec("UPDATE questions SET client_id=?, customer_id=?, question=?, status=? WHERE question_id=?", clientID, customerID, r.FormValue("question"), r.FormValue("status"), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
@@ -131,18 +131,18 @@ func UpdateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("HX-Refresh", "true")
|
||||
}
|
||||
|
||||
func DeleteQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) DeleteQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
DB.Exec("DELETE FROM questions WHERE question_id = ?", id)
|
||||
a.DB.Exec("DELETE FROM questions WHERE question_id = ?", id)
|
||||
}
|
||||
|
||||
func ListAnswers(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) ListAnswers(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -154,13 +154,13 @@ func ListAnswers(w http.ResponseWriter, r *http.Request) {
|
||||
limit = 20
|
||||
}
|
||||
|
||||
answers, err := db.ListAnswersWithDetails(DB, accountID, questionID, limit, offset)
|
||||
answers, err := db.ListAnswersWithDetails(a.DB, accountID, questionID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
questions, err := db.ListQuestions(DB, 0, limit, offset)
|
||||
questions, err := db.ListQuestions(a.DB, 0, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -173,7 +173,7 @@ func ListAnswers(w http.ResponseWriter, r *http.Request) {
|
||||
questionText[q.QuestionID] = q.Question
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
@@ -202,19 +202,19 @@ func ListAnswers(w http.ResponseWriter, r *http.Request) {
|
||||
</thead>
|
||||
<tbody id="answerList">
|
||||
`))
|
||||
for _, a := range answers {
|
||||
qText := a.QuestionText
|
||||
for _, a2 := range answers {
|
||||
qText := a2.QuestionText
|
||||
if qText == "" {
|
||||
qText = questionText[a.QuestionID]
|
||||
qText = questionText[a2.QuestionID]
|
||||
if qText == "" {
|
||||
qText = strconv.FormatInt(a.QuestionID, 10)
|
||||
qText = strconv.FormatInt(a2.QuestionID, 10)
|
||||
}
|
||||
}
|
||||
clientName := a.ClientName
|
||||
clientName := a2.ClientName
|
||||
if clientName == "" {
|
||||
clientName = strconv.FormatInt(a.ClientID, 10)
|
||||
clientName = strconv.FormatInt(a2.ClientID, 10)
|
||||
}
|
||||
customerName := a.CustomerName
|
||||
customerName := a2.CustomerName
|
||||
if customerName == "" {
|
||||
customerName = "Unknown"
|
||||
}
|
||||
@@ -223,24 +223,24 @@ func ListAnswers(w http.ResponseWriter, r *http.Request) {
|
||||
<td>` + clientName + `</td>
|
||||
<td>` + customerName + `</td>
|
||||
<td>` + qText + `</td>
|
||||
<td>` + a.Answer + `</td>
|
||||
<td>` + a.Status + `</td>
|
||||
<td>` + a2.Answer + `</td>
|
||||
<td>` + a2.Status + `</td>
|
||||
<td>
|
||||
<a href="/answers/` + strconv.FormatInt(a.AnswerID, 10) + `">View</a>
|
||||
<button type="button" onclick="document.getElementById('editA`+strconv.FormatInt(a.AnswerID, 10)+`').style.display='table-row'">Edit</button>
|
||||
<form method="DELETE" style="display:inline" hx-delete="/answers/`+strconv.FormatInt(a.AnswerID, 10)+`" hx-target="closest tr">
|
||||
<a href="/answers/` + strconv.FormatInt(a2.AnswerID, 10) + `">View</a>
|
||||
<button type="button" onclick="document.getElementById('editA` + strconv.FormatInt(a2.AnswerID, 10) + `').style.display='table-row'">Edit</button>
|
||||
<form method="DELETE" style="display:inline" hx-delete="/answers/` + strconv.FormatInt(a2.AnswerID, 10) + `" hx-target="closest tr">
|
||||
<button type="submit">Delete</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="editA`+strconv.FormatInt(a.AnswerID, 10)+`" class="edit-row" style="display:none">
|
||||
<tr id="editA` + strconv.FormatInt(a2.AnswerID, 10) + `" class="edit-row" style="display:none">
|
||||
<td colspan="6">
|
||||
<form hx-put="/answers/`+strconv.FormatInt(a.AnswerID, 10)+`" hx-target="#answerList" hx-swap="innerHTML">
|
||||
<form hx-put="/answers/` + strconv.FormatInt(a2.AnswerID, 10) + `" hx-target="#answerList" hx-swap="innerHTML">
|
||||
<select name="question_id">
|
||||
<option value="`+strconv.FormatInt(a.QuestionID, 10)+`">`+qText+`</option>
|
||||
`+questionOptions+`
|
||||
<option value="` + strconv.FormatInt(a2.QuestionID, 10) + `">` + qText + `</option>
|
||||
` + questionOptions + `
|
||||
</select>
|
||||
<textarea name="answer">`+a.Answer+`</textarea>
|
||||
<textarea name="answer">` + a2.Answer + `</textarea>
|
||||
<button type="submit">Save</button>
|
||||
</form>
|
||||
</td>
|
||||
@@ -253,8 +253,8 @@ func ListAnswers(w http.ResponseWriter, r *http.Request) {
|
||||
</html>`))
|
||||
}
|
||||
|
||||
func CreateAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) CreateAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -263,14 +263,14 @@ func CreateAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
questionID, _ := strconv.ParseInt(r.FormValue("question_id"), 10, 64)
|
||||
|
||||
var clientID int64
|
||||
err := DB.QueryRow("SELECT client_id FROM questions WHERE question_id = ?", questionID).Scan(&clientID)
|
||||
err := a.DB.QueryRow("SELECT client_id FROM questions WHERE question_id = ?", questionID).Scan(&clientID)
|
||||
if err != nil {
|
||||
http.Error(w, "Question not found", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var checkID int64
|
||||
err = DB.QueryRow("SELECT client_id FROM clients WHERE client_id = ? AND account_id = ?", clientID, accountID).Scan(&checkID)
|
||||
err = a.DB.QueryRow("SELECT client_id FROM clients WHERE client_id = ? AND account_id = ?", clientID, accountID).Scan(&checkID)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid question", http.StatusBadRequest)
|
||||
return
|
||||
@@ -282,10 +282,10 @@ func CreateAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
Answer: r.FormValue("answer"),
|
||||
Timestamp: time.Now().Unix(),
|
||||
Status: "active",
|
||||
CreatedAt: time.Now().Unix(),
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}
|
||||
|
||||
if err := answer.Create(DB); err != nil {
|
||||
if err := answer.Create(a.DB); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
@@ -293,26 +293,26 @@ func CreateAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("HX-Refresh", "true")
|
||||
}
|
||||
|
||||
func ViewAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) ViewAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
var a db.Answer
|
||||
err := DB.QueryRow("SELECT answer_id, client_id, question_id, answer, timestamp, status, created_at FROM answers WHERE answer_id = ?", id).Scan(&a.AnswerID, &a.ClientID, &a.QuestionID, &a.Answer, &a.Timestamp, &a.Status, &a.CreatedAt)
|
||||
var ans db.Answer
|
||||
err := a.DB.QueryRow("SELECT answer_id, client_id, question_id, answer, timestamp, status, created_at FROM answers WHERE answer_id = ?", id).Scan(&ans.AnswerID, &ans.ClientID, &ans.QuestionID, &ans.Answer, &ans.Timestamp, &ans.Status, &ans.CreatedAt)
|
||||
if err != nil {
|
||||
http.Error(w, "Answer not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Write([]byte(`<!DOCTYPE html><body><h1>Answer</h1><p>Question ID: ` + strconv.FormatInt(a.QuestionID, 10) + `</p><p>Answer: ` + a.Answer + `</p><a href="/answers">Back</a></body></html>`))
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html><body><h1>Answer</h1><p>Question ID: ` + strconv.FormatInt(ans.QuestionID, 10) + `</p><p>Answer: ` + ans.Answer + `</p><a href="/answers">Back</a></body></html>`))
|
||||
}
|
||||
|
||||
func UpdateAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) UpdateAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -320,7 +320,7 @@ func UpdateAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
r.ParseForm()
|
||||
questionID, _ := strconv.ParseInt(r.FormValue("question_id"), 10, 64)
|
||||
_, err := DB.Exec("UPDATE answers SET question_id=?, answer=? WHERE answer_id=?", questionID, r.FormValue("answer"), id)
|
||||
_, err := a.DB.Exec("UPDATE answers SET question_id=?, answer=? WHERE answer_id=?", questionID, r.FormValue("answer"), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
@@ -328,12 +328,45 @@ func UpdateAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("HX-Refresh", "true")
|
||||
}
|
||||
|
||||
func DeleteAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) DeleteAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
DB.Exec("DELETE FROM answers WHERE answer_id = ?", id)
|
||||
}
|
||||
a.DB.Exec("DELETE FROM answers WHERE answer_id = ?", id)
|
||||
}
|
||||
|
||||
// --- package-level shims kept for existing tests ---
|
||||
|
||||
func ListQuestions(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).ListQuestions(w, r)
|
||||
}
|
||||
func CreateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).CreateQuestion(w, r)
|
||||
}
|
||||
func ViewQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).ViewQuestion(w, r)
|
||||
}
|
||||
func UpdateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).UpdateQuestion(w, r)
|
||||
}
|
||||
func DeleteQuestion(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).DeleteQuestion(w, r)
|
||||
}
|
||||
func ListAnswers(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).ListAnswers(w, r)
|
||||
}
|
||||
func CreateAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).CreateAnswer(w, r)
|
||||
}
|
||||
func ViewAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).ViewAnswer(w, r)
|
||||
}
|
||||
func UpdateAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).UpdateAnswer(w, r)
|
||||
}
|
||||
func DeleteAnswer(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).DeleteAnswer(w, r)
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type serviceCount struct {
|
||||
Name string
|
||||
Count int
|
||||
}
|
||||
|
||||
type reportData struct {
|
||||
TotalLeads int
|
||||
ServiceCounts []serviceCount
|
||||
StatusCounts []serviceCount
|
||||
TotalScheduled int
|
||||
ConversionRate float64
|
||||
TotalRevenue float64
|
||||
TotalSales int
|
||||
AverageTicket float64
|
||||
TopServices []serviceCount
|
||||
MonthLabel string
|
||||
}
|
||||
|
||||
// MonthlyReport renders the monthly performance report for the current month.
|
||||
// GET /report
|
||||
func (a *App) MonthlyReport(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
clientID := a.clientIDForAccount(accountID)
|
||||
if clientID == 0 {
|
||||
http.Error(w, "No client found for account", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()).Unix()
|
||||
nextMonth := time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, now.Location()).Unix()
|
||||
|
||||
rd := reportData{MonthLabel: now.Format("January 2006")}
|
||||
|
||||
a.DB.QueryRow(
|
||||
"SELECT COUNT(*) FROM leads WHERE client_id = ? AND created_at >= ? AND created_at < ?",
|
||||
clientID, monthStart, nextMonth,
|
||||
).Scan(&rd.TotalLeads)
|
||||
|
||||
rows, err := a.DB.Query(
|
||||
`SELECT service_interest, COUNT(*) as cnt FROM leads
|
||||
WHERE client_id = ? AND created_at >= ? AND created_at < ?
|
||||
GROUP BY service_interest ORDER BY cnt DESC`,
|
||||
clientID, monthStart, nextMonth,
|
||||
)
|
||||
if err == nil {
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var sc serviceCount
|
||||
rows.Scan(&sc.Name, &sc.Count)
|
||||
rd.ServiceCounts = append(rd.ServiceCounts, sc)
|
||||
}
|
||||
}
|
||||
|
||||
statusRows, err := a.DB.Query(
|
||||
`SELECT status, COUNT(*) as cnt FROM leads
|
||||
WHERE client_id = ? AND created_at >= ? AND created_at < ?
|
||||
GROUP BY status ORDER BY cnt DESC`,
|
||||
clientID, monthStart, nextMonth,
|
||||
)
|
||||
if err == nil {
|
||||
defer statusRows.Close()
|
||||
for statusRows.Next() {
|
||||
var sc serviceCount
|
||||
statusRows.Scan(&sc.Name, &sc.Count)
|
||||
rd.StatusCounts = append(rd.StatusCounts, sc)
|
||||
}
|
||||
}
|
||||
|
||||
a.DB.QueryRow(
|
||||
"SELECT COUNT(*) FROM leads WHERE client_id = ? AND status = 'Agendou' AND created_at >= ? AND created_at < ?",
|
||||
clientID, monthStart, nextMonth,
|
||||
).Scan(&rd.TotalScheduled)
|
||||
|
||||
if rd.TotalLeads > 0 {
|
||||
rd.ConversionRate = math.Round(float64(rd.TotalScheduled)/float64(rd.TotalLeads)*100*10) / 10
|
||||
}
|
||||
|
||||
a.DB.QueryRow(
|
||||
`SELECT COALESCE(SUM(amount),0), COUNT(*) FROM payments
|
||||
WHERE client_id = ? AND has_paid = 1 AND created_at >= ? AND created_at < ?`,
|
||||
clientID, monthStart, nextMonth,
|
||||
).Scan(&rd.TotalRevenue, &rd.TotalSales)
|
||||
|
||||
if rd.TotalSales > 0 {
|
||||
rd.AverageTicket = math.Round(rd.TotalRevenue/float64(rd.TotalSales)*100) / 100
|
||||
}
|
||||
|
||||
topRows, err := a.DB.Query(
|
||||
`SELECT s.name, COUNT(*) as cnt
|
||||
FROM payments p
|
||||
JOIN scheduling sch ON p.schedule_id = sch.schedule_id
|
||||
JOIN services s ON sch.service_id = s.service_id
|
||||
WHERE p.client_id = ? AND p.has_paid = 1 AND p.created_at >= ? AND p.created_at < ?
|
||||
GROUP BY s.name ORDER BY cnt DESC LIMIT 5`,
|
||||
clientID, monthStart, nextMonth,
|
||||
)
|
||||
if err == nil {
|
||||
defer topRows.Close()
|
||||
for topRows.Next() {
|
||||
var sc serviceCount
|
||||
topRows.Scan(&sc.Name, &sc.Count)
|
||||
rd.TopServices = append(rd.TopServices, sc)
|
||||
}
|
||||
}
|
||||
|
||||
var reviewCount int
|
||||
a.DB.QueryRow("SELECT COUNT(*) FROM leads WHERE client_id = ? AND needs_review = 1", clientID).Scan(&reviewCount)
|
||||
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
fmt.Fprintf(w, `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Monthly Report — %s</title>
|
||||
<style>
|
||||
body { font-family: sans-serif; padding: 1rem; max-width: 900px; margin: 0 auto; }
|
||||
h1, h2 { color: #333; }
|
||||
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem; }
|
||||
.card { border: 1px solid #ddd; border-radius: 8px; padding: 1rem; background: #fafafa; }
|
||||
.card .value { font-size: 2rem; font-weight: bold; color: #2c7be5; }
|
||||
.card .label { color: #666; font-size: 0.9rem; margin-top: 0.25rem; }
|
||||
table { border-collapse: collapse; width: 100%%; margin-bottom: 1.5rem; }
|
||||
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
|
||||
th { background: #f5f5f5; }
|
||||
.badge { background: #dc3545; color: #fff; border-radius: 1rem; padding: 0.2rem 0.6rem; font-size: 0.8rem; }
|
||||
nav { margin-bottom: 1rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Monthly Report — %s</h1>
|
||||
<nav>
|
||||
<a href="/">Home</a> |
|
||||
<a href="/leads/review">Review Queue <span class="badge">%d</span></a> |
|
||||
<a href="/leads/all">All Leads</a> |
|
||||
<a href="/leads/keywords">Keyword Mapping</a>
|
||||
</nav>
|
||||
|
||||
<h2>Overview</h2>
|
||||
<div class="grid">
|
||||
<div class="card"><div class="value">%d</div><div class="label">Total Leads</div></div>
|
||||
<div class="card"><div class="value">%d</div><div class="label">Agendamentos</div></div>
|
||||
<div class="card"><div class="value">%.1f%%</div><div class="label">Conversion Rate</div></div>
|
||||
</div>
|
||||
|
||||
<h2>Revenue</h2>
|
||||
<div class="grid">
|
||||
<div class="card"><div class="value">R$ %.2f</div><div class="label">Total Month Revenue</div></div>
|
||||
<div class="card"><div class="value">%d</div><div class="label">Total Sales</div></div>
|
||||
<div class="card"><div class="value">R$ %.2f</div><div class="label">Average Ticket</div></div>
|
||||
</div>
|
||||
|
||||
<h2>Leads by Service Interest</h2>
|
||||
%s
|
||||
|
||||
<h2>Leads by Status</h2>
|
||||
%s
|
||||
|
||||
<h2>Top 5 Services Sold</h2>
|
||||
%s
|
||||
|
||||
</body></html>`,
|
||||
rd.MonthLabel,
|
||||
rd.MonthLabel,
|
||||
reviewCount,
|
||||
rd.TotalLeads, rd.TotalScheduled, rd.ConversionRate,
|
||||
rd.TotalRevenue, rd.TotalSales, rd.AverageTicket,
|
||||
renderServiceTable(rd.ServiceCounts, rd.TotalLeads),
|
||||
renderServiceTable(rd.StatusCounts, rd.TotalLeads),
|
||||
renderTopServicesTable(rd.TopServices),
|
||||
)
|
||||
}
|
||||
|
||||
func renderServiceTable(counts []serviceCount, total int) string {
|
||||
if len(counts) == 0 {
|
||||
return `<p style="color:#888">No data for this month.</p>`
|
||||
}
|
||||
out := `<table><thead><tr><th>Name</th><th>Quantity</th><th>%</th></tr></thead><tbody>`
|
||||
for _, sc := range counts {
|
||||
pct := 0.0
|
||||
if total > 0 {
|
||||
pct = math.Round(float64(sc.Count)/float64(total)*100*10) / 10
|
||||
}
|
||||
out += fmt.Sprintf(`<tr><td>%s</td><td>%d</td><td>%.1f%%</td></tr>`,
|
||||
htmlEscape(sc.Name), sc.Count, pct)
|
||||
}
|
||||
out += `</tbody></table>`
|
||||
return out
|
||||
}
|
||||
|
||||
func renderTopServicesTable(counts []serviceCount) string {
|
||||
if len(counts) == 0 {
|
||||
return `<p style="color:#888">No sales data for this month.</p>`
|
||||
}
|
||||
out := `<table><thead><tr><th>Service</th><th>Sales</th></tr></thead><tbody>`
|
||||
for _, sc := range counts {
|
||||
out += fmt.Sprintf(`<tr><td>%s</td><td>%d</td></tr>`, htmlEscape(sc.Name), sc.Count)
|
||||
}
|
||||
out += `</tbody></table>`
|
||||
return out
|
||||
}
|
||||
|
||||
// --- package-level shim kept for existing tests ---
|
||||
|
||||
func MonthlyReport(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).MonthlyReport(w, r)
|
||||
}
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func ListSchedules(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) ListSchedules(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -24,25 +24,25 @@ func ListSchedules(w http.ResponseWriter, r *http.Request) {
|
||||
limit = 20
|
||||
}
|
||||
|
||||
schedules, err := db.ListSchedules(DB, clientID, customerID, limit, offset)
|
||||
schedules, err := db.ListSchedules(a.DB, clientID, customerID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
clients, err := db.ListClients(DB, accountID, limit, offset)
|
||||
clients, err := db.ListClients(a.DB, accountID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
customers, err := db.ListCustomers(DB, accountID, clientID, limit, offset)
|
||||
customers, err := db.ListCustomers(a.DB, accountID, clientID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
services, err := db.ListServices(DB, accountID, clientID, limit, offset)
|
||||
services, err := db.ListServices(a.DB, accountID, clientID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -65,7 +65,7 @@ func ListSchedules(w http.ResponseWriter, r *http.Request) {
|
||||
serviceNames[s.ServiceID] = s.Name
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html><html><head><script src="https://unpkg.com/[email protected]"></script><style>.edit-row{display:none}</style></head><body><h1>Scheduling</h1><button class="btn" onclick="document.getElementById('scheduleForm').style.display='block'">Add Schedule</button><div id="scheduleForm" style="display:none; margin-top:1rem;"><form hx-post="/scheduling" hx-target="#scheduleList"><select name="client_id" required><option value="">Select Client</option>` + clientOptions + `</select><select name="customer_id" required><option value="">Select Customer</option>` + customerOptions + `</select><select name="service_id" required><option value="">Select Service</option>` + serviceOptions + `</select><input type="date" name="plan_date"><input type="time" name="time"><select name="status"><option value="pending">Pending</option><option value="confirmed">Confirmed</option><option value="cancelled">Cancelled</option></select><button type="submit">Add</button></form></div><table><thead><tr><th>Client</th><th>Customer</th><th>Service</th><th>Date</th><th>Hour</th><th>Status</th><th>Actions</th></tr></thead><tbody id="scheduleList">`))
|
||||
for _, s := range schedules {
|
||||
clientName := clientNames[s.ClientID]
|
||||
@@ -85,8 +85,8 @@ func ListSchedules(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`</tbody></table></body></html>`))
|
||||
}
|
||||
|
||||
func CreateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) CreateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -96,16 +96,16 @@ func CreateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
customerID, _ := strconv.ParseInt(r.FormValue("customer_id"), 10, 64)
|
||||
serviceID, _ := strconv.ParseInt(r.FormValue("service_id"), 10, 64)
|
||||
schedule := db.Schedule{
|
||||
ClientID: clientID,
|
||||
ClientID: clientID,
|
||||
CustomerID: customerID,
|
||||
ServiceID: serviceID,
|
||||
PlanDate: r.FormValue("plan_date"),
|
||||
Time: r.FormValue("time"),
|
||||
Status: r.FormValue("status"),
|
||||
CreatedAt: time.Now().Unix(),
|
||||
Time: r.FormValue("time"),
|
||||
Status: r.FormValue("status"),
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}
|
||||
|
||||
if err := schedule.Create(DB); err != nil {
|
||||
if err := schedule.Create(a.DB); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
@@ -113,26 +113,26 @@ func CreateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("HX-Refresh", "true")
|
||||
}
|
||||
|
||||
func ViewSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) ViewSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
var sch db.Schedule
|
||||
err := DB.QueryRow("SELECT schedule_id, client_id, customer_id, service_id, plan_date, time, status, created_at FROM scheduling WHERE schedule_id = ?", id).Scan(&sch.ScheduleID, &sch.ClientID, &sch.CustomerID, &sch.ServiceID, &sch.PlanDate, &sch.Time, &sch.Status, &sch.CreatedAt)
|
||||
err := a.DB.QueryRow("SELECT schedule_id, client_id, customer_id, service_id, plan_date, time, status, created_at FROM scheduling WHERE schedule_id = ?", id).Scan(&sch.ScheduleID, &sch.ClientID, &sch.CustomerID, &sch.ServiceID, &sch.PlanDate, &sch.Time, &sch.Status, &sch.CreatedAt)
|
||||
if err != nil {
|
||||
http.Error(w, "Schedule not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html><body><h1>Schedule</h1><p>Client ID: ` + strconv.FormatInt(sch.ClientID, 10) + `</p><p>Customer ID: ` + strconv.FormatInt(sch.CustomerID, 10) + `</p><p>Service ID: ` + strconv.FormatInt(sch.ServiceID, 10) + `</p><p>Date: ` + sch.PlanDate + `</p><p>Time: ` + sch.Time + `</p><p>Status: ` + sch.Status + `</p><a href="/scheduling">Back</a></body></html>`))
|
||||
}
|
||||
|
||||
func UpdateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) UpdateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -142,7 +142,7 @@ func UpdateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||
customerID, _ := strconv.ParseInt(r.FormValue("customer_id"), 10, 64)
|
||||
serviceID, _ := strconv.ParseInt(r.FormValue("service_id"), 10, 64)
|
||||
_, err := DB.Exec("UPDATE scheduling SET client_id=?, customer_id=?, service_id=?, plan_date=?, time=?, status=? WHERE schedule_id=?", clientID, customerID, serviceID, r.FormValue("plan_date"), r.FormValue("time"), r.FormValue("status"), id)
|
||||
_, err := a.DB.Exec("UPDATE scheduling SET client_id=?, customer_id=?, service_id=?, plan_date=?, time=?, status=? WHERE schedule_id=?", clientID, customerID, serviceID, r.FormValue("plan_date"), r.FormValue("time"), r.FormValue("status"), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
@@ -150,12 +150,30 @@ func UpdateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("HX-Refresh", "true")
|
||||
}
|
||||
|
||||
func DeleteSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) DeleteSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
DB.Exec("DELETE FROM scheduling WHERE schedule_id = ?", id)
|
||||
}
|
||||
a.DB.Exec("DELETE FROM scheduling WHERE schedule_id = ?", id)
|
||||
}
|
||||
|
||||
// --- package-level shims kept for existing tests ---
|
||||
|
||||
func ListSchedules(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).ListSchedules(w, r)
|
||||
}
|
||||
func CreateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).CreateSchedule(w, r)
|
||||
}
|
||||
func ViewSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).ViewSchedule(w, r)
|
||||
}
|
||||
func UpdateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).UpdateSchedule(w, r)
|
||||
}
|
||||
func DeleteSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).DeleteSchedule(w, r)
|
||||
}
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func ListServices(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) ListServices(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -23,13 +23,13 @@ func ListServices(w http.ResponseWriter, r *http.Request) {
|
||||
limit = 20
|
||||
}
|
||||
|
||||
services, err := db.ListServices(DB, accountID, clientID, limit, offset)
|
||||
services, err := db.ListServices(a.DB, accountID, clientID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
clients, err := db.ListClients(DB, accountID, limit, offset)
|
||||
clients, err := db.ListClients(a.DB, accountID, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -40,7 +40,7 @@ func ListServices(w http.ResponseWriter, r *http.Request) {
|
||||
clientOptions += `<option value="` + strconv.FormatInt(c.ClientID, 10) + `">` + c.Name + `</option>`
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html><html><head><script src="https://unpkg.com/[email protected]"></script></head><body><h1>Services</h1><button class="btn" onclick="document.getElementById('serviceForm').style.display='block'">Add Service</button><div id="serviceForm" style="display:none; margin-top:1rem;"><form hx-post="/services" hx-target="#serviceList"><input type="text" name="name" placeholder="Service Name" required><input type="number" name="price" placeholder="Price" step="0.01"><textarea name="description" placeholder="Description"></textarea><input type="text" name="duration" placeholder="Duration"><select name="client_id" required><option value="">Select Client</option>` + clientOptions + `</select><button type="submit">Add</button></form></div><table><thead><tr><th>Name</th><th>Price</th><th>Duration</th><th>Actions</th></tr></thead><tbody id="serviceList">`))
|
||||
for _, s := range services {
|
||||
w.Write([]byte(`<tr><td>` + s.Name + `</td><td>` + strconv.FormatFloat(s.Price, 'f', 2, 64) + `</td><td>` + s.Duration + `</td><td><a href="/services/` + strconv.FormatInt(s.ServiceID, 10) + `">View</a><button type="button" onclick="document.getElementById('editServ` + strconv.FormatInt(s.ServiceID, 10) + `').style.display='table-row'">Edit</button><form method="DELETE" style="display:inline" hx-delete="/services/` + strconv.FormatInt(s.ServiceID, 10) + `" hx-target="closest tr"><button type="submit">Delete</button></form></td></tr><tr id="editServ` + strconv.FormatInt(s.ServiceID, 10) + `" style="display:none"><td colspan="4"><form hx-put="/services/` + strconv.FormatInt(s.ServiceID, 10) + `" hx-target="#serviceList" hx-swap="innerHTML"><input type="text" name="name" value="` + s.Name + `"><input type="number" name="price" value="` + strconv.FormatFloat(s.Price, 'f', 2, 64) + `"><textarea name="description">` + s.Description + `</textarea><input type="text" name="duration" value="` + s.Duration + `"><select name="client_id"><option value="` + strconv.FormatInt(s.ClientID, 10) + `">` + s.Name + `</option>` + clientOptions + `</select><button type="submit">Save</button></form></td></tr>`))
|
||||
@@ -48,8 +48,8 @@ func ListServices(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`</tbody></table></body></html>`))
|
||||
}
|
||||
|
||||
func CreateService(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := requireAuth(w, r)
|
||||
func (a *App) CreateService(w http.ResponseWriter, r *http.Request) {
|
||||
accountID, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -58,7 +58,7 @@ func CreateService(w http.ResponseWriter, r *http.Request) {
|
||||
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||
|
||||
var checkID int64
|
||||
err := DB.QueryRow("SELECT client_id FROM clients WHERE client_id = ? AND account_id = ?", clientID, accountID).Scan(&checkID)
|
||||
err := a.DB.QueryRow("SELECT client_id FROM clients WHERE client_id = ? AND account_id = ?", clientID, accountID).Scan(&checkID)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid client", http.StatusBadRequest)
|
||||
return
|
||||
@@ -67,14 +67,14 @@ func CreateService(w http.ResponseWriter, r *http.Request) {
|
||||
price, _ := strconv.ParseFloat(r.FormValue("price"), 64)
|
||||
service := db.Service{
|
||||
ClientID: clientID,
|
||||
Name: r.FormValue("name"),
|
||||
Price: price,
|
||||
Name: r.FormValue("name"),
|
||||
Price: price,
|
||||
Description: r.FormValue("description"),
|
||||
Duration: r.FormValue("duration"),
|
||||
CreatedAt: time.Now().Unix(),
|
||||
Duration: r.FormValue("duration"),
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}
|
||||
|
||||
if err := service.Create(DB); err != nil {
|
||||
if err := service.Create(a.DB); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
@@ -82,26 +82,26 @@ func CreateService(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("HX-Refresh", "true")
|
||||
}
|
||||
|
||||
func ViewService(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) ViewService(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
var s db.Service
|
||||
err := DB.QueryRow("SELECT service_id, client_id, name, price, description, duration, created_at FROM services WHERE service_id = ?", id).Scan(&s.ServiceID, &s.ClientID, &s.Name, &s.Price, &s.Description, &s.Duration, &s.CreatedAt)
|
||||
err := a.DB.QueryRow("SELECT service_id, client_id, name, price, description, duration, created_at FROM services WHERE service_id = ?", id).Scan(&s.ServiceID, &s.ClientID, &s.Name, &s.Price, &s.Description, &s.Duration, &s.CreatedAt)
|
||||
if err != nil {
|
||||
http.Error(w, "Service not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html><body><h1>` + s.Name + `</h1><p>Price: ` + strconv.FormatFloat(s.Price, 'f', 2, 64) + `</p><p>Description: ` + s.Description + `</p><p>Duration: ` + s.Duration + `</p><a href="/services">Back</a></body></html>`))
|
||||
}
|
||||
|
||||
func UpdateService(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) UpdateService(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -110,7 +110,7 @@ func UpdateService(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||
price, _ := strconv.ParseFloat(r.FormValue("price"), 64)
|
||||
_, err := DB.Exec("UPDATE services SET client_id=?, name=?, price=?, description=?, duration=? WHERE service_id=?", clientID, r.FormValue("name"), price, r.FormValue("description"), r.FormValue("duration"), id)
|
||||
_, err := a.DB.Exec("UPDATE services SET client_id=?, name=?, price=?, description=?, duration=? WHERE service_id=?", clientID, r.FormValue("name"), price, r.FormValue("description"), r.FormValue("duration"), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
@@ -118,12 +118,30 @@ func UpdateService(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("HX-Refresh", "true")
|
||||
}
|
||||
|
||||
func DeleteService(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := requireAuth(w, r)
|
||||
func (a *App) DeleteService(w http.ResponseWriter, r *http.Request) {
|
||||
_, ok := a.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
DB.Exec("DELETE FROM services WHERE service_id = ?", id)
|
||||
}
|
||||
a.DB.Exec("DELETE FROM services WHERE service_id = ?", id)
|
||||
}
|
||||
|
||||
// --- package-level shims kept for existing tests ---
|
||||
|
||||
func ListServices(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).ListServices(w, r)
|
||||
}
|
||||
func CreateService(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).CreateService(w, r)
|
||||
}
|
||||
func ViewService(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).ViewService(w, r)
|
||||
}
|
||||
func UpdateService(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).UpdateService(w, r)
|
||||
}
|
||||
func DeleteService(w http.ResponseWriter, r *http.Request) {
|
||||
(&App{DB: DB, WAConnector: WAConnector}).DeleteService(w, r)
|
||||
}
|
||||
@@ -5,10 +5,28 @@ import (
|
||||
"time"
|
||||
|
||||
"go-crm/internal/whatsapp"
|
||||
"go-crm/pkg/usecase"
|
||||
)
|
||||
|
||||
// App holds the application dependencies injected at startup.
|
||||
// All handler methods live on *App, eliminating package-level global state.
|
||||
type App struct {
|
||||
DB *sql.DB
|
||||
LeadService *usecase.LeadService
|
||||
WAConnector whatsapp.Connector
|
||||
}
|
||||
|
||||
// NewApp constructs an App with the given database, lead service, and WhatsApp connector.
|
||||
func NewApp(db *sql.DB, leadSvc *usecase.LeadService, wa whatsapp.Connector) *App {
|
||||
return &App{DB: db, LeadService: leadSvc, WAConnector: wa}
|
||||
}
|
||||
|
||||
// WAConnector is a package-level global kept for backward-compat with existing tests.
|
||||
// New code should use App.WAConnector via NewApp.
|
||||
var WAConnector whatsapp.Connector
|
||||
|
||||
// SetupHandlers is kept for backward compatibility with existing tests.
|
||||
// New code should use NewApp directly.
|
||||
func SetupHandlers(db *sql.DB, wa whatsapp.Connector) {
|
||||
DB = db
|
||||
WAConnector = wa
|
||||
@@ -16,4 +34,4 @@ func SetupHandlers(db *sql.DB, wa whatsapp.Connector) {
|
||||
|
||||
func getCurrentTimestamp() int64 {
|
||||
return time.Now().Unix()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go-crm/internal/db"
|
||||
"go-crm/internal/whatsapp"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestListClientsWhatsAppStatusIndicators(t *testing.T) {
|
||||
tmpfile, err := os.CreateTemp("", "test_*.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(tmpfile.Name())
|
||||
tmpfile.Close()
|
||||
|
||||
testDB, err := db.Init(tmpfile.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to init db: %v", err)
|
||||
}
|
||||
defer testDB.Close()
|
||||
|
||||
fakeWA := whatsapp.NewFakeConnector()
|
||||
fakeWA.MarkConnected(1)
|
||||
|
||||
DB = testDB
|
||||
WAConnector = fakeWA
|
||||
|
||||
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||
"[email protected]", "Test Account", string(hashedPassword), time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create account: %v", err)
|
||||
}
|
||||
|
||||
var accountID int64
|
||||
err = testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "[email protected]").Scan(&accountID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get account id: %v", err)
|
||||
}
|
||||
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO clients (account_id, name, phone, whatsapp_number, whatsapp_connected, created_at) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
accountID, "Connected Client", "+5521987654321", "+5521987654321", 1, time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create connected client: %v", err)
|
||||
}
|
||||
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO clients (account_id, name, phone, whatsapp_number, whatsapp_connected, created_at) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
accountID, "Disconnected Client", "+5521987654322", "+5521987654322", 1, time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create disconnected client: %v", err)
|
||||
}
|
||||
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO clients (account_id, name, phone, created_at) VALUES (?, ?, ?, ?)",
|
||||
accountID, "No WhatsApp Client", "+5521987654323", time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create no-wa client: %v", err)
|
||||
}
|
||||
|
||||
sessionID := "test-session-status"
|
||||
expires := time.Now().Add(time.Hour).Unix()
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
|
||||
sessionID, accountID, expires,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create session: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/clients", nil)
|
||||
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
ListClients(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
body := w.Body.String()
|
||||
|
||||
if !strings.Contains(body, "Connected Client") {
|
||||
t.Error("expected to find connected client")
|
||||
}
|
||||
|
||||
if !strings.Contains(body, "Disconnected Client") {
|
||||
t.Error("expected to find disconnected client")
|
||||
}
|
||||
|
||||
if !strings.Contains(body, "No WhatsApp Client") {
|
||||
t.Error("expected to find no-wa client")
|
||||
}
|
||||
|
||||
if !strings.Contains(body, "Connect") {
|
||||
t.Error("expected Connect link for clients without active connection")
|
||||
}
|
||||
|
||||
greenDot := `color:#28a745`
|
||||
if !strings.Contains(body, greenDot) {
|
||||
t.Error("expected green dot for connected client")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go-crm/internal/db"
|
||||
"go-crm/internal/whatsapp"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestViewClientShowsWhatsAppInfo(t *testing.T) {
|
||||
tmpfile, err := os.CreateTemp("", "test_*.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(tmpfile.Name())
|
||||
tmpfile.Close()
|
||||
|
||||
testDB, err := db.Init(tmpfile.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to init db: %v", err)
|
||||
}
|
||||
defer testDB.Close()
|
||||
|
||||
fakeWA := whatsapp.NewFakeConnector()
|
||||
fakeWA.MarkConnected(1)
|
||||
|
||||
DB = testDB
|
||||
WAConnector = fakeWA
|
||||
|
||||
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||
"[email protected]", "Test Account", string(hashedPassword), time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create account: %v", err)
|
||||
}
|
||||
|
||||
var accountID int64
|
||||
err = testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "[email protected]").Scan(&accountID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get account id: %v", err)
|
||||
}
|
||||
|
||||
var clientID int64
|
||||
testDB.QueryRow(
|
||||
"INSERT INTO clients (account_id, name, phone, whatsapp_number, whatsapp_connected, created_at) VALUES (?, ?, ?, ?, ?, ?) RETURNING client_id",
|
||||
accountID, "WA Client", "+5521987654321", "+5521987654321", 1, time.Now().Unix(),
|
||||
).Scan(&clientID)
|
||||
|
||||
sessionID := "test-session-viewclient"
|
||||
expires := time.Now().Add(time.Hour).Unix()
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
|
||||
sessionID, accountID, expires,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create session: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/clients/"+strconv.FormatInt(clientID, 10), nil)
|
||||
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||
rctx := chi.NewRouteContext()
|
||||
rctx.URLParams.Add("id", strconv.FormatInt(clientID, 10))
|
||||
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
ViewClient(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
body := w.Body.String()
|
||||
|
||||
if !strings.Contains(body, "+5521987654321") {
|
||||
t.Error("expected ViewClient to show WhatsApp number")
|
||||
}
|
||||
|
||||
if !strings.Contains(body, "WhatsApp") {
|
||||
t.Error("expected ViewClient to show WhatsApp label")
|
||||
}
|
||||
}
|
||||
|
||||
func TestViewClientShowsNotConnected(t *testing.T) {
|
||||
tmpfile, err := os.CreateTemp("", "test_*.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(tmpfile.Name())
|
||||
tmpfile.Close()
|
||||
|
||||
testDB, err := db.Init(tmpfile.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to init db: %v", err)
|
||||
}
|
||||
defer testDB.Close()
|
||||
|
||||
DB = testDB
|
||||
WAConnector = whatsapp.NewFakeConnector()
|
||||
|
||||
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||
"[email protected]", "Test Account", string(hashedPassword), time.Now().Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create account: %v", err)
|
||||
}
|
||||
|
||||
var accountID int64
|
||||
err = testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "[email protected]").Scan(&accountID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get account id: %v", err)
|
||||
}
|
||||
|
||||
var clientID int64
|
||||
testDB.QueryRow(
|
||||
"INSERT INTO clients (account_id, name, phone, created_at) VALUES (?, ?, ?, ?) RETURNING client_id",
|
||||
accountID, "No WA Client", "+5521987654322", time.Now().Unix(),
|
||||
).Scan(&clientID)
|
||||
|
||||
sessionID := "test-session-viewclient-no-wa"
|
||||
expires := time.Now().Add(time.Hour).Unix()
|
||||
_, err = testDB.Exec(
|
||||
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
|
||||
sessionID, accountID, expires,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create session: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/clients/"+strconv.FormatInt(clientID, 10), nil)
|
||||
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||
rctx := chi.NewRouteContext()
|
||||
rctx.URLParams.Add("id", strconv.FormatInt(clientID, 10))
|
||||
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
ViewClient(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
body := w.Body.String()
|
||||
|
||||
if !strings.Contains(body, "WhatsApp") {
|
||||
t.Error("expected ViewClient to show WhatsApp section even when not connected")
|
||||
}
|
||||
|
||||
if !strings.Contains(body, "Connect") {
|
||||
t.Error("expected ViewClient to show Connect link when not connected")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
// ForceUTF8Middleware forces the browser to interpret HTML as UTF-8 for all responses.
|
||||
func ForceUTF8Middleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Package parser provides message text parsing utilities for the CRM.
|
||||
// It extracts structured lead information from raw WhatsApp message text.
|
||||
package parser
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
// ExtractService scans msg for any keyword in the mapping (case-insensitive,
|
||||
// accent-insensitive) and returns the corresponding service name.
|
||||
// If no keyword matches, it returns "Não especificou".
|
||||
//
|
||||
// mapping is a map[keyword]serviceName loaded from the service_keywords table.
|
||||
func ExtractService(msg string, mapping map[string]string) string {
|
||||
normalized := normalizeText(msg)
|
||||
|
||||
// Sort by keyword length descending so longer phrases match before shorter ones.
|
||||
// We iterate the map which has no order, so we do two passes:
|
||||
// first collect all matches, then pick the longest keyword match.
|
||||
type match struct {
|
||||
keyword string
|
||||
service string
|
||||
}
|
||||
var best match
|
||||
|
||||
for kw, svc := range mapping {
|
||||
normKW := normalizeText(kw)
|
||||
if strings.Contains(normalized, normKW) {
|
||||
if len(kw) > len(best.keyword) {
|
||||
best = match{keyword: kw, service: svc}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if best.service != "" {
|
||||
return best.service
|
||||
}
|
||||
return "Não especificou"
|
||||
}
|
||||
|
||||
// NormalizePhone converts a raw WhatsApp phone string to E.164 format (+countrycode...).
|
||||
// It strips the @s.whatsapp.net suffix, removes non-digit characters, and prepends "+".
|
||||
func NormalizePhone(raw string) string {
|
||||
// Strip WhatsApp JID suffix.
|
||||
if idx := strings.Index(raw, "@"); idx != -1 {
|
||||
raw = raw[:idx]
|
||||
}
|
||||
// Keep only digits.
|
||||
digits := regexp.MustCompile(`\D`).ReplaceAllString(raw, "")
|
||||
if digits == "" {
|
||||
return raw
|
||||
}
|
||||
return "+" + digits
|
||||
}
|
||||
|
||||
// normalizeText lowercases and removes accents from s for fuzzy comparison.
|
||||
func normalizeText(s string) string {
|
||||
// NFD decomposition splits accented characters into base + combining marks.
|
||||
t := norm.NFD.String(strings.ToLower(s))
|
||||
// Remove combining marks (Unicode category Mn).
|
||||
var b strings.Builder
|
||||
for _, r := range t {
|
||||
if unicode.Is(unicode.Mn, r) {
|
||||
continue
|
||||
}
|
||||
b.WriteRune(r)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package parser_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"go-crm/internal/parser"
|
||||
)
|
||||
|
||||
func TestExtractService_KnownKeywords(t *testing.T) {
|
||||
keywords := map[string]string{
|
||||
"head spa": "Head Spa",
|
||||
"head-spa": "Head Spa",
|
||||
"headspa": "Head Spa",
|
||||
"massagem": "Massagem completa",
|
||||
"massagem completa": "Massagem completa",
|
||||
"drenagem": "Drenagem linfatica",
|
||||
"linfática": "Drenagem linfatica",
|
||||
"hydra": "Hydra Boost",
|
||||
"hydra boost": "Hydra Boost",
|
||||
"henna": "Design Henna",
|
||||
"design henna": "Design Henna",
|
||||
"masculino": "Masculino",
|
||||
"masc": "Masculino",
|
||||
}
|
||||
|
||||
mapping := map[string]string{
|
||||
"head spa": "Head Spa",
|
||||
"head-spa": "Head Spa",
|
||||
"headspa": "Head Spa",
|
||||
"massagem": "Massagem completa",
|
||||
"massagem completa": "Massagem completa",
|
||||
"drenagem": "Drenagem linfatica",
|
||||
"linfática": "Drenagem linfatica",
|
||||
"hydra": "Hydra Boost",
|
||||
"hydra boost": "Hydra Boost",
|
||||
"henna": "Design Henna",
|
||||
"design henna": "Design Henna",
|
||||
"masculino": "Masculino",
|
||||
"masc": "Masculino",
|
||||
}
|
||||
|
||||
for kw, expected := range keywords {
|
||||
// Build messages in Portuguese with the keyword embedded in natural phrasing.
|
||||
messages := []string{
|
||||
"Olá, gostaria de agendar um " + kw,
|
||||
"Boa tarde! Quero fazer " + kw + " por favor",
|
||||
"Quanto custa " + kw + "?",
|
||||
kw,
|
||||
}
|
||||
for _, msg := range messages {
|
||||
got := parser.ExtractService(msg, mapping)
|
||||
if got != expected {
|
||||
t.Errorf("message %q with keyword %q: got %q, want %q", msg, kw, got, expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractService_UnknownMessage_ReturnsNaoEspecificou(t *testing.T) {
|
||||
mapping := map[string]string{
|
||||
"massagem": "Massagem completa",
|
||||
}
|
||||
|
||||
messages := []string{
|
||||
"Olá, tudo bem?",
|
||||
"Qual o horário de funcionamento?",
|
||||
"Vocês atendem no sábado?",
|
||||
"",
|
||||
}
|
||||
|
||||
for _, msg := range messages {
|
||||
got := parser.ExtractService(msg, mapping)
|
||||
if got != "Não especificou" {
|
||||
t.Errorf("message %q: got %q, want %q", msg, got, "Não especificou")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractService_CaseInsensitive(t *testing.T) {
|
||||
mapping := map[string]string{
|
||||
"head spa": "Head Spa",
|
||||
"henna": "Design Henna",
|
||||
}
|
||||
|
||||
cases := map[string]string{
|
||||
"Quero HEAD SPA": "Head Spa",
|
||||
"HENNA por favor": "Design Henna",
|
||||
"Head Spa agora": "Head Spa",
|
||||
}
|
||||
|
||||
for msg, expected := range cases {
|
||||
got := parser.ExtractService(msg, mapping)
|
||||
if got != expected {
|
||||
t.Errorf("message %q: got %q, want %q", msg, got, expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizePhone(t *testing.T) {
|
||||
cases := []struct {
|
||||
raw string
|
||||
want string
|
||||
}{
|
||||
{"[email protected]", "+5511999999999"},
|
||||
{"5511999999999", "+5511999999999"},
|
||||
{"+5511999999999", "+5511999999999"},
|
||||
{"55 11 99999-9999", "+5511999999999"},
|
||||
{"11999999999", "+11999999999"},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
got := parser.NormalizePhone(c.raw)
|
||||
if got != c.want {
|
||||
t.Errorf("NormalizePhone(%q) = %q, want %q", c.raw, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,7 @@ func Layout(title, content string) *template.Template {
|
||||
<nav>
|
||||
<ul>
|
||||
<li><a href="/">Home</a></li>
|
||||
<li><a href="/leads">Leads</a></li>
|
||||
<li><a href="/clients">Clients</a></li>
|
||||
<li><a href="/customers">Customers</a></li>
|
||||
<li><a href="/services">Services</a></li>
|
||||
|
||||
@@ -24,6 +24,7 @@ type QRFrame struct {
|
||||
type Contact struct {
|
||||
Phone string
|
||||
Name string
|
||||
Message string // raw text of the first/incoming message
|
||||
FromMe bool
|
||||
Time time.Time
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package whatsapp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"bytes"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPostContactLogsErrorOnFailure(t *testing.T) {
|
||||
// Capture log output.
|
||||
var buf bytes.Buffer
|
||||
log.SetOutput(&buf)
|
||||
defer log.SetOutput(os.Stderr)
|
||||
|
||||
// Create adapter with invalid endpoint (connection refused).
|
||||
adapter := &WhatsmeowAdapter{
|
||||
goEndpoint: "http://localhost:1",
|
||||
internalSecret: "test-secret",
|
||||
}
|
||||
|
||||
contact := Contact{
|
||||
Phone: "5511999999999",
|
||||
Name: "Test",
|
||||
Message: "test message",
|
||||
}
|
||||
|
||||
adapter.postContact(context.Background(), 1, contact, "test-msg-id-123")
|
||||
|
||||
output := buf.String()
|
||||
if !strings.Contains(output, "postContact") {
|
||||
t.Errorf("expected log to contain 'postContact', got: %s", output)
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -239,24 +240,50 @@ func (a *WhatsmeowAdapter) startQRSession(clientID int64) (<-chan QRFrame, error
|
||||
}
|
||||
|
||||
func (a *WhatsmeowAdapter) addMessageHandler(client *whatsmeow.Client, clientID int64) {
|
||||
log.Printf("[Client-%d] Registering message handler", clientID)
|
||||
client.AddEventHandler(func(evt interface{}) {
|
||||
log.Printf("[Client-%d] Event received: %T", clientID, evt)
|
||||
msg, ok := evt.(*events.Message)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if msg.Info.IsFromMe {
|
||||
log.Printf("[Client-%d] Message event: IsFromMe=%v, Sender=%v, Chat=%v", clientID, msg.Info.IsFromMe, msg.Info.Sender, msg.Info.Chat)
|
||||
|
||||
// Skip messages from our own device.
|
||||
// Compare sender JID with device JID (LID messages may have IsFromMe=true incorrectly).
|
||||
if client.Store.ID != nil && msg.Info.Sender.User == client.Store.ID.User {
|
||||
log.Printf("[Client-%d] Skipping message from own device", clientID)
|
||||
return
|
||||
}
|
||||
phone := msg.Info.Sender.String()
|
||||
|
||||
// Prefer phone JID (SenderAlt) when sender is LID.
|
||||
sender := msg.Info.Sender
|
||||
if sender.Server == types.HiddenUserServer && !msg.Info.SenderAlt.IsEmpty() && msg.Info.SenderAlt.Server == types.DefaultUserServer {
|
||||
sender = msg.Info.SenderAlt
|
||||
}
|
||||
phone := sender.String()
|
||||
pushName := msg.Info.PushName
|
||||
|
||||
// Extract text body from the message.
|
||||
var text string
|
||||
if msg.Message != nil {
|
||||
if c := msg.Message.GetConversation(); c != "" {
|
||||
text = c
|
||||
} else if ext := msg.Message.GetExtendedTextMessage(); ext != nil {
|
||||
text = ext.GetText()
|
||||
}
|
||||
}
|
||||
log.Printf("[Client-%d] Incoming msg from %s (pushName=%s): text=%q", clientID, phone, pushName, text)
|
||||
|
||||
if phone != "" {
|
||||
contact := Contact{
|
||||
Phone: phone,
|
||||
Name: pushName,
|
||||
FromMe: false,
|
||||
Time: time.Now(),
|
||||
Phone: phone,
|
||||
Name: pushName,
|
||||
Message: text,
|
||||
FromMe: false,
|
||||
Time: time.Now(),
|
||||
}
|
||||
a.postContact(a.appCtx, clientID, contact)
|
||||
a.postContact(a.appCtx, clientID, contact, msg.Info.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -266,21 +293,35 @@ func (a *WhatsmeowAdapter) syncContacts(client *whatsmeow.Client, clientID int64
|
||||
// Simplified for build - real implementation would use new API
|
||||
}
|
||||
|
||||
func (a *WhatsmeowAdapter) postContact(ctx context.Context, clientID int64, contact Contact) {
|
||||
func (a *WhatsmeowAdapter) postContact(ctx context.Context, clientID int64, contact Contact, messageID string) {
|
||||
payload := map[string]interface{}{
|
||||
"client_id": clientID,
|
||||
"name": contact.Name,
|
||||
"phone": contact.Phone,
|
||||
"client_id": clientID,
|
||||
"name": contact.Name,
|
||||
"phone": contact.Phone,
|
||||
"message": contact.Message,
|
||||
"message_id": messageID,
|
||||
}
|
||||
|
||||
body, _ := json.Marshal(payload)
|
||||
httpBody := bytes.NewReader(body)
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", a.goEndpoint+"/customers", httpBody)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", a.goEndpoint+"/leads/ingest", httpBody)
|
||||
req.Header.Set("Content-Type", "application/json; charset=utf-8")
|
||||
req.Header.Set("X-Internal-Secret", a.internalSecret)
|
||||
|
||||
log.Printf("[Client-%d] postContact payload: %s", clientID, string(body))
|
||||
|
||||
httpClient := &http.Client{Timeout: 10 * time.Second}
|
||||
httpClient.Do(req)
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
log.Printf("postContact failed to ingest lead for client %d: %v", clientID, err)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 400 {
|
||||
log.Printf("postContact ingest failed for client %d: status %d", clientID, resp.StatusCode)
|
||||
} else {
|
||||
log.Printf("[Client-%d] postContact success: status %d", clientID, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *WhatsmeowAdapter) getJIDFromDB(clientID int64) (string, error) {
|
||||
@@ -323,10 +364,25 @@ func (a *WhatsmeowAdapter) saveJIDOnConnect(client *whatsmeow.Client, clientID i
|
||||
if jid == "" {
|
||||
return
|
||||
}
|
||||
phone := strings.Split(jid, "@")[0]
|
||||
_ = a.SaveJID(clientID, jid)
|
||||
_ = a.saveWhatsAppNumber(clientID, phone)
|
||||
_ = a.markConnected(clientID)
|
||||
}
|
||||
|
||||
func (a *WhatsmeowAdapter) saveWhatsAppNumber(clientID int64, phone string) error {
|
||||
a.mu.RLock()
|
||||
db := a.db
|
||||
a.mu.RUnlock()
|
||||
|
||||
if db == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
_, err := db.Exec("UPDATE clients SET whatsapp_number = ? WHERE client_id = ?", phone, clientID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *WhatsmeowAdapter) markConnected(clientID int64) error {
|
||||
a.mu.RLock()
|
||||
db := a.db
|
||||
@@ -402,18 +458,32 @@ func (a *WhatsmeowAdapter) IsConnected(ctx context.Context, clientID int64) (boo
|
||||
if a == nil {
|
||||
return false, fmt.Errorf("adapter not initialized")
|
||||
}
|
||||
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
|
||||
client, ok := a.clients[clientID]
|
||||
if !ok {
|
||||
a.mu.RUnlock()
|
||||
|
||||
if ok && client != nil && client.IsLoggedIn() {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// No client in memory — try to resume from stored JID.
|
||||
jid, err := a.getJIDFromDB(clientID)
|
||||
if err != nil || jid == "" {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if client == nil {
|
||||
return false, nil
|
||||
// Attempt to reconnect silently.
|
||||
if ch, err := a.Connect(ctx, clientID); err == nil {
|
||||
for frame := range ch {
|
||||
if frame.State == StateConnected {
|
||||
return true, nil
|
||||
}
|
||||
if frame.State == StateFailed {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// IsLoggedIn() checks WhatsApp session authentication, not just WebSocket connectivity.
|
||||
return client.IsLoggedIn(), nil
|
||||
return false, nil
|
||||
}
|
||||
+97
-70
@@ -6,10 +6,13 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"go-crm/config"
|
||||
"go-crm/internal/db"
|
||||
"go-crm/internal/handlers"
|
||||
"go-crm/internal/templates"
|
||||
wa "go-crm/internal/whatsapp"
|
||||
"go-crm/pkg/repo"
|
||||
"go-crm/pkg/usecase"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
@@ -17,13 +20,17 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
database, err := db.Init("/workspace/data/go-crm.db")
|
||||
fmt.Println("main: starting db init")
|
||||
database, err := db.Init(config.DatabasePath())
|
||||
fmt.Println("main: db init returned")
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to initialize database: %v", err)
|
||||
}
|
||||
defer database.Close()
|
||||
|
||||
waConnector, err := wa.NewWhatsmeowAdapter("/workspace/data/whatsapp.db", "http://localhost:8080", "internal-secret")
|
||||
fmt.Println("main: initializing WhatsApp adapter")
|
||||
waConnector, err := wa.NewWhatsmeowAdapter(config.WhatsAppStorePath(), config.HTTPServerEndpoint(), config.InternalSecret())
|
||||
fmt.Println("main: WhatsApp adapter init returned")
|
||||
if err != nil {
|
||||
log.Printf("Warning: failed to initialize WhatsApp connector: %v", err)
|
||||
waConnector = nil
|
||||
@@ -31,6 +38,15 @@ func main() {
|
||||
waConnector.SetClientDB(database)
|
||||
}
|
||||
|
||||
// App is the single dependency-injection container.
|
||||
// All handler methods receive DB and WAConnector through it,
|
||||
// eliminating package-level global state.
|
||||
// Build our clean-arch layers for leads
|
||||
leadRepo := repo.NewSQLiteLeadRepository(database)
|
||||
leadSvc := usecase.NewLeadService(leadRepo)
|
||||
app := handlers.NewApp(database, leadSvc, waConnector)
|
||||
|
||||
// Also populate legacy globals so existing tests continue to work.
|
||||
handlers.SetupHandlers(database, waConnector)
|
||||
|
||||
r := chi.NewRouter()
|
||||
@@ -39,60 +55,51 @@ func main() {
|
||||
r.Use(middleware.Recoverer)
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(cors.Handler(cors.Options{
|
||||
AllowedOrigins: []string{"*"},
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"},
|
||||
AllowedHeaders: []string{"Accept", "Content-Type", "X-Internal-Secret", "Origin"},
|
||||
ExposedHeaders: []string{"Content-Length", "Content-Type"},
|
||||
AllowedOrigins: []string{"*"},
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"},
|
||||
AllowedHeaders: []string{"Accept", "Content-Type", "X-Internal-Secret", "Origin"},
|
||||
ExposedHeaders: []string{"Content-Length", "Content-Type"},
|
||||
AllowCredentials: false,
|
||||
MaxAge: 86400,
|
||||
MaxAge: 86400,
|
||||
}))
|
||||
|
||||
templates.Init()
|
||||
|
||||
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
_, err := handlers.GetAccountID(r)
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/auth/login", http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Write([]byte(`<!DOCTYPE html><html><head><title>Dashboard</title></head><body><h1>Welcome to CRM</h1><nav><a href="/clients">Clients</a> | <a href="/customers">Customers</a> | <a href="/services">Services</a> | <a href="/scheduling">Scheduling</a> | <a href="/payments">Payments</a> | <a href="/questions">Questions</a> | <a href="/answers">Answers</a> | <a href="/auth/account">Account</a> | <form method="POST" action="/auth/logout" style="display:inline"><button type="submit">Logout</button></form></nav></body></html>`))
|
||||
})
|
||||
r.Get("/", app.Dashboard)
|
||||
|
||||
r.Route("/auth", func(r chi.Router) {
|
||||
r.Get("/signup", handlers.SignupPage)
|
||||
r.Post("/signup", handlers.Signup)
|
||||
r.Get("/login", handlers.LoginPage)
|
||||
r.Post("/login", handlers.Login)
|
||||
r.Post("/logout", handlers.Logout)
|
||||
r.Get("/account", handlers.AccountPage)
|
||||
r.Post("/account", handlers.UpdateAccount)
|
||||
r.Get("/signup", app.SignupPage)
|
||||
r.Post("/signup", app.Signup)
|
||||
r.Get("/login", app.LoginPage)
|
||||
r.Post("/login", app.Login)
|
||||
r.Post("/logout", app.Logout)
|
||||
r.Get("/account", app.AccountPage)
|
||||
r.Post("/account", app.UpdateAccount)
|
||||
})
|
||||
|
||||
r.Route("/clients", func(r chi.Router) {
|
||||
r.Get("/", handlers.ListClients)
|
||||
r.Post("/", handlers.CreateClient)
|
||||
r.Get("/{id}", handlers.ViewClient)
|
||||
r.Put("/{id}", handlers.UpdateClient)
|
||||
r.Delete("/{id}", handlers.DeleteClient)
|
||||
r.Get("/", app.ListClients)
|
||||
r.Post("/", app.CreateClient)
|
||||
r.Get("/{id}", app.ViewClient)
|
||||
r.Put("/{id}", app.UpdateClient)
|
||||
r.Delete("/{id}", app.DeleteClient)
|
||||
})
|
||||
|
||||
r.Route("/customers", func(r chi.Router) {
|
||||
r.Get("/", handlers.ListCustomers)
|
||||
r.Post("/", handlers.CreateCustomer)
|
||||
r.Get("/{id}", handlers.ViewCustomer)
|
||||
r.Put("/{id}", handlers.UpdateCustomer)
|
||||
r.Delete("/{id}", handlers.DeleteCustomer)
|
||||
r.Get("/", app.ListCustomers)
|
||||
r.Post("/", app.CreateCustomer)
|
||||
r.Get("/{id}", app.ViewCustomer)
|
||||
r.Put("/{id}", app.UpdateCustomer)
|
||||
r.Delete("/{id}", app.DeleteCustomer)
|
||||
})
|
||||
|
||||
r.Get("/debug/cors-test", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"status":"ok","origin":"`+r.Header.Get("Origin")+`"}`))
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Write([]byte(`{"status":"ok","origin":"` + r.Header.Get("Origin") + `"}`))
|
||||
})
|
||||
|
||||
r.Get("/debug/whatsapp", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if waConnector == nil {
|
||||
w.Write([]byte(`{"status":"error","error":"WhatsApp connector not initialized"}`))
|
||||
return
|
||||
@@ -101,7 +108,7 @@ func main() {
|
||||
})
|
||||
|
||||
r.Get("/debug/net-test", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
resp, err := http.Get("https://www.google.com")
|
||||
if err != nil {
|
||||
w.Write([]byte(`{"status":"error","error":` + err.Error() + `}`))
|
||||
@@ -112,53 +119,73 @@ func main() {
|
||||
})
|
||||
|
||||
r.Route("/leads", func(r chi.Router) {
|
||||
r.Get("/", handlers.ListLeads)
|
||||
r.Get("/connect", handlers.LeadsConnectPage)
|
||||
r.Get("/qr", handlers.LeadsQR)
|
||||
r.Put("/{id}", handlers.UpdateLead)
|
||||
r.Delete("/{id}", handlers.DeleteLead)
|
||||
r.Get("/", app.ListLeads)
|
||||
r.Get("/connect", app.LeadsConnectPage)
|
||||
r.Get("/qr", app.LeadsQR)
|
||||
r.Get("/verify/{client_id}", app.VerifyLead)
|
||||
r.Put("/{id}", app.UpdateLead)
|
||||
r.Delete("/{id}", app.DeleteLead)
|
||||
|
||||
// Lead pipeline
|
||||
r.Post("/ingest", app.IngestLead)
|
||||
r.Get("/review", app.LeadReviewQueue)
|
||||
r.Put("/{id}/review", app.ConfirmLeadReview)
|
||||
r.Get("/all", app.LeadAllList)
|
||||
r.Delete("/{id}", app.DeleteLeadNew)
|
||||
|
||||
// Keyword management
|
||||
r.Get("/keywords", app.LeadKeywordsPage)
|
||||
r.Post("/keywords", app.AddServiceKeyword)
|
||||
r.Delete("/keywords/{id}", app.DeleteServiceKeywordHandler)
|
||||
|
||||
// Status management
|
||||
r.Post("/statuses", app.AddLeadStatusHandler)
|
||||
r.Delete("/statuses/{id}", app.DeleteLeadStatusHandler)
|
||||
})
|
||||
|
||||
r.Get("/report", app.MonthlyReport)
|
||||
|
||||
r.Route("/services", func(r chi.Router) {
|
||||
r.Get("/", handlers.ListServices)
|
||||
r.Post("/", handlers.CreateService)
|
||||
r.Get("/{id}", handlers.ViewService)
|
||||
r.Put("/{id}", handlers.UpdateService)
|
||||
r.Delete("/{id}", handlers.DeleteService)
|
||||
r.Get("/", app.ListServices)
|
||||
r.Post("/", app.CreateService)
|
||||
r.Get("/{id}", app.ViewService)
|
||||
r.Put("/{id}", app.UpdateService)
|
||||
r.Delete("/{id}", app.DeleteService)
|
||||
})
|
||||
|
||||
r.Route("/scheduling", func(r chi.Router) {
|
||||
r.Get("/", handlers.ListSchedules)
|
||||
r.Post("/", handlers.CreateSchedule)
|
||||
r.Get("/{id}", handlers.ViewSchedule)
|
||||
r.Put("/{id}", handlers.UpdateSchedule)
|
||||
r.Delete("/{id}", handlers.DeleteSchedule)
|
||||
r.Get("/", app.ListSchedules)
|
||||
r.Post("/", app.CreateSchedule)
|
||||
r.Get("/{id}", app.ViewSchedule)
|
||||
r.Put("/{id}", app.UpdateSchedule)
|
||||
r.Delete("/{id}", app.DeleteSchedule)
|
||||
})
|
||||
|
||||
r.Route("/payments", func(r chi.Router) {
|
||||
r.Get("/", handlers.ListPayments)
|
||||
r.Post("/", handlers.CreatePayment)
|
||||
r.Get("/{id}", handlers.ViewPayment)
|
||||
r.Put("/{id}", handlers.UpdatePayment)
|
||||
r.Delete("/{id}", handlers.DeletePayment)
|
||||
r.Route("/payments", func(r chi.Router) {
|
||||
r.Get("/", app.ListPayments)
|
||||
r.Post("/", app.CreatePayment)
|
||||
r.Get("/{id}", app.ViewPayment)
|
||||
r.Put("/{id}", app.UpdatePayment)
|
||||
r.Delete("/{id}", app.DeletePayment)
|
||||
})
|
||||
|
||||
r.Route("/questions", func(r chi.Router) {
|
||||
r.Get("/", handlers.ListQuestions)
|
||||
r.Post("/", handlers.CreateQuestion)
|
||||
r.Get("/{id}", handlers.ViewQuestion)
|
||||
r.Put("/{id}", handlers.UpdateQuestion)
|
||||
r.Delete("/{id}", handlers.DeleteQuestion)
|
||||
r.Get("/", app.ListQuestions)
|
||||
r.Post("/", app.CreateQuestion)
|
||||
r.Get("/{id}", app.ViewQuestion)
|
||||
r.Put("/{id}", app.UpdateQuestion)
|
||||
r.Delete("/{id}", app.DeleteQuestion)
|
||||
})
|
||||
|
||||
r.Route("/answers", func(r chi.Router) {
|
||||
r.Get("/", handlers.ListAnswers)
|
||||
r.Post("/", handlers.CreateAnswer)
|
||||
r.Get("/{id}", handlers.ViewAnswer)
|
||||
r.Put("/{id}", handlers.UpdateAnswer)
|
||||
r.Delete("/{id}", handlers.DeleteAnswer)
|
||||
r.Get("/", app.ListAnswers)
|
||||
r.Post("/", app.CreateAnswer)
|
||||
r.Get("/{id}", app.ViewAnswer)
|
||||
r.Put("/{id}", app.UpdateAnswer)
|
||||
r.Delete("/{id}", app.DeleteAnswer)
|
||||
})
|
||||
|
||||
fmt.Println("main: ready to serve")
|
||||
fmt.Println("CRM server running on http://localhost:8080")
|
||||
log.Fatal(http.ListenAndServe(":8080", r))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// Package domain defines core business entities and interfaces.
|
||||
package domain
|
||||
|
||||
import "context"
|
||||
|
||||
// Lead represents a customer lead with service interest, status, and payment info.
|
||||
type Lead struct {
|
||||
LeadID int64 `json:"lead_id"`
|
||||
ClientID int64 `json:"client_id"`
|
||||
Name string `json:"name"`
|
||||
PhoneRaw string `json:"phone_raw"`
|
||||
PhoneNormalized string `json:"phone_normalized"`
|
||||
ServiceInterest string `json:"service_interest"`
|
||||
Status string `json:"status"`
|
||||
NeedsReview bool `json:"needs_review"`
|
||||
AppointmentDate string `json:"appointment_date,omitempty"`
|
||||
AppointmentTime string `json:"appointment_time,omitempty"`
|
||||
PaymentStatus string `json:"payment_status"`
|
||||
PaymentAmount float64 `json:"payment_amount,omitempty"`
|
||||
PaymentDate string `json:"payment_date,omitempty"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
LastContactAt int64 `json:"last_contact_at"`
|
||||
}
|
||||
|
||||
// LeadRepository defines persistence operations for leads.
|
||||
type LeadRepository interface {
|
||||
// ListAll retrieves all leads for a client, with pagination.
|
||||
ListAll(ctx context.Context, clientID int64, limit, offset int) ([]Lead, error)
|
||||
// Update saves changes to an existing lead.
|
||||
Update(ctx context.Context, lead Lead) error
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// Package repo provides SQLite implementations of repository interfaces.
|
||||
package repo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"go-crm/pkg/domain"
|
||||
)
|
||||
|
||||
// SQLiteLeadRepository implements domain.LeadRepository using SQLite.
|
||||
type SQLiteLeadRepository struct {
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
// NewSQLiteLeadRepository returns a new SQLiteLeadRepository.
|
||||
func NewSQLiteLeadRepository(db *sql.DB) *SQLiteLeadRepository {
|
||||
return &SQLiteLeadRepository{DB: db}
|
||||
}
|
||||
|
||||
// ListAll retrieves leads for a client with pagination.
|
||||
func (r *SQLiteLeadRepository) ListAll(ctx context.Context, clientID int64, limit, offset int) ([]domain.Lead, error) {
|
||||
query := `SELECT lead_id, client_id, name, phone_raw, phone_normalized,
|
||||
service_interest, status, needs_review,
|
||||
COALESCE(appointment_date,''), COALESCE(appointment_time,''), payment_status,
|
||||
COALESCE(payment_amount,0), COALESCE(payment_date,''), created_at, last_contact_at
|
||||
FROM leads WHERE client_id = ?
|
||||
ORDER BY created_at DESC LIMIT ? OFFSET ?`
|
||||
rows, err := r.DB.QueryContext(ctx, query, clientID, limit, offset)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ListAll query error: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var leads []domain.Lead
|
||||
for rows.Next() {
|
||||
var l domain.Lead
|
||||
var needsReview int
|
||||
if err := rows.Scan(
|
||||
&l.LeadID, &l.ClientID, &l.Name, &l.PhoneRaw, &l.PhoneNormalized,
|
||||
&l.ServiceInterest, &l.Status, &needsReview,
|
||||
&l.AppointmentDate, &l.AppointmentTime, &l.PaymentStatus,
|
||||
&l.PaymentAmount, &l.PaymentDate, &l.CreatedAt, &l.LastContactAt,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("ListAll scan error: %w", err)
|
||||
}
|
||||
l.NeedsReview = needsReview == 1
|
||||
leads = append(leads, l)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("ListAll rows error: %w", err)
|
||||
}
|
||||
return leads, nil
|
||||
}
|
||||
|
||||
// Update saves changes to an existing lead.
|
||||
func (r *SQLiteLeadRepository) Update(ctx context.Context, lead domain.Lead) error {
|
||||
_, err := r.DB.ExecContext(ctx,
|
||||
`UPDATE leads SET name=?, service_interest=?, status=?, needs_review=?,
|
||||
appointment_date=?, appointment_time=?, payment_status=?, payment_amount=?, payment_date=?
|
||||
WHERE lead_id=? AND client_id=?`,
|
||||
lead.Name, lead.ServiceInterest, lead.Status, boolToInt(lead.NeedsReview),
|
||||
lead.AppointmentDate, lead.AppointmentTime, lead.PaymentStatus, lead.PaymentAmount, lead.PaymentDate,
|
||||
lead.LeadID, lead.ClientID,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Update lead error: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func boolToInt(b bool) int {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// Package usecase implements application business logic.
|
||||
package usecase
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go-crm/pkg/domain"
|
||||
)
|
||||
|
||||
// LeadService coordinates lead-related business rules.
|
||||
type LeadService struct {
|
||||
Repo domain.LeadRepository
|
||||
}
|
||||
|
||||
// NewLeadService constructs a LeadService with the given repository.
|
||||
func NewLeadService(repo domain.LeadRepository) *LeadService {
|
||||
return &LeadService{Repo: repo}
|
||||
}
|
||||
|
||||
// ListAllLeads returns paginated leads for a client.
|
||||
func (s *LeadService) ListAllLeads(ctx context.Context, clientID int64, limit, offset int) ([]domain.Lead, error) {
|
||||
return s.Repo.ListAll(ctx, clientID, limit, offset)
|
||||
}
|
||||
|
||||
// UpdateLead applies updates to a lead.
|
||||
func (s *LeadService) UpdateLead(ctx context.Context, lead domain.Lead) error {
|
||||
return s.Repo.Update(ctx, lead)
|
||||
}
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/bash
|
||||
# Run all go-crm tests
|
||||
# Usage: ./run-tests.sh
|
||||
# Or: make test
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$SCRIPT_DIR"
|
||||
go test ./... -v "$@"
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Simple local development runner for go-crm
|
||||
# For junior-friendly setup: no Docker, no file watchers, just plain Go.
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
APP_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
DEV_DATA_DIR="${DEV_DATA_DIR:-$APP_ROOT/.dev-data}"
|
||||
|
||||
mkdir -p "$DEV_DATA_DIR"
|
||||
|
||||
export CRM_DATABASE_PATH="${CRM_DATABASE_PATH:-$DEV_DATA_DIR/go-crm.db}"
|
||||
export CRM_WHATSAPP_STORE_PATH="${CRM_WHATSAPP_STORE_PATH:-$DEV_DATA_DIR/whatsapp.db}"
|
||||
export CRM_HTTP_ENDPOINT="${CRM_HTTP_ENDPOINT:-http://localhost:8080}"
|
||||
export CRM_INTERNAL_SECRET="${CRM_INTERNAL_SECRET:-internal-secret}"
|
||||
|
||||
cd "$APP_ROOT"
|
||||
|
||||
echo "Starting go-crm..."
|
||||
go run main.go
|
||||
Generated
+1228
-485
File diff suppressed because it is too large.
Load diff
@@ -13,10 +13,10 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^12.8.0",
|
||||
"node-cron": "3.0.3",
|
||||
"node-cron": "^4.2.1",
|
||||
"qrcode-terminal": "0.12.0",
|
||||
"sql.js": "1.10.2",
|
||||
"whatsapp-web.js": "1.23.0"
|
||||
"whatsapp-web.js": "^1.34.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/preset-env": "^7.29.2",
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// whatsapp-sync entrypoint stub
|
||||
// This file exists so `npm run start` and `npm run dev` do not fail.
|
||||
// To run the one-off JSONL sync: `npm run sync`
|
||||
// To start the WhatsApp->CRM integration: `node src/whatsapp-leads.js`
|
||||
|
||||
console.log('whatsapp-sync service stub. No long-running logic implemented.');
|
||||
console.log('Use `npm run sync` to fetch messages, or `node src/whatsapp-leads.js` to start WhatsApp->CRM sync.');
|
||||
@@ -0,0 +1,530 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
_ "github.com/glebarez/sqlite"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/store/sqlstore"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
"go.mau.fi/whatsmeow/types/events"
|
||||
waLog "go.mau.fi/whatsmeow/util/log"
|
||||
)
|
||||
|
||||
//go:embed templates/*
|
||||
var templateFS embed.FS
|
||||
|
||||
type ConnectionState string
|
||||
|
||||
const (
|
||||
StateDisconnected ConnectionState = "disconnected"
|
||||
StateConnecting ConnectionState = "connecting"
|
||||
StateWaitingQR ConnectionState = "waiting_qr"
|
||||
StateConnected ConnectionState = "connected"
|
||||
StateFailed ConnectionState = "failed"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
ID int64
|
||||
Phone string
|
||||
Name string
|
||||
Message string
|
||||
MessageID string
|
||||
Timestamp int64
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
Type string `json:"type"`
|
||||
State string `json:"state,omitempty"`
|
||||
QR string `json:"qr,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Message *Message `json:"message,omitempty"`
|
||||
Log string `json:"log,omitempty"`
|
||||
}
|
||||
|
||||
type App struct {
|
||||
db *sql.DB
|
||||
client *whatsmeow.Client
|
||||
container *sqlstore.Container
|
||||
mu sync.RWMutex
|
||||
state ConnectionState
|
||||
currentQR string
|
||||
eventChan chan Event
|
||||
logger *slog.Logger
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
dataDir string
|
||||
}
|
||||
|
||||
func main() {
|
||||
port := os.Getenv("WHATSME_PORT")
|
||||
if port == "" {
|
||||
port = "8080"
|
||||
}
|
||||
dataDir := os.Getenv("WHATSME_DATA_DIR")
|
||||
if dataDir == "" {
|
||||
dataDir = "./whatsme"
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(dataDir, 0755); err != nil {
|
||||
slog.Error("failed to create data dir", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
app := &App{
|
||||
eventChan: make(chan Event, 100),
|
||||
logger: logger,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
dataDir: dataDir,
|
||||
state: StateDisconnected,
|
||||
}
|
||||
|
||||
if err := app.initDB(); err != nil {
|
||||
logger.Error("failed to init DB", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer app.db.Close()
|
||||
|
||||
if err := app.initWhatsApp(); err != nil {
|
||||
logger.Error("failed to init WhatsApp", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
go app.autoResume()
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Get("/", app.handleIndex)
|
||||
r.Get("/events", app.handleEvents)
|
||||
r.Get("/health", app.handleHealth)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: ":" + port,
|
||||
Handler: r,
|
||||
}
|
||||
|
||||
go func() {
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-sig
|
||||
logger.Info("shutting down...")
|
||||
cancel()
|
||||
if app.client != nil {
|
||||
app.client.Disconnect()
|
||||
}
|
||||
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer shutdownCancel()
|
||||
srv.Shutdown(shutdownCtx)
|
||||
}()
|
||||
|
||||
logger.Info("starting", "port", port, "data_dir", dataDir)
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
logger.Error("server error", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) initDB() error {
|
||||
dbPath := filepath.Join(a.dataDir, "messages.db")
|
||||
db, err := sql.Open("sqlite", dbPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open db: %w", err)
|
||||
}
|
||||
if _, err := db.Exec("PRAGMA foreign_keys = ON"); err != nil {
|
||||
return fmt.Errorf("enable foreign keys: %w", err)
|
||||
}
|
||||
schema := `
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
phone TEXT NOT NULL,
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
message TEXT NOT NULL DEFAULT '',
|
||||
message_id TEXT NOT NULL,
|
||||
timestamp INTEGER NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_message_id ON messages(message_id);
|
||||
`
|
||||
if _, err := db.Exec(schema); err != nil {
|
||||
return fmt.Errorf("exec schema: %w", err)
|
||||
}
|
||||
a.db = db
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) initWhatsApp() error {
|
||||
sessionPath := filepath.Join(a.dataDir, "session.db")
|
||||
db, err := sql.Open("sqlite", sessionPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open session db: %w", err)
|
||||
}
|
||||
if _, err := db.Exec("PRAGMA foreign_keys = ON"); err != nil {
|
||||
return fmt.Errorf("enable foreign keys: %w", err)
|
||||
}
|
||||
a.container = sqlstore.NewWithDB(db, "sqlite", waLog.Stdout("SQL", "DEBUG", true))
|
||||
if err := a.container.Upgrade(a.ctx); err != nil {
|
||||
return fmt.Errorf("upgrade session db: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) autoResume() {
|
||||
a.mu.Lock()
|
||||
stores, err := a.container.GetAllDevices(a.ctx)
|
||||
a.mu.Unlock()
|
||||
if err != nil {
|
||||
a.logger.Error("failed to get stores", "error", err)
|
||||
return
|
||||
}
|
||||
if len(stores) == 0 {
|
||||
a.logger.Info("no stored session, starting QR flow")
|
||||
a.startQRFlow()
|
||||
return
|
||||
}
|
||||
a.logger.Info("found stored session, resuming")
|
||||
a.startQRFlow()
|
||||
}
|
||||
|
||||
func (a *App) startQRFlow() {
|
||||
device := a.container.NewDevice()
|
||||
client := whatsmeow.NewClient(device, waLog.Stdout("Client", "DEBUG", true))
|
||||
a.mu.Lock()
|
||||
a.client = client
|
||||
a.state = StateWaitingQR
|
||||
a.mu.Unlock()
|
||||
|
||||
qrChan, err := client.GetQRChannel(a.ctx)
|
||||
if err != nil {
|
||||
a.logger.Error("failed to get QR channel", "error", err)
|
||||
a.setState(StateFailed, "failed to get QR channel")
|
||||
return
|
||||
}
|
||||
|
||||
if err := client.Connect(); err != nil {
|
||||
a.logger.Error("failed to connect", "error", err)
|
||||
a.setState(StateFailed, "connection failed")
|
||||
return
|
||||
}
|
||||
|
||||
a.addMessageHandler(client)
|
||||
|
||||
go func() {
|
||||
for evt := range qrChan {
|
||||
switch evt.Event {
|
||||
case whatsmeow.QRChannelSuccess.Event:
|
||||
a.logger.Info("WhatsApp connected successfully")
|
||||
a.setState(StateConnected, "")
|
||||
return
|
||||
case whatsmeow.QRChannelEventError:
|
||||
a.logger.Error("QR error", "error", evt.Error)
|
||||
a.setState(StateFailed, evt.Error.Error())
|
||||
return
|
||||
case whatsmeow.QRChannelTimeout.Event:
|
||||
a.logger.Info("QR timeout, restarting")
|
||||
a.setState(StateDisconnected, "QR timed out")
|
||||
go a.startQRFlow()
|
||||
return
|
||||
default:
|
||||
if evt.Code != "" {
|
||||
a.mu.Lock()
|
||||
a.currentQR = evt.Code
|
||||
a.state = StateWaitingQR
|
||||
a.mu.Unlock()
|
||||
a.broadcastQR(evt.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (a *App) setState(state ConnectionState, errMsg string) {
|
||||
a.mu.Lock()
|
||||
a.state = state
|
||||
if errMsg != "" {
|
||||
a.logger.Info("state changed", "state", state, "error", errMsg)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
a.eventChan <- Event{
|
||||
Type: "state",
|
||||
State: string(state),
|
||||
Error: errMsg,
|
||||
}
|
||||
a.eventChan <- Event{
|
||||
Type: "log",
|
||||
Log: fmt.Sprintf("[%s] %s", time.Now().Format("15:04:05"), state),
|
||||
}
|
||||
|
||||
if state == StateDisconnected {
|
||||
go a.startQRFlow()
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) broadcastQR(code string) {
|
||||
a.eventChan <- Event{
|
||||
Type: "state",
|
||||
State: string(StateWaitingQR),
|
||||
QR: code,
|
||||
}
|
||||
a.eventChan <- Event{
|
||||
Type: "log",
|
||||
Log: fmt.Sprintf("[%s] QR code generated", time.Now().Format("15:04:05")),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) addMessageHandler(client *whatsmeow.Client) {
|
||||
client.AddEventHandler(func(raw interface{}) {
|
||||
evt, ok := raw.(*events.Message)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
a.logger.Debug("raw event",
|
||||
"type", fmt.Sprintf("%T", raw),
|
||||
"is_from_me", evt.Info.IsFromMe,
|
||||
"sender", evt.Info.Sender.String(),
|
||||
"chat", evt.Info.Chat.String(),
|
||||
"message_id", evt.Info.ID,
|
||||
"timestamp", evt.Info.Timestamp,
|
||||
"push_name", evt.Info.PushName,
|
||||
"sender_server", evt.Info.Sender.Server,
|
||||
"chat_server", evt.Info.Chat.Server,
|
||||
"message_type", fmt.Sprintf("%T", evt.Message),
|
||||
)
|
||||
|
||||
if evt.Info.IsFromMe {
|
||||
a.logger.Info("skipping own message", "message_id", evt.Info.ID)
|
||||
return
|
||||
}
|
||||
|
||||
if evt.Info.Chat.Server == types.GroupServer {
|
||||
a.logger.Info("skipping group message", "chat", evt.Info.Chat.String())
|
||||
return
|
||||
}
|
||||
|
||||
if evt.Info.ID == "" {
|
||||
a.logger.Info("skipping message with empty ID")
|
||||
return
|
||||
}
|
||||
|
||||
sender := evt.Info.Sender
|
||||
phone := sender.User
|
||||
if phone == "" {
|
||||
phone = sender.String()
|
||||
}
|
||||
if !strings.HasPrefix(phone, "+") {
|
||||
phone = "+" + phone
|
||||
}
|
||||
if strings.HasSuffix(phone, "@s.whatsapp.net") {
|
||||
phone = strings.TrimSuffix(phone, "@s.whatsapp.net")
|
||||
phone = "+" + strings.TrimPrefix(phone, "+")
|
||||
}
|
||||
|
||||
pushName := evt.Info.PushName
|
||||
|
||||
var text string
|
||||
if evt.Message != nil {
|
||||
if c := evt.Message.GetConversation(); c != "" {
|
||||
text = c
|
||||
} else if ext := evt.Message.GetExtendedTextMessage(); ext != nil {
|
||||
text = ext.GetText()
|
||||
}
|
||||
}
|
||||
|
||||
if text == "" {
|
||||
a.logger.Info("skipping non-text message", "message_id", evt.Info.ID)
|
||||
return
|
||||
}
|
||||
|
||||
ts := evt.Info.Timestamp.Unix()
|
||||
if ts == 0 {
|
||||
ts = time.Now().Unix()
|
||||
}
|
||||
|
||||
msg := &Message{
|
||||
Phone: phone,
|
||||
Name: pushName,
|
||||
Message: text,
|
||||
MessageID: evt.Info.ID,
|
||||
Timestamp: ts,
|
||||
}
|
||||
|
||||
if err := a.saveMessage(msg); err != nil {
|
||||
a.logger.Error("failed to save message", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
a.logger.Info("message saved",
|
||||
"phone", phone,
|
||||
"name", pushName,
|
||||
"message", text,
|
||||
"message_id", evt.Info.ID,
|
||||
)
|
||||
|
||||
output := map[string]interface{}{
|
||||
"phone": phone,
|
||||
"name": pushName,
|
||||
"message": text,
|
||||
"message_id": evt.Info.ID,
|
||||
"timestamp": ts,
|
||||
}
|
||||
if b, err := json.Marshal(output); err == nil {
|
||||
fmt.Println(string(b))
|
||||
}
|
||||
|
||||
a.eventChan <- Event{
|
||||
Type: "message",
|
||||
Message: msg,
|
||||
}
|
||||
a.eventChan <- Event{
|
||||
Type: "log",
|
||||
Log: fmt.Sprintf("[%s] MSG from %s (%s): %s", time.Now().Format("15:04:05"), phone, pushName, text),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) saveMessage(msg *Message) error {
|
||||
_, err := a.db.Exec(
|
||||
`INSERT OR IGNORE INTO messages (phone, name, message, message_id, timestamp) VALUES (?, ?, ?, ?, ?)`,
|
||||
msg.Phone, msg.Name, msg.Message, msg.MessageID, msg.Timestamp,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) getMessages() ([]Message, error) {
|
||||
rows, err := a.db.Query(
|
||||
`SELECT id, phone, name, message, message_id, timestamp FROM messages ORDER BY timestamp DESC LIMIT 100`,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var msgs []Message
|
||||
for rows.Next() {
|
||||
var m Message
|
||||
if err := rows.Scan(&m.ID, &m.Phone, &m.Name, &m.Message, &m.MessageID, &m.Timestamp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
func (a *App) handleIndex(w http.ResponseWriter, r *http.Request) {
|
||||
a.mu.RLock()
|
||||
state := a.state
|
||||
currentQR := a.currentQR
|
||||
a.mu.RUnlock()
|
||||
|
||||
msgs, err := a.getMessages()
|
||||
if err != nil {
|
||||
a.logger.Error("failed to get messages", "error", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
tmpl, err := template.ParseFS(templateFS, "templates/index.gohtml")
|
||||
if err != nil {
|
||||
a.logger.Error("failed to parse template", "error", err)
|
||||
http.Error(w, "template error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
data := struct {
|
||||
State string
|
||||
QR string
|
||||
Messages []Message
|
||||
}{
|
||||
State: string(state),
|
||||
QR: currentQR,
|
||||
Messages: msgs,
|
||||
}
|
||||
|
||||
if err := tmpl.Execute(w, data); err != nil {
|
||||
a.logger.Error("failed to render template", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) handleEvents(w http.ResponseWriter, r *http.Request) {
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming not supported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
|
||||
a.mu.RLock()
|
||||
state := a.state
|
||||
currentQR := a.currentQR
|
||||
a.mu.RUnlock()
|
||||
|
||||
if state == StateWaitingQR && currentQR != "" {
|
||||
fmt.Fprintf(w, "event: state\ndata: {\"type\":\"state\",\"state\":\"%s\",\"qr\":\"%s\"}\n\n", state, escapeJSON(currentQR))
|
||||
flusher.Flush()
|
||||
} else {
|
||||
fmt.Fprintf(w, "event: state\ndata: {\"type\":\"state\",\"state\":\"%s\"}\n\n", state)
|
||||
flusher.Flush()
|
||||
}
|
||||
|
||||
for evt := range a.eventChan {
|
||||
switch evt.Type {
|
||||
case "state":
|
||||
if evt.QR != "" {
|
||||
fmt.Fprintf(w, "event: state\ndata: {\"type\":\"state\",\"state\":\"%s\",\"qr\":\"%s\",\"error\":\"%s\"}\n\n", evt.State, escapeJSON(evt.QR), evt.Error)
|
||||
} else {
|
||||
fmt.Fprintf(w, "event: state\ndata: {\"type\":\"state\",\"state\":\"%s\",\"error\":\"%s\"}\n\n", evt.State, evt.Error)
|
||||
}
|
||||
case "message":
|
||||
if evt.Message != nil {
|
||||
msgJSON, _ := json.Marshal(evt.Message)
|
||||
fmt.Fprintf(w, "event: message\ndata: {\"type\":\"message\",\"message\":%s}\n\n", msgJSON)
|
||||
}
|
||||
case "log":
|
||||
fmt.Fprintf(w, "event: log\ndata: {\"type\":\"log\",\"log\":\"%s\"}\n\n", escapeJSON(evt.Log))
|
||||
}
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
a.mu.RLock()
|
||||
state := a.state
|
||||
a.mu.RUnlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"status": "ok",
|
||||
"connected": state == StateConnected,
|
||||
"state": state,
|
||||
})
|
||||
}
|
||||
|
||||
func escapeJSON(s string) string {
|
||||
s = strings.ReplaceAll(s, "\n", "\\n")
|
||||
s = strings.ReplaceAll(s, "\r", "\\r")
|
||||
s = strings.ReplaceAll(s, "\t", "\\t")
|
||||
s = strings.ReplaceAll(s, `"`, `\"`)
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build ignore
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"github.com/mdp/qrterminal/v3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
println("usage: go run qr_render.go <code>")
|
||||
os.Exit(1)
|
||||
}
|
||||
config := qrterminal.Config{
|
||||
Level: qrterminal.M,
|
||||
Writer: os.Stdout,
|
||||
BlackChar: qrterminal.BLACK,
|
||||
WhiteChar: qrterminal.WHITE,
|
||||
QuietZone: 1,
|
||||
}
|
||||
qrterminal.GenerateWithConfig(os.Args[1], config)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build ignore
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"github.com/mdp/qrterminal/v3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
println("usage: go run qr_render2.go <code>")
|
||||
os.Exit(1)
|
||||
}
|
||||
config := qrterminal.Config{
|
||||
Level: qrterminal.M,
|
||||
Writer: os.Stdout,
|
||||
BlackChar: "##",
|
||||
WhiteChar: " ",
|
||||
QuietZone: 1,
|
||||
}
|
||||
qrterminal.GenerateWithConfig(os.Args[1], config)
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>whatsme</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
|
||||
<script src="https://unpkg.com/[email protected]"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/qrcode.min.js"></script>
|
||||
<style>
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
html { font-size: 14px; }
|
||||
body {
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
background: #0a0a0a;
|
||||
color: #a0a0a0;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
header {
|
||||
border-bottom: 1px solid #1a1a1a;
|
||||
padding: 0.75rem 1.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
header h1 {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 700;
|
||||
color: #e0e0e0;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
.status-badge {
|
||||
font-size: 0.75rem;
|
||||
padding: 0.2rem 0.6rem;
|
||||
border: 1px solid;
|
||||
border-radius: 2px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.1em;
|
||||
}
|
||||
.status-waiting_qr { color: #d4a017; border-color: #d4a017; }
|
||||
.status-connected { color: #4ade80; border-color: #4ade80; }
|
||||
.status-disconnected { color: #f87171; border-color: #f87171; }
|
||||
.status-failed { color: #f87171; border-color: #f87171; }
|
||||
.status-connecting { color: #60a5fa; border-color: #60a5fa; }
|
||||
main {
|
||||
flex: 1;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
grid-template-rows: auto 1fr;
|
||||
gap: 1px;
|
||||
background: #1a1a1a;
|
||||
}
|
||||
.panel {
|
||||
background: #0a0a0a;
|
||||
padding: 1rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
.panel-header {
|
||||
font-size: 0.7rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.15em;
|
||||
color: #505050;
|
||||
margin-bottom: 0.75rem;
|
||||
padding-bottom: 0.5rem;
|
||||
border-bottom: 1px solid #1a1a1a;
|
||||
}
|
||||
#qr-panel { grid-column: 1; grid-row: 1; }
|
||||
#messages-panel { grid-column: 1; grid-row: 2; }
|
||||
#log-panel { grid-column: 2; grid-row: 1 / span 2; }
|
||||
#qr-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
background: #111;
|
||||
padding: 1rem;
|
||||
border: 1px solid #1a1a1a;
|
||||
}
|
||||
#qr-container canvas {
|
||||
image-rendering: pixelated;
|
||||
border: 4px solid #e0e0e0;
|
||||
}
|
||||
#messages-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
max-height: calc(100vh - 280px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
.message {
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-left: 2px solid #2a2a2a;
|
||||
background: #0d0d0d;
|
||||
}
|
||||
.message:hover { border-left-color: #d4a017; }
|
||||
.message-phone { color: #d4a017; font-size: 0.8rem; }
|
||||
.message-name { color: #606060; font-size: 0.7rem; margin-left: 0.5rem; }
|
||||
.message-text { color: #c0c0c0; margin-top: 0.25rem; font-size: 0.85rem; }
|
||||
.message-time { color: #404040; font-size: 0.65rem; margin-top: 0.25rem; }
|
||||
#log-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
max-height: calc(100vh - 120px);
|
||||
overflow-y: auto;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.log-entry { color: #505050; }
|
||||
.log-entry:last-child { color: #a0a0a0; }
|
||||
.prompt { color: #4ade80; }
|
||||
.prompt::before { content: "$ "; }
|
||||
.empty-state {
|
||||
color: #303030;
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>whatsme</h1>
|
||||
<span class="status-badge status-{{.State}}">{{.State}}</span>
|
||||
</header>
|
||||
<main>
|
||||
<div class="panel" id="qr-panel">
|
||||
<div class="panel-header">QR Code</div>
|
||||
{{if eq .State "waiting_qr"}}
|
||||
{{if .QR}}
|
||||
<div id="qr-container"></div>
|
||||
<input type="hidden" id="qr-code" value="{{.QR}}">
|
||||
{{else}}
|
||||
<div class="empty-state">generating qr code...</div>
|
||||
{{end}}
|
||||
{{else if eq .State "connected"}}
|
||||
<div class="empty-state"><span class="prompt">device connected</span></div>
|
||||
{{else if eq .State "disconnected"}}
|
||||
<div class="empty-state"><span class="prompt">reconnecting...</span></div>
|
||||
{{else if eq .State "failed"}}
|
||||
<div class="empty-state"><span class="prompt">connection failed</span></div>
|
||||
{{else}}
|
||||
<div class="empty-state"><span class="prompt">waiting for connection...</span></div>
|
||||
{{end}}
|
||||
</div>
|
||||
<div class="panel" id="messages-panel">
|
||||
<div class="panel-header">Messages</div>
|
||||
<div id="messages-list">
|
||||
{{if .Messages}}
|
||||
{{range .Messages}}
|
||||
<div class="message">
|
||||
<span class="message-phone">{{.Phone}}</span>
|
||||
<span class="message-name">{{.Name}}</span>
|
||||
<div class="message-text">{{.Message}}</div>
|
||||
<div class="message-time">{{.Timestamp}}</div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{else}}
|
||||
<div class="empty-state">no messages yet</div>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel" id="log-panel">
|
||||
<div class="panel-header">Activity Log</div>
|
||||
<div id="log-list">
|
||||
<div class="log-entry"><span class="prompt">whatsme started</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
const qrContainer = document.getElementById('qr-container');
|
||||
const qrCodeInput = document.getElementById('qr-code');
|
||||
|
||||
function renderQR(code) {
|
||||
if (!qrContainer) return;
|
||||
qrContainer.innerHTML = '';
|
||||
QRCode.toCanvas(qrContainer, code, {
|
||||
width: 256,
|
||||
margin: 2,
|
||||
color: { dark: '#e0e0e0', light: '#0a0a0a' }
|
||||
}, function (err) {
|
||||
if (err) console.error(err);
|
||||
});
|
||||
}
|
||||
|
||||
if (qrCodeInput && qrCodeInput.value) {
|
||||
renderQR(qrCodeInput.value);
|
||||
}
|
||||
|
||||
const evtSource = new EventSource('/events');
|
||||
const messagesList = document.getElementById('messages-list');
|
||||
const logList = document.getElementById('log-list');
|
||||
const statusBadge = document.querySelector('.status-badge');
|
||||
|
||||
evtSource.addEventListener('state', (e) => {
|
||||
const data = JSON.parse(e.data);
|
||||
if (data.qr) {
|
||||
renderQR(data.qr);
|
||||
}
|
||||
if (statusBadge) {
|
||||
statusBadge.textContent = data.state;
|
||||
statusBadge.className = 'status-badge status-' + data.state;
|
||||
}
|
||||
});
|
||||
|
||||
evtSource.addEventListener('message', (e) => {
|
||||
const data = JSON.parse(e.data);
|
||||
const msg = data.message;
|
||||
const emptyState = messagesList.querySelector('.empty-state');
|
||||
if (emptyState) emptyState.remove();
|
||||
|
||||
const div = document.createElement('div');
|
||||
div.className = 'message';
|
||||
div.innerHTML = `
|
||||
<span class="message-phone">${msg.Phone}</span>
|
||||
<span class="message-name">${msg.Name}</span>
|
||||
<div class="message-text">${msg.Message}</div>
|
||||
<div class="message-time">${new Date(msg.Timestamp * 1000).toLocaleTimeString()}</div>
|
||||
`;
|
||||
messagesList.insertBefore(div, messagesList.firstChild);
|
||||
});
|
||||
|
||||
evtSource.addEventListener('log', (e) => {
|
||||
const data = JSON.parse(e.data);
|
||||
const div = document.createElement('div');
|
||||
div.className = 'log-entry';
|
||||
div.innerHTML = `<span class="prompt">${data.log}</span>`;
|
||||
logList.appendChild(div);
|
||||
logList.scrollTop = logList.scrollHeight;
|
||||
});
|
||||
|
||||
evtSource.onerror = () => {
|
||||
setTimeout(() => {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'log-entry';
|
||||
div.innerHTML = `<span class="prompt">[sse reconnecting...]</span>`;
|
||||
logList.appendChild(div);
|
||||
}, 100);
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,44 @@
|
||||
module whatsme
|
||||
|
||||
go 1.26.2
|
||||
|
||||
require (
|
||||
github.com/glebarez/sqlite v1.11.0
|
||||
github.com/go-chi/chi/v5 v5.2.5
|
||||
github.com/mdp/qrterminal/v3 v3.2.1
|
||||
go.mau.fi/whatsmeow v0.0.0-20260506122147-6a7198d94d26
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
github.com/beeper/argo-go v1.1.2 // indirect
|
||||
github.com/coder/websocket v1.8.14 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/elliotchance/orderedmap/v3 v3.1.0 // indirect
|
||||
github.com/glebarez/go-sqlite v1.21.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/rs/zerolog v1.35.0 // indirect
|
||||
github.com/vektah/gqlparser/v2 v2.5.27 // indirect
|
||||
go.mau.fi/libsignal v0.2.1 // indirect
|
||||
go.mau.fi/util v0.9.8 // indirect
|
||||
golang.org/x/crypto v0.50.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
|
||||
golang.org/x/net v0.53.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.43.0 // indirect
|
||||
golang.org/x/term v0.42.0 // indirect
|
||||
golang.org/x/text v0.36.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gorm.io/gorm v1.25.7 // indirect
|
||||
modernc.org/libc v1.22.5 // indirect
|
||||
modernc.org/mathutil v1.5.0 // indirect
|
||||
modernc.org/memory v1.5.0 // indirect
|
||||
modernc.org/sqlite v1.23.1 // indirect
|
||||
rsc.io/qr v0.2.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,94 @@
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
|
||||
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
|
||||
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
|
||||
github.com/beeper/argo-go v1.1.2 h1:UQI2G8F+NLfGTOmTUI0254pGKx/HUU/etbUGTJv91Fs=
|
||||
github.com/beeper/argo-go v1.1.2/go.mod h1:M+LJAnyowKVQ6Rdj6XYGEn+qcVFkb3R/MUpqkGR0hM4=
|
||||
github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=
|
||||
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/elliotchance/orderedmap/v3 v3.1.0 h1:j4DJ5ObEmMBt/lcwIecKcoRxIQUEnw0L804lXYDt/pg=
|
||||
github.com/elliotchance/orderedmap/v3 v3.1.0/go.mod h1:G+Hc2RwaZvJMcS4JpGCOyViCnGeKf0bTYCGTO4uhjSo=
|
||||
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
|
||||
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
|
||||
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
|
||||
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
|
||||
github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
|
||||
github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.42 h1:MigqEP4ZmHw3aIdIT7T+9TLa90Z6smwcthx+Azv4Cgo=
|
||||
github.com/mattn/go-sqlite3 v1.14.42/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ=
|
||||
github.com/mdp/qrterminal/v3 v3.2.1 h1:6+yQjiiOsSuXT5n9/m60E54vdgFsw0zhADHhHLrFet4=
|
||||
github.com/mdp/qrterminal/v3 v3.2.1/go.mod h1:jOTmXvnBsMy5xqLniO0R++Jmjs2sTm9dFSuQ5kpz/SU=
|
||||
github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81 h1:WDsQxOJDy0N1VRAjXLpi8sCEZRSGarLWQevDxpTBRrM=
|
||||
github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rs/zerolog v1.35.0 h1:VD0ykx7HMiMJytqINBsKcbLS+BJ4WYjz+05us+LRTdI=
|
||||
github.com/rs/zerolog v1.35.0/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw=
|
||||
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
|
||||
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/vektah/gqlparser/v2 v2.5.27 h1:RHPD3JOplpk5mP5JGX8RKZkt2/Vwj/PZv0HxTdwFp0s=
|
||||
github.com/vektah/gqlparser/v2 v2.5.27/go.mod h1:D1/VCZtV3LPnQrcPBeR/q5jkSQIPti0uYCP/RI0gIeo=
|
||||
go.mau.fi/libsignal v0.2.1 h1:vRZG4EzTn70XY6Oh/pVKrQGuMHBkAWlGRC22/85m9L0=
|
||||
go.mau.fi/libsignal v0.2.1/go.mod h1:iVvjrHyfQqWajOUaMEsIfo3IqgVMrhWcPiiEzk7NgoU=
|
||||
go.mau.fi/util v0.9.8 h1:+/jf8eM2dAT2wx9UidmaneH28r/CSCKCniCyby1qWz8=
|
||||
go.mau.fi/util v0.9.8/go.mod h1:up/5mbzH2M1pSBNXqRxODn8dg/hEKbLJu92W4/SNAX0=
|
||||
go.mau.fi/whatsmeow v0.0.0-20260506122147-6a7198d94d26 h1:DyFksXWn7z/NN+TNJ0DomV1/drWjkyiVuJ6RIiy/bo4=
|
||||
go.mau.fi/whatsmeow v0.0.0-20260506122147-6a7198d94d26/go.mod h1:ijfkzOXauA/Vz/htXEMfOAJSUgglribW5oQeYC9tSSg=
|
||||
golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
|
||||
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM=
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80=
|
||||
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
|
||||
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY=
|
||||
golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY=
|
||||
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
|
||||
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/gorm v1.25.7 h1:VsD6acwRjz2zFxGO50gPO6AkNs7KKnvfzUjHQhZDz/A=
|
||||
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
|
||||
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
|
||||
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
|
||||
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
|
||||
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
|
||||
modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM=
|
||||
modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=
|
||||
rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY=
|
||||
rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs=
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 30 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
@@ -0,0 +1,36 @@
|
||||
---
|
||||
name: backend-driven-ui
|
||||
description: Create distinctive, production-grade frontend interfaces using Golang and Hypermedia (HTMX/Templ). Use this skill to build reactive web components and pages that prioritize performance and maintainability without the complexity of modern JavaScript frameworks.
|
||||
---
|
||||
|
||||
This skill guides the creation of high-end, "vibe-coded" interfaces using a **Golang-centric stack**. It avoids the maintenance burden of React/JS frameworks by leveraging **HTMX** and **Templ**, focusing on server-side logic that delivers rich, interactive client experiences.
|
||||
|
||||
## Design Thinking & "Vibe Coding"
|
||||
|
||||
Before coding, commit to a BOLD aesthetic direction that feels "hand-crafted" rather than "framework-default":
|
||||
- **Hypermedia First**: Architecture relies on HTML fragments. Every interaction is a server-side transition, making the app feel incredibly fast and robust.
|
||||
- **Tone**: Since we are avoiding the "React look," lean into distinctive styles: **High-Tech Industrial**, **Neo-Brutalist**, **Swiss International**, or **Terminal-Core**.
|
||||
- **The "Vibe"**: Aim for the "vibe coding" energy—fast feedback loops, visible data flowing through the terminal, and interfaces that feel like specialized tools rather than generic SaaS dashboards.
|
||||
|
||||
## Frontend Aesthetics Guidelines
|
||||
|
||||
Focus on:
|
||||
- **Typography**: Use characterful fonts that reflect the precision of Go. Lean towards high-quality Monospace (e.g., JetBrains Mono, Berkeley Graphics) for a "tooling" feel, or sophisticated Serifs paired with tight Grotesks for an editorial look.
|
||||
- **Color & Theme**: Use high-contrast themes. Since this is built with **Tailwind CSS**, use specific color scales (e.g., Zinc, Slate, or custom olive/amber palettes) to avoid the "Tailwind default" blue.
|
||||
- **Motion (CSS-Only)**: Prioritize CSS transitions and HTMX swapping animations (`htmx-settling`, `htmx-requesting`). Use staggered reveals and smooth opacity fades to mask the server-side round trip, making it feel "instant."
|
||||
- **Interaction**: Use **HTMX attributes** (`hx-get`, `hx-post`, `hx-target`) to create "Active Search," "Infinite Scroll," and "Inline Editing" patterns that surprise users who expect a heavy JS bundle.
|
||||
|
||||
## Technical Implementation (The Go Stack)
|
||||
|
||||
- **Templ over HTML**: All components must be written in `.templ` files. This ensures type safety and allows you to pass Go structs directly into your UI components.
|
||||
- **HTMX over JavaScript**: Replace `useState` and `useEffect` with `hx-trigger` and `hx-swap`. Maintain application state in the Go backend or the URL, not in a complex client-side store.
|
||||
- **Tailwind for Styling**: Use utility classes to keep styles local to the HTML. Avoid external CSS files to maintain the "Locality of Behavior" principle.
|
||||
- **Zero-JS Interactivity**: If client-side logic is strictly necessary (modals, toggles), use **Alpine.js** for its minimal footprint, keeping the code readable within the HTML.
|
||||
|
||||
## What to Avoid
|
||||
- **No Heavy Frameworks**: Strictly avoid React, Vue, or Angular.
|
||||
- **No JS "Glue Code"**: Avoid writing custom vanilla JavaScript for things HTMX can handle natively.
|
||||
- **No "AI Slop" Aesthetics**: Avoid the "Inter font + purple gradient + rounded card" combo.
|
||||
- **No JSON APIs for the UI**: Do not build internal JSON endpoints for your own frontend; return HTML fragments instead.
|
||||
|
||||
**IMPORTANT**: The beauty of this approach lies in its **mechanical elegance**. The code should be as clean and performant as the Go binary itself. Show that a "Vibe" can be achieved through clever hypermedia patterns and rock-solid backend engineering.
|
||||
Reference in new issue
Block a user