Compare commits
16
Commits
main
...
744868caa1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
744868caa1 | ||
|
|
57920d45d6 | ||
|
|
57e6e5a6fd | ||
|
|
8833e38b80 | ||
|
|
31247a63f6 | ||
|
|
ee6673265f | ||
|
|
fcaec5ea46 | ||
|
|
f8135d0e1b | ||
|
|
5b8107c169 | ||
|
|
31039ea4af | ||
|
|
000e7b5104 | ||
|
|
0e601a254e | ||
|
|
30ccdab8af | ||
|
|
299de83f2f | ||
|
|
32e5eb8906 | ||
|
|
e8bb767884 |
No files matched your search
+35
@@ -1,3 +1,6 @@
|
|||||||
|
# Plans
|
||||||
|
plans/
|
||||||
|
|
||||||
# Byte-compiled / cache files
|
# Byte-compiled / cache files
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
@@ -47,3 +50,35 @@ Thumbs.db
|
|||||||
|
|
||||||
|
|
||||||
.opencode-sandbox/.env
|
.opencode-sandbox/.env
|
||||||
|
|
||||||
|
# Go CRM data
|
||||||
|
data/*.db
|
||||||
|
|
||||||
|
# Databases (all locations)
|
||||||
|
*.db
|
||||||
|
*.db-journal
|
||||||
|
|
||||||
|
# WhatsApp session auth
|
||||||
|
.wwebjs_auth/
|
||||||
|
|
||||||
|
# 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
|
||||||
@@ -7,9 +7,25 @@ RUN pacman -Syu --noconfirm && \
|
|||||||
npm \
|
npm \
|
||||||
git \
|
git \
|
||||||
iptables \
|
iptables \
|
||||||
|
openssh \
|
||||||
opencode \
|
opencode \
|
||||||
|
curl \
|
||||||
|
go \
|
||||||
|
sqlite \
|
||||||
&& pacman -Scc --noconfirm
|
&& pacman -Scc --noconfirm
|
||||||
|
|
||||||
|
RUN npx -y skills add JuliusBrussee/caveman -g -a opencode -s caveman -y
|
||||||
|
|
||||||
|
# 2. Install air using Go
|
||||||
|
RUN go install github.com/air-verse/air@latest
|
||||||
|
|
||||||
|
# Add Go binaries to your PATH so you can actually run 'air'
|
||||||
|
ENV PATH="/root/go/bin:${PATH}"
|
||||||
|
|
||||||
|
# Git safe directory system-wide config
|
||||||
|
RUN git config --system --add safe.directory /workspace
|
||||||
|
RUN git config --system --add safe.directory '*'
|
||||||
|
|
||||||
# Firewall script — blocks everything except your Gitea instance
|
# Firewall script — blocks everything except your Gitea instance
|
||||||
COPY entrypoint.sh /entrypoint.sh
|
COPY entrypoint.sh /entrypoint.sh
|
||||||
RUN chmod +x /entrypoint.sh
|
RUN chmod +x /entrypoint.sh
|
||||||
|
|||||||
@@ -9,15 +9,28 @@ services:
|
|||||||
- NET_ADMIN # required for iptables in entrypoint
|
- NET_ADMIN # required for iptables in entrypoint
|
||||||
- NET_RAW
|
- NET_RAW
|
||||||
volumes:
|
volumes:
|
||||||
# Your monorepo — opencode's working directory
|
# Your monorepo
|
||||||
- ../:/workspace
|
- /home/ga/workspace:/workspace
|
||||||
# Persist opencode auth so you don't re-login every time
|
# Mount entire SSH directory from host
|
||||||
|
- /home/ga/.ssh:/root/.ssh
|
||||||
|
# Persist opencode auth
|
||||||
- opencode-auth:/root/.local/share/opencode
|
- opencode-auth:/root/.local/share/opencode
|
||||||
|
# Go CRM database
|
||||||
|
- ./data:/workspace/data
|
||||||
environment:
|
environment:
|
||||||
- OPENCODE_API_KEY=${OPENCODE_API_KEY}
|
- OPENCODE_API_KEY=${OPENCODE_API_KEY}
|
||||||
stdin_open: true
|
stdin_open: true
|
||||||
tty: true
|
tty: true
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
working_dir: /workspace
|
working_dir: /workspace
|
||||||
|
networks:
|
||||||
|
- crm-network
|
||||||
|
|
||||||
|
networks:
|
||||||
|
crm-network:
|
||||||
|
name: crm-network
|
||||||
|
external: true
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
opencode-auth:
|
opencode-auth:
|
||||||
@@ -1,2 +1,24 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Fix SSH directory permissions
|
||||||
|
chmod 700 /root/.ssh
|
||||||
|
chmod 600 /root/.ssh/id_ed25519
|
||||||
|
|
||||||
|
# Copy known_hosts to tmp if it's read-only (from host mount)
|
||||||
|
cp /root/.ssh/known_hosts /tmp/known_hosts 2>/dev/null || touch /tmp/known_hosts
|
||||||
|
chmod 600 /tmp/known_hosts
|
||||||
|
|
||||||
|
# Add Gitea to known_hosts
|
||||||
|
ssh-keyscan -H -p 222 git.processhub.work >> /tmp/known_hosts 2>/dev/null || true
|
||||||
|
|
||||||
|
# Configure SSH
|
||||||
|
export GIT_SSH_COMMAND="ssh -p 222 -i /root/.ssh/id_ed25519 -o UserKnownHostsFile=/tmp/known_hosts -o StrictHostKeyChecking=accept-new"
|
||||||
|
|
||||||
|
# Git config
|
||||||
|
git config --global user.email "[email protected]"
|
||||||
|
git config --global user.name "gabspereira"
|
||||||
|
git config --system --add safe.directory '*'
|
||||||
|
git config --global --add safe.directory /workspace
|
||||||
|
|
||||||
|
# Run opencode
|
||||||
exec opencode
|
exec opencode
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
module.exports = {
|
||||||
|
preset: 'ts-jest',
|
||||||
|
testEnvironment: 'node',
|
||||||
|
rootDir: '.',
|
||||||
|
testMatch: ['**/tests/**/*.test.ts'],
|
||||||
|
verbose: true,
|
||||||
|
forceExit: true,
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"name": "opencode-sandbox",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"test:coverage": "jest --coverage"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/jest": "29.5.12",
|
||||||
|
"@types/node": "20.11.0",
|
||||||
|
"jest": "29.7.0",
|
||||||
|
"ts-jest": "29.1.2",
|
||||||
|
"typescript": "5.3.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { exec } from 'child_process'
|
||||||
|
import { promisify } from 'util'
|
||||||
|
import * as fs from 'fs'
|
||||||
|
import * as path from 'path'
|
||||||
|
|
||||||
|
const execAsync = promisify(exec)
|
||||||
|
|
||||||
|
describe('SSH/Gitea Integration', () => {
|
||||||
|
const SSH_DIR = '/root/.ssh'
|
||||||
|
const SSH_KEY = path.join(SSH_DIR, 'id_ed25519')
|
||||||
|
const KNOWN_HOSTS = path.join(SSH_DIR, 'known_hosts')
|
||||||
|
|
||||||
|
describe('SSH Key Setup', () => {
|
||||||
|
test('SSH directory exists', () => {
|
||||||
|
expect(fs.existsSync(SSH_DIR)).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('SSH directory has correct permissions (0700)', () => {
|
||||||
|
const stats = fs.statSync(SSH_DIR)
|
||||||
|
const mode = stats.mode & 0o777
|
||||||
|
expect(mode).toBe(0o700)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('SSH key file exists', () => {
|
||||||
|
expect(fs.existsSync(SSH_KEY)).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('SSH key has correct permissions (0600)', () => {
|
||||||
|
const stats = fs.statSync(SSH_KEY)
|
||||||
|
const mode = stats.mode & 0o777
|
||||||
|
expect(mode).toBe(0o600)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Gitea Server', () => {
|
||||||
|
test('known_hosts file exists', () => {
|
||||||
|
expect(fs.existsSync(KNOWN_HOSTS)).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('known_hosts contains git.processhub.work', () => {
|
||||||
|
const content = fs.readFileSync(KNOWN_HOSTS, 'utf8')
|
||||||
|
expect(content).toContain('git.processhub.work')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Git Configuration', () => {
|
||||||
|
test('git user.email is configured', async () => {
|
||||||
|
const { stdout } = await execAsync('git config --global user.email')
|
||||||
|
expect(stdout.trim()).toBe('[email protected]')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('git user.name is configured', async () => {
|
||||||
|
const { stdout } = await execAsync('git config --global user.name')
|
||||||
|
expect(stdout.trim()).toBe('gabspereira')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Gitea SSH Connection', () => {
|
||||||
|
test('SSH connection to Gitea succeeds', async () => {
|
||||||
|
try {
|
||||||
|
const { stdout, stderr } = await execAsync(
|
||||||
|
'ssh -T -o ConnectTimeout=10 [email protected]',
|
||||||
|
{ timeout: 15000 }
|
||||||
|
)
|
||||||
|
const output = stdout + stderr
|
||||||
|
expect(output).toContain('successfully authenticated')
|
||||||
|
} catch (error: any) {
|
||||||
|
const output = error.stdout + error.stderr
|
||||||
|
expect(output).toContain('gabspereira')
|
||||||
|
expect(output).toContain('successfully authenticated')
|
||||||
|
}
|
||||||
|
}, 20000)
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Git Remote Access', () => {
|
||||||
|
test('Can access Gitea repository', async () => {
|
||||||
|
const { stdout, stderr } = await execAsync(
|
||||||
|
'git ls-remote [email protected]:gabspereira/workspace.git HEAD',
|
||||||
|
{ timeout: 15000 }
|
||||||
|
)
|
||||||
|
expect(stdout).toMatch(/[a-f0-9]+\s+HEAD/)
|
||||||
|
}, 20000)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"module": "commonjs",
|
||||||
|
"lib": ["ES2020"],
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"types": ["node", "jest"]
|
||||||
|
},
|
||||||
|
"include": ["tests/**/*"],
|
||||||
|
"exclude": ["node_modules"]
|
||||||
|
}
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# ADR Format
|
||||||
|
|
||||||
|
ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc.
|
||||||
|
|
||||||
|
Create the `docs/adr/` directory lazily — only when the first ADR is needed.
|
||||||
|
|
||||||
|
## Template
|
||||||
|
|
||||||
|
```md
|
||||||
|
# {Short title of the decision}
|
||||||
|
|
||||||
|
{1-3 sentences: what's the context, what did we decide, and why.}
|
||||||
|
```
|
||||||
|
|
||||||
|
That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why* — not in filling out sections.
|
||||||
|
|
||||||
|
## Optional sections
|
||||||
|
|
||||||
|
Only include these when they add genuine value. Most ADRs won't need them.
|
||||||
|
|
||||||
|
- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`) — useful when decisions are revisited
|
||||||
|
- **Considered Options** — only when the rejected alternatives are worth remembering
|
||||||
|
- **Consequences** — only when non-obvious downstream effects need to be called out
|
||||||
|
|
||||||
|
## Numbering
|
||||||
|
|
||||||
|
Scan `docs/adr/` for the highest existing number and increment by one.
|
||||||
|
|
||||||
|
## When to offer an ADR
|
||||||
|
|
||||||
|
All three of these must be true:
|
||||||
|
|
||||||
|
1. **Hard to reverse** — the cost of changing your mind later is meaningful
|
||||||
|
2. **Surprising without context** — a future reader will look at the code and wonder "why on earth did they do it this way?"
|
||||||
|
3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons
|
||||||
|
|
||||||
|
If a decision is easy to reverse, skip it — you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing."
|
||||||
|
|
||||||
|
### What qualifies
|
||||||
|
|
||||||
|
- **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres."
|
||||||
|
- **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP."
|
||||||
|
- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library — just the ones that would take a quarter to swap out.
|
||||||
|
- **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s.
|
||||||
|
- **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate.
|
||||||
|
- **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract."
|
||||||
|
- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it — otherwise someone will suggest GraphQL again in six months.
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# CONTEXT.md Format
|
||||||
|
|
||||||
|
## Structure
|
||||||
|
|
||||||
|
```md
|
||||||
|
# {Context Name}
|
||||||
|
|
||||||
|
{One or two sentence description of what this context is and why it exists.}
|
||||||
|
|
||||||
|
## Language
|
||||||
|
|
||||||
|
**Order**:
|
||||||
|
A customer's request to purchase one or more items.
|
||||||
|
_Avoid_: Purchase, transaction
|
||||||
|
|
||||||
|
**Invoice**:
|
||||||
|
A request for payment sent to a customer after delivery.
|
||||||
|
_Avoid_: Bill, payment request
|
||||||
|
|
||||||
|
**Customer**:
|
||||||
|
A person or organization that places orders.
|
||||||
|
_Avoid_: Client, buyer, account
|
||||||
|
|
||||||
|
## Relationships
|
||||||
|
|
||||||
|
- An **Order** produces one or more **Invoices**
|
||||||
|
- An **Invoice** belongs to exactly one **Customer**
|
||||||
|
|
||||||
|
## Example dialogue
|
||||||
|
|
||||||
|
> **Dev:** "When a **Customer** places an **Order**, do we create the **Invoice** immediately?"
|
||||||
|
> **Domain expert:** "No — an **Invoice** is only generated once a **Fulfillment** is confirmed."
|
||||||
|
|
||||||
|
## Flagged ambiguities
|
||||||
|
|
||||||
|
- "account" was used to mean both **Customer** and **User** — resolved: these are distinct concepts.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Rules
|
||||||
|
|
||||||
|
- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others as aliases to avoid.
|
||||||
|
- **Flag conflicts explicitly.** If a term is used ambiguously, call it out in "Flagged ambiguities" with a clear resolution.
|
||||||
|
- **Keep definitions tight.** One sentence max. Define what it IS, not what it does.
|
||||||
|
- **Show relationships.** Use bold term names and express cardinality where obvious.
|
||||||
|
- **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs.
|
||||||
|
- **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine.
|
||||||
|
- **Write an example dialogue.** A conversation between a dev and a domain expert that demonstrates how the terms interact naturally and clarifies boundaries between related concepts.
|
||||||
|
|
||||||
|
## Single vs multi-context repos
|
||||||
|
|
||||||
|
**Single context (most repos):** One `CONTEXT.md` at the repo root.
|
||||||
|
|
||||||
|
**Multiple contexts:** A `CONTEXT-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other:
|
||||||
|
|
||||||
|
```md
|
||||||
|
# Context Map
|
||||||
|
|
||||||
|
## Contexts
|
||||||
|
|
||||||
|
- [Ordering](./src/ordering/CONTEXT.md) — receives and tracks customer orders
|
||||||
|
- [Billing](./src/billing/CONTEXT.md) — generates invoices and processes payments
|
||||||
|
- [Fulfillment](./src/fulfillment/CONTEXT.md) — manages warehouse picking and shipping
|
||||||
|
|
||||||
|
## Relationships
|
||||||
|
|
||||||
|
- **Ordering → Fulfillment**: Ordering emits `OrderPlaced` events; Fulfillment consumes them to start picking
|
||||||
|
- **Fulfillment → Billing**: Fulfillment emits `ShipmentDispatched` events; Billing consumes them to generate invoices
|
||||||
|
- **Ordering ↔ Billing**: Shared types for `CustomerId` and `Money`
|
||||||
|
```
|
||||||
|
|
||||||
|
The skill infers which structure applies:
|
||||||
|
|
||||||
|
- If `CONTEXT-MAP.md` exists, read it to find contexts
|
||||||
|
- If only a root `CONTEXT.md` exists, single context
|
||||||
|
- If neither exists, create a root `CONTEXT.md` lazily when the first term is resolved
|
||||||
|
|
||||||
|
When multiple contexts exist, infer which one the current topic relates to. If unclear, ask.
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
---
|
||||||
|
name: domain-model
|
||||||
|
description: Grilling session that challenges your plan against the existing domain model, sharpens terminology, and updates documentation (CONTEXT.md, ADRs) inline as decisions crystallise. Use when user wants to stress-test a plan against their project's language and documented decisions.
|
||||||
|
disable-model-invocation: true
|
||||||
|
---
|
||||||
|
|
||||||
|
Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer.
|
||||||
|
|
||||||
|
Ask the questions one at a time, waiting for feedback on each question before continuing.
|
||||||
|
|
||||||
|
If a question can be answered by exploring the codebase, explore the codebase instead.
|
||||||
|
|
||||||
|
## Domain awareness
|
||||||
|
|
||||||
|
During codebase exploration, also look for existing documentation:
|
||||||
|
|
||||||
|
### File structure
|
||||||
|
|
||||||
|
Most repos have a single context:
|
||||||
|
|
||||||
|
```
|
||||||
|
/
|
||||||
|
├── CONTEXT.md
|
||||||
|
├── docs/
|
||||||
|
│ └── adr/
|
||||||
|
│ ├── 0001-event-sourced-orders.md
|
||||||
|
│ └── 0002-postgres-for-write-model.md
|
||||||
|
└── src/
|
||||||
|
```
|
||||||
|
|
||||||
|
If a `CONTEXT-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives:
|
||||||
|
|
||||||
|
```
|
||||||
|
/
|
||||||
|
├── CONTEXT-MAP.md
|
||||||
|
├── docs/
|
||||||
|
│ └── adr/ ← system-wide decisions
|
||||||
|
├── src/
|
||||||
|
│ ├── ordering/
|
||||||
|
│ │ ├── CONTEXT.md
|
||||||
|
│ │ └── docs/adr/ ← context-specific decisions
|
||||||
|
│ └── billing/
|
||||||
|
│ ├── CONTEXT.md
|
||||||
|
│ └── docs/adr/
|
||||||
|
```
|
||||||
|
|
||||||
|
Create files lazily — only when you have something to write. If no `CONTEXT.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed.
|
||||||
|
|
||||||
|
## During the session
|
||||||
|
|
||||||
|
### Challenge against the glossary
|
||||||
|
|
||||||
|
When the user uses a term that conflicts with the existing language in `CONTEXT.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y — which is it?"
|
||||||
|
|
||||||
|
### Sharpen fuzzy language
|
||||||
|
|
||||||
|
When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account' — do you mean the Customer or the User? Those are different things."
|
||||||
|
|
||||||
|
### Discuss concrete scenarios
|
||||||
|
|
||||||
|
When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts.
|
||||||
|
|
||||||
|
### Cross-reference with code
|
||||||
|
|
||||||
|
When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible — which is right?"
|
||||||
|
|
||||||
|
### Update CONTEXT.md inline
|
||||||
|
|
||||||
|
When a term is resolved, update `CONTEXT.md` right there. Don't batch these up — capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md).
|
||||||
|
|
||||||
|
Don't couple `CONTEXT.md` to implementation details. Only include terms that are meaningful to domain experts.
|
||||||
|
|
||||||
|
### Offer ADRs sparingly
|
||||||
|
|
||||||
|
Only offer to create an ADR when all three are true:
|
||||||
|
|
||||||
|
1. **Hard to reverse** — the cost of changing your mind later is meaningful
|
||||||
|
2. **Surprising without context** — a future reader will wonder "why did they do it this way?"
|
||||||
|
3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons
|
||||||
|
|
||||||
|
If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md).
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
---
|
||||||
|
name: grill-me
|
||||||
|
description: Interview the user relentlessly about a plan or design until reaching shared understanding, resolving each branch of the decision tree. Use when user wants to stress-test a plan, get grilled on their design, or mentions "grill me".
|
||||||
|
---
|
||||||
|
|
||||||
|
Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer.
|
||||||
|
|
||||||
|
Ask the questions one at a time.
|
||||||
|
|
||||||
|
If a question can be answered by exploring the codebase, explore the codebase instead.
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# Deepening
|
||||||
|
|
||||||
|
How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**.
|
||||||
|
|
||||||
|
## Dependency categories
|
||||||
|
|
||||||
|
When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam.
|
||||||
|
|
||||||
|
### 1. In-process
|
||||||
|
|
||||||
|
Pure computation, in-memory state, no I/O. Always deepenable — merge the modules and test through the new interface directly. No adapter needed.
|
||||||
|
|
||||||
|
### 2. Local-substitutable
|
||||||
|
|
||||||
|
Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface.
|
||||||
|
|
||||||
|
### 3. Remote but owned (Ports & Adapters)
|
||||||
|
|
||||||
|
Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter.
|
||||||
|
|
||||||
|
Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."*
|
||||||
|
|
||||||
|
### 4. True external (Mock)
|
||||||
|
|
||||||
|
Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter.
|
||||||
|
|
||||||
|
## Seam discipline
|
||||||
|
|
||||||
|
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection.
|
||||||
|
- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them.
|
||||||
|
|
||||||
|
## Testing strategy: replace, don't layer
|
||||||
|
|
||||||
|
- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist — delete them.
|
||||||
|
- Write new tests at the deepened module's interface. The **interface is the test surface**.
|
||||||
|
- Tests assert on observable outcomes through the interface, not internal state.
|
||||||
|
- Tests should survive internal refactors — they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface.
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Interface Design
|
||||||
|
|
||||||
|
When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout) — your first idea is unlikely to be the best.
|
||||||
|
|
||||||
|
Uses the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**, **leverage**.
|
||||||
|
|
||||||
|
## Process
|
||||||
|
|
||||||
|
### 1. Frame the problem space
|
||||||
|
|
||||||
|
Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate:
|
||||||
|
|
||||||
|
- The constraints any new interface would need to satisfy
|
||||||
|
- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md))
|
||||||
|
- A rough illustrative code sketch to ground the constraints — not a proposal, just a way to make the constraints concrete
|
||||||
|
|
||||||
|
Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel.
|
||||||
|
|
||||||
|
### 2. Spawn sub-agents
|
||||||
|
|
||||||
|
Spawn 3+ sub-agents in parallel using the Agent tool. Each must produce a **radically different** interface for the deepened module.
|
||||||
|
|
||||||
|
Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint:
|
||||||
|
|
||||||
|
- Agent 1: "Minimize the interface — aim for 1–3 entry points max. Maximise leverage per entry point."
|
||||||
|
- Agent 2: "Maximise flexibility — support many use cases and extension."
|
||||||
|
- Agent 3: "Optimise for the most common caller — make the default case trivial."
|
||||||
|
- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies."
|
||||||
|
|
||||||
|
Include both [LANGUAGE.md](LANGUAGE.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language.
|
||||||
|
|
||||||
|
Each sub-agent outputs:
|
||||||
|
|
||||||
|
1. Interface (types, methods, params — plus invariants, ordering, error modes)
|
||||||
|
2. Usage example showing how callers use it
|
||||||
|
3. What the implementation hides behind the seam
|
||||||
|
4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md))
|
||||||
|
5. Trade-offs — where leverage is high, where it's thin
|
||||||
|
|
||||||
|
### 3. Present and compare
|
||||||
|
|
||||||
|
Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**.
|
||||||
|
|
||||||
|
After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated — the user wants a strong read, not a menu.
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# Language
|
||||||
|
|
||||||
|
Shared vocabulary for every suggestion this skill makes. Use these terms exactly — don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point.
|
||||||
|
|
||||||
|
## Terms
|
||||||
|
|
||||||
|
**Module**
|
||||||
|
Anything with an interface and an implementation. Deliberately scale-agnostic — applies equally to a function, class, package, or tier-spanning slice.
|
||||||
|
_Avoid_: unit, component, service.
|
||||||
|
|
||||||
|
**Interface**
|
||||||
|
Everything a caller must know to use the module correctly. Includes the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics.
|
||||||
|
_Avoid_: API, signature (too narrow — those refer only to the type-level surface).
|
||||||
|
|
||||||
|
**Implementation**
|
||||||
|
What's inside a module — its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise.
|
||||||
|
|
||||||
|
**Depth**
|
||||||
|
Leverage at the interface — the amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface. A module is **shallow** when the interface is nearly as complex as the implementation.
|
||||||
|
|
||||||
|
**Seam** _(from Michael Feathers)_
|
||||||
|
A place where you can alter behaviour without editing in that place. The *location* at which a module's interface lives. Choosing where to put the seam is its own design decision, distinct from what goes behind it.
|
||||||
|
_Avoid_: boundary (overloaded with DDD's bounded context).
|
||||||
|
|
||||||
|
**Adapter**
|
||||||
|
A concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside).
|
||||||
|
|
||||||
|
**Leverage**
|
||||||
|
What callers get from depth. More capability per unit of interface they have to learn. One implementation pays back across N call sites and M tests.
|
||||||
|
|
||||||
|
**Locality**
|
||||||
|
What maintainers get from depth. Change, bugs, knowledge, and verification concentrate at one place rather than spreading across callers. Fix once, fixed everywhere.
|
||||||
|
|
||||||
|
## Principles
|
||||||
|
|
||||||
|
- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts — they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface.
|
||||||
|
- **The deletion test.** Imagine deleting the module. If complexity vanishes, the module wasn't hiding anything (it was a pass-through). If complexity reappears across N callers, the module was earning its keep.
|
||||||
|
- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape.
|
||||||
|
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it.
|
||||||
|
|
||||||
|
## Relationships
|
||||||
|
|
||||||
|
- A **Module** has exactly one **Interface** (the surface it presents to callers and tests).
|
||||||
|
- **Depth** is a property of a **Module**, measured against its **Interface**.
|
||||||
|
- A **Seam** is where a **Module**'s **Interface** lives.
|
||||||
|
- An **Adapter** sits at a **Seam** and satisfies the **Interface**.
|
||||||
|
- **Depth** produces **Leverage** for callers and **Locality** for maintainers.
|
||||||
|
|
||||||
|
## Rejected framings
|
||||||
|
|
||||||
|
- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead.
|
||||||
|
- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow — interface here includes every fact a caller must know.
|
||||||
|
- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**.
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
---
|
||||||
|
name: improve-codebase-architecture
|
||||||
|
description: Find deepening opportunities in a codebase, informed by the domain language in CONTEXT.md and the decisions in docs/adr/. Use when the user wants to improve architecture, find refactoring opportunities, consolidate tightly-coupled modules, or make a codebase more testable and AI-navigable.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Improve Codebase Architecture
|
||||||
|
|
||||||
|
Surface architectural friction and propose **deepening opportunities** — refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability.
|
||||||
|
|
||||||
|
## Glossary
|
||||||
|
|
||||||
|
Use these terms exactly in every suggestion. Consistent language is the point — don't drift into "component," "service," "API," or "boundary." Full definitions in [LANGUAGE.md](LANGUAGE.md).
|
||||||
|
|
||||||
|
- **Module** — anything with an interface and an implementation (function, class, package, slice).
|
||||||
|
- **Interface** — everything a caller must know to use the module: types, invariants, error modes, ordering, config. Not just the type signature.
|
||||||
|
- **Implementation** — the code inside.
|
||||||
|
- **Depth** — leverage at the interface: a lot of behaviour behind a small interface. **Deep** = high leverage. **Shallow** = interface nearly as complex as the implementation.
|
||||||
|
- **Seam** — where an interface lives; a place behaviour can be altered without editing in place. (Use this, not "boundary.")
|
||||||
|
- **Adapter** — a concrete thing satisfying an interface at a seam.
|
||||||
|
- **Leverage** — what callers get from depth.
|
||||||
|
- **Locality** — what maintainers get from depth: change, bugs, knowledge concentrated in one place.
|
||||||
|
|
||||||
|
Key principles (see [LANGUAGE.md](LANGUAGE.md) for the full list):
|
||||||
|
|
||||||
|
- **Deletion test**: imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep.
|
||||||
|
- **The interface is the test surface.**
|
||||||
|
- **One adapter = hypothetical seam. Two adapters = real seam.**
|
||||||
|
|
||||||
|
This skill is _informed_ by the project's domain model — `CONTEXT.md` and any `docs/adr/`. The domain language gives names to good seams; ADRs record decisions the skill should not re-litigate. See [CONTEXT-FORMAT.md](../domain-model/CONTEXT-FORMAT.md) and [ADR-FORMAT.md](../domain-model/ADR-FORMAT.md).
|
||||||
|
|
||||||
|
## Process
|
||||||
|
|
||||||
|
### 1. Explore
|
||||||
|
|
||||||
|
Read existing documentation first:
|
||||||
|
|
||||||
|
- `CONTEXT.md` (or `CONTEXT-MAP.md` + each `CONTEXT.md` in a multi-context repo)
|
||||||
|
- Relevant ADRs in `docs/adr/` (and any context-scoped `docs/adr/` directories)
|
||||||
|
|
||||||
|
If any of these files don't exist, proceed silently — don't flag their absence or suggest creating them upfront.
|
||||||
|
|
||||||
|
Then use the Agent tool with `subagent_type=Explore` to walk the codebase. Don't follow rigid heuristics — explore organically and note where you experience friction:
|
||||||
|
|
||||||
|
- Where does understanding one concept require bouncing between many small modules?
|
||||||
|
- Where are modules **shallow** — interface nearly as complex as the implementation?
|
||||||
|
- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)?
|
||||||
|
- Where do tightly-coupled modules leak across their seams?
|
||||||
|
- Which parts of the codebase are untested, or hard to test through their current interface?
|
||||||
|
|
||||||
|
Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want.
|
||||||
|
|
||||||
|
### 2. Present candidates
|
||||||
|
|
||||||
|
Present a numbered list of deepening opportunities. For each candidate:
|
||||||
|
|
||||||
|
- **Files** — which files/modules are involved
|
||||||
|
- **Problem** — why the current architecture is causing friction
|
||||||
|
- **Solution** — plain English description of what would change
|
||||||
|
- **Benefits** — explained in terms of locality and leverage, and also in how tests would improve
|
||||||
|
|
||||||
|
**Use CONTEXT.md vocabulary for the domain, and [LANGUAGE.md](LANGUAGE.md) vocabulary for the architecture.** If `CONTEXT.md` defines "Order," talk about "the Order intake module" — not "the FooBarHandler," and not "the Order service."
|
||||||
|
|
||||||
|
**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly (e.g. _"contradicts ADR-0007 — but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids.
|
||||||
|
|
||||||
|
Do NOT propose interfaces yet. Ask the user: "Which of these would you like to explore?"
|
||||||
|
|
||||||
|
### 3. Grilling loop
|
||||||
|
|
||||||
|
Once the user picks a candidate, drop into a grilling conversation. Walk the design tree with them — constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive.
|
||||||
|
|
||||||
|
Side effects happen inline as decisions crystallize:
|
||||||
|
|
||||||
|
- **Naming a deepened module after a concept not in `CONTEXT.md`?** Add the term to `CONTEXT.md` — same discipline as `/domain-model` (see [CONTEXT-FORMAT.md](../domain-model/CONTEXT-FORMAT.md)). Create the file lazily if it doesn't exist.
|
||||||
|
- **Sharpening a fuzzy term during the conversation?** Update `CONTEXT.md` right there.
|
||||||
|
- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing — skip ephemeral reasons ("not worth it right now") and self-evident ones. See [ADR-FORMAT.md](../domain-model/ADR-FORMAT.md).
|
||||||
|
- **Want to explore alternative interfaces for the deepened module?** See [INTERFACE-DESIGN.md](INTERFACE-DESIGN.md).
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
---
|
||||||
|
name: to-prd
|
||||||
|
description: Turn the current conversation context into a PRD and submit it as a GitHub issue. Use when user wants to create a PRD from the current context.
|
||||||
|
---
|
||||||
|
|
||||||
|
This skill takes the current conversation context and codebase understanding and produces a PRD. Do NOT interview the user — just synthesize what you already know.
|
||||||
|
|
||||||
|
## Process
|
||||||
|
|
||||||
|
1. Explore the repo to understand the current state of the codebase, if you haven't already.
|
||||||
|
|
||||||
|
2. Sketch out the major modules you will need to build or modify to complete the implementation. Actively look for opportunities to extract deep modules that can be tested in isolation.
|
||||||
|
|
||||||
|
A deep module (as opposed to a shallow module) is one which encapsulates a lot of functionality in a simple, testable interface which rarely changes.
|
||||||
|
|
||||||
|
Check with the user that these modules match their expectations. Check with the user which modules they want tests written for.
|
||||||
|
|
||||||
|
3. Write the PRD using the template below and submit it as a GitHub issue.
|
||||||
|
|
||||||
|
<prd-template>
|
||||||
|
|
||||||
|
## Problem Statement
|
||||||
|
|
||||||
|
The problem that the user is facing, from the user's perspective.
|
||||||
|
|
||||||
|
## Solution
|
||||||
|
|
||||||
|
The solution to the problem, from the user's perspective.
|
||||||
|
|
||||||
|
## User Stories
|
||||||
|
|
||||||
|
A LONG, numbered list of user stories. Each user story should be in the format of:
|
||||||
|
|
||||||
|
1. As an <actor>, I want a <feature>, so that <benefit>
|
||||||
|
|
||||||
|
<user-story-example>
|
||||||
|
1. As a mobile bank customer, I want to see balance on my accounts, so that I can make better informed decisions about my spending
|
||||||
|
</user-story-example>
|
||||||
|
|
||||||
|
This list of user stories should be extremely extensive and cover all aspects of the feature.
|
||||||
|
|
||||||
|
## Implementation Decisions
|
||||||
|
|
||||||
|
A list of implementation decisions that were made. This can include:
|
||||||
|
|
||||||
|
- The modules that will be built/modified
|
||||||
|
- The interfaces of those modules that will be modified
|
||||||
|
- Technical clarifications from the developer
|
||||||
|
- Architectural decisions
|
||||||
|
- Schema changes
|
||||||
|
- API contracts
|
||||||
|
- Specific interactions
|
||||||
|
|
||||||
|
Do NOT include specific file paths or code snippets. They may end up being outdated very quickly.
|
||||||
|
|
||||||
|
## Testing Decisions
|
||||||
|
|
||||||
|
A list of testing decisions that were made. Include:
|
||||||
|
|
||||||
|
- A description of what makes a good test (only test external behavior, not implementation details)
|
||||||
|
- Which modules will be tested
|
||||||
|
- Prior art for the tests (i.e. similar types of tests in the codebase)
|
||||||
|
|
||||||
|
## Out of Scope
|
||||||
|
|
||||||
|
A description of the things that are out of scope for this PRD.
|
||||||
|
|
||||||
|
## Further Notes
|
||||||
|
|
||||||
|
Any further notes about the feature.
|
||||||
|
|
||||||
|
</prd-template>
|
||||||
|
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
---
|
||||||
|
name: tdd
|
||||||
|
description: Test-driven development with red-green-refactor loop. Use when user wants to build features or fix bugs using TDD, mentions "red-green-refactor", wants integration tests, or asks for test-first development.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Test-Driven Development
|
||||||
|
|
||||||
|
## Philosophy
|
||||||
|
|
||||||
|
**Core principle**: Tests should verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't.
|
||||||
|
|
||||||
|
**Good tests** are integration-style: they exercise real code paths through public APIs. They describe _what_ the system does, not _how_ it does it. A good test reads like a specification - "user can checkout with valid cart" tells you exactly what capability exists. These tests survive refactors because they don't care about internal structure.
|
||||||
|
|
||||||
|
**Bad tests** are coupled to implementation. They mock internal collaborators, test private methods, or verify through external means (like querying a database directly instead of using the interface). The warning sign: your test breaks when you refactor, but behavior hasn't changed. If you rename an internal function and tests fail, those tests were testing implementation, not behavior.
|
||||||
|
|
||||||
|
See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines.
|
||||||
|
|
||||||
|
## Anti-Pattern: Horizontal Slices
|
||||||
|
|
||||||
|
**DO NOT write all tests first, then all implementation.** This is "horizontal slicing" - treating RED as "write all tests" and GREEN as "write all code."
|
||||||
|
|
||||||
|
This produces **crap tests**:
|
||||||
|
|
||||||
|
- Tests written in bulk test _imagined_ behavior, not _actual_ behavior
|
||||||
|
- You end up testing the _shape_ of things (data structures, function signatures) rather than user-facing behavior
|
||||||
|
- Tests become insensitive to real changes - they pass when behavior breaks, fail when behavior is fine
|
||||||
|
- You outrun your headlights, committing to test structure before understanding the implementation
|
||||||
|
|
||||||
|
**Correct approach**: Vertical slices via tracer bullets. One test → one implementation → repeat. Each test responds to what you learned from the previous cycle. Because you just wrote the code, you know exactly what behavior matters and how to verify it.
|
||||||
|
|
||||||
|
```
|
||||||
|
WRONG (horizontal):
|
||||||
|
RED: test1, test2, test3, test4, test5
|
||||||
|
GREEN: impl1, impl2, impl3, impl4, impl5
|
||||||
|
|
||||||
|
RIGHT (vertical):
|
||||||
|
RED→GREEN: test1→impl1
|
||||||
|
RED→GREEN: test2→impl2
|
||||||
|
RED→GREEN: test3→impl3
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
### 1. Planning
|
||||||
|
|
||||||
|
Before writing any code:
|
||||||
|
|
||||||
|
- [ ] Confirm with user what interface changes are needed
|
||||||
|
- [ ] Confirm with user which behaviors to test (prioritize)
|
||||||
|
- [ ] Identify opportunities for [deep modules](deep-modules.md) (small interface, deep implementation)
|
||||||
|
- [ ] Design interfaces for [testability](interface-design.md)
|
||||||
|
- [ ] List the behaviors to test (not implementation steps)
|
||||||
|
- [ ] Get user approval on the plan
|
||||||
|
|
||||||
|
Ask: "What should the public interface look like? Which behaviors are most important to test?"
|
||||||
|
|
||||||
|
**You can't test everything.** Confirm with the user exactly which behaviors matter most. Focus testing effort on critical paths and complex logic, not every possible edge case.
|
||||||
|
|
||||||
|
### 2. Tracer Bullet
|
||||||
|
|
||||||
|
Write ONE test that confirms ONE thing about the system:
|
||||||
|
|
||||||
|
```
|
||||||
|
RED: Write test for first behavior → test fails
|
||||||
|
GREEN: Write minimal code to pass → test passes
|
||||||
|
```
|
||||||
|
|
||||||
|
This is your tracer bullet - proves the path works end-to-end.
|
||||||
|
|
||||||
|
### 3. Incremental Loop
|
||||||
|
|
||||||
|
For each remaining behavior:
|
||||||
|
|
||||||
|
```
|
||||||
|
RED: Write next test → fails
|
||||||
|
GREEN: Minimal code to pass → passes
|
||||||
|
```
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- One test at a time
|
||||||
|
- Only enough code to pass current test
|
||||||
|
- Don't anticipate future tests
|
||||||
|
- Keep tests focused on observable behavior
|
||||||
|
|
||||||
|
### 4. Refactor
|
||||||
|
|
||||||
|
After all tests pass, look for [refactor candidates](refactoring.md):
|
||||||
|
|
||||||
|
- [ ] Extract duplication
|
||||||
|
- [ ] Deepen modules (move complexity behind simple interfaces)
|
||||||
|
- [ ] Apply SOLID principles where natural
|
||||||
|
- [ ] Consider what new code reveals about existing code
|
||||||
|
- [ ] Run tests after each refactor step
|
||||||
|
|
||||||
|
**Never refactor while RED.** Get to GREEN first.
|
||||||
|
|
||||||
|
## Checklist Per Cycle
|
||||||
|
|
||||||
|
```
|
||||||
|
[ ] Test describes behavior, not implementation
|
||||||
|
[ ] Test uses public interface only
|
||||||
|
[ ] Test would survive internal refactor
|
||||||
|
[ ] Code is minimal for this test
|
||||||
|
[ ] No speculative features added
|
||||||
|
```
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Deep Modules
|
||||||
|
|
||||||
|
From "A Philosophy of Software Design":
|
||||||
|
|
||||||
|
**Deep module** = small interface + lots of implementation
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────┐
|
||||||
|
│ Small Interface │ ← Few methods, simple params
|
||||||
|
├─────────────────────┤
|
||||||
|
│ │
|
||||||
|
│ │
|
||||||
|
│ Deep Implementation│ ← Complex logic hidden
|
||||||
|
│ │
|
||||||
|
│ │
|
||||||
|
└─────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**Shallow module** = large interface + little implementation (avoid)
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────┐
|
||||||
|
│ Large Interface │ ← Many methods, complex params
|
||||||
|
├─────────────────────────────────┤
|
||||||
|
│ Thin Implementation │ ← Just passes through
|
||||||
|
└─────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
When designing interfaces, ask:
|
||||||
|
|
||||||
|
- Can I reduce the number of methods?
|
||||||
|
- Can I simplify the parameters?
|
||||||
|
- Can I hide more complexity inside?
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# Interface Design for Testability
|
||||||
|
|
||||||
|
Good interfaces make testing natural:
|
||||||
|
|
||||||
|
1. **Accept dependencies, don't create them**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Testable
|
||||||
|
function processOrder(order, paymentGateway) {}
|
||||||
|
|
||||||
|
// Hard to test
|
||||||
|
function processOrder(order) {
|
||||||
|
const gateway = new StripeGateway();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Return results, don't produce side effects**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Testable
|
||||||
|
function calculateDiscount(cart): Discount {}
|
||||||
|
|
||||||
|
// Hard to test
|
||||||
|
function applyDiscount(cart): void {
|
||||||
|
cart.total -= discount;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Small surface area**
|
||||||
|
- Fewer methods = fewer tests needed
|
||||||
|
- Fewer params = simpler test setup
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# When to Mock
|
||||||
|
|
||||||
|
Mock at **system boundaries** only:
|
||||||
|
|
||||||
|
- External APIs (payment, email, etc.)
|
||||||
|
- Databases (sometimes - prefer test DB)
|
||||||
|
- Time/randomness
|
||||||
|
- File system (sometimes)
|
||||||
|
|
||||||
|
Don't mock:
|
||||||
|
|
||||||
|
- Your own classes/modules
|
||||||
|
- Internal collaborators
|
||||||
|
- Anything you control
|
||||||
|
|
||||||
|
## Designing for Mockability
|
||||||
|
|
||||||
|
At system boundaries, design interfaces that are easy to mock:
|
||||||
|
|
||||||
|
**1. Use dependency injection**
|
||||||
|
|
||||||
|
Pass external dependencies in rather than creating them internally:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Easy to mock
|
||||||
|
function processPayment(order, paymentClient) {
|
||||||
|
return paymentClient.charge(order.total);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hard to mock
|
||||||
|
function processPayment(order) {
|
||||||
|
const client = new StripeClient(process.env.STRIPE_KEY);
|
||||||
|
return client.charge(order.total);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. Prefer SDK-style interfaces over generic fetchers**
|
||||||
|
|
||||||
|
Create specific functions for each external operation instead of one generic function with conditional logic:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// GOOD: Each function is independently mockable
|
||||||
|
const api = {
|
||||||
|
getUser: (id) => fetch(`/users/${id}`),
|
||||||
|
getOrders: (userId) => fetch(`/users/${userId}/orders`),
|
||||||
|
createOrder: (data) => fetch('/orders', { method: 'POST', body: data }),
|
||||||
|
};
|
||||||
|
|
||||||
|
// BAD: Mocking requires conditional logic inside the mock
|
||||||
|
const api = {
|
||||||
|
fetch: (endpoint, options) => fetch(endpoint, options),
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
The SDK approach means:
|
||||||
|
- Each mock returns one specific shape
|
||||||
|
- No conditional logic in test setup
|
||||||
|
- Easier to see which endpoints a test exercises
|
||||||
|
- Type safety per endpoint
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Refactor Candidates
|
||||||
|
|
||||||
|
After TDD cycle, look for:
|
||||||
|
|
||||||
|
- **Duplication** → Extract function/class
|
||||||
|
- **Long methods** → Break into private helpers (keep tests on public interface)
|
||||||
|
- **Shallow modules** → Combine or deepen
|
||||||
|
- **Feature envy** → Move logic to where data lives
|
||||||
|
- **Primitive obsession** → Introduce value objects
|
||||||
|
- **Existing code** the new code reveals as problematic
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
# Good and Bad Tests
|
||||||
|
|
||||||
|
## Good Tests
|
||||||
|
|
||||||
|
**Integration-style**: Test through real interfaces, not mocks of internal parts.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// GOOD: Tests observable behavior
|
||||||
|
test("user can checkout with valid cart", async () => {
|
||||||
|
const cart = createCart();
|
||||||
|
cart.add(product);
|
||||||
|
const result = await checkout(cart, paymentMethod);
|
||||||
|
expect(result.status).toBe("confirmed");
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Characteristics:
|
||||||
|
|
||||||
|
- Tests behavior users/callers care about
|
||||||
|
- Uses public API only
|
||||||
|
- Survives internal refactors
|
||||||
|
- Describes WHAT, not HOW
|
||||||
|
- One logical assertion per test
|
||||||
|
|
||||||
|
## Bad Tests
|
||||||
|
|
||||||
|
**Implementation-detail tests**: Coupled to internal structure.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// BAD: Tests implementation details
|
||||||
|
test("checkout calls paymentService.process", async () => {
|
||||||
|
const mockPayment = jest.mock(paymentService);
|
||||||
|
await checkout(cart, payment);
|
||||||
|
expect(mockPayment.process).toHaveBeenCalledWith(cart.total);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Red flags:
|
||||||
|
|
||||||
|
- Mocking internal collaborators
|
||||||
|
- Testing private methods
|
||||||
|
- Asserting on call counts/order
|
||||||
|
- Test breaks when refactoring without behavior change
|
||||||
|
- Test name describes HOW not WHAT
|
||||||
|
- Verifying through external means instead of interface
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// BAD: Bypasses interface to verify
|
||||||
|
test("createUser saves to database", async () => {
|
||||||
|
await createUser({ name: "Alice" });
|
||||||
|
const row = await db.query("SELECT * FROM users WHERE name = ?", ["Alice"]);
|
||||||
|
expect(row).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
// GOOD: Verifies through interface
|
||||||
|
test("createUser makes user retrievable", async () => {
|
||||||
|
const user = await createUser({ name: "Alice" });
|
||||||
|
const retrieved = await getUser(user.id);
|
||||||
|
expect(retrieved.name).toBe("Alice");
|
||||||
|
});
|
||||||
|
```
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
---
|
||||||
|
name: to-prd
|
||||||
|
description: Turn the current conversation context into a PRD and submit it as a GitHub issue. Use when user wants to create a PRD from the current context.
|
||||||
|
---
|
||||||
|
|
||||||
|
This skill takes the current conversation context and codebase understanding and produces a PRD. Do NOT interview the user — just synthesize what you already know.
|
||||||
|
|
||||||
|
## Process
|
||||||
|
|
||||||
|
1. Explore the repo to understand the current state of the codebase, if you haven't already.
|
||||||
|
|
||||||
|
2. Sketch out the major modules you will need to build or modify to complete the implementation. Actively look for opportunities to extract deep modules that can be tested in isolation.
|
||||||
|
|
||||||
|
A deep module (as opposed to a shallow module) is one which encapsulates a lot of functionality in a simple, testable interface which rarely changes.
|
||||||
|
|
||||||
|
Check with the user that these modules match their expectations. Check with the user which modules they want tests written for.
|
||||||
|
|
||||||
|
3. Write the PRD using the template below and submit it as a GitHub issue.
|
||||||
|
|
||||||
|
<prd-template>
|
||||||
|
|
||||||
|
## Problem Statement
|
||||||
|
|
||||||
|
The problem that the user is facing, from the user's perspective.
|
||||||
|
|
||||||
|
## Solution
|
||||||
|
|
||||||
|
The solution to the problem, from the user's perspective.
|
||||||
|
|
||||||
|
## User Stories
|
||||||
|
|
||||||
|
A LONG, numbered list of user stories. Each user story should be in the format of:
|
||||||
|
|
||||||
|
1. As an <actor>, I want a <feature>, so that <benefit>
|
||||||
|
|
||||||
|
<user-story-example>
|
||||||
|
1. As a mobile bank customer, I want to see balance on my accounts, so that I can make better informed decisions about my spending
|
||||||
|
</user-story-example>
|
||||||
|
|
||||||
|
This list of user stories should be extremely extensive and cover all aspects of the feature.
|
||||||
|
|
||||||
|
## Implementation Decisions
|
||||||
|
|
||||||
|
A list of implementation decisions that were made. This can include:
|
||||||
|
|
||||||
|
- The modules that will be built/modified
|
||||||
|
- The interfaces of those modules that will be modified
|
||||||
|
- Technical clarifications from the developer
|
||||||
|
- Architectural decisions
|
||||||
|
- Schema changes
|
||||||
|
- API contracts
|
||||||
|
- Specific interactions
|
||||||
|
|
||||||
|
Do NOT include specific file paths or code snippets. They may end up being outdated very quickly.
|
||||||
|
|
||||||
|
## Testing Decisions
|
||||||
|
|
||||||
|
A list of testing decisions that were made. Include:
|
||||||
|
|
||||||
|
- A description of what makes a good test (only test external behavior, not implementation details)
|
||||||
|
- Which modules will be tested
|
||||||
|
- Prior art for the tests (i.e. similar types of tests in the codebase)
|
||||||
|
|
||||||
|
## Out of Scope
|
||||||
|
|
||||||
|
A description of the things that are out of scope for this PRD.
|
||||||
|
|
||||||
|
## Further Notes
|
||||||
|
|
||||||
|
Any further notes about the feature.
|
||||||
|
|
||||||
|
</prd-template>
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
---
|
||||||
|
name: ubiquitous-language
|
||||||
|
description: Extract a DDD-style ubiquitous language glossary from the current conversation, flagging ambiguities and proposing canonical terms. Saves to UBIQUITOUS_LANGUAGE.md. Use when user wants to define domain terms, build a glossary, harden terminology, create a ubiquitous language, or mentions "domain model" or "DDD".
|
||||||
|
disable-model-invocation: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# Ubiquitous Language
|
||||||
|
|
||||||
|
Extract and formalize domain terminology from the current conversation into a consistent glossary, saved to a local file.
|
||||||
|
|
||||||
|
## Process
|
||||||
|
|
||||||
|
1. **Scan the conversation** for domain-relevant nouns, verbs, and concepts
|
||||||
|
2. **Identify problems**:
|
||||||
|
- Same word used for different concepts (ambiguity)
|
||||||
|
- Different words used for the same concept (synonyms)
|
||||||
|
- Vague or overloaded terms
|
||||||
|
3. **Propose a canonical glossary** with opinionated term choices
|
||||||
|
4. **Write to `UBIQUITOUS_LANGUAGE.md`** in the working directory using the format below
|
||||||
|
5. **Output a summary** inline in the conversation
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
|
||||||
|
Write a `UBIQUITOUS_LANGUAGE.md` file with this structure:
|
||||||
|
|
||||||
|
```md
|
||||||
|
# Ubiquitous Language
|
||||||
|
|
||||||
|
## Order lifecycle
|
||||||
|
|
||||||
|
| Term | Definition | Aliases to avoid |
|
||||||
|
| ----------- | ------------------------------------------------------- | --------------------- |
|
||||||
|
| **Order** | A customer's request to purchase one or more items | Purchase, transaction |
|
||||||
|
| **Invoice** | A request for payment sent to a customer after delivery | Bill, payment request |
|
||||||
|
|
||||||
|
## People
|
||||||
|
|
||||||
|
| Term | Definition | Aliases to avoid |
|
||||||
|
| ------------ | ------------------------------------------- | ---------------------- |
|
||||||
|
| **Customer** | A person or organization that places orders | Client, buyer, account |
|
||||||
|
| **User** | An authentication identity in the system | Login, account |
|
||||||
|
|
||||||
|
## Relationships
|
||||||
|
|
||||||
|
- An **Invoice** belongs to exactly one **Customer**
|
||||||
|
- An **Order** produces one or more **Invoices**
|
||||||
|
|
||||||
|
## Example dialogue
|
||||||
|
|
||||||
|
> **Dev:** "When a **Customer** places an **Order**, do we create the **Invoice** immediately?"
|
||||||
|
> **Domain expert:** "No — an **Invoice** is only generated once a **Fulfillment** is confirmed. A single **Order** can produce multiple **Invoices** if items ship in separate **Shipments**."
|
||||||
|
> **Dev:** "So if a **Shipment** is cancelled before dispatch, no **Invoice** exists for it?"
|
||||||
|
> **Domain expert:** "Exactly. The **Invoice** lifecycle is tied to the **Fulfillment**, not the **Order**."
|
||||||
|
|
||||||
|
## Flagged ambiguities
|
||||||
|
|
||||||
|
- "account" was used to mean both **Customer** and **User** — these are distinct concepts: a **Customer** places orders, while a **User** is an authentication identity that may or may not represent a **Customer**.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Rules
|
||||||
|
|
||||||
|
- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others as aliases to avoid.
|
||||||
|
- **Flag conflicts explicitly.** If a term is used ambiguously in the conversation, call it out in the "Flagged ambiguities" section with a clear recommendation.
|
||||||
|
- **Only include terms relevant for domain experts.** Skip the names of modules or classes unless they have meaning in the domain language.
|
||||||
|
- **Keep definitions tight.** One sentence max. Define what it IS, not what it does.
|
||||||
|
- **Show relationships.** Use bold term names and express cardinality where obvious.
|
||||||
|
- **Only include domain terms.** Skip generic programming concepts (array, function, endpoint) unless they have domain-specific meaning.
|
||||||
|
- **Group terms into multiple tables** when natural clusters emerge (e.g. by subdomain, lifecycle, or actor). Each group gets its own heading and table. If all terms belong to a single cohesive domain, one table is fine — don't force groupings.
|
||||||
|
- **Write an example dialogue.** A short conversation (3-5 exchanges) between a dev and a domain expert that demonstrates how the terms interact naturally. The dialogue should clarify boundaries between related concepts and show terms being used precisely.
|
||||||
|
|
||||||
|
<example>
|
||||||
|
|
||||||
|
## Example dialogue
|
||||||
|
|
||||||
|
> **Dev:** "How do I test the **sync service** without Docker?"
|
||||||
|
|
||||||
|
> **Domain expert:** "Provide the **filesystem layer** instead of the **Docker layer**. It implements the same **Sandbox service** interface but uses a local directory as the **sandbox**."
|
||||||
|
|
||||||
|
> **Dev:** "So **sync-in** still creates a **bundle** and unpacks it?"
|
||||||
|
|
||||||
|
> **Domain expert:** "Exactly. The **sync service** doesn't know which layer it's talking to. It calls `exec` and `copyIn` — the **filesystem layer** just runs those as local shell commands."
|
||||||
|
|
||||||
|
</example>
|
||||||
|
|
||||||
|
## Re-running
|
||||||
|
|
||||||
|
When invoked again in the same conversation:
|
||||||
|
|
||||||
|
1. Read the existing `UBIQUITOUS_LANGUAGE.md`
|
||||||
|
2. Incorporate any new terms from subsequent discussion
|
||||||
|
3. Update definitions if understanding has evolved
|
||||||
|
4. Re-flag any new ambiguities
|
||||||
|
5. Rewrite the example dialogue to incorporate new terms
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
# AGENTS.md
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
workspace/
|
||||||
|
├── apps/
|
||||||
|
│ ├── 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
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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 mod tidy # clean go.mod/go.sum
|
||||||
|
|
||||||
|
# DB: /workspace/data/go-crm.db (hardcoded path — do not change)
|
||||||
|
# WhatsApp session: /workspace/data/whatsapp.db (hardcoded path)
|
||||||
|
```
|
||||||
|
|
||||||
|
### whatsapp-crm
|
||||||
|
```bash
|
||||||
|
cd apps/whatsapp-crm
|
||||||
|
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 (mocks qrcode-terminal + whatsapp-web.js)
|
||||||
|
```
|
||||||
|
|
||||||
|
### whatsapp-reader
|
||||||
|
```bash
|
||||||
|
cd apps/whatsapp-reader
|
||||||
|
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
|
||||||
|
|
||||||
|
# See apps/timesfm-forecast/README.md for CUDA/CPU wheel guidance
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Important Quirks
|
||||||
|
|
||||||
|
### 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
|
||||||
|
- Path alias `@/*` maps to `src/*`
|
||||||
|
|
||||||
|
### Testing mocks
|
||||||
|
- `whatsapp-sync` has manual mocks for `qrcode-terminal` and `whatsapp-web.js` in `tests/__mocks__/`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What to Avoid
|
||||||
|
|
||||||
|
- 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
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
root_dir = "."
|
||||||
|
tmp_dir = "tmp"
|
||||||
|
|
||||||
|
[build]
|
||||||
|
bin = "./tmp/main"
|
||||||
|
cmd = "go build -buildvcs=false -o ./tmp/main ."
|
||||||
|
delay = 2000
|
||||||
|
exclude_dir = ["assets", "tmp", "vendor", "data", "node_modules", ".git"]
|
||||||
|
exclude_file = []
|
||||||
|
exclude_regex = ["_test.go", "\\.db$", "\\.db-journal$", "\\.db-shm$", "\\.db-wal$"]
|
||||||
|
exclude_unchanged = true
|
||||||
|
follow_symlink = false
|
||||||
|
full_screen = false
|
||||||
|
include_dir = ["internal"]
|
||||||
|
include_ext = ["go", "templ"]
|
||||||
|
kill_delay = "2s"
|
||||||
|
log = "build-errors.toml"
|
||||||
|
send_exit = false
|
||||||
|
send_user = false
|
||||||
|
stop_on_error = true
|
||||||
|
|
||||||
|
[log]
|
||||||
|
main_only = false
|
||||||
|
time = false
|
||||||
|
|
||||||
|
[misc]
|
||||||
|
clean_on_exit = false
|
||||||
|
dao = "0x60"
|
||||||
|
force_kill = true
|
||||||
|
kill = true
|
||||||
|
restart = true
|
||||||
|
|
||||||
|
[screen]
|
||||||
|
clear_on_rebuild = false
|
||||||
|
extra_resize = false
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Binaries
|
||||||
|
/go-crm
|
||||||
|
/main
|
||||||
|
/migrate
|
||||||
|
/go-crm-test
|
||||||
|
*.exe
|
||||||
|
*.dll
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
|
|
||||||
|
# Build artifacts
|
||||||
|
tmp/
|
||||||
|
*.out
|
||||||
|
*.log
|
||||||
|
build-errors.*
|
||||||
|
|
||||||
|
# SQLite databases
|
||||||
|
data/
|
||||||
|
.dev-data/
|
||||||
|
*.db
|
||||||
|
*.db-journal
|
||||||
|
*.db-shm
|
||||||
|
*.db-wal
|
||||||
|
*.db.bak
|
||||||
|
|
||||||
|
# Test output
|
||||||
|
*.test
|
||||||
|
*.cover
|
||||||
|
*.cov
|
||||||
|
coverage/
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# WhatsApp session files (if ever synced here)
|
||||||
|
.wwebjs_auth/
|
||||||
|
.wwebjs_cache/
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
FROM archlinux:latest
|
||||||
|
|
||||||
|
RUN pacman -Syu --noconfirm && \
|
||||||
|
pacman -S --noconfirm \
|
||||||
|
go \
|
||||||
|
git \
|
||||||
|
sqlite \
|
||||||
|
curl \
|
||||||
|
nodejs \
|
||||||
|
npm \
|
||||||
|
chromium \
|
||||||
|
&& pacman -Scc --noconfirm
|
||||||
|
|
||||||
|
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
|
||||||
|
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
|
||||||
|
|
||||||
|
WORKDIR /tmp
|
||||||
|
|
||||||
|
RUN curl -sSL https://github.com/air-verse/air/releases/download/v1.27.10/air_1.27.10_linux_amd64.tar.gz | tar -xz && \
|
||||||
|
chmod +x air && \
|
||||||
|
mv air /usr/local/bin/air
|
||||||
|
|
||||||
|
WORKDIR /workspace/apps/go-crm
|
||||||
|
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
CMD ["air"]
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
services:
|
||||||
|
go-crm:
|
||||||
|
build: .
|
||||||
|
container_name: go-crm
|
||||||
|
ports:
|
||||||
|
- "8888:8080"
|
||||||
|
volumes:
|
||||||
|
- /home/ga/workspace:/workspace
|
||||||
|
- ./data:/workspace/data
|
||||||
|
networks:
|
||||||
|
- crm-network
|
||||||
|
working_dir: /workspace/apps/go-crm
|
||||||
|
command: air
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 2G
|
||||||
|
|
||||||
|
networks:
|
||||||
|
crm-network:
|
||||||
|
external: false
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
module go-crm
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/glebarez/go-sqlite v1.21.2
|
||||||
|
github.com/glebarez/sqlite v1.11.0
|
||||||
|
github.com/go-chi/chi/v5 v5.1.0
|
||||||
|
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 (
|
||||||
|
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/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/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
|
||||||
|
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
|
||||||
|
)
|
||||||
|
|
||||||
|
replace go.mau.eu/whatsmeow => go.mau.fi/whatsmeow v0.0.0-20260427122815-7514259253a7
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
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.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
|
||||||
|
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
|
||||||
|
github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
|
||||||
|
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
|
||||||
|
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/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-20260427122815-7514259253a7 h1:jEOI4I7kU+MYUNI1L94rhYXhUg8N9+YUNHVY525aYTc=
|
||||||
|
go.mau.fi/whatsmeow v0.0.0-20260427122815-7514259253a7/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/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=
|
||||||
|
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=
|
||||||
@@ -0,0 +1,804 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Client struct {
|
||||||
|
ClientID int64 `json:"client_id"`
|
||||||
|
AccountID int64 `json:"account_id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Phone string `json:"phone,omitempty"`
|
||||||
|
Email string `json:"email,omitempty"`
|
||||||
|
Address string `json:"address,omitempty"`
|
||||||
|
Notes string `json:"notes,omitempty"`
|
||||||
|
WhatsAppNumber string `json:"whatsapp_number,omitempty"`
|
||||||
|
WhatsAppConnected int `json:"whatsapp_connected"`
|
||||||
|
WhatsAppJID string `json:"whatsapp_jid,omitempty"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Customer struct {
|
||||||
|
CustomerID int64 `json:"customer_id"`
|
||||||
|
ClientID int64 `json:"client_id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Phone string `json:"phone,omitempty"`
|
||||||
|
BirthDate string `json:"birth_date,omitempty"`
|
||||||
|
Instagram string `json:"instagram,omitempty"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
WhatsAppConnected int `json:"whatsapp_connected"`
|
||||||
|
WhatsAppNumber string `json:"whatsapp_number,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
ServiceID int64 `json:"service_id"`
|
||||||
|
ClientID int64 `json:"client_id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Price float64 `json:"price,omitempty"`
|
||||||
|
Description string `json:"description,omitempty"`
|
||||||
|
Duration string `json:"duration,omitempty"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Schedule struct {
|
||||||
|
ScheduleID int64 `json:"schedule_id"`
|
||||||
|
ClientID int64 `json:"client_id"`
|
||||||
|
CustomerID int64 `json:"customer_id"`
|
||||||
|
ServiceID int64 `json:"service_id"`
|
||||||
|
PlanDate string `json:"plan_date,omitempty"`
|
||||||
|
Time string `json:"time,omitempty"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Payment struct {
|
||||||
|
PaymentID int64 `json:"payment_id"`
|
||||||
|
ClientID int64 `json:"client_id"`
|
||||||
|
CustomerID int64 `json:"customer_id"`
|
||||||
|
ScheduleID int64 `json:"schedule_id,omitempty"`
|
||||||
|
HasPaid bool `json:"has_paid"`
|
||||||
|
Amount float64 `json:"amount,omitempty"`
|
||||||
|
PaymentDate string `json:"payment_date,omitempty"`
|
||||||
|
PaymentMethod string `json:"payment_method,omitempty"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Create(db *sql.DB) error {
|
||||||
|
result, err := db.Exec(
|
||||||
|
"INSERT INTO clients (account_id, name, phone, email, address, notes, whatsapp_number, whatsapp_connected, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
c.AccountID, c.Name, c.Phone, c.Email, c.Address, c.Notes, c.WhatsAppNumber, c.WhatsAppConnected, c.CreatedAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id, err := result.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c.ClientID = id
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Read(db *sql.DB, id int64) error {
|
||||||
|
return db.QueryRow(
|
||||||
|
"SELECT client_id, account_id, name, COALESCE(phone,''), COALESCE(email,''), COALESCE(address,''), COALESCE(notes,''), COALESCE(whatsapp_number,''), COALESCE(whatsapp_connected,0), COALESCE(whatsapp_jid,''), created_at FROM clients WHERE client_id = ?",
|
||||||
|
id,
|
||||||
|
).Scan(&c.ClientID, &c.AccountID, &c.Name, &c.Phone, &c.Email, &c.Address, &c.Notes, &c.WhatsAppNumber, &c.WhatsAppConnected, &c.WhatsAppJID, &c.CreatedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Update(db *sql.DB) error {
|
||||||
|
_, err := db.Exec(
|
||||||
|
"UPDATE clients SET name = ?, phone = ?, email = ?, address = ?, notes = ?, whatsapp_number = ?, whatsapp_connected = ?, whatsapp_jid = ? WHERE client_id = ? AND account_id = ?",
|
||||||
|
c.Name, c.Phone, c.Email, c.Address, c.Notes, c.WhatsAppNumber, c.WhatsAppConnected, c.WhatsAppJID, c.ClientID, c.AccountID,
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Delete(db *sql.DB) error {
|
||||||
|
_, err := db.Exec("DELETE FROM clients WHERE client_id = ? AND account_id = ?", c.ClientID, c.AccountID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListClients(db *sql.DB, accountID int64, limit, offset int) ([]Client, error) {
|
||||||
|
query := "SELECT client_id, account_id, name, COALESCE(phone,''), COALESCE(email,''), COALESCE(address,''), COALESCE(notes,''), COALESCE(whatsapp_number,''), COALESCE(whatsapp_connected,0), COALESCE(whatsapp_jid,''), created_at FROM clients"
|
||||||
|
args := []interface{}{}
|
||||||
|
if accountID > 0 {
|
||||||
|
query += " WHERE account_id = ?"
|
||||||
|
args = append(args, accountID)
|
||||||
|
}
|
||||||
|
query += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
|
||||||
|
args = append(args, limit, offset)
|
||||||
|
|
||||||
|
rows, err := db.Query(query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var clients []Client
|
||||||
|
for rows.Next() {
|
||||||
|
var c Client
|
||||||
|
if err := rows.Scan(&c.ClientID, &c.AccountID, &c.Name, &c.Phone, &c.Email, &c.Address, &c.Notes, &c.WhatsAppNumber, &c.WhatsAppConnected, &c.WhatsAppJID, &c.CreatedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
clients = append(clients, c)
|
||||||
|
}
|
||||||
|
return clients, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetClientByID(db *sql.DB, accountID, id int64) (*Client, error) {
|
||||||
|
var c Client
|
||||||
|
err := db.QueryRow(
|
||||||
|
"SELECT client_id, account_id, name, COALESCE(phone,''), COALESCE(email,''), COALESCE(address,''), COALESCE(notes,''), COALESCE(whatsapp_number,''), COALESCE(whatsapp_connected,0), COALESCE(whatsapp_jid,''), created_at FROM clients WHERE client_id = ? AND account_id = ?",
|
||||||
|
id, accountID,
|
||||||
|
).Scan(&c.ClientID, &c.AccountID, &c.Name, &c.Phone, &c.Email, &c.Address, &c.Notes, &c.WhatsAppNumber, &c.WhatsAppConnected, &c.WhatsAppJID, &c.CreatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cu *Customer) Create(db *sql.DB) error {
|
||||||
|
result, err := db.Exec(
|
||||||
|
"INSERT INTO customers (client_id, name, phone, birth_date, instagram, created_at) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
cu.ClientID, cu.Name, cu.Phone, cu.BirthDate, cu.Instagram, cu.CreatedAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id, err := result.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
cu.CustomerID = id
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListCustomers(db *sql.DB, accountID, clientID int64, limit, offset int) ([]Customer, error) {
|
||||||
|
args := []interface{}{}
|
||||||
|
query := "SELECT customer_id, client_id, name, phone, birth_date, instagram, created_at FROM customers"
|
||||||
|
cond := ""
|
||||||
|
if clientID > 0 {
|
||||||
|
cond = "client_id = ?"
|
||||||
|
args = append(args, clientID)
|
||||||
|
}
|
||||||
|
if accountID > 0 {
|
||||||
|
if cond != "" {
|
||||||
|
cond += " AND "
|
||||||
|
}
|
||||||
|
cond += "client_id IN (SELECT client_id FROM clients WHERE account_id = ?)"
|
||||||
|
args = append(args, accountID)
|
||||||
|
}
|
||||||
|
if cond != "" {
|
||||||
|
query += " WHERE " + cond
|
||||||
|
}
|
||||||
|
query += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
|
||||||
|
args = append(args, limit, offset)
|
||||||
|
|
||||||
|
rows, err := db.Query(query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var customers []Customer
|
||||||
|
for rows.Next() {
|
||||||
|
var cu Customer
|
||||||
|
if err := rows.Scan(&cu.CustomerID, &cu.ClientID, &cu.Name, &cu.Phone, &cu.BirthDate, &cu.Instagram, &cu.CreatedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
customers = append(customers, cu)
|
||||||
|
}
|
||||||
|
return customers, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) Create(db *sql.DB) error {
|
||||||
|
result, err := db.Exec(
|
||||||
|
"INSERT INTO services (client_id, name, price, description, duration, created_at) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
s.ClientID, s.Name, s.Price, s.Description, s.Duration, s.CreatedAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id, err := result.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s.ServiceID = id
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListServices(db *sql.DB, accountID, clientID int64, limit, offset int) ([]Service, error) {
|
||||||
|
args := []interface{}{}
|
||||||
|
query := "SELECT service_id, client_id, name, price, description, duration, created_at FROM services"
|
||||||
|
cond := ""
|
||||||
|
if clientID > 0 {
|
||||||
|
cond = "client_id = ?"
|
||||||
|
args = append(args, clientID)
|
||||||
|
}
|
||||||
|
if accountID > 0 {
|
||||||
|
if cond != "" {
|
||||||
|
cond += " AND "
|
||||||
|
}
|
||||||
|
cond += "client_id IN (SELECT client_id FROM clients WHERE account_id = ?)"
|
||||||
|
args = append(args, accountID)
|
||||||
|
}
|
||||||
|
if cond != "" {
|
||||||
|
query += " WHERE " + cond
|
||||||
|
}
|
||||||
|
query += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
|
||||||
|
args = append(args, limit, offset)
|
||||||
|
|
||||||
|
rows, err := db.Query(query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var services []Service
|
||||||
|
for rows.Next() {
|
||||||
|
var s Service
|
||||||
|
if err := rows.Scan(&s.ServiceID, &s.ClientID, &s.Name, &s.Price, &s.Description, &s.Duration, &s.CreatedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
services = append(services, s)
|
||||||
|
}
|
||||||
|
return services, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (sch *Schedule) Create(db *sql.DB) error {
|
||||||
|
result, err := db.Exec(
|
||||||
|
"INSERT INTO scheduling (client_id, customer_id, service_id, plan_date, time, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
sch.ClientID, sch.CustomerID, sch.ServiceID, sch.PlanDate, sch.Time, sch.Status, sch.CreatedAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id, err := result.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sch.ScheduleID = id
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListSchedules(db *sql.DB, clientID, customerID int64, limit, offset int) ([]Schedule, error) {
|
||||||
|
query := "SELECT schedule_id, client_id, customer_id, service_id, plan_date, time, status, created_at FROM scheduling WHERE 1=1"
|
||||||
|
var args []interface{}
|
||||||
|
if clientID > 0 {
|
||||||
|
query += " AND client_id = ?"
|
||||||
|
args = append(args, clientID)
|
||||||
|
}
|
||||||
|
if customerID > 0 {
|
||||||
|
query += " AND customer_id = ?"
|
||||||
|
args = append(args, customerID)
|
||||||
|
}
|
||||||
|
query += " ORDER BY plan_date DESC LIMIT ? OFFSET ?"
|
||||||
|
args = append(args, limit, offset)
|
||||||
|
|
||||||
|
rows, err := db.Query(query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var schedules []Schedule
|
||||||
|
for rows.Next() {
|
||||||
|
var sch Schedule
|
||||||
|
if err := rows.Scan(&sch.ScheduleID, &sch.ClientID, &sch.CustomerID, &sch.ServiceID, &sch.PlanDate, &sch.Time, &sch.Status, &sch.CreatedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
schedules = append(schedules, sch)
|
||||||
|
}
|
||||||
|
return schedules, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Payment) Create(db *sql.DB) error {
|
||||||
|
result, err := db.Exec(
|
||||||
|
"INSERT INTO payments (client_id, customer_id, schedule_id, has_paid, amount, payment_date, payment_method, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
p.ClientID, p.CustomerID, p.ScheduleID, boolToInt(p.HasPaid), p.Amount, p.PaymentDate, p.PaymentMethod, p.CreatedAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id, err := result.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.PaymentID = id
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListPayments(db *sql.DB, clientID int64, limit, offset int) ([]Payment, error) {
|
||||||
|
query := "SELECT payment_id, client_id, customer_id, schedule_id, has_paid, amount, payment_date, payment_method, created_at FROM payments"
|
||||||
|
var args []interface{}
|
||||||
|
if clientID > 0 {
|
||||||
|
query += " WHERE client_id = ?"
|
||||||
|
args = append(args, clientID)
|
||||||
|
}
|
||||||
|
query += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
|
||||||
|
args = append(args, limit, offset)
|
||||||
|
|
||||||
|
rows, err := db.Query(query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var payments []Payment
|
||||||
|
for rows.Next() {
|
||||||
|
var p Payment
|
||||||
|
var hasPaid int
|
||||||
|
if err := rows.Scan(&p.PaymentID, &p.ClientID, &p.CustomerID, &p.ScheduleID, &hasPaid, &p.Amount, &p.PaymentDate, &p.PaymentMethod, &p.CreatedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
p.HasPaid = hasPaid == 1
|
||||||
|
payments = append(payments, p)
|
||||||
|
}
|
||||||
|
return payments, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func boolToInt(b bool) int {
|
||||||
|
if b {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Lead
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
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"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func CreateLead(db *sql.DB, l *Lead) error {
|
||||||
|
now := time.Now().Unix()
|
||||||
|
l.CreatedAt = now
|
||||||
|
l.LastContactAt = now
|
||||||
|
result, err := db.Exec(
|
||||||
|
`INSERT INTO leads
|
||||||
|
(client_id, name, phone_raw, phone_normalized, service_interest, status, needs_review,
|
||||||
|
appointment_date, appointment_time, payment_status, payment_amount, payment_date, created_at, last_contact_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
|
l.ClientID, l.Name, l.PhoneRaw, l.PhoneNormalized, l.ServiceInterest, l.Status, boolToInt(l.NeedsReview),
|
||||||
|
l.AppointmentDate, l.AppointmentTime, l.PaymentStatus, l.PaymentAmount, l.PaymentDate,
|
||||||
|
l.CreatedAt, l.LastContactAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id, err := result.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
l.LeadID = id
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetLeadByPhone(db *sql.DB, clientID int64, phoneNormalized string) (*Lead, error) {
|
||||||
|
var l Lead
|
||||||
|
var needsReview int
|
||||||
|
err := db.QueryRow(
|
||||||
|
`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 = ? AND phone_normalized = ?`,
|
||||||
|
clientID, phoneNormalized,
|
||||||
|
).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,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
l.NeedsReview = needsReview == 1
|
||||||
|
return &l, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetLeadByID(db *sql.DB, clientID, leadID int64) (*Lead, error) {
|
||||||
|
var l Lead
|
||||||
|
var needsReview int
|
||||||
|
err := db.QueryRow(
|
||||||
|
`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 lead_id = ? AND client_id = ?`,
|
||||||
|
leadID, clientID,
|
||||||
|
).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,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
l.NeedsReview = needsReview == 1
|
||||||
|
return &l, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TouchLeadContact(db *sql.DB, leadID int64) error {
|
||||||
|
_, err := db.Exec(
|
||||||
|
"UPDATE leads SET last_contact_at = ? WHERE lead_id = ?",
|
||||||
|
time.Now().Unix(), leadID,
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateLead(db *sql.DB, l *Lead) error {
|
||||||
|
_, err := db.Exec(
|
||||||
|
`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=?`,
|
||||||
|
l.Name, l.ServiceInterest, l.Status, boolToInt(l.NeedsReview),
|
||||||
|
l.AppointmentDate, l.AppointmentTime, l.PaymentStatus, l.PaymentAmount, l.PaymentDate,
|
||||||
|
l.LeadID, l.ClientID,
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListLeadsForReview(db *sql.DB, clientID int64, limit, offset int) ([]Lead, error) {
|
||||||
|
rows, err := db.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 = ? AND needs_review = 1
|
||||||
|
ORDER BY created_at DESC LIMIT ? OFFSET ?`,
|
||||||
|
clientID, limit, offset,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
return scanLeads(rows)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListAllLeads(db *sql.DB, clientID int64, limit, offset int) ([]Lead, error) {
|
||||||
|
rows, err := db.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 ?`,
|
||||||
|
clientID, limit, offset,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
return scanLeads(rows)
|
||||||
|
}
|
||||||
|
|
||||||
|
func CountLeadsNeedingReview(db *sql.DB, clientID int64) (int, error) {
|
||||||
|
var n int
|
||||||
|
err := db.QueryRow(
|
||||||
|
"SELECT COUNT(*) FROM leads WHERE client_id = ? AND needs_review = 1",
|
||||||
|
clientID,
|
||||||
|
).Scan(&n)
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanLeads(rows *sql.Rows) ([]Lead, error) {
|
||||||
|
var leads []Lead
|
||||||
|
for rows.Next() {
|
||||||
|
var l 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, err
|
||||||
|
}
|
||||||
|
l.NeedsReview = needsReview == 1
|
||||||
|
leads = append(leads, l)
|
||||||
|
}
|
||||||
|
return leads, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// ServiceKeyword
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
type ServiceKeyword struct {
|
||||||
|
KeywordID int64 `json:"keyword_id"`
|
||||||
|
ClientID int64 `json:"client_id"`
|
||||||
|
ServiceName string `json:"service_name"`
|
||||||
|
Keyword string `json:"keyword"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListServiceKeywords(db *sql.DB, clientID int64) ([]ServiceKeyword, error) {
|
||||||
|
rows, err := db.Query(
|
||||||
|
"SELECT keyword_id, client_id, service_name, keyword, created_at FROM service_keywords WHERE client_id = ? ORDER BY service_name, keyword",
|
||||||
|
clientID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var kws []ServiceKeyword
|
||||||
|
for rows.Next() {
|
||||||
|
var kw ServiceKeyword
|
||||||
|
if err := rows.Scan(&kw.KeywordID, &kw.ClientID, &kw.ServiceName, &kw.Keyword, &kw.CreatedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
kws = append(kws, kw)
|
||||||
|
}
|
||||||
|
return kws, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadKeywordMapping(db *sql.DB, clientID int64) (map[string]string, error) {
|
||||||
|
kws, err := ListServiceKeywords(db, clientID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
m := make(map[string]string, len(kws))
|
||||||
|
for _, kw := range kws {
|
||||||
|
m[kw.Keyword] = kw.ServiceName
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddServiceKeyword(db *sql.DB, clientID int64, serviceName, keyword string) error {
|
||||||
|
_, err := db.Exec(
|
||||||
|
"INSERT INTO service_keywords (client_id, service_name, keyword, created_at) VALUES (?, ?, ?, ?)",
|
||||||
|
clientID, serviceName, keyword, time.Now().Unix(),
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeleteServiceKeyword(db *sql.DB, clientID, keywordID int64) error {
|
||||||
|
_, err := db.Exec(
|
||||||
|
"DELETE FROM service_keywords WHERE keyword_id = ? AND client_id = ?",
|
||||||
|
keywordID, clientID,
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// LeadStatus
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
type LeadStatus struct {
|
||||||
|
StatusID int64 `json:"status_id"`
|
||||||
|
ClientID int64 `json:"client_id"`
|
||||||
|
StatusName string `json:"status_name"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListLeadStatuses(db *sql.DB, clientID int64) ([]LeadStatus, error) {
|
||||||
|
rows, err := db.Query(
|
||||||
|
"SELECT status_id, client_id, status_name, created_at FROM lead_statuses WHERE client_id = ? ORDER BY created_at",
|
||||||
|
clientID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var statuses []LeadStatus
|
||||||
|
for rows.Next() {
|
||||||
|
var s LeadStatus
|
||||||
|
if err := rows.Scan(&s.StatusID, &s.ClientID, &s.StatusName, &s.CreatedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
statuses = append(statuses, s)
|
||||||
|
}
|
||||||
|
return statuses, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddLeadStatus(db *sql.DB, clientID int64, statusName string) error {
|
||||||
|
_, err := db.Exec(
|
||||||
|
"INSERT INTO lead_statuses (client_id, status_name, created_at) VALUES (?, ?, ?)",
|
||||||
|
clientID, statusName, time.Now().Unix(),
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeleteLeadStatus(db *sql.DB, clientID, statusID int64) error {
|
||||||
|
_, err := db.Exec(
|
||||||
|
"DELETE FROM lead_statuses WHERE status_id = ? AND client_id = ?",
|
||||||
|
statusID, clientID,
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
type Question struct {
|
||||||
|
QuestionID int64 `json:"question_id"`
|
||||||
|
ClientID int64 `json:"client_id"`
|
||||||
|
CustomerID int64 `json:"customer_id"`
|
||||||
|
Question string `json:"question"`
|
||||||
|
Timestamp int64 `json:"timestamp"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Question) Create(db *sql.DB) error {
|
||||||
|
result, err := db.Exec(
|
||||||
|
"INSERT INTO questions (client_id, customer_id, question, timestamp, status, created_at) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
q.ClientID, q.CustomerID, q.Question, q.Timestamp, q.Status, q.CreatedAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id, err := result.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
q.QuestionID = id
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListQuestions(db *sql.DB, clientID int64, limit, offset int) ([]Question, error) {
|
||||||
|
query := "SELECT question_id, client_id, customer_id, question, timestamp, status, created_at FROM questions WHERE 1=1"
|
||||||
|
var args []interface{}
|
||||||
|
if clientID > 0 {
|
||||||
|
query += " AND client_id = ?"
|
||||||
|
args = append(args, clientID)
|
||||||
|
}
|
||||||
|
query += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
|
||||||
|
args = append(args, limit, offset)
|
||||||
|
|
||||||
|
rows, err := db.Query(query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var questions []Question
|
||||||
|
for rows.Next() {
|
||||||
|
var q Question
|
||||||
|
if err := rows.Scan(&q.QuestionID, &q.ClientID, &q.CustomerID, &q.Question, &q.Timestamp, &q.Status, &q.CreatedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
questions = append(questions, q)
|
||||||
|
}
|
||||||
|
return questions, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
type Answer struct {
|
||||||
|
AnswerID int64 `json:"answer_id"`
|
||||||
|
ClientID int64 `json:"client_id"`
|
||||||
|
QuestionID int64 `json:"question_id"`
|
||||||
|
Answer string `json:"answer"`
|
||||||
|
Timestamp int64 `json:"timestamp"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Answer) Create(db *sql.DB) error {
|
||||||
|
result, err := db.Exec(
|
||||||
|
"INSERT INTO answers (client_id, question_id, answer, timestamp, status, created_at) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
a.ClientID, a.QuestionID, a.Answer, a.Timestamp, a.Status, a.CreatedAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id, err := result.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.AnswerID = id
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListAnswers(db *sql.DB, questionID int64, limit, offset int) ([]Answer, error) {
|
||||||
|
query := "SELECT answer_id, client_id, question_id, answer, timestamp, status, created_at FROM answers WHERE 1=1"
|
||||||
|
var args []interface{}
|
||||||
|
if questionID > 0 {
|
||||||
|
query += " AND question_id = ?"
|
||||||
|
args = append(args, questionID)
|
||||||
|
}
|
||||||
|
query += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
|
||||||
|
args = append(args, limit, offset)
|
||||||
|
|
||||||
|
rows, err := db.Query(query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var answers []Answer
|
||||||
|
for rows.Next() {
|
||||||
|
var a Answer
|
||||||
|
if err := rows.Scan(&a.AnswerID, &a.ClientID, &a.QuestionID, &a.Answer, &a.Timestamp, &a.Status, &a.CreatedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
answers = append(answers, a)
|
||||||
|
}
|
||||||
|
return answers, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
type AnswerWithDetails struct {
|
||||||
|
AnswerID int64 `json:"answer_id"`
|
||||||
|
ClientID int64 `json:"client_id"`
|
||||||
|
QuestionID int64 `json:"question_id"`
|
||||||
|
Answer string `json:"answer"`
|
||||||
|
Timestamp int64 `json:"timestamp"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
ClientName string `json:"client_name"`
|
||||||
|
CustomerName string `json:"customer_name"`
|
||||||
|
QuestionText string `json:"question_text"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListAnswersWithDetails(db *sql.DB, accountID, questionID int64, limit, offset int) ([]AnswerWithDetails, error) {
|
||||||
|
args := []interface{}{accountID}
|
||||||
|
query := `
|
||||||
|
SELECT
|
||||||
|
a.answer_id, a.client_id, a.question_id, a.answer, a.timestamp, a.status, a.created_at,
|
||||||
|
c.name as client_name,
|
||||||
|
cu.name as customer_name,
|
||||||
|
q.question as question_text
|
||||||
|
FROM answers a
|
||||||
|
JOIN questions q ON a.question_id = q.question_id
|
||||||
|
JOIN customers cu ON q.customer_id = cu.customer_id
|
||||||
|
JOIN clients c ON q.client_id = c.client_id
|
||||||
|
WHERE c.account_id = ?`
|
||||||
|
if questionID > 0 {
|
||||||
|
query += " AND a.question_id = ?"
|
||||||
|
args = append(args, questionID)
|
||||||
|
}
|
||||||
|
query += " ORDER BY a.created_at DESC LIMIT ? OFFSET ?"
|
||||||
|
args = append(args, limit, offset)
|
||||||
|
|
||||||
|
rows, err := db.Query(query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var answers []AnswerWithDetails
|
||||||
|
for rows.Next() {
|
||||||
|
var a AnswerWithDetails
|
||||||
|
if err := rows.Scan(&a.AnswerID, &a.ClientID, &a.QuestionID, &a.Answer, &a.Timestamp, &a.Status, &a.CreatedAt, &a.ClientName, &a.CustomerName, &a.QuestionText); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
answers = append(answers, a)
|
||||||
|
}
|
||||||
|
return answers, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Processed Messages (dedup)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func IsMessageProcessed(db *sql.DB, clientID int64, messageID string) (bool, error) {
|
||||||
|
var count int
|
||||||
|
err := db.QueryRow(
|
||||||
|
`SELECT COUNT(*) FROM processed_messages WHERE client_id = ? AND message_id = ?`,
|
||||||
|
clientID, messageID,
|
||||||
|
).Scan(&count)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return count > 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func RecordProcessedMessage(db *sql.DB, clientID int64, messageID string) error {
|
||||||
|
_, err := db.Exec(
|
||||||
|
`INSERT OR IGNORE INTO processed_messages (message_id, client_id) VALUES (?, ?)`,
|
||||||
|
messageID, clientID,
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestClientWhatsAppColumns(t *testing.T) {
|
||||||
|
tmpfile, err := os.CreateTemp("", "test_*.db")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer os.Remove(tmpfile.Name())
|
||||||
|
tmpfile.Close()
|
||||||
|
|
||||||
|
db, err := Init(tmpfile.Name())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to init db: %v", err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
client := Client{
|
||||||
|
AccountID: 1,
|
||||||
|
Name: "Test Client",
|
||||||
|
Phone: "+5521987654321",
|
||||||
|
WhatsAppNumber: "+5521987654321",
|
||||||
|
WhatsAppConnected: 1,
|
||||||
|
CreatedAt: 1234567890,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := client.Create(db); err != nil {
|
||||||
|
t.Fatalf("failed to create client: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if client.ClientID == 0 {
|
||||||
|
t.Error("expected client_id to be set after create")
|
||||||
|
}
|
||||||
|
|
||||||
|
var found Client
|
||||||
|
if err := found.Read(db, client.ClientID); err != nil {
|
||||||
|
t.Fatalf("failed to read client: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if found.WhatsAppNumber != "+5521987654321" {
|
||||||
|
t.Errorf("expected whatsapp_number to be +5521987654321, got %s", found.WhatsAppNumber)
|
||||||
|
}
|
||||||
|
|
||||||
|
if found.WhatsAppConnected != 1 {
|
||||||
|
t.Errorf("expected whatsapp_connected to be 1, got %d", found.WhatsAppConnected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClientWhatsAppColumnsNullable(t *testing.T) {
|
||||||
|
tmpfile, err := os.CreateTemp("", "test_*.db")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer os.Remove(tmpfile.Name())
|
||||||
|
tmpfile.Close()
|
||||||
|
|
||||||
|
db, err := Init(tmpfile.Name())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to init db: %v", err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
client := Client{
|
||||||
|
AccountID: 1,
|
||||||
|
Name: "Test Client",
|
||||||
|
Phone: "+5521987654321",
|
||||||
|
CreatedAt: 1234567890,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := client.Create(db); err != nil {
|
||||||
|
t.Fatalf("failed to create client: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var found Client
|
||||||
|
if err := found.Read(db, client.ClientID); err != nil {
|
||||||
|
t.Fatalf("failed to read client: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if found.WhatsAppNumber != "" {
|
||||||
|
t.Errorf("expected whatsapp_number to be empty, got %s", found.WhatsAppNumber)
|
||||||
|
}
|
||||||
|
|
||||||
|
if found.WhatsAppConnected != 0 {
|
||||||
|
t.Errorf("expected whatsapp_connected to default to 0, got %d", found.WhatsAppConnected)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,395 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"golang.org/x/text/encoding/charmap"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
_ "github.com/glebarez/sqlite"
|
||||||
|
)
|
||||||
|
|
||||||
|
const schema = `
|
||||||
|
CREATE TABLE IF NOT EXISTS accounts (
|
||||||
|
account_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
email TEXT UNIQUE NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
password TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
session_id TEXT PRIMARY KEY,
|
||||||
|
account_id INTEGER NOT NULL,
|
||||||
|
expires INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (account_id) REFERENCES accounts(account_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS clients (
|
||||||
|
client_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
account_id INTEGER NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
phone TEXT,
|
||||||
|
email TEXT,
|
||||||
|
address TEXT,
|
||||||
|
notes TEXT,
|
||||||
|
whatsapp_number TEXT,
|
||||||
|
whatsapp_connected INTEGER DEFAULT 0,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
whatsapp_jid TEXT,
|
||||||
|
FOREIGN KEY (account_id) REFERENCES accounts(account_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS customers (
|
||||||
|
customer_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
client_id INTEGER NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
phone TEXT,
|
||||||
|
birth_date TEXT,
|
||||||
|
instagram TEXT,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients(client_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS services (
|
||||||
|
service_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
client_id INTEGER NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
price REAL,
|
||||||
|
description TEXT,
|
||||||
|
duration TEXT,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients(client_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS scheduling (
|
||||||
|
schedule_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
client_id INTEGER NOT NULL,
|
||||||
|
customer_id INTEGER NOT NULL,
|
||||||
|
service_id INTEGER NOT NULL,
|
||||||
|
plan_date TEXT,
|
||||||
|
time TEXT,
|
||||||
|
status TEXT DEFAULT 'pending',
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients(client_id),
|
||||||
|
FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
|
||||||
|
FOREIGN KEY (service_id) REFERENCES services(service_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS payments (
|
||||||
|
payment_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
client_id INTEGER NOT NULL,
|
||||||
|
customer_id INTEGER NOT NULL,
|
||||||
|
schedule_id INTEGER,
|
||||||
|
has_paid INTEGER DEFAULT 0,
|
||||||
|
amount REAL,
|
||||||
|
payment_date TEXT,
|
||||||
|
payment_method TEXT,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients(client_id),
|
||||||
|
FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
|
||||||
|
FOREIGN KEY (schedule_id) REFERENCES scheduling(schedule_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS questions (
|
||||||
|
question_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
client_id INTEGER NOT NULL,
|
||||||
|
customer_id INTEGER NOT NULL,
|
||||||
|
question TEXT NOT NULL,
|
||||||
|
timestamp INTEGER NOT NULL,
|
||||||
|
status TEXT DEFAULT 'pending',
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients(client_id),
|
||||||
|
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS answers (
|
||||||
|
answer_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
client_id INTEGER NOT NULL,
|
||||||
|
question_id INTEGER NOT NULL,
|
||||||
|
answer TEXT NOT NULL,
|
||||||
|
timestamp INTEGER NOT NULL,
|
||||||
|
status TEXT DEFAULT 'active',
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients(client_id),
|
||||||
|
FOREIGN KEY (question_id) REFERENCES questions(question_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS leads (
|
||||||
|
lead_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
client_id INTEGER NOT NULL,
|
||||||
|
name TEXT NOT NULL DEFAULT '',
|
||||||
|
phone_raw TEXT NOT NULL DEFAULT '',
|
||||||
|
phone_normalized TEXT NOT NULL DEFAULT '',
|
||||||
|
service_interest TEXT NOT NULL DEFAULT 'Não especificou',
|
||||||
|
status TEXT NOT NULL DEFAULT 'Não agendou',
|
||||||
|
needs_review INTEGER NOT NULL DEFAULT 1,
|
||||||
|
appointment_date TEXT,
|
||||||
|
appointment_time TEXT,
|
||||||
|
payment_status TEXT NOT NULL DEFAULT 'Não pago',
|
||||||
|
payment_amount REAL,
|
||||||
|
payment_date TEXT,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
last_contact_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients(client_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS processed_messages (
|
||||||
|
message_id TEXT NOT NULL,
|
||||||
|
client_id INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (message_id, client_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS service_keywords (
|
||||||
|
keyword_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
client_id INTEGER NOT NULL,
|
||||||
|
service_name TEXT NOT NULL,
|
||||||
|
keyword TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients(client_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS lead_statuses (
|
||||||
|
status_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
client_id INTEGER NOT NULL,
|
||||||
|
status_name TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (client_id) REFERENCES clients(client_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
`
|
||||||
|
|
||||||
|
var dbPath = "data/go-crm.db"
|
||||||
|
|
||||||
|
func Init(path string) (*sql.DB, error) {
|
||||||
|
if path != "" {
|
||||||
|
dbPath = path
|
||||||
|
}
|
||||||
|
|
||||||
|
dir := filepath.Dir(dbPath)
|
||||||
|
fmt.Println("db.Init: data dir", dir)
|
||||||
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create data directory: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
dsn := fmt.Sprintf("file:%s?mode=rwc&_pragma=encoding(UTF8)", filepath.ToSlash(dbPath))
|
||||||
|
fmt.Println("db.Init: opening database", dbPath)
|
||||||
|
database, err := sql.Open("sqlite", dsn)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to open database: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("db.Init: ping database")
|
||||||
|
if err := database.Ping(); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to ping database: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("db.Init: executing schema")
|
||||||
|
if _, err := database.Exec(schema); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create schema: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("db.Init: running migrate")
|
||||||
|
if err := migrate(database); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to migrate: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("db.Init: migration complete")
|
||||||
|
return database, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrate(db *sql.DB) error {
|
||||||
|
fmt.Println("db.migrate: add account_id column")
|
||||||
|
_, err := db.Exec("ALTER TABLE clients ADD COLUMN account_id INTEGER")
|
||||||
|
if err != nil {
|
||||||
|
if !strings.Contains(err.Error(), "duplicate column name") {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("db.migrate: add whatsapp_number column")
|
||||||
|
_, err = db.Exec("ALTER TABLE clients ADD COLUMN whatsapp_number TEXT")
|
||||||
|
if err != nil {
|
||||||
|
if !strings.Contains(err.Error(), "duplicate column name") {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("db.migrate: add whatsapp_connected column")
|
||||||
|
_, err = db.Exec("ALTER TABLE clients ADD COLUMN whatsapp_connected INTEGER DEFAULT 0")
|
||||||
|
if err != nil {
|
||||||
|
if !strings.Contains(err.Error(), "duplicate column name") {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("db.migrate: add whatsapp_jid column")
|
||||||
|
_, err = db.Exec("ALTER TABLE clients ADD COLUMN whatsapp_jid TEXT")
|
||||||
|
if err != nil {
|
||||||
|
if !strings.Contains(err.Error(), "duplicate column name") {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("db.migrate: seeding default keywords")
|
||||||
|
// Seed default service keywords per client if none exist yet.
|
||||||
|
if err := seedDefaultKeywords(db); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("db.migrate: seeding default statuses")
|
||||||
|
// Seed default lead statuses per client if none exist yet.
|
||||||
|
if err := seedDefaultStatuses(db); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("db.migrate: sanitizing encodings")
|
||||||
|
// Sanitize mojibake from legacy data: decode Latin1->UTF8
|
||||||
|
if err := sanitizeEncoding(db); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedDefaultKeywords(db *sql.DB) error {
|
||||||
|
fmt.Println("seedDefaultKeywords: querying clients")
|
||||||
|
// Fetch all client IDs.
|
||||||
|
rows, err := db.Query("SELECT client_id FROM clients")
|
||||||
|
if err != nil {
|
||||||
|
return nil // table may not exist yet on very first run — ignore
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
defaults := map[string][]string{
|
||||||
|
"Head Spa": {"head spa", "head-spa", "headspa"},
|
||||||
|
"Massagem completa": {"massagem", "massagem completa"},
|
||||||
|
"Drenagem linfatica": {"drenagem", "linfática", "linfahtica", "drenagem linfatica"},
|
||||||
|
"Hydra Boost": {"hydra", "hydra boost", "hydraboost"},
|
||||||
|
"Design Henna": {"henna", "design henna"},
|
||||||
|
"Masculino": {"masculino", "masc"},
|
||||||
|
"Não especificou": {"nao especificou", "não especificou"},
|
||||||
|
}
|
||||||
|
|
||||||
|
now := int64(0)
|
||||||
|
for rows.Next() {
|
||||||
|
var clientID int64
|
||||||
|
if err := rows.Scan(&clientID); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fmt.Println("seedDefaultKeywords: client", clientID)
|
||||||
|
var count int
|
||||||
|
db.QueryRow("SELECT COUNT(*) FROM service_keywords WHERE client_id = ?", clientID).Scan(&count)
|
||||||
|
if count > 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for svc, keywords := range defaults {
|
||||||
|
for _, kw := range keywords {
|
||||||
|
db.Exec(
|
||||||
|
"INSERT INTO service_keywords (client_id, service_name, keyword, created_at) VALUES (?, ?, ?, ?)",
|
||||||
|
clientID, svc, kw, now,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedDefaultStatuses(db *sql.DB) error {
|
||||||
|
rows, err := db.Query("SELECT client_id FROM clients")
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
defaults := []string{"Não agendou", "Agendou", "Sem retorno / não evoluiu"}
|
||||||
|
now := int64(0)
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var clientID int64
|
||||||
|
if err := rows.Scan(&clientID); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
db.QueryRow("SELECT COUNT(*) FROM lead_statuses WHERE client_id = ?", clientID).Scan(&count)
|
||||||
|
if count > 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, s := range defaults {
|
||||||
|
db.Exec(
|
||||||
|
"INSERT INTO lead_statuses (client_id, status_name, created_at) VALUES (?, ?, ?)",
|
||||||
|
clientID, s, now,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func sanitizeEncoding(db *sql.DB) error {
|
||||||
|
type statusRow struct {
|
||||||
|
id int64
|
||||||
|
name string
|
||||||
|
created int64
|
||||||
|
}
|
||||||
|
type keywordRow struct {
|
||||||
|
id int64
|
||||||
|
keyword string
|
||||||
|
created int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read all statuses first, then update to avoid SQLite read/write deadlock.
|
||||||
|
var statuses []statusRow
|
||||||
|
if rows, err := db.Query("SELECT status_id, status_name, created_at FROM lead_statuses"); err == nil {
|
||||||
|
for rows.Next() {
|
||||||
|
var r statusRow
|
||||||
|
if err := rows.Scan(&r.id, &r.name, &r.created); err == nil && r.created != 0 {
|
||||||
|
statuses = append(statuses, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
}
|
||||||
|
for _, r := range statuses {
|
||||||
|
cleaned := decodeLatin1(r.name)
|
||||||
|
if cleaned != r.name {
|
||||||
|
db.Exec("UPDATE lead_statuses SET status_name = ? WHERE status_id = ?", cleaned, r.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read all keywords first, then update.
|
||||||
|
var keywords []keywordRow
|
||||||
|
if rows2, err := db.Query("SELECT keyword_id, keyword, created_at FROM service_keywords"); err == nil {
|
||||||
|
for rows2.Next() {
|
||||||
|
var r keywordRow
|
||||||
|
if err := rows2.Scan(&r.id, &r.keyword, &r.created); err == nil && r.created != 0 {
|
||||||
|
keywords = append(keywords, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows2.Close()
|
||||||
|
}
|
||||||
|
for _, r := range keywords {
|
||||||
|
cleaned := decodeLatin1(r.keyword)
|
||||||
|
if cleaned != r.keyword {
|
||||||
|
db.Exec("UPDATE service_keywords SET keyword = ? WHERE keyword_id = ?", cleaned, r.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeLatin1(value string) string {
|
||||||
|
if utf8.ValidString(value) {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
dec := charmap.ISO8859_1.NewDecoder()
|
||||||
|
cleaned := value
|
||||||
|
for {
|
||||||
|
next, err := dec.String(cleaned)
|
||||||
|
if err != nil || next == cleaned {
|
||||||
|
return cleaned
|
||||||
|
}
|
||||||
|
cleaned = next
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Sign Up</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Sign Up</h1>
|
||||||
|
<form method="POST" action="/auth/signup">
|
||||||
|
<input type="email" name="email" placeholder="Email" required>
|
||||||
|
<input type="text" name="name" placeholder="Name" required>
|
||||||
|
<input type="password" name="password" placeholder="Password" required>
|
||||||
|
<button type="submit">Sign Up</button>
|
||||||
|
</form>
|
||||||
|
<p>Already have an account? <a href="/auth/login">Login</a></p>
|
||||||
|
</body>
|
||||||
|
</html>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) Signup(w http.ResponseWriter, r *http.Request) {
|
||||||
|
r.ParseForm()
|
||||||
|
email := r.FormValue("email")
|
||||||
|
name := r.FormValue("name")
|
||||||
|
password := r.FormValue("password")
|
||||||
|
|
||||||
|
if email == "" || name == "" || password == "" {
|
||||||
|
http.Error(w, "All fields required", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Failed to hash password", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 = tx.Exec(
|
||||||
|
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||||
|
email, name, string(hashedPassword), time.Now().Unix(),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Email already exists", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var accountID int64
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err = tx.Exec(
|
||||||
|
"INSERT INTO clients (account_id, name, created_at) VALUES (?, ?, ?)",
|
||||||
|
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()
|
||||||
|
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 (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>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Login</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Login</h1>
|
||||||
|
<form method="POST" action="/auth/login">
|
||||||
|
<input type="email" name="email" placeholder="Email" required>
|
||||||
|
<input type="password" name="password" placeholder="Password" required>
|
||||||
|
<button type="submit">Login</button>
|
||||||
|
</form>
|
||||||
|
<p>Don't have an account? <a href="/auth/signup">Sign Up</a></p>
|
||||||
|
</body>
|
||||||
|
</html>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
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 := 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
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)); err != nil {
|
||||||
|
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
sessionID := generateSessionID()
|
||||||
|
expires := time.Now().Add(24 * time.Hour).Unix()
|
||||||
|
|
||||||
|
_, 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
|
||||||
|
}
|
||||||
|
|
||||||
|
http.SetCookie(w, &http.Cookie{Name: "session", Value: sessionID, Path: "/"})
|
||||||
|
http.Redirect(w, r, "/", http.StatusFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) Logout(w http.ResponseWriter, r *http.Request) {
|
||||||
|
cookie, err := r.Cookie("session")
|
||||||
|
if err == nil {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
func randomString(n int) string {
|
||||||
|
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||||
|
b := make([]byte, n)
|
||||||
|
for i := range b {
|
||||||
|
b[i] = letters[time.Now().UnixNano()%int64(len(letters))]
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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.
|
||||||
|
|
||||||
|
func SignupPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
a := &App{DB: DB, WAConnector: WAConnector}
|
||||||
|
a.SignupPage(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Signup(w http.ResponseWriter, r *http.Request) {
|
||||||
|
a := &App{DB: DB, WAConnector: WAConnector}
|
||||||
|
a.Signup(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoginPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
a := &App{DB: DB, WAConnector: WAConnector}
|
||||||
|
a.LoginPage(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Login(w http.ResponseWriter, r *http.Request) {
|
||||||
|
a := &App{DB: DB, WAConnector: WAConnector}
|
||||||
|
a.Login(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
a := &App{DB: DB, WAConnector: WAConnector}
|
||||||
|
a.AccountPage(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateAccount(w http.ResponseWriter, r *http.Request) {
|
||||||
|
a := &App{DB: DB, WAConnector: WAConnector}
|
||||||
|
a.UpdateAccount(w, r)
|
||||||
|
}
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-crm/internal/db"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (a *App) ListClients(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||||
|
if limit == 0 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
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; charset=utf-8")
|
||||||
|
w.Write([]byte(`<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Clients</title>
|
||||||
|
<script src="https://unpkg.com/[email protected]"></script>
|
||||||
|
<style>
|
||||||
|
.edit-form { display:none; margin-top:0.5rem; padding:0.5rem; border:1px solid #ccc; }
|
||||||
|
.edit-row { display:none; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Clients</h1>
|
||||||
|
<button class="btn" onclick="document.getElementById('clientForm').style.display='block'">Add Client</button>
|
||||||
|
<div id="clientForm" style="display:none; margin-top:1rem;">
|
||||||
|
<form hx-post="/clients" hx-target="#clientList" hx-swap="innerHTML">
|
||||||
|
<input type="text" name="name" placeholder="Name" required>
|
||||||
|
<input type="tel" name="phone" placeholder="Phone">
|
||||||
|
<input type="email" name="email" placeholder="Email">
|
||||||
|
<input type="text" name="address" placeholder="Address">
|
||||||
|
<textarea name="notes" placeholder="Notes"></textarea>
|
||||||
|
<button type="submit">Add Client</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr><th>Name</th><th>Phone</th><th>WhatsApp</th><th>Actions</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="clientList">
|
||||||
|
`))
|
||||||
|
for _, c := range clients {
|
||||||
|
var whatsappCell string
|
||||||
|
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>`
|
||||||
|
}
|
||||||
|
w.Write([]byte(`<tr>
|
||||||
|
<td>` + c.Name + `</td>
|
||||||
|
<td>` + c.Phone + `</td>
|
||||||
|
<td>` + whatsappCell + `</td>
|
||||||
|
<td>
|
||||||
|
<a href="/clients/` + strconv.FormatInt(c.ClientID, 10) + `">View</a>
|
||||||
|
<button type="button" onclick="document.getElementById('editForm` + strconv.FormatInt(c.ClientID, 10) + `').style.display='block'">Edit</button>
|
||||||
|
<form method="DELETE" style="display:inline" hx-delete="/clients/` + strconv.FormatInt(c.ClientID, 10) + `" hx-target="closest tr">
|
||||||
|
<button type="submit">Delete</button>
|
||||||
|
</form>
|
||||||
|
<tr id="editForm` + strconv.FormatInt(c.ClientID, 10) + `" class="edit-row"><td colspan="4">
|
||||||
|
<form hx-put="/clients/` + strconv.FormatInt(c.ClientID, 10) + `" hx-target="#clientList" hx-swap="innerHTML">
|
||||||
|
<input type="text" name="name" value="` + c.Name + `">
|
||||||
|
<input type="tel" name="phone" value="` + c.Phone + `">
|
||||||
|
<input type="email" name="email" value="` + c.Email + `">
|
||||||
|
<input type="text" name="address" value="` + c.Address + `">
|
||||||
|
<textarea name="notes">` + c.Notes + `</textarea>
|
||||||
|
<button type="submit">Save</button>
|
||||||
|
</form>
|
||||||
|
</td></tr>
|
||||||
|
</td>
|
||||||
|
</tr>`))
|
||||||
|
}
|
||||||
|
w.Write([]byte(`</tbody></table>
|
||||||
|
<p><a href="/">Back to Home</a></p>
|
||||||
|
</body></html>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) CreateClient(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
r.ParseForm()
|
||||||
|
client := db.Client{
|
||||||
|
AccountID: accountID,
|
||||||
|
Name: r.FormValue("name"),
|
||||||
|
Phone: r.FormValue("phone"),
|
||||||
|
Email: r.FormValue("email"),
|
||||||
|
Address: r.FormValue("address"),
|
||||||
|
Notes: r.FormValue("notes"),
|
||||||
|
CreatedAt: time.Now().Unix(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := client.Create(a.DB); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
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(a.DB, accountID, id)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Client not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
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>
|
||||||
|
<body>
|
||||||
|
<h1>` + client.Name + `</h1>
|
||||||
|
<p>Client ID: ` + strconv.FormatInt(client.ClientID, 10) + `</p>
|
||||||
|
<p>Phone: ` + client.Phone + `</p>
|
||||||
|
<p>Email: ` + client.Email + `</p>
|
||||||
|
<p>Address: ` + client.Address + `</p>
|
||||||
|
<p>Notes: ` + client.Notes + `</p>` + whatsappSection + `
|
||||||
|
<a href="/clients">Back</a>
|
||||||
|
</body></html>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) UpdateClient(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
r.ParseForm()
|
||||||
|
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"),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := client.Update(a.DB); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
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(a.DB); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,337 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-crm/internal/db"
|
||||||
|
"go-crm/internal/whatsapp"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestListClientsWhatsAppDisplay(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"
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = testDB.Exec(
|
||||||
|
"INSERT INTO clients (account_id, name, phone, created_at) VALUES (?, ?, ?, ?)",
|
||||||
|
accountID, "Client Without WhatsApp", "+5521987654321", time.Now().Unix(),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create client without wa: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = testDB.Exec(
|
||||||
|
"INSERT INTO clients (account_id, name, phone, whatsapp_number, whatsapp_connected, created_at) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
accountID, "Client With WhatsApp", "+5521987654322", "+5521987654322", 1, time.Now().Unix(),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create client with wa: %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, "Client Without WhatsApp") {
|
||||||
|
t.Error("expected to find client without wa in response")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(body, "Connect") {
|
||||||
|
t.Error("expected Connect button for client without WhatsApp")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(body, "Client With WhatsApp") {
|
||||||
|
t.Error("expected to find client with wa in response")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(body, "+5521987654322") {
|
||||||
|
t.Error("expected WhatsApp number displayed for connected client")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetupTestDB(t *testing.T) (*sql.DB, func()) {
|
||||||
|
tmpfile, err := os.CreateTemp("", "test_*.db")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
tmpfile.Close()
|
||||||
|
|
||||||
|
testDB, err := db.Init(tmpfile.Name())
|
||||||
|
if err != nil {
|
||||||
|
os.Remove(tmpfile.Name())
|
||||||
|
t.Fatalf("failed to init db: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup := func() {
|
||||||
|
testDB.Close()
|
||||||
|
os.Remove(tmpfile.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
return testDB, cleanup
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLeadsConnectPage(t *testing.T) {
|
||||||
|
testDB, cleanup := SetupTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
DB = testDB
|
||||||
|
WAConnector = whatsapp.NewFakeConnector()
|
||||||
|
|
||||||
|
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
||||||
|
testDB.Exec(
|
||||||
|
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||||
|
"[email protected]", "Test Account", string(hashedPassword), time.Now().Unix(),
|
||||||
|
)
|
||||||
|
|
||||||
|
var accountID int64
|
||||||
|
testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "[email protected]").Scan(&accountID)
|
||||||
|
|
||||||
|
sessionID := "test-session"
|
||||||
|
testDB.Exec(
|
||||||
|
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
|
||||||
|
sessionID, accountID, time.Now().Add(time.Hour).Unix(),
|
||||||
|
)
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/leads/connect?client_id="+strconv.FormatInt(clientID, 10), nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
LeadsConnectPage(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status 200, got %d", w.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
body := w.Body.String()
|
||||||
|
|
||||||
|
if !strings.Contains(body, "Scan to Connect") && !strings.Contains(body, "WhatsApp") {
|
||||||
|
t.Error("expected QR connection page with WhatsApp messaging")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(strconv.FormatInt(clientID, 10), "") {
|
||||||
|
t.Log("client_id passed to page")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLeadsQRPolling(t *testing.T) {
|
||||||
|
testDB, cleanup := SetupTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
DB = testDB
|
||||||
|
WAConnector = whatsapp.NewFakeConnector()
|
||||||
|
|
||||||
|
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
||||||
|
testDB.Exec(
|
||||||
|
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||||
|
"[email protected]", "Test Account", string(hashedPassword), time.Now().Unix(),
|
||||||
|
)
|
||||||
|
|
||||||
|
var accountID int64
|
||||||
|
testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "[email protected]").Scan(&accountID)
|
||||||
|
|
||||||
|
sessionID := "test-session"
|
||||||
|
testDB.Exec(
|
||||||
|
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
|
||||||
|
sessionID, accountID, time.Now().Add(time.Hour).Unix(),
|
||||||
|
)
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/leads/qr?client_id="+strconv.FormatInt(clientID, 10), nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
LeadsQR(w, req)
|
||||||
|
|
||||||
|
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,184 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-crm/config"
|
||||||
|
"go-crm/internal/db"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (a *App) ListCustomers(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||||
|
clientID, _ := strconv.ParseInt(r.URL.Query().Get("client_id"), 10, 64)
|
||||||
|
if limit == 0 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
customers, err := db.ListCustomers(a.DB, accountID, clientID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
clients, err := db.ListClients(a.DB, accountID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var clientOptions string
|
||||||
|
for _, c := range clients {
|
||||||
|
clientOptions += `<option value="` + strconv.FormatInt(c.ClientID, 10) + `">` + c.Name + `</option>`
|
||||||
|
}
|
||||||
|
|
||||||
|
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-form{display:none;margin-top:0.5rem;padding:0.5rem;border:1px solid #ccc}</style></head><body><h1>Customers</h1><button class="btn" onclick="document.getElementById('customerForm').style.display='block'">Add Customer</button><div id="customerForm" style="display:none; margin-top:1rem;"><form hx-post="/customers" hx-target="#customerList"><input type="text" name="name" placeholder="Name" required><input type="tel" name="phone" placeholder="Phone"><input type="date" name="birth_date" placeholder="Birth Date"><input type="text" name="instagram" placeholder="Instagram"><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>Phone</th><th>Birth Date</th><th>Instagram</th><th>Actions</th></tr></thead><tbody id="customerList">`))
|
||||||
|
for _, c := range customers {
|
||||||
|
w.Write([]byte(`<tr><td>` + c.Name + `</td><td>` + c.Phone + `</td><td>` + c.BirthDate + `</td><td>` + c.Instagram + `</td><td><a href="/customers/` + strconv.FormatInt(c.CustomerID, 10) + `">View</a><button type="button" onclick="document.getElementById('editCust` + strconv.FormatInt(c.CustomerID, 10) + `').style.display='block'">Edit</button><form method="DELETE" style="display:inline" hx-delete="/customers/` + strconv.FormatInt(c.CustomerID, 10) + `" hx-target="closest tr"><button type="submit">Delete</button></form></td></tr><tr id="editCust` + strconv.FormatInt(c.CustomerID, 10) + `" style="display:none"><td colspan="5"><form hx-put="/customers/` + strconv.FormatInt(c.CustomerID, 10) + `" hx-target="#customerList" hx-swap="innerHTML"><input type="text" name="name" value="` + c.Name + `"><input type="tel" name="phone" value="` + c.Phone + `"><input type="date" name="birth_date" value="` + c.BirthDate + `"><input type="text" name="instagram" value="` + c.Instagram + `"><select name="client_id"><option value="` + strconv.FormatInt(c.ClientID, 10) + `">` + c.Name + `</option>` + clientOptions + `</select><button type="submit">Save</button></form></td></tr>`))
|
||||||
|
}
|
||||||
|
w.Write([]byte(`</tbody></table></body></html>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) CreateCustomer(w http.ResponseWriter, r *http.Request) {
|
||||||
|
isInternal := r.Header.Get("X-Internal-Secret") == config.InternalSecret()
|
||||||
|
|
||||||
|
var accountID int64
|
||||||
|
var clientID int64
|
||||||
|
var ok bool
|
||||||
|
|
||||||
|
if isInternal {
|
||||||
|
clientID, _ = strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||||
|
accountID = clientID
|
||||||
|
ok = true
|
||||||
|
} else {
|
||||||
|
accountID, ok = a.requireAuth(w, r)
|
||||||
|
if ok {
|
||||||
|
clientID, _ = strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
r.ParseForm()
|
||||||
|
if clientID == 0 {
|
||||||
|
clientID, _ = strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !isInternal {
|
||||||
|
var checkID int64
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
customer := db.Customer{
|
||||||
|
ClientID: clientID,
|
||||||
|
Name: r.FormValue("name"),
|
||||||
|
Phone: r.FormValue("phone"),
|
||||||
|
BirthDate: r.FormValue("birth_date"),
|
||||||
|
Instagram: r.FormValue("instagram"),
|
||||||
|
CreatedAt: time.Now().Unix(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if phone := r.FormValue("phone"); phone != "" {
|
||||||
|
var existingID int64
|
||||||
|
err := a.DB.QueryRow(
|
||||||
|
"SELECT customer_id FROM customers WHERE client_id = ? AND phone = ?",
|
||||||
|
clientID, phone,
|
||||||
|
).Scan(&existingID)
|
||||||
|
if err == nil {
|
||||||
|
_, err = a.DB.Exec(
|
||||||
|
"UPDATE customers SET name = ?, birth_date = ?, instagram = ? WHERE customer_id = ?",
|
||||||
|
r.FormValue("name"), r.FormValue("birth_date"), r.FormValue("instagram"), existingID,
|
||||||
|
)
|
||||||
|
if err == nil {
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := customer.Create(a.DB); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) ViewCustomer(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
var c db.Customer
|
||||||
|
err := a.DB.QueryRow("SELECT customer_id, client_id, name, phone, birth_date, instagram, created_at FROM customers WHERE customer_id = ?", id).Scan(&c.CustomerID, &c.ClientID, &c.Name, &c.Phone, &c.BirthDate, &c.Instagram, &c.CreatedAt)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Customer not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Write([]byte(`<!DOCTYPE html><body><h1>` + c.Name + `</h1><p>Phone: ` + c.Phone + `</p><p>Birth Date: ` + c.BirthDate + `</p><p>Instagram: ` + c.Instagram + `</p><a href="/customers">Back</a></body></html>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) UpdateCustomer(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
r.ParseForm()
|
||||||
|
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||||
|
_, err := a.DB.Exec("UPDATE customers SET client_id=?, name=?, phone=?, birth_date=?, instagram=? WHERE customer_id=?", clientID, r.FormValue("name"), r.FormValue("phone"), r.FormValue("birth_date"), r.FormValue("instagram"), id)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) DeleteCustomer(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
a.DB.Exec("DELETE FROM customers WHERE customer_id = ?", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- package-level shims kept for existing tests ---
|
||||||
|
|
||||||
|
func ListCustomers(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).ListCustomers(w, r)
|
||||||
|
}
|
||||||
|
func CreateCustomer(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).CreateCustomer(w, r)
|
||||||
|
}
|
||||||
|
func ViewCustomer(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).ViewCustomer(w, r)
|
||||||
|
}
|
||||||
|
func UpdateCustomer(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).UpdateCustomer(w, r)
|
||||||
|
}
|
||||||
|
func DeleteCustomer(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).DeleteCustomer(w, r)
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCreateCustomerInternalSecret(t *testing.T) {
|
||||||
|
testDB, cleanup := SetupTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
DB = testDB
|
||||||
|
|
||||||
|
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
||||||
|
testDB.Exec(
|
||||||
|
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||||
|
"[email protected]", "Test Account", string(hashedPassword), time.Now().Unix(),
|
||||||
|
)
|
||||||
|
|
||||||
|
var accountID int64
|
||||||
|
testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "[email protected]").Scan(&accountID)
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/customers", nil)
|
||||||
|
req.PostForm = map[string][]string{
|
||||||
|
"name": {"+5521987654321"},
|
||||||
|
"phone": {"+5521987654321"},
|
||||||
|
"client_id": {string(rune(clientID))},
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
req.Header.Set("X-Internal-Secret", "internal-secret")
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
CreateCustomer(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK && w.Code != http.StatusFound {
|
||||||
|
t.Fatalf("expected success with internal secret, got %d", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"go-crm/config"
|
||||||
|
"go-crm/internal/db"
|
||||||
|
"go-crm/internal/parser"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ingestRequest is the JSON body sent by the WhatsApp adapter.
|
||||||
|
type ingestRequest struct {
|
||||||
|
ClientID int64 `json:"client_id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Phone string `json:"phone"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
MessageID string `json:"message_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// IngestLead is the internal-only endpoint called by the WhatsApp adapter.
|
||||||
|
// POST /leads/ingest (X-Internal-Secret required)
|
||||||
|
func (a *App) IngestLead(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Header.Get("X-Internal-Secret") != config.InternalSecret() {
|
||||||
|
http.Error(w, "forbidden", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req ingestRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
http.Error(w, "bad request", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.ClientID == 0 || req.Phone == "" {
|
||||||
|
http.Error(w, "client_id and phone required", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
phoneNorm := parser.NormalizePhone(req.Phone)
|
||||||
|
|
||||||
|
// Dedup: skip if this message was already processed.
|
||||||
|
if req.MessageID != "" {
|
||||||
|
processed, err := db.IsMessageProcessed(a.DB, req.ClientID, req.MessageID)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("IngestLead: db error checking processed message: %v", err)
|
||||||
|
}
|
||||||
|
if processed {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if lead already exists for this phone.
|
||||||
|
existing, err := db.GetLeadByPhone(a.DB, req.ClientID, phoneNorm)
|
||||||
|
if err != nil && err != sql.ErrNoRows {
|
||||||
|
log.Printf("IngestLead: db error checking existing lead: %v", err)
|
||||||
|
http.Error(w, "db error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if existing != nil {
|
||||||
|
// Known lead — just update last contact timestamp.
|
||||||
|
if terr := db.TouchLeadContact(a.DB, existing.LeadID); terr != nil {
|
||||||
|
log.Printf("IngestLead: failed to touch lead %d: %v", existing.LeadID, terr)
|
||||||
|
}
|
||||||
|
if req.MessageID != "" {
|
||||||
|
if err := db.RecordProcessedMessage(a.DB, req.ClientID, req.MessageID); err != nil {
|
||||||
|
log.Printf("IngestLead: failed to record processed message: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// New lead — extract service from message text.
|
||||||
|
mapping, err := db.LoadKeywordMapping(a.DB, req.ClientID)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("IngestLead: failed to load keyword mapping: %v", err)
|
||||||
|
mapping = map[string]string{}
|
||||||
|
}
|
||||||
|
|
||||||
|
serviceInterest := parser.ExtractService(req.Message, mapping)
|
||||||
|
needsReview := serviceInterest == "Não especificou"
|
||||||
|
|
||||||
|
lead := &db.Lead{
|
||||||
|
ClientID: req.ClientID,
|
||||||
|
Name: req.Name,
|
||||||
|
PhoneRaw: req.Phone,
|
||||||
|
PhoneNormalized: phoneNorm,
|
||||||
|
ServiceInterest: serviceInterest,
|
||||||
|
Status: "Não agendou",
|
||||||
|
NeedsReview: needsReview,
|
||||||
|
PaymentStatus: "Não pago",
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.CreateLead(a.DB, lead); err != nil {
|
||||||
|
log.Printf("IngestLead: failed to create lead: %v", err)
|
||||||
|
http.Error(w, "db error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.MessageID != "" {
|
||||||
|
if err := db.RecordProcessedMessage(a.DB, req.ClientID, req.MessageID); err != nil {
|
||||||
|
log.Printf("IngestLead: failed to record processed message: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seed default statuses/keywords for this client if first lead.
|
||||||
|
go seedClientDefaults(a.DB, req.ClientID)
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
}
|
||||||
|
|
||||||
|
// seedClientDefaults seeds default statuses and keywords for a client on first lead.
|
||||||
|
// It accepts the DB as a parameter so it can be called from both the App method
|
||||||
|
// and the legacy package-level shim without touching global state.
|
||||||
|
func seedClientDefaults(database *sql.DB, clientID int64) {
|
||||||
|
statuses, _ := db.ListLeadStatuses(database, clientID)
|
||||||
|
if len(statuses) == 0 {
|
||||||
|
defaults := []string{"Não agendou", "Agendou", "Sem retorno / não evoluiu"}
|
||||||
|
for _, s := range defaults {
|
||||||
|
db.AddLeadStatus(database, clientID, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
kws, _ := db.ListServiceKeywords(database, clientID)
|
||||||
|
if len(kws) == 0 {
|
||||||
|
defaultKWs := map[string][]string{
|
||||||
|
"Head Spa": {"head spa", "head-spa", "headspa"},
|
||||||
|
"Massagem completa": {"massagem", "massagem completa"},
|
||||||
|
"Drenagem linfatica": {"drenagem", "linfática", "drenagem linfatica"},
|
||||||
|
"Hydra Boost": {"hydra", "hydra boost"},
|
||||||
|
"Design Henna": {"henna", "design henna"},
|
||||||
|
"Masculino": {"masculino", "masc"},
|
||||||
|
}
|
||||||
|
for svc, keywords := range defaultKWs {
|
||||||
|
for _, kw := range keywords {
|
||||||
|
db.AddServiceKeyword(database, clientID, svc, kw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- package-level shim kept for existing tests ---
|
||||||
|
|
||||||
|
func IngestLead(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).IngestLead(w, r)
|
||||||
|
}
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"go-crm/internal/db"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LeadKeywordsPage renders the keyword mapping management screen.
|
||||||
|
// GET /leads/keywords
|
||||||
|
func (a *App) LeadKeywordsPage(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
|
||||||
|
}
|
||||||
|
|
||||||
|
kws, err := db.ListServiceKeywords(a.DB, clientID)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
statuses, _ := db.ListLeadStatuses(a.DB, clientID)
|
||||||
|
services := a.serviceNames(clientID)
|
||||||
|
|
||||||
|
pendingCount, _ := db.CountLeadsNeedingReview(a.DB, clientID)
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
fmt.Fprintf(w, `<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Keyword Mapping</title>
|
||||||
|
<script src="https://unpkg.com/[email protected]"></script>
|
||||||
|
<style>
|
||||||
|
body { font-family: sans-serif; padding: 1rem; }
|
||||||
|
table { border-collapse: collapse; width: 100%%; margin-bottom: 2rem; }
|
||||||
|
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; }
|
||||||
|
.section { margin-top: 2rem; }
|
||||||
|
form.inline { display: inline; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Keyword Mapping</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="/report">Monthly Report</a>
|
||||||
|
</nav>
|
||||||
|
<br>
|
||||||
|
|
||||||
|
<h2>Service Keywords</h2>
|
||||||
|
<p>Add keywords that trigger automatic service detection. Case and accent insensitive.</p>
|
||||||
|
<form hx-post="/leads/keywords" hx-target="#keywordTable" hx-swap="outerHTML">
|
||||||
|
<select name="service_name">%s</select>
|
||||||
|
<input type="text" name="keyword" placeholder="Keyword (e.g. massagem)" required>
|
||||||
|
<button type="submit">Add Keyword</button>
|
||||||
|
</form>
|
||||||
|
<br><br>
|
||||||
|
%s
|
||||||
|
|
||||||
|
<div class="section">
|
||||||
|
<h2>Lead Statuses</h2>
|
||||||
|
<p>Manage the status options available for leads.</p>
|
||||||
|
<form hx-post="/leads/statuses" hx-target="#statusTable" hx-swap="outerHTML">
|
||||||
|
<input type="text" name="status_name" placeholder="New status name" required>
|
||||||
|
<button type="submit">Add Status</button>
|
||||||
|
</form>
|
||||||
|
<br><br>
|
||||||
|
%s
|
||||||
|
</div>
|
||||||
|
</body></html>`,
|
||||||
|
pendingCount,
|
||||||
|
buildServiceSelectOptions(services),
|
||||||
|
renderKeywordTable(kws),
|
||||||
|
renderStatusTable(statuses),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddServiceKeyword adds a new keyword mapping.
|
||||||
|
// POST /leads/keywords
|
||||||
|
func (a *App) AddServiceKeyword(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
clientID := a.clientIDForAccount(accountID)
|
||||||
|
r.ParseForm()
|
||||||
|
svc := r.FormValue("service_name")
|
||||||
|
kw := r.FormValue("keyword")
|
||||||
|
if svc == "" || kw == "" {
|
||||||
|
http.Error(w, "service_name and keyword required", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db.AddServiceKeyword(a.DB, clientID, svc, kw)
|
||||||
|
|
||||||
|
kws, _ := db.ListServiceKeywords(a.DB, clientID)
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
fmt.Fprint(w, renderKeywordTable(kws))
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteServiceKeywordHandler removes a keyword mapping.
|
||||||
|
// DELETE /leads/keywords/{id}
|
||||||
|
func (a *App) DeleteServiceKeywordHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
clientID := a.clientIDForAccount(accountID)
|
||||||
|
kwID, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
db.DeleteServiceKeyword(a.DB, clientID, kwID)
|
||||||
|
|
||||||
|
kws, _ := db.ListServiceKeywords(a.DB, clientID)
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
fmt.Fprint(w, renderKeywordTable(kws))
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddLeadStatusHandler adds a new custom lead status.
|
||||||
|
// POST /leads/statuses
|
||||||
|
func (a *App) AddLeadStatusHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
clientID := a.clientIDForAccount(accountID)
|
||||||
|
r.ParseForm()
|
||||||
|
statusName := r.FormValue("status_name")
|
||||||
|
if statusName == "" {
|
||||||
|
http.Error(w, "status_name required", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db.AddLeadStatus(a.DB, clientID, statusName)
|
||||||
|
|
||||||
|
statuses, _ := db.ListLeadStatuses(a.DB, clientID)
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
fmt.Fprint(w, renderStatusTable(statuses))
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteLeadStatusHandler removes a lead status.
|
||||||
|
// DELETE /leads/statuses/{id}
|
||||||
|
func (a *App) DeleteLeadStatusHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
clientID := a.clientIDForAccount(accountID)
|
||||||
|
statusID, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
db.DeleteLeadStatus(a.DB, clientID, statusID)
|
||||||
|
|
||||||
|
statuses, _ := db.ListLeadStatuses(a.DB, clientID)
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
fmt.Fprint(w, renderStatusTable(statuses))
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- rendering helpers -------------------------------------------------------
|
||||||
|
|
||||||
|
func buildServiceSelectOptions(services []string) string {
|
||||||
|
out := ""
|
||||||
|
for _, s := range services {
|
||||||
|
if s == "Não especificou" {
|
||||||
|
continue // don't map keywords to the fallback
|
||||||
|
}
|
||||||
|
out += fmt.Sprintf(`<option value="%s">%s</option>`, htmlEscape(s), htmlEscape(s))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderKeywordTable(kws []db.ServiceKeyword) string {
|
||||||
|
out := `<table id="keywordTable">
|
||||||
|
<thead><tr><th>Service</th><th>Keyword</th><th>Actions</th></tr></thead>
|
||||||
|
<tbody>`
|
||||||
|
if len(kws) == 0 {
|
||||||
|
out += `<tr><td colspan="3">No keywords defined.</td></tr>`
|
||||||
|
}
|
||||||
|
for _, kw := range kws {
|
||||||
|
out += fmt.Sprintf(`
|
||||||
|
<tr>
|
||||||
|
<td>%s</td>
|
||||||
|
<td>%s</td>
|
||||||
|
<td>
|
||||||
|
<form hx-delete="/leads/keywords/%d" hx-target="#keywordTable" hx-swap="outerHTML" style="display:inline">
|
||||||
|
<button type="submit">Remove</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>`, htmlEscape(kw.ServiceName), htmlEscape(kw.Keyword), kw.KeywordID)
|
||||||
|
}
|
||||||
|
out += `</tbody></table>`
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderStatusTable(statuses []db.LeadStatus) string {
|
||||||
|
out := `<table id="statusTable">
|
||||||
|
<thead><tr><th>Status</th><th>Actions</th></tr></thead>
|
||||||
|
<tbody>`
|
||||||
|
if len(statuses) == 0 {
|
||||||
|
out += `<tr><td colspan="2">No statuses defined.</td></tr>`
|
||||||
|
}
|
||||||
|
for _, s := range statuses {
|
||||||
|
out += fmt.Sprintf(`
|
||||||
|
<tr>
|
||||||
|
<td>%s</td>
|
||||||
|
<td>
|
||||||
|
<form hx-delete="/leads/statuses/%d" hx-target="#statusTable" hx-swap="outerHTML" style="display:inline">
|
||||||
|
<button type="submit">Remove</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>`, htmlEscape(s.StatusName), s.StatusID)
|
||||||
|
}
|
||||||
|
out += `</tbody></table>`
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- package-level shims kept for existing tests ---
|
||||||
|
|
||||||
|
func LeadKeywordsPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).LeadKeywordsPage(w, r)
|
||||||
|
}
|
||||||
|
func AddServiceKeyword(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).AddServiceKeyword(w, r)
|
||||||
|
}
|
||||||
|
func DeleteServiceKeywordHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).DeleteServiceKeywordHandler(w, r)
|
||||||
|
}
|
||||||
|
func AddLeadStatusHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).AddLeadStatusHandler(w, r)
|
||||||
|
}
|
||||||
|
func DeleteLeadStatusHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).DeleteLeadStatusHandler(w, r)
|
||||||
|
}
|
||||||
@@ -0,0 +1,423 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-crm/internal/db"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LeadReviewQueue renders the review queue: leads where needs_review = 1.
|
||||||
|
// GET /leads/review
|
||||||
|
func (a *App) LeadReviewQueue(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
|
||||||
|
}
|
||||||
|
|
||||||
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||||
|
if limit == 0 {
|
||||||
|
limit = 50
|
||||||
|
}
|
||||||
|
|
||||||
|
leads, err := db.ListLeadsForReview(a.DB, clientID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
statuses, _ := db.ListLeadStatuses(a.DB, clientID)
|
||||||
|
services := a.serviceNames(clientID)
|
||||||
|
|
||||||
|
pendingCount := len(leads)
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
fmt.Fprintf(w, `<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Review Queue (%d pending)</title>
|
||||||
|
<script src="https://unpkg.com/[email protected]"></script>
|
||||||
|
<style>
|
||||||
|
body { font-family: sans-serif; padding: 1rem; }
|
||||||
|
h1 { display: flex; align-items: center; gap: 0.5rem; }
|
||||||
|
.badge { background: #dc3545; color: #fff; border-radius: 1rem; padding: 0.2rem 0.6rem; font-size: 0.85rem; }
|
||||||
|
table { border-collapse: collapse; width: 100%%; }
|
||||||
|
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; vertical-align: top; }
|
||||||
|
th { background: #f5f5f5; }
|
||||||
|
form { display: inline; }
|
||||||
|
select, input[type=text] { width: 100%%; box-sizing: border-box; }
|
||||||
|
.actions button { margin-right: 4px; }
|
||||||
|
.empty { padding: 2rem; color: #888; text-align: center; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Review Queue <span class="badge">%d</span></h1>
|
||||||
|
<p>Leads with service interest not yet identified. Confirm or correct each entry.</p>
|
||||||
|
<nav><a href="/">Home</a> | <a href="/leads/all">All Leads</a> | <a href="/leads/keywords">Keyword Mapping</a> | <a href="/report">Monthly Report</a></nav>
|
||||||
|
<br>
|
||||||
|
`, pendingCount, pendingCount)
|
||||||
|
|
||||||
|
if len(leads) == 0 {
|
||||||
|
fmt.Fprintf(w, `<div class="empty">No leads pending review.</div>`)
|
||||||
|
} else {
|
||||||
|
fmt.Fprintf(w, `<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Phone</th>
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Service Interest</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th>Arrived</th>
|
||||||
|
<th>Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="reviewList">`)
|
||||||
|
|
||||||
|
for _, l := range leads {
|
||||||
|
arrived := time.Unix(l.CreatedAt, 0).Format("02/01 15:04")
|
||||||
|
fmt.Fprintf(w, `
|
||||||
|
<tr id="row-%d">
|
||||||
|
<td>%s</td>
|
||||||
|
<td>%s</td>
|
||||||
|
<td>
|
||||||
|
<form hx-put="/leads/%d/review" hx-target="#row-%d" hx-swap="outerHTML">
|
||||||
|
<select name="service_interest">%s</select>
|
||||||
|
<select name="status">%s</select>
|
||||||
|
<input type="text" name="name" value="%s" placeholder="Name">
|
||||||
|
<div class="actions">
|
||||||
|
<button type="submit">Confirm</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
<td>%s</td>
|
||||||
|
<td>%s</td>
|
||||||
|
<td>
|
||||||
|
<form hx-delete="/leads/%d" hx-target="#row-%d" hx-swap="outerHTML">
|
||||||
|
<button type="submit" onclick="return confirm('Delete this lead?')">Delete</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>`,
|
||||||
|
l.LeadID,
|
||||||
|
htmlEscape(l.PhoneNormalized),
|
||||||
|
htmlEscape(l.Name),
|
||||||
|
l.LeadID, l.LeadID,
|
||||||
|
buildServiceOptions(services, l.ServiceInterest),
|
||||||
|
buildStatusOptions(statuses, l.Status),
|
||||||
|
htmlEscape(l.Name),
|
||||||
|
htmlEscape(l.Status),
|
||||||
|
arrived,
|
||||||
|
l.LeadID, l.LeadID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, `</tbody></table>`)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintf(w, `</body></html>`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConfirmLeadReview handles the form submission from the review queue.
|
||||||
|
// PUT /leads/{id}/review
|
||||||
|
func (a *App) ConfirmLeadReview(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", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
leadID, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
r.ParseForm()
|
||||||
|
|
||||||
|
lead, err := db.GetLeadByID(a.DB, clientID, leadID)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Lead not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
lead.Name = r.FormValue("name")
|
||||||
|
lead.ServiceInterest = r.FormValue("service_interest")
|
||||||
|
lead.Status = r.FormValue("status")
|
||||||
|
lead.NeedsReview = false
|
||||||
|
|
||||||
|
if err := db.UpdateLead(a.DB, lead); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
fmt.Fprintf(w, `<tr id="row-%d" style="display:none"></tr>`, leadID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LeadAllList renders all leads (not just review queue).
|
||||||
|
// GET /leads/all
|
||||||
|
func (a *App) LeadAllList(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
|
||||||
|
}
|
||||||
|
|
||||||
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||||
|
if limit == 0 {
|
||||||
|
limit = 50
|
||||||
|
}
|
||||||
|
|
||||||
|
var leads []db.Lead
|
||||||
|
var err error
|
||||||
|
if a.LeadService != nil {
|
||||||
|
domainLeads, svcErr := a.LeadService.ListAllLeads(r.Context(), clientID, limit, offset)
|
||||||
|
if svcErr != nil {
|
||||||
|
http.Error(w, svcErr.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// convert domain.Leaf to db.Lead
|
||||||
|
leads = make([]db.Lead, len(domainLeads))
|
||||||
|
for i, dl := range domainLeads {
|
||||||
|
leads[i] = db.Lead{
|
||||||
|
LeadID: dl.LeadID,
|
||||||
|
ClientID: dl.ClientID,
|
||||||
|
Name: dl.Name,
|
||||||
|
PhoneRaw: dl.PhoneRaw,
|
||||||
|
PhoneNormalized: dl.PhoneNormalized,
|
||||||
|
ServiceInterest: dl.ServiceInterest,
|
||||||
|
Status: dl.Status,
|
||||||
|
NeedsReview: dl.NeedsReview,
|
||||||
|
AppointmentDate: dl.AppointmentDate,
|
||||||
|
AppointmentTime: dl.AppointmentTime,
|
||||||
|
PaymentStatus: dl.PaymentStatus,
|
||||||
|
PaymentAmount: dl.PaymentAmount,
|
||||||
|
PaymentDate: dl.PaymentDate,
|
||||||
|
CreatedAt: dl.CreatedAt,
|
||||||
|
LastContactAt: dl.LastContactAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
leads, err = db.ListAllLeads(a.DB, clientID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pendingCount, _ := db.CountLeadsNeedingReview(a.DB, clientID)
|
||||||
|
statuses, _ := db.ListLeadStatuses(a.DB, clientID)
|
||||||
|
services := a.serviceNames(clientID)
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
fmt.Fprintf(w, `<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>All Leads</title>
|
||||||
|
<script src="https://unpkg.com/[email protected]"></script>
|
||||||
|
<style>
|
||||||
|
body { font-family: sans-serif; padding: 1rem; }
|
||||||
|
table { border-collapse: collapse; width: 100%%; }
|
||||||
|
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; }
|
||||||
|
.needs-review { background: #fff3cd; }
|
||||||
|
select, input[type=text] { width: 100%%; box-sizing: border-box; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>All Leads</h1>
|
||||||
|
<nav>
|
||||||
|
<a href="/">Home</a> |
|
||||||
|
<a href="/leads/review">Review Queue <span class="badge">%d</span></a> |
|
||||||
|
<a href="/leads/keywords">Keyword Mapping</a> |
|
||||||
|
<a href="/report">Monthly Report</a>
|
||||||
|
</nav>
|
||||||
|
<br>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Phone</th><th>Name</th><th>Service</th><th>Status</th>
|
||||||
|
<th>Payment</th><th>Arrived</th><th>Last Contact</th><th>Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="leadsList">
|
||||||
|
`, pendingCount)
|
||||||
|
|
||||||
|
for _, l := range leads {
|
||||||
|
arrived := time.Unix(l.CreatedAt, 0).Format("02/01/2006 15:04")
|
||||||
|
lastContact := time.Unix(l.LastContactAt, 0).Format("02/01/2006 15:04")
|
||||||
|
rowClass := ""
|
||||||
|
if l.NeedsReview {
|
||||||
|
rowClass = `class="needs-review"`
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, `
|
||||||
|
<tr %s id="lead-%d">
|
||||||
|
<td>%s</td>
|
||||||
|
<td>%s</td>
|
||||||
|
<td>%s</td>
|
||||||
|
<td>%s</td>
|
||||||
|
<td>%s</td>
|
||||||
|
<td>%s</td>
|
||||||
|
<td>%s</td>
|
||||||
|
<td>
|
||||||
|
<button onclick="document.getElementById('edit-%d').style.display='table-row'">Edit</button>
|
||||||
|
<form hx-delete="/leads/%d" hx-target="#lead-%d" hx-swap="outerHTML" style="display:inline">
|
||||||
|
<button onclick="return confirm('Delete?')">Delete</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr id="edit-%d" style="display:none">
|
||||||
|
<td colspan="8">
|
||||||
|
<form hx-put="/leads/%d/review" hx-target="#lead-%d" hx-swap="outerHTML">
|
||||||
|
<input type="text" name="name" value="%s" placeholder="Name">
|
||||||
|
<select name="service_interest">%s</select>
|
||||||
|
<select name="status">%s</select>
|
||||||
|
<button type="submit">Save</button>
|
||||||
|
<button type="button" onclick="document.getElementById('edit-%d').style.display='none'">Cancel</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>`,
|
||||||
|
rowClass, l.LeadID,
|
||||||
|
htmlEscape(l.PhoneNormalized),
|
||||||
|
htmlEscape(l.Name),
|
||||||
|
htmlEscape(l.ServiceInterest),
|
||||||
|
htmlEscape(l.Status),
|
||||||
|
htmlEscape(l.PaymentStatus),
|
||||||
|
arrived,
|
||||||
|
lastContact,
|
||||||
|
l.LeadID,
|
||||||
|
l.LeadID, l.LeadID,
|
||||||
|
l.LeadID,
|
||||||
|
l.LeadID, l.LeadID,
|
||||||
|
htmlEscape(l.Name),
|
||||||
|
buildServiceOptions(services, l.ServiceInterest),
|
||||||
|
buildStatusOptions(statuses, l.Status),
|
||||||
|
l.LeadID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintf(w, `</tbody></table></body></html>`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteLeadNew handles DELETE /leads/{id}
|
||||||
|
func (a *App) DeleteLeadNew(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
clientID := a.clientIDForAccount(accountID)
|
||||||
|
leadID, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
a.DB.Exec("DELETE FROM leads WHERE lead_id = ? AND client_id = ?", leadID, clientID)
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Write([]byte(""))
|
||||||
|
}
|
||||||
|
|
||||||
|
// serviceNames returns the list of service names for the review/all-leads dropdowns.
|
||||||
|
// It reads from the DB-backed services table first, then falls back to the
|
||||||
|
// hardcoded defaults so the dropdown is never empty on a fresh install.
|
||||||
|
func (a *App) serviceNames(clientID int64) []string {
|
||||||
|
rows, err := a.DB.Query(
|
||||||
|
"SELECT DISTINCT name FROM services WHERE client_id = ? ORDER BY name",
|
||||||
|
clientID,
|
||||||
|
)
|
||||||
|
if err == nil {
|
||||||
|
defer rows.Close()
|
||||||
|
var names []string
|
||||||
|
for rows.Next() {
|
||||||
|
var n string
|
||||||
|
if rows.Scan(&n) == nil {
|
||||||
|
names = append(names, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(names) > 0 {
|
||||||
|
// Ensure "Não especificou" is always first.
|
||||||
|
hasDefault := false
|
||||||
|
for _, n := range names {
|
||||||
|
if n == "Não especificou" {
|
||||||
|
hasDefault = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !hasDefault {
|
||||||
|
names = append([]string{"Não especificou"}, names...)
|
||||||
|
}
|
||||||
|
return names
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Fallback: hardcoded defaults for a fresh install with no services yet.
|
||||||
|
return []string{
|
||||||
|
"Não especificou",
|
||||||
|
"Head Spa",
|
||||||
|
"Massagem completa",
|
||||||
|
"Drenagem linfatica",
|
||||||
|
"Hydra Boost",
|
||||||
|
"Design Henna",
|
||||||
|
"Masculino",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- rendering helpers -------------------------------------------------------
|
||||||
|
|
||||||
|
func buildServiceOptions(services []string, selected string) string {
|
||||||
|
out := ""
|
||||||
|
for _, s := range services {
|
||||||
|
sel := ""
|
||||||
|
if s == selected {
|
||||||
|
sel = ` selected`
|
||||||
|
}
|
||||||
|
out += fmt.Sprintf(`<option value="%s"%s>%s</option>`, htmlEscape(s), sel, htmlEscape(s))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildStatusOptions(statuses []db.LeadStatus, selected string) string {
|
||||||
|
out := ""
|
||||||
|
for _, s := range statuses {
|
||||||
|
sel := ""
|
||||||
|
if s.StatusName == selected {
|
||||||
|
sel = ` selected`
|
||||||
|
}
|
||||||
|
out += fmt.Sprintf(`<option value="%s"%s>%s</option>`, htmlEscape(s.StatusName), sel, htmlEscape(s.StatusName))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func htmlEscape(s string) string {
|
||||||
|
s = strings.ReplaceAll(s, "&", "&")
|
||||||
|
s = strings.ReplaceAll(s, "<", "<")
|
||||||
|
s = strings.ReplaceAll(s, ">", ">")
|
||||||
|
s = strings.ReplaceAll(s, `"`, """)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- package-level shims kept for existing tests ---
|
||||||
|
|
||||||
|
func LeadReviewQueue(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).LeadReviewQueue(w, r)
|
||||||
|
}
|
||||||
|
func ConfirmLeadReview(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).ConfirmLeadReview(w, r)
|
||||||
|
}
|
||||||
|
func LeadAllList(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).LeadAllList(w, r)
|
||||||
|
}
|
||||||
|
func DeleteLeadNew(w http.ResponseWriter, r *http.Request) {
|
||||||
|
(&App{DB: DB, WAConnector: WAConnector}).DeleteLeadNew(w, r)
|
||||||
|
}
|
||||||
@@ -0,0 +1,384 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-crm/internal/db"
|
||||||
|
"go-crm/internal/whatsapp"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (a *App) ListLeads(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
search := r.URL.Query().Get("search")
|
||||||
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||||
|
if limit == 0 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
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 != "" {
|
||||||
|
query += " AND (name LIKE ? OR phone LIKE ?)"
|
||||||
|
searchPat := "%" + search + "%"
|
||||||
|
args = append(args, searchPat, searchPat)
|
||||||
|
}
|
||||||
|
|
||||||
|
query += " ORDER BY cu.created_at DESC LIMIT ? OFFSET ?"
|
||||||
|
args = append(args, limit, offset)
|
||||||
|
|
||||||
|
rows, err := a.DB.Query(query, args...)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
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, &c.WhatsAppConnected, &c.WhatsAppNumber); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
customers = append(customers, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Write([]byte(`<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Leads</title>
|
||||||
|
<script src="https://unpkg.com/[email protected]"></script>
|
||||||
|
<style>
|
||||||
|
body { font-family: sans-serif; padding: 1rem; }
|
||||||
|
table { border-collapse: collapse; width: 100%; }
|
||||||
|
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
|
||||||
|
th { background: #f5f5f5; }
|
||||||
|
.search-box { margin-bottom: 1rem; }
|
||||||
|
.edit-row { display: none; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Leads</h1>
|
||||||
|
<div class="search-box">
|
||||||
|
<form hx-get="/leads" hx-target="#leadList" hx-swap="innerHTML">
|
||||||
|
<input type="text" name="search" placeholder="Search by name or phone" value="` + search + `">
|
||||||
|
<button type="submit">Search</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<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">
|
||||||
|
<button type="submit">Delete</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr id="editLead` + strconv.FormatInt(c.CustomerID, 10) + `" class="edit-row">
|
||||||
|
<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 + `">
|
||||||
|
<input type="date" name="birth_date" value="` + c.BirthDate + `">
|
||||||
|
<input type="text" name="instagram" value="` + c.Instagram + `">
|
||||||
|
<button type="submit">Save</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Write([]byte(`</tbody></table>
|
||||||
|
<p><a href="/">Back to Home</a> | <a href="/clients">Back to Clients</a></p>
|
||||||
|
</body></html>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) UpdateLead(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
r.ParseForm()
|
||||||
|
|
||||||
|
_, 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,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
a.ListLeads(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 := a.DB.Exec(
|
||||||
|
"DELETE FROM customers WHERE customer_id = ? AND client_id IN (SELECT client_id FROM clients WHERE account_id = ?)",
|
||||||
|
id, accountID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Write([]byte("OK"))
|
||||||
|
}
|
||||||
|
|
||||||
|
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(a.DB, accountID, clientID)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Client not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Write([]byte(`<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Connect WhatsApp</title>
|
||||||
|
<script src="https://unpkg.com/[email protected]"></script>
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
|
||||||
|
<style>
|
||||||
|
body { font-family: sans-serif; padding: 2rem; text-align: center; }
|
||||||
|
#qrcode { margin: 2rem auto; display: flex; justify-content: center; }
|
||||||
|
#status { padding: 1rem; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Connect WhatsApp</h1>
|
||||||
|
<p>Scan the QR code below with your WhatsApp app to connect</p>
|
||||||
|
<div id="qrcode"></div>
|
||||||
|
<p id="status">Loading...</p>
|
||||||
|
<script>
|
||||||
|
var lastQR = '';
|
||||||
|
function pollQR() {
|
||||||
|
fetch('/leads/qr?client_id=` + strconv.FormatInt(client.ClientID, 10) + `')
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(data => {
|
||||||
|
if (data.qr) {
|
||||||
|
if (data.qr !== lastQR) {
|
||||||
|
lastQR = data.qr;
|
||||||
|
document.getElementById('qrcode').innerHTML = '';
|
||||||
|
new QRCode(document.getElementById('qrcode'), {
|
||||||
|
text: data.qr,
|
||||||
|
width: 256,
|
||||||
|
height: 256
|
||||||
|
});
|
||||||
|
}
|
||||||
|
document.getElementById('status').textContent = 'Scan with WhatsApp';
|
||||||
|
setTimeout(pollQR, 5000);
|
||||||
|
} else if (data.status === 'ready') {
|
||||||
|
document.getElementById('status').textContent = 'Connected! Verifying phone...';
|
||||||
|
document.getElementById('qrcode').innerHTML = '✓';
|
||||||
|
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...';
|
||||||
|
setTimeout(pollQR, 8000);
|
||||||
|
} else {
|
||||||
|
document.getElementById('status').textContent = 'Status: ' + data.status;
|
||||||
|
setTimeout(pollQR, 5000);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
document.getElementById('status').textContent = 'Connection error — retrying...';
|
||||||
|
setTimeout(pollQR, 5000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
pollQR();
|
||||||
|
</script>
|
||||||
|
<p><a href="/">Back to Home</a> | <a href="/clients">Back to Clients</a></p>
|
||||||
|
</body></html>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func jsonEscape(s string) string {
|
||||||
|
b, _ := json.Marshal(s)
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
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(a.DB, accountID, clientID)
|
||||||
|
if err != nil {
|
||||||
|
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 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 := a.WAConnector.IsConnected(r.Context(), clientID)
|
||||||
|
if err != nil {
|
||||||
|
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; charset=utf-8")
|
||||||
|
w.Write([]byte(`{"client_id":` + strconv.FormatInt(client.ClientID, 10) + `,"status":"ready"}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
log.Printf("QR: Starting Connect for client %d", 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()) + `}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
timeout := time.After(30 * time.Second)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-timeout:
|
||||||
|
log.Printf("QR: Timeout waiting for client %d", clientID)
|
||||||
|
w.Write([]byte(`{"client_id":` + strconv.FormatInt(client.ClientID, 10) + `,"status":"error","error":` + jsonEscape("timeout waiting for QR code") + `}`))
|
||||||
|
return
|
||||||
|
case frame, ok := <-qrChan:
|
||||||
|
if !ok {
|
||||||
|
w.Write([]byte(`{"client_id":` + strconv.FormatInt(client.ClientID, 10) + `,"status":"error","error":"connection closed"}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if frame.QR != "" {
|
||||||
|
w.Write([]byte(`{"client_id":` + strconv.FormatInt(client.ClientID, 10) + `,"qr":` + jsonEscape(frame.QR) + `,"status":"waiting"}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if frame.State == whatsapp.StateConnected {
|
||||||
|
w.Write([]byte(`{"client_id":` + strconv.FormatInt(client.ClientID, 10) + `,"status":"ready"}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if frame.State == whatsapp.StateFailed {
|
||||||
|
w.Write([]byte(`{"client_id":` + strconv.FormatInt(client.ClientID, 10) + `,"status":"error","error":` + jsonEscape(frame.Error) + `}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-crm/internal/whatsapp"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newQRTestEnv(t *testing.T) (clientID int64, sessionID string, cleanup func()) {
|
||||||
|
t.Helper()
|
||||||
|
testDB, cleanupDB := SetupTestDB(t)
|
||||||
|
|
||||||
|
DB = testDB
|
||||||
|
WAConnector = whatsapp.NewFakeConnector()
|
||||||
|
|
||||||
|
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
||||||
|
testDB.Exec(
|
||||||
|
"INSERT INTO accounts (email, name, password, created_at) VALUES (?, ?, ?, ?)",
|
||||||
|
"[email protected]", "QR Test Account", string(hashedPassword), time.Now().Unix(),
|
||||||
|
)
|
||||||
|
|
||||||
|
var accountID int64
|
||||||
|
testDB.QueryRow("SELECT account_id FROM accounts WHERE email = ?", "[email protected]").Scan(&accountID)
|
||||||
|
|
||||||
|
sessionID = "qr-test-session"
|
||||||
|
testDB.Exec(
|
||||||
|
"INSERT INTO sessions (session_id, account_id, expires) VALUES (?, ?, ?)",
|
||||||
|
sessionID, accountID, time.Now().Add(time.Hour).Unix(),
|
||||||
|
)
|
||||||
|
|
||||||
|
testDB.QueryRow(
|
||||||
|
"INSERT INTO clients (account_id, name, phone, created_at) VALUES (?, ?, ?, ?) RETURNING client_id",
|
||||||
|
accountID, "QR Test Client", "+5521999999999", time.Now().Unix(),
|
||||||
|
).Scan(&clientID)
|
||||||
|
|
||||||
|
return clientID, sessionID, cleanupDB
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLeadsQR_FirstPollReturnsQRCode(t *testing.T) {
|
||||||
|
clientID, sessionID, cleanup := newQRTestEnv(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/leads/qr?client_id="+strconv.FormatInt(clientID, 10), nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
LeadsQR(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var resp map[string]interface{}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||||
|
t.Fatalf("invalid JSON: %v — body: %s", err, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp["qr"] == nil || resp["qr"] == "" {
|
||||||
|
t.Errorf("expected non-empty qr field, got: %v", resp)
|
||||||
|
}
|
||||||
|
if resp["status"] != "waiting" {
|
||||||
|
t.Errorf("expected status=waiting, got: %v", resp["status"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLeadsQR_AlreadyConnectedReturnsReady(t *testing.T) {
|
||||||
|
clientID, sessionID, cleanup := newQRTestEnv(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
// Mark the client as connected in the fake connector.
|
||||||
|
WAConnector.(*whatsapp.FakeConnector).MarkConnected(clientID)
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/leads/qr?client_id="+strconv.FormatInt(clientID, 10), nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
LeadsQR(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var resp map[string]interface{}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||||
|
t.Fatalf("invalid JSON: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp["status"] != "ready" {
|
||||||
|
t.Errorf("expected status=ready, got: %v", resp["status"])
|
||||||
|
}
|
||||||
|
if resp["qr"] != nil {
|
||||||
|
t.Errorf("expected no qr field when already connected, got: %v", resp["qr"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLeadsQR_ConnectorErrorReturnsErrorStatus(t *testing.T) {
|
||||||
|
clientID, sessionID, cleanup := newQRTestEnv(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
fake := whatsapp.NewFakeConnector()
|
||||||
|
fake.SetConnectError(fmt.Errorf("connector unavailable"))
|
||||||
|
WAConnector = fake
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/leads/qr?client_id="+strconv.FormatInt(clientID, 10), nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
LeadsQR(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d", w.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
var resp map[string]interface{}
|
||||||
|
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||||
|
t.Fatalf("invalid JSON: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp["status"] != "error" {
|
||||||
|
t.Errorf("expected status=error, got: %v", resp["status"])
|
||||||
|
}
|
||||||
|
if resp["error"] == nil || resp["error"] == "" {
|
||||||
|
t.Errorf("expected non-empty error field")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLeadsQR_UnknownClientReturnsNotFound(t *testing.T) {
|
||||||
|
_, sessionID, cleanup := newQRTestEnv(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/leads/qr?client_id=99999", nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
LeadsQR(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLeadsQR_NoSessionReturnsUnauthorized(t *testing.T) {
|
||||||
|
clientID, _, cleanup := newQRTestEnv(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/leads/qr?client_id="+strconv.FormatInt(clientID, 10), nil)
|
||||||
|
// No session cookie.
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
LeadsQR(w, req)
|
||||||
|
|
||||||
|
// /leads/qr is API-mode: returns JSON {"error":"unauthorized"}, not a redirect.
|
||||||
|
body := w.Body.String()
|
||||||
|
if !strings.Contains(body, "unauthorized") {
|
||||||
|
t.Errorf("expected unauthorized in response body, got: %s", body)
|
||||||
|
}
|
||||||
|
// Must not return a QR code or ready status.
|
||||||
|
if strings.Contains(body, `"qr"`) || strings.Contains(body, `"ready"`) {
|
||||||
|
t.Errorf("unauthenticated response must not contain qr or ready: %s", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLeadsQR_WAConnectorNilReturns503(t *testing.T) {
|
||||||
|
clientID, sessionID, cleanup := newQRTestEnv(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
WAConnector = nil
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/leads/qr?client_id="+strconv.FormatInt(clientID, 10), nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
LeadsQR(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusServiceUnavailable {
|
||||||
|
t.Errorf("expected 503, got %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLeadsQR_SecondPollBeforeScanStillReturnsQR(t *testing.T) {
|
||||||
|
clientID, sessionID, cleanup := newQRTestEnv(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
// Pre-queue two QR frames so both polls have something to read from the shared channel.
|
||||||
|
fake := WAConnector.(*whatsapp.FakeConnector)
|
||||||
|
fake.QueueQR(clientID,
|
||||||
|
whatsapp.QRFrame{QR: "qr-code-poll-1", State: whatsapp.StateWaitingQR},
|
||||||
|
whatsapp.QRFrame{QR: "qr-code-poll-2", State: whatsapp.StateWaitingQR},
|
||||||
|
)
|
||||||
|
|
||||||
|
// First poll.
|
||||||
|
req1 := httptest.NewRequest(http.MethodGet, "/leads/qr?client_id="+strconv.FormatInt(clientID, 10), nil)
|
||||||
|
req1.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||||
|
w1 := httptest.NewRecorder()
|
||||||
|
LeadsQR(w1, req1)
|
||||||
|
|
||||||
|
var resp1 map[string]interface{}
|
||||||
|
json.Unmarshal(w1.Body.Bytes(), &resp1)
|
||||||
|
if resp1["status"] != "waiting" {
|
||||||
|
t.Fatalf("first poll: expected waiting, got %v — body: %s", resp1["status"], w1.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Second poll — same channel reused, second QR frame available.
|
||||||
|
req2 := httptest.NewRequest(http.MethodGet, "/leads/qr?client_id="+strconv.FormatInt(clientID, 10), nil)
|
||||||
|
req2.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||||
|
w2 := httptest.NewRecorder()
|
||||||
|
LeadsQR(w2, req2)
|
||||||
|
|
||||||
|
var resp2 map[string]interface{}
|
||||||
|
if err := json.Unmarshal(w2.Body.Bytes(), &resp2); err != nil {
|
||||||
|
t.Fatalf("second poll: invalid JSON: %v — body: %s", err, w2.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp2["status"] == "ready" {
|
||||||
|
t.Errorf("second poll: got ready before scan — IsConnected/IsLoggedIn mismatch bug present")
|
||||||
|
}
|
||||||
|
if resp2["qr"] == nil || resp2["qr"] == "" {
|
||||||
|
t.Errorf("second poll: expected QR code, got: %v", resp2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLeadsQR_QRCodeResponseContainsClientID(t *testing.T) {
|
||||||
|
clientID, sessionID, cleanup := newQRTestEnv(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/leads/qr?client_id="+strconv.FormatInt(clientID, 10), nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: "session", Value: sessionID})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
|
||||||
|
LeadsQR(w, req)
|
||||||
|
|
||||||
|
body := w.Body.String()
|
||||||
|
if !strings.Contains(body, strconv.FormatInt(clientID, 10)) {
|
||||||
|
t.Errorf("response missing client_id: %s", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-crm/internal/db"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (a *App) ListPayments(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||||
|
clientID, _ := strconv.ParseInt(r.URL.Query().Get("client_id"), 10, 64)
|
||||||
|
if limit == 0 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
payments, err := db.ListPayments(a.DB, clientID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
clients, err := db.ListClients(a.DB, accountID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
customers, err := db.ListCustomers(a.DB, accountID, clientID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var clientOptions, customerOptions string
|
||||||
|
clientNames := make(map[int64]string)
|
||||||
|
customerNames := make(map[int64]string)
|
||||||
|
for _, c := range clients {
|
||||||
|
clientOptions += `<option value="` + strconv.FormatInt(c.ClientID, 10) + `">` + c.Name + `</option>`
|
||||||
|
clientNames[c.ClientID] = c.Name
|
||||||
|
}
|
||||||
|
for _, cu := range customers {
|
||||||
|
customerOptions += `<option value="` + strconv.FormatInt(cu.CustomerID, 10) + `">` + cu.Name + `</option>`
|
||||||
|
customerNames[cu.CustomerID] = cu.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
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"
|
||||||
|
if p.HasPaid {
|
||||||
|
paid = "Yes"
|
||||||
|
}
|
||||||
|
clientName := clientNames[p.ClientID]
|
||||||
|
if clientName == "" {
|
||||||
|
clientName = strconv.FormatInt(p.ClientID, 10)
|
||||||
|
}
|
||||||
|
customerName := customerNames[p.CustomerID]
|
||||||
|
if customerName == "" {
|
||||||
|
customerName = strconv.FormatInt(p.CustomerID, 10)
|
||||||
|
}
|
||||||
|
w.Write([]byte(`<tr><td>` + clientName + `</td><td>` + customerName + `</td><td>` + strconv.FormatFloat(p.Amount, 'f', 2, 64) + `</td><td>` + paid + `</td><td>` + p.PaymentDate + `</td><td>` + p.PaymentMethod + `</td><td><a href="/payments/` + strconv.FormatInt(p.PaymentID, 10) + `">View</a><button type="button" onclick="document.getElementById('editPay` + strconv.FormatInt(p.PaymentID, 10) + `').style.display='table-row'">Edit</button><form method="DELETE" style="display:inline" hx-delete="/payments/` + strconv.FormatInt(p.PaymentID, 10) + `" hx-target="closest tr"><button type="submit">Delete</button></form></td></tr><tr id="editPay` + strconv.FormatInt(p.PaymentID, 10) + `" style="display:none"><td colspan="7"><form hx-put="/payments/` + strconv.FormatInt(p.PaymentID, 10) + `" hx-target="#paymentList" hx-swap="innerHTML"><select name="client_id"><option value="` + strconv.FormatInt(p.ClientID, 10) + `">` + clientName + `</option>` + clientOptions + `</select><select name="customer_id"><option value="` + strconv.FormatInt(p.CustomerID, 10) + `">` + customerName + `</option>` + customerOptions + `</select><input type="checkbox" name="has_paid"><input type="number" name="amount" value="` + strconv.FormatFloat(p.Amount, 'f', 2, 64) + `"><input type="date" name="payment_date" value="` + p.PaymentDate + `"><select name="payment_method"><option value="` + p.PaymentMethod + `">` + p.PaymentMethod + `</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">Save</button></form></td></tr>`))
|
||||||
|
}
|
||||||
|
w.Write([]byte(`</tbody></table></body></html>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) CreatePayment(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
r.ParseForm()
|
||||||
|
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||||
|
customerID, _ := strconv.ParseInt(r.FormValue("customer_id"), 10, 64)
|
||||||
|
scheduleID, _ := strconv.ParseInt(r.FormValue("schedule_id"), 10, 64)
|
||||||
|
amount, _ := strconv.ParseFloat(r.FormValue("amount"), 64)
|
||||||
|
hasPaid := r.FormValue("has_paid") == "on"
|
||||||
|
|
||||||
|
payment := db.Payment{
|
||||||
|
ClientID: clientID,
|
||||||
|
CustomerID: customerID,
|
||||||
|
ScheduleID: scheduleID,
|
||||||
|
HasPaid: hasPaid,
|
||||||
|
Amount: amount,
|
||||||
|
PaymentDate: r.FormValue("payment_date"),
|
||||||
|
PaymentMethod: r.FormValue("payment_method"),
|
||||||
|
CreatedAt: time.Now().Unix(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := payment.Create(a.DB); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) ViewPayment(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id, _ := strconv.ParseInt(r.URL.Query().Get("id"), 10, 64)
|
||||||
|
var p db.Payment
|
||||||
|
var hasPaid int
|
||||||
|
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; 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 (a *App) UpdatePayment(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
r.ParseForm()
|
||||||
|
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||||
|
customerID, _ := strconv.ParseInt(r.FormValue("customer_id"), 10, 64)
|
||||||
|
amount, _ := strconv.ParseFloat(r.FormValue("amount"), 64)
|
||||||
|
hasPaid := r.FormValue("has_paid") == "on"
|
||||||
|
_, 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
|
||||||
|
}
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
a.DB.Exec("DELETE FROM payments WHERE payment_id = ?", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-crm/internal/db"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (a *App) ListQuestions(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||||
|
clientID, _ := strconv.ParseInt(r.URL.Query().Get("client_id"), 10, 64)
|
||||||
|
if limit == 0 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
questions, err := db.ListQuestions(a.DB, clientID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
clients, err := db.ListClients(a.DB, accountID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
customers, err := db.ListCustomers(a.DB, accountID, clientID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var clientOptions, customerOptions string
|
||||||
|
clientNames := make(map[int64]string)
|
||||||
|
customerNames := make(map[int64]string)
|
||||||
|
for _, c := range clients {
|
||||||
|
clientOptions += `<option value="` + strconv.FormatInt(c.ClientID, 10) + `">` + c.Name + `</option>`
|
||||||
|
clientNames[c.ClientID] = c.Name
|
||||||
|
}
|
||||||
|
for _, cu := range customers {
|
||||||
|
customerOptions += `<option value="` + strconv.FormatInt(cu.CustomerID, 10) + `">` + cu.Name + `</option>`
|
||||||
|
customerNames[cu.CustomerID] = cu.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
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]
|
||||||
|
if clientName == "" {
|
||||||
|
clientName = strconv.FormatInt(q.ClientID, 10)
|
||||||
|
}
|
||||||
|
customerName := customerNames[q.CustomerID]
|
||||||
|
if customerName == "" {
|
||||||
|
customerName = strconv.FormatInt(q.CustomerID, 10)
|
||||||
|
}
|
||||||
|
w.Write([]byte(`<tr><td>` + clientName + `</td><td>` + customerName + `</td><td>` + q.Question + `</td><td>` + q.Status + `</td><td><a href="/questions/` + strconv.FormatInt(q.QuestionID, 10) + `">View</a><button type="button" onclick="document.getElementById('editQ` + strconv.FormatInt(q.QuestionID, 10) + `').style.display='table-row'">Edit</button><form method="DELETE" style="display:inline" hx-delete="/questions/` + strconv.FormatInt(q.QuestionID, 10) + `" hx-target="closest tr"><button type="submit">Delete</button></form></td></tr><tr id="editQ` + strconv.FormatInt(q.QuestionID, 10) + `" style="display:none"><td colspan="5"><form hx-put="/questions/` + strconv.FormatInt(q.QuestionID, 10) + `" hx-target="#questionList" hx-swap="innerHTML"><select name="client_id"><option value="` + strconv.FormatInt(q.ClientID, 10) + `">` + clientName + `</option>` + clientOptions + `</select><select name="customer_id"><option value="` + strconv.FormatInt(q.CustomerID, 10) + `">` + customerName + `</option>` + customerOptions + `</select><textarea name="question">` + q.Question + `</textarea><select name="status"><option value="` + q.Status + `">` + q.Status + `</option><option value="pending">Pending</option><option value="answered">Answered</option></select><button type="submit">Save</button></form></td></tr>`))
|
||||||
|
}
|
||||||
|
w.Write([]byte(`</tbody></table></body></html>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) CreateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
r.ParseForm()
|
||||||
|
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||||
|
customerID, _ := strconv.ParseInt(r.FormValue("customer_id"), 10, 64)
|
||||||
|
question := db.Question{
|
||||||
|
ClientID: clientID,
|
||||||
|
CustomerID: customerID,
|
||||||
|
Question: r.FormValue("question"),
|
||||||
|
Timestamp: time.Now().Unix(),
|
||||||
|
Status: r.FormValue("status"),
|
||||||
|
CreatedAt: time.Now().Unix(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := question.Create(a.DB); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
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 := 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; 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 (a *App) UpdateQuestion(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
r.ParseForm()
|
||||||
|
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||||
|
customerID, _ := strconv.ParseInt(r.FormValue("customer_id"), 10, 64)
|
||||||
|
_, 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
|
||||||
|
}
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
a.DB.Exec("DELETE FROM questions WHERE question_id = ?", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) ListAnswers(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||||
|
questionID, _ := strconv.ParseInt(r.URL.Query().Get("question_id"), 10, 64)
|
||||||
|
if limit == 0 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
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(a.DB, 0, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var questionOptions string
|
||||||
|
questionText := make(map[int64]string)
|
||||||
|
for _, q := range questions {
|
||||||
|
questionOptions += `<option value="` + strconv.FormatInt(q.QuestionID, 10) + `">` + q.Question + `</option>`
|
||||||
|
questionText[q.QuestionID] = q.Question
|
||||||
|
}
|
||||||
|
|
||||||
|
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-form { display:none; margin-top:0.5rem; padding:0.5rem; border:1px solid #ccc; }
|
||||||
|
.edit-row { display:none; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Answers</h1>
|
||||||
|
<button class="btn" onclick="document.getElementById('answerForm').style.display='block'">Add Answer</button>
|
||||||
|
<div id="answerForm" style="display:none; margin-top:1rem;">
|
||||||
|
<form hx-post="/answers" hx-target="#answerList" hx-swap="innerHTML">
|
||||||
|
<select name="question_id" required>
|
||||||
|
<option value="">Select Question</option>
|
||||||
|
` + questionOptions + `
|
||||||
|
</select>
|
||||||
|
<textarea name="answer" placeholder="Answer" required></textarea>
|
||||||
|
<button type="submit">Add Answer</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr><th>Client</th><th>Customer</th><th>Question</th><th>Answer</th><th>Status</th><th>Actions</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="answerList">
|
||||||
|
`))
|
||||||
|
for _, a2 := range answers {
|
||||||
|
qText := a2.QuestionText
|
||||||
|
if qText == "" {
|
||||||
|
qText = questionText[a2.QuestionID]
|
||||||
|
if qText == "" {
|
||||||
|
qText = strconv.FormatInt(a2.QuestionID, 10)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
clientName := a2.ClientName
|
||||||
|
if clientName == "" {
|
||||||
|
clientName = strconv.FormatInt(a2.ClientID, 10)
|
||||||
|
}
|
||||||
|
customerName := a2.CustomerName
|
||||||
|
if customerName == "" {
|
||||||
|
customerName = "Unknown"
|
||||||
|
}
|
||||||
|
w.Write([]byte(`
|
||||||
|
<tr>
|
||||||
|
<td>` + clientName + `</td>
|
||||||
|
<td>` + customerName + `</td>
|
||||||
|
<td>` + qText + `</td>
|
||||||
|
<td>` + a2.Answer + `</td>
|
||||||
|
<td>` + a2.Status + `</td>
|
||||||
|
<td>
|
||||||
|
<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(a2.AnswerID, 10) + `" class="edit-row" style="display:none">
|
||||||
|
<td colspan="6">
|
||||||
|
<form hx-put="/answers/` + strconv.FormatInt(a2.AnswerID, 10) + `" hx-target="#answerList" hx-swap="innerHTML">
|
||||||
|
<select name="question_id">
|
||||||
|
<option value="` + strconv.FormatInt(a2.QuestionID, 10) + `">` + qText + `</option>
|
||||||
|
` + questionOptions + `
|
||||||
|
</select>
|
||||||
|
<textarea name="answer">` + a2.Answer + `</textarea>
|
||||||
|
<button type="submit">Save</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>`))
|
||||||
|
}
|
||||||
|
w.Write([]byte(`
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) CreateAnswer(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
r.ParseForm()
|
||||||
|
questionID, _ := strconv.ParseInt(r.FormValue("question_id"), 10, 64)
|
||||||
|
|
||||||
|
var clientID int64
|
||||||
|
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 = 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
|
||||||
|
}
|
||||||
|
|
||||||
|
answer := db.Answer{
|
||||||
|
ClientID: clientID,
|
||||||
|
QuestionID: questionID,
|
||||||
|
Answer: r.FormValue("answer"),
|
||||||
|
Timestamp: time.Now().Unix(),
|
||||||
|
Status: "active",
|
||||||
|
CreatedAt: time.Now().Unix(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := answer.Create(a.DB); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
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 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; 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 (a *App) UpdateAnswer(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
r.ParseForm()
|
||||||
|
questionID, _ := strconv.ParseInt(r.FormValue("question_id"), 10, 64)
|
||||||
|
_, 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
|
||||||
|
}
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-crm/internal/db"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (a *App) ListSchedules(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||||
|
clientID, _ := strconv.ParseInt(r.URL.Query().Get("client_id"), 10, 64)
|
||||||
|
customerID, _ := strconv.ParseInt(r.URL.Query().Get("customer_id"), 10, 64)
|
||||||
|
if limit == 0 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
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(a.DB, accountID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
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(a.DB, accountID, clientID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var clientOptions, customerOptions, serviceOptions string
|
||||||
|
clientNames := make(map[int64]string)
|
||||||
|
customerNames := make(map[int64]string)
|
||||||
|
serviceNames := make(map[int64]string)
|
||||||
|
for _, c := range clients {
|
||||||
|
clientOptions += `<option value="` + strconv.FormatInt(c.ClientID, 10) + `">` + c.Name + `</option>`
|
||||||
|
clientNames[c.ClientID] = c.Name
|
||||||
|
}
|
||||||
|
for _, cu := range customers {
|
||||||
|
customerOptions += `<option value="` + strconv.FormatInt(cu.CustomerID, 10) + `">` + cu.Name + `</option>`
|
||||||
|
customerNames[cu.CustomerID] = cu.Name
|
||||||
|
}
|
||||||
|
for _, s := range services {
|
||||||
|
serviceOptions += `<option value="` + strconv.FormatInt(s.ServiceID, 10) + `">` + s.Name + `</option>`
|
||||||
|
serviceNames[s.ServiceID] = s.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
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]
|
||||||
|
if clientName == "" {
|
||||||
|
clientName = strconv.FormatInt(s.ClientID, 10)
|
||||||
|
}
|
||||||
|
customerName := customerNames[s.CustomerID]
|
||||||
|
if customerName == "" {
|
||||||
|
customerName = strconv.FormatInt(s.CustomerID, 10)
|
||||||
|
}
|
||||||
|
serviceName := serviceNames[s.ServiceID]
|
||||||
|
if serviceName == "" {
|
||||||
|
serviceName = strconv.FormatInt(s.ServiceID, 10)
|
||||||
|
}
|
||||||
|
w.Write([]byte(`<tr><td>` + clientName + `</td><td>` + customerName + `</td><td>` + serviceName + `</td><td>` + s.PlanDate + `</td><td>` + s.Time + `</td><td>` + s.Status + `</td><td><a href="/scheduling/` + strconv.FormatInt(s.ScheduleID, 10) + `">View</a><button type="button" onclick="document.getElementById('editSched` + strconv.FormatInt(s.ScheduleID, 10) + `').style.display='table-row'">Edit</button><form method="DELETE" style="display:inline" hx-delete="/scheduling/` + strconv.FormatInt(s.ScheduleID, 10) + `" hx-target="closest tr"><button type="submit">Delete</button></form></td></tr><tr id="editSched` + strconv.FormatInt(s.ScheduleID, 10) + `" class="edit-row" style="display:none"><td colspan="7"><form hx-put="/scheduling/` + strconv.FormatInt(s.ScheduleID, 10) + `" hx-target="#scheduleList" hx-swap="innerHTML"><select name="client_id"><option value="` + strconv.FormatInt(s.ClientID, 10) + `">` + clientName + `</option>` + clientOptions + `</select><select name="customer_id"><option value="` + strconv.FormatInt(s.CustomerID, 10) + `">` + customerName + `</option>` + customerOptions + `</select><select name="service_id"><option value="` + strconv.FormatInt(s.ServiceID, 10) + `">` + serviceName + `</option>` + serviceOptions + `</select><input type="date" name="plan_date" value="` + s.PlanDate + `"><input type="time" name="time" value="` + s.Time + `"><select name="status"><option value="` + s.Status + `">` + s.Status + `</option><option value="pending">Pending</option><option value="confirmed">Confirmed</option><option value="cancelled">Cancelled</option></select><button type="submit">Save</button></form></td></tr>`))
|
||||||
|
}
|
||||||
|
w.Write([]byte(`</tbody></table></body></html>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) CreateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
r.ParseForm()
|
||||||
|
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)
|
||||||
|
schedule := db.Schedule{
|
||||||
|
ClientID: clientID,
|
||||||
|
CustomerID: customerID,
|
||||||
|
ServiceID: serviceID,
|
||||||
|
PlanDate: r.FormValue("plan_date"),
|
||||||
|
Time: r.FormValue("time"),
|
||||||
|
Status: r.FormValue("status"),
|
||||||
|
CreatedAt: time.Now().Unix(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := schedule.Create(a.DB); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
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 := 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; 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 (a *App) UpdateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
r.ParseForm()
|
||||||
|
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 := 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
|
||||||
|
}
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-crm/internal/db"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (a *App) ListServices(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||||
|
clientID, _ := strconv.ParseInt(r.URL.Query().Get("client_id"), 10, 64)
|
||||||
|
if limit == 0 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
|
||||||
|
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(a.DB, accountID, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var clientOptions string
|
||||||
|
for _, c := range clients {
|
||||||
|
clientOptions += `<option value="` + strconv.FormatInt(c.ClientID, 10) + `">` + c.Name + `</option>`
|
||||||
|
}
|
||||||
|
|
||||||
|
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>`))
|
||||||
|
}
|
||||||
|
w.Write([]byte(`</tbody></table></body></html>`))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) CreateService(w http.ResponseWriter, r *http.Request) {
|
||||||
|
accountID, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
r.ParseForm()
|
||||||
|
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||||
|
|
||||||
|
var checkID int64
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
price, _ := strconv.ParseFloat(r.FormValue("price"), 64)
|
||||||
|
service := db.Service{
|
||||||
|
ClientID: clientID,
|
||||||
|
Name: r.FormValue("name"),
|
||||||
|
Price: price,
|
||||||
|
Description: r.FormValue("description"),
|
||||||
|
Duration: r.FormValue("duration"),
|
||||||
|
CreatedAt: time.Now().Unix(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := service.Create(a.DB); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
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 := 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; 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 (a *App) UpdateService(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, ok := a.requireAuth(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
r.ParseForm()
|
||||||
|
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
|
||||||
|
price, _ := strconv.ParseFloat(r.FormValue("price"), 64)
|
||||||
|
_, 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
|
||||||
|
}
|
||||||
|
w.Header().Set("HX-Refresh", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{{ define "content" }}
|
||||||
|
<h1>Welcome to CRM</h1>
|
||||||
|
<p>Manage your clients, customers, and scheduling.</p>
|
||||||
|
{{ end }}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package templates
|
||||||
|
|
||||||
|
import (
|
||||||
|
"html/template"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
templates *template.Template
|
||||||
|
mu sync.RWMutex
|
||||||
|
)
|
||||||
|
|
||||||
|
func Init() {
|
||||||
|
templates = template.Must(template.New("").ParseGlob("internal/templates/*.html"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Layout(title, content string) *template.Template {
|
||||||
|
mu.RLock()
|
||||||
|
defer mu.RUnlock()
|
||||||
|
|
||||||
|
tmpl := template.Must(template.New("layout.html").Parse(`<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>{{ .Title }}</title>
|
||||||
|
<script src="https://unpkg.com/[email protected]"></script>
|
||||||
|
<style>
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; }
|
||||||
|
.container { max-width: 1200px; margin: 0 auto; padding: 20px; }
|
||||||
|
nav { background: white; border-bottom: 1px solid #e0e0e0; padding: 1rem 0; margin-bottom: 2rem; }
|
||||||
|
nav ul { list-style: none; display: flex; gap: 1.5rem; max-width: 1200px; margin: 0 auto; padding: 0 20px; }
|
||||||
|
nav a { color: #333; text-decoration: none; }
|
||||||
|
nav a:hover { color: #007bff; }
|
||||||
|
.card { background: white; border-radius: 8px; padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
|
||||||
|
.btn { display: inline-block; padding: 0.5rem 1rem; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; text-decoration: none; }
|
||||||
|
.btn:hover { background: #0056b3; }
|
||||||
|
.btn-secondary { background: #6c757d; }
|
||||||
|
.btn-danger { background: #dc3545; }
|
||||||
|
table { width: 100%; border-collapse: collapse; }
|
||||||
|
th, td { padding: 0.75rem; text-align: left; border-bottom: 1px solid #e0e0e0; }
|
||||||
|
th { background: #f8f9fa; font-weight: 600; }
|
||||||
|
form { display: flex; flex-direction: column; gap: 1rem; max-width: 500px; }
|
||||||
|
input, textarea, select { padding: 0.5rem; border: 1px solid #ddd; border-radius: 4px; width: 100%; }
|
||||||
|
textarea { min-height: 100px; }
|
||||||
|
.error { color: #dc3545; }
|
||||||
|
.success { color: #28a745; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<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>
|
||||||
|
<li><a href="/scheduling">Scheduling</a></li>
|
||||||
|
<li><a href="/payments">Payments</a></li>
|
||||||
|
<li><a href="/questions">Questions</a></li>
|
||||||
|
<li><a href="/answers">Answers</a></li>
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
<div class="container">
|
||||||
|
{{ .Content }}
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>`))
|
||||||
|
|
||||||
|
return tmpl
|
||||||
|
}
|
||||||
|
|
||||||
|
func Get(name string) *template.Template {
|
||||||
|
mu.RLock()
|
||||||
|
defer mu.RUnlock()
|
||||||
|
return templates.Lookup(name)
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package whatsapp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ConnectionState string
|
||||||
|
|
||||||
|
const (
|
||||||
|
StateDisconnected ConnectionState = "disconnected"
|
||||||
|
StateConnecting ConnectionState = "connecting"
|
||||||
|
StateWaitingQR ConnectionState = "waiting_qr"
|
||||||
|
StateConnected ConnectionState = "connected"
|
||||||
|
StateFailed ConnectionState = "failed"
|
||||||
|
)
|
||||||
|
|
||||||
|
type QRFrame struct {
|
||||||
|
QR string
|
||||||
|
State ConnectionState
|
||||||
|
Error string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Contact struct {
|
||||||
|
Phone string
|
||||||
|
Name string
|
||||||
|
Message string // raw text of the first/incoming message
|
||||||
|
FromMe bool
|
||||||
|
Time time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type ContactHandler interface {
|
||||||
|
OnContact(ctx context.Context, clientID int64, contact Contact) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Connector interface {
|
||||||
|
Connect(ctx context.Context, clientID int64) (<-chan QRFrame, error)
|
||||||
|
Disconnect(ctx context.Context, clientID int64) error
|
||||||
|
IsConnected(ctx context.Context, clientID int64) (bool, error)
|
||||||
|
SetClientDB(db interface{})
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package whatsapp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FakeConnector struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
connected map[int64]bool
|
||||||
|
qrChan map[int64]chan QRFrame
|
||||||
|
qrQueue map[int64][]QRFrame
|
||||||
|
connectErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFakeConnector() *FakeConnector {
|
||||||
|
return &FakeConnector{
|
||||||
|
connected: make(map[int64]bool),
|
||||||
|
qrChan: make(map[int64]chan QRFrame),
|
||||||
|
qrQueue: make(map[int64][]QRFrame),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FakeConnector) SetConnectError(err error) {
|
||||||
|
f.connectErr = err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FakeConnector) QueueQR(clientID int64, frames ...QRFrame) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
f.qrQueue[clientID] = append(f.qrQueue[clientID], frames...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FakeConnector) Connect(ctx context.Context, clientID int64) (<-chan QRFrame, error) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
|
||||||
|
if f.connectErr != nil {
|
||||||
|
return nil, f.connectErr
|
||||||
|
}
|
||||||
|
|
||||||
|
// Already connected — return immediately.
|
||||||
|
if f.connected[clientID] {
|
||||||
|
ch := make(chan QRFrame, 1)
|
||||||
|
ch <- QRFrame{State: StateConnected}
|
||||||
|
close(ch)
|
||||||
|
return ch, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// QR session already in progress — reuse same channel (mirrors real adapter behaviour).
|
||||||
|
if ch, ok := f.qrChan[clientID]; ok {
|
||||||
|
return ch, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// New session — create channel and seed with QR frame(s).
|
||||||
|
ch := make(chan QRFrame, 20)
|
||||||
|
f.qrChan[clientID] = ch
|
||||||
|
|
||||||
|
queue := f.qrQueue[clientID]
|
||||||
|
if len(queue) == 0 {
|
||||||
|
ch <- QRFrame{QR: "fake-qr-code-for-testing", State: StateWaitingQR}
|
||||||
|
} else {
|
||||||
|
for _, frame := range queue {
|
||||||
|
ch <- frame
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ch, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FakeConnector) Disconnect(ctx context.Context, clientID int64) error {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
|
||||||
|
if ch, ok := f.qrChan[clientID]; ok {
|
||||||
|
close(ch)
|
||||||
|
delete(f.qrChan, clientID)
|
||||||
|
}
|
||||||
|
delete(f.connected, clientID)
|
||||||
|
delete(f.qrQueue, clientID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FakeConnector) IsConnected(ctx context.Context, clientID int64) (bool, error) {
|
||||||
|
f.mu.RLock()
|
||||||
|
defer f.mu.RUnlock()
|
||||||
|
return f.connected[clientID], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FakeConnector) MarkConnected(clientID int64) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
f.connected[clientID] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FakeConnector) SetClientDB(db interface{}) {}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package whatsapp_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go-crm/internal/whatsapp"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestFakeConnector_FirstConnectReturnsQR verifies that a fresh Connect()
|
||||||
|
// emits a QR frame before the connected state.
|
||||||
|
func TestFakeConnector_FirstConnectReturnsQR(t *testing.T) {
|
||||||
|
fc := whatsapp.NewFakeConnector()
|
||||||
|
ch, err := fc.Connect(context.Background(), 1)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Connect failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case frame := <-ch:
|
||||||
|
if frame.QR == "" {
|
||||||
|
t.Errorf("expected QR code in first frame, got empty QR with state=%s", frame.State)
|
||||||
|
}
|
||||||
|
if frame.State != whatsapp.StateWaitingQR {
|
||||||
|
t.Errorf("expected StateWaitingQR, got %s", frame.State)
|
||||||
|
}
|
||||||
|
case <-time.After(500 * time.Millisecond):
|
||||||
|
t.Fatal("timeout waiting for QR frame")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFakeConnector_IsConnectedFalseBeforeScan verifies IsConnected returns false
|
||||||
|
// until MarkConnected is explicitly called — mirrors the IsLoggedIn() semantics.
|
||||||
|
func TestFakeConnector_IsConnectedFalseBeforeScan(t *testing.T) {
|
||||||
|
fc := whatsapp.NewFakeConnector()
|
||||||
|
|
||||||
|
connected, err := fc.IsConnected(context.Background(), 1)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("IsConnected error: %v", err)
|
||||||
|
}
|
||||||
|
if connected {
|
||||||
|
t.Errorf("expected not connected before any scan, got connected=true")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connect and drain QR frame — still not authenticated.
|
||||||
|
ch, _ := fc.Connect(context.Background(), 1)
|
||||||
|
<-ch // consume QR frame
|
||||||
|
|
||||||
|
connected, err = fc.IsConnected(context.Background(), 1)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("IsConnected error after Connect: %v", err)
|
||||||
|
}
|
||||||
|
if connected {
|
||||||
|
t.Errorf("expected not connected after QR issued but before scan, got connected=true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFakeConnector_IsConnectedTrueAfterMarkConnected verifies MarkConnected flips IsConnected.
|
||||||
|
func TestFakeConnector_IsConnectedTrueAfterMarkConnected(t *testing.T) {
|
||||||
|
fc := whatsapp.NewFakeConnector()
|
||||||
|
fc.MarkConnected(1)
|
||||||
|
|
||||||
|
connected, err := fc.IsConnected(context.Background(), 1)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("IsConnected error: %v", err)
|
||||||
|
}
|
||||||
|
if !connected {
|
||||||
|
t.Errorf("expected connected=true after MarkConnected, got false")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFakeConnector_ConnectErrorPropagates verifies SetConnectError is returned from Connect.
|
||||||
|
func TestFakeConnector_ConnectErrorPropagates(t *testing.T) {
|
||||||
|
fc := whatsapp.NewFakeConnector()
|
||||||
|
fc.SetConnectError(fmt.Errorf("simulated failure"))
|
||||||
|
|
||||||
|
_, err := fc.Connect(context.Background(), 1)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error from Connect, got nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFakeConnector_QueuedFramesDeliveredInOrder verifies custom QR frames via QueueQR.
|
||||||
|
func TestFakeConnector_QueuedFramesDeliveredInOrder(t *testing.T) {
|
||||||
|
fc := whatsapp.NewFakeConnector()
|
||||||
|
fc.QueueQR(1,
|
||||||
|
whatsapp.QRFrame{QR: "qr-frame-1", State: whatsapp.StateWaitingQR},
|
||||||
|
whatsapp.QRFrame{QR: "qr-frame-2", State: whatsapp.StateWaitingQR},
|
||||||
|
)
|
||||||
|
|
||||||
|
ch, err := fc.Connect(context.Background(), 1)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Connect failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
first := <-ch
|
||||||
|
if first.QR != "qr-frame-1" {
|
||||||
|
t.Errorf("expected qr-frame-1, got %q", first.QR)
|
||||||
|
}
|
||||||
|
|
||||||
|
second := <-ch
|
||||||
|
if second.QR != "qr-frame-2" {
|
||||||
|
t.Errorf("expected qr-frame-2, got %q", second.QR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFakeConnector_DisconnectClearsState verifies Disconnect removes connected state.
|
||||||
|
func TestFakeConnector_DisconnectClearsState(t *testing.T) {
|
||||||
|
fc := whatsapp.NewFakeConnector()
|
||||||
|
fc.MarkConnected(1)
|
||||||
|
|
||||||
|
if err := fc.Disconnect(context.Background(), 1); err != nil {
|
||||||
|
t.Fatalf("Disconnect error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
connected, _ := fc.IsConnected(context.Background(), 1)
|
||||||
|
if connected {
|
||||||
|
t.Errorf("expected connected=false after Disconnect")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFakeConnector_MultipleClientsIsolated verifies separate clients don't share state.
|
||||||
|
func TestFakeConnector_MultipleClientsIsolated(t *testing.T) {
|
||||||
|
fc := whatsapp.NewFakeConnector()
|
||||||
|
fc.MarkConnected(1)
|
||||||
|
|
||||||
|
connected1, _ := fc.IsConnected(context.Background(), 1)
|
||||||
|
connected2, _ := fc.IsConnected(context.Background(), 2)
|
||||||
|
|
||||||
|
if !connected1 {
|
||||||
|
t.Errorf("client 1 should be connected")
|
||||||
|
}
|
||||||
|
if connected2 {
|
||||||
|
t.Errorf("client 2 should not be connected")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,489 @@
|
|||||||
|
package whatsapp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
_ "github.com/glebarez/go-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"
|
||||||
|
)
|
||||||
|
|
||||||
|
type WhatsmeowAdapter struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
clients map[int64]*whatsmeow.Client
|
||||||
|
qrChans map[int64]chan QRFrame // persistent QR channel per client, reused across polls
|
||||||
|
container *sqlstore.Container
|
||||||
|
db *sql.DB
|
||||||
|
goEndpoint string
|
||||||
|
internalSecret string
|
||||||
|
appCtx context.Context
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewWhatsmeowAdapter(storePath, goEndpoint, internalSecret string) (*WhatsmeowAdapter, error) {
|
||||||
|
db, err := sql.Open("sqlite", storePath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to open database: %w", err)
|
||||||
|
}
|
||||||
|
_, err = db.Exec("PRAGMA foreign_keys = ON")
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to enable foreign keys: %w", err)
|
||||||
|
}
|
||||||
|
container := sqlstore.NewWithDB(db, "sqlite", waLog.Stdout("SQL", "DEBUG", true))
|
||||||
|
if err = container.Upgrade(context.Background()); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to upgrade database: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &WhatsmeowAdapter{
|
||||||
|
clients: make(map[int64]*whatsmeow.Client),
|
||||||
|
qrChans: make(map[int64]chan QRFrame),
|
||||||
|
container: container,
|
||||||
|
db: db,
|
||||||
|
goEndpoint: goEndpoint,
|
||||||
|
internalSecret: internalSecret,
|
||||||
|
appCtx: context.Background(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *WhatsmeowAdapter) Connect(ctx context.Context, clientID int64) (<-chan QRFrame, error) {
|
||||||
|
a.mu.Lock()
|
||||||
|
|
||||||
|
// Already authenticated — return immediately.
|
||||||
|
if client, ok := a.clients[clientID]; ok && client.IsLoggedIn() {
|
||||||
|
a.mu.Unlock()
|
||||||
|
ch := make(chan QRFrame, 1)
|
||||||
|
ch <- QRFrame{State: StateConnected}
|
||||||
|
close(ch)
|
||||||
|
return ch, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// QR session already in progress — return the same persistent channel.
|
||||||
|
// The goroutine keeps writing QR codes to it; each poll reads the latest one.
|
||||||
|
if ch, ok := a.qrChans[clientID]; ok {
|
||||||
|
a.mu.Unlock()
|
||||||
|
log.Printf("WA-Connect: Reusing existing QR session for client %d", clientID)
|
||||||
|
return ch, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read stored JID before releasing lock.
|
||||||
|
jid, _ := a.getJIDFromDBLocked(clientID)
|
||||||
|
a.mu.Unlock()
|
||||||
|
|
||||||
|
// Try to resume a previously paired session (no QR needed).
|
||||||
|
if jid != "" {
|
||||||
|
if ch, err := a.resumeSession(clientID, jid); err == nil {
|
||||||
|
return ch, nil
|
||||||
|
}
|
||||||
|
log.Printf("WA-Connect: Resume failed for client %d, starting QR flow", clientID)
|
||||||
|
// Clear stale JID so we don't retry resume on every poll.
|
||||||
|
a.clearJIDFromDB(clientID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start a fresh QR session — all network I/O, no lock held.
|
||||||
|
return a.startQRSession(clientID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// resumeSession attempts to reconnect a previously paired device using its stored JID.
|
||||||
|
func (a *WhatsmeowAdapter) resumeSession(clientID int64, jid string) (<-chan QRFrame, error) {
|
||||||
|
parsedJID, err := types.ParseJID(jid)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
device, err := a.container.GetDevice(a.appCtx, parsedJID)
|
||||||
|
if err != nil || device == nil {
|
||||||
|
return nil, fmt.Errorf("device not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
client := whatsmeow.NewClient(device, waLog.Stdout("Client-"+strconv.FormatInt(clientID, 10), "DEBUG", true))
|
||||||
|
|
||||||
|
a.mu.Lock()
|
||||||
|
a.clients[clientID] = client
|
||||||
|
a.mu.Unlock()
|
||||||
|
|
||||||
|
if err := client.Connect(); err != nil {
|
||||||
|
a.mu.Lock()
|
||||||
|
delete(a.clients, clientID)
|
||||||
|
a.mu.Unlock()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
a.addMessageHandler(client, clientID)
|
||||||
|
ch := make(chan QRFrame, 1)
|
||||||
|
ch <- QRFrame{State: StateConnected}
|
||||||
|
close(ch)
|
||||||
|
return ch, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// startQRSession creates a fresh device, initiates the WhatsApp WebSocket connection,
|
||||||
|
// and returns a persistent channel that emits QR frames. All network I/O without holding mutex.
|
||||||
|
// The channel is stored in a.qrChans so subsequent polls reuse it without restarting the session.
|
||||||
|
func (a *WhatsmeowAdapter) startQRSession(clientID int64) (<-chan QRFrame, error) {
|
||||||
|
device := a.container.NewDevice()
|
||||||
|
log.Printf("WA-Connect: Created device for client %d", clientID)
|
||||||
|
client := whatsmeow.NewClient(device, waLog.Stdout("Client-"+strconv.FormatInt(clientID, 10), "DEBUG", true))
|
||||||
|
|
||||||
|
// GetQRChannel must be called before Connect().
|
||||||
|
log.Printf("WA-Connect: Getting QR channel for client %d", clientID)
|
||||||
|
qrChan, err := client.GetQRChannel(a.appCtx)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("WA-Connect: GetQRChannel error for client %d: %v", clientID, err)
|
||||||
|
return nil, fmt.Errorf("failed to get QR channel: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ch is buffered so QR codes accumulate; polls read the latest available frame.
|
||||||
|
// Size 20 = enough to hold multiple rotated QR codes without blocking the goroutine.
|
||||||
|
ch := make(chan QRFrame, 20)
|
||||||
|
|
||||||
|
a.mu.Lock()
|
||||||
|
a.clients[clientID] = client
|
||||||
|
a.qrChans[clientID] = ch
|
||||||
|
a.mu.Unlock()
|
||||||
|
|
||||||
|
connectErr := make(chan error, 1)
|
||||||
|
|
||||||
|
log.Printf("WA-Connect: Starting Connect() goroutine for client %d", clientID)
|
||||||
|
go func() {
|
||||||
|
if err := client.Connect(); err != nil {
|
||||||
|
log.Printf("WA-Connect: Connect() error for client %d: %v", clientID, err)
|
||||||
|
connectErr <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("WA-Connect: Connect() succeeded for client %d", clientID)
|
||||||
|
connectErr <- nil
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Wait for WS handshake — lock NOT held, no deadlock risk.
|
||||||
|
select {
|
||||||
|
case err := <-connectErr:
|
||||||
|
if err != nil {
|
||||||
|
a.mu.Lock()
|
||||||
|
delete(a.clients, clientID)
|
||||||
|
delete(a.qrChans, clientID)
|
||||||
|
a.mu.Unlock()
|
||||||
|
return nil, fmt.Errorf("failed to connect: %w", err)
|
||||||
|
}
|
||||||
|
case <-time.After(15 * time.Second):
|
||||||
|
log.Printf("WA-Connect: Connect() timeout for client %d", clientID)
|
||||||
|
a.mu.Lock()
|
||||||
|
delete(a.clients, clientID)
|
||||||
|
delete(a.qrChans, clientID)
|
||||||
|
a.mu.Unlock()
|
||||||
|
return nil, fmt.Errorf("connection timeout")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fan-out goroutine: translates whatsmeow events into QRFrames on the persistent ch.
|
||||||
|
// Outlives any HTTP request. Cleans up qrChans entry on terminal events.
|
||||||
|
go func() {
|
||||||
|
defer func() {
|
||||||
|
a.mu.Lock()
|
||||||
|
delete(a.qrChans, clientID)
|
||||||
|
a.mu.Unlock()
|
||||||
|
close(ch)
|
||||||
|
}()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case evt, ok := <-qrChan:
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch evt.Event {
|
||||||
|
case whatsmeow.QRChannelEventCode:
|
||||||
|
// Drain stale QR frames so the buffer holds only the latest code.
|
||||||
|
for len(ch) > 0 {
|
||||||
|
<-ch
|
||||||
|
}
|
||||||
|
ch <- QRFrame{QR: evt.Code, State: StateWaitingQR}
|
||||||
|
log.Printf("WA-Connect: QR code updated for client %d", clientID)
|
||||||
|
case whatsmeow.QRChannelSuccess.Event:
|
||||||
|
go a.syncContacts(client, clientID)
|
||||||
|
go a.saveJIDOnConnect(client, clientID)
|
||||||
|
ch <- QRFrame{State: StateConnected}
|
||||||
|
return
|
||||||
|
case whatsmeow.QRChannelEventError:
|
||||||
|
errMsg := "pairing error"
|
||||||
|
if evt.Error != nil {
|
||||||
|
errMsg = evt.Error.Error()
|
||||||
|
}
|
||||||
|
ch <- QRFrame{State: StateFailed, Error: errMsg}
|
||||||
|
return
|
||||||
|
case whatsmeow.QRChannelTimeout.Event:
|
||||||
|
ch <- QRFrame{State: StateFailed, Error: "QR code timed out"}
|
||||||
|
return
|
||||||
|
case whatsmeow.QRChannelClientOutdated.Event:
|
||||||
|
ch <- QRFrame{State: StateFailed, Error: "client outdated"}
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
ch <- QRFrame{State: StateFailed, Error: "unexpected event: " + evt.Event}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case <-a.appCtx.Done():
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
a.addMessageHandler(client, clientID)
|
||||||
|
|
||||||
|
return ch, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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,
|
||||||
|
Message: text,
|
||||||
|
FromMe: false,
|
||||||
|
Time: time.Now(),
|
||||||
|
}
|
||||||
|
a.postContact(a.appCtx, clientID, contact, msg.Info.ID)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *WhatsmeowAdapter) syncContacts(client *whatsmeow.Client, clientID int64) {
|
||||||
|
// Note: GetChats API changed in newer versions
|
||||||
|
// Simplified for build - real implementation would use new API
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
"message": contact.Message,
|
||||||
|
"message_id": messageID,
|
||||||
|
}
|
||||||
|
|
||||||
|
body, _ := json.Marshal(payload)
|
||||||
|
httpBody := bytes.NewReader(body)
|
||||||
|
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}
|
||||||
|
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) {
|
||||||
|
a.mu.RLock()
|
||||||
|
db := a.db
|
||||||
|
a.mu.RUnlock()
|
||||||
|
return a.queryJID(db, clientID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// getJIDFromDBLocked reads JID from DB; caller must hold a.mu (read or write).
|
||||||
|
func (a *WhatsmeowAdapter) getJIDFromDBLocked(clientID int64) (string, error) {
|
||||||
|
return a.queryJID(a.db, clientID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *WhatsmeowAdapter) queryJID(db *sql.DB, clientID int64) (string, error) {
|
||||||
|
if db == nil {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var jid string
|
||||||
|
err := db.QueryRow("SELECT whatsapp_jid FROM clients WHERE client_id = ?", clientID).Scan(&jid)
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return jid, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *WhatsmeowAdapter) getDeviceFromStore(jid string) interface{} {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *WhatsmeowAdapter) saveJIDOnConnect(client *whatsmeow.Client, clientID int64) {
|
||||||
|
if client.Store.ID == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
jid := client.Store.ID.User
|
||||||
|
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
|
||||||
|
a.mu.RUnlock()
|
||||||
|
|
||||||
|
if db == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := db.Exec("UPDATE clients SET whatsapp_connected = 1 WHERE client_id = ?", clientID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *WhatsmeowAdapter) Disconnect(ctx context.Context, clientID int64) error {
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
|
||||||
|
client, ok := a.clients[clientID]
|
||||||
|
if ok {
|
||||||
|
client.Disconnect()
|
||||||
|
delete(a.clients, clientID)
|
||||||
|
}
|
||||||
|
delete(a.qrChans, clientID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *WhatsmeowAdapter) clearJIDFromDB(clientID int64) {
|
||||||
|
a.mu.RLock()
|
||||||
|
db := a.db
|
||||||
|
a.mu.RUnlock()
|
||||||
|
if db != nil {
|
||||||
|
db.Exec("UPDATE clients SET whatsapp_jid = '' WHERE client_id = ?", clientID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *WhatsmeowAdapter) SetClientDB(db interface{}) {
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
a.db = db.(*sql.DB)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *WhatsmeowAdapter) SaveJID(clientID int64, jid string) error {
|
||||||
|
a.mu.RLock()
|
||||||
|
db := a.db
|
||||||
|
a.mu.RUnlock()
|
||||||
|
|
||||||
|
if db == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := db.Exec("UPDATE clients SET whatsapp_jid = ? WHERE client_id = ?", jid, clientID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *WhatsmeowAdapter) GetJID(clientID int64) (string, error) {
|
||||||
|
a.mu.RLock()
|
||||||
|
db := a.db
|
||||||
|
a.mu.RUnlock()
|
||||||
|
|
||||||
|
if db == nil {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var jid string
|
||||||
|
err := db.QueryRow("SELECT whatsapp_jid FROM clients WHERE client_id = ?", clientID).Scan(&jid)
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
return jid, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *WhatsmeowAdapter) IsConnected(ctx context.Context, clientID int64) (bool, error) {
|
||||||
|
if a == nil {
|
||||||
|
return false, fmt.Errorf("adapter not initialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
a.mu.RLock()
|
||||||
|
client, ok := a.clients[clientID]
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"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"
|
||||||
|
"github.com/go-chi/cors"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
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()
|
||||||
|
|
||||||
|
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
|
||||||
|
} else {
|
||||||
|
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()
|
||||||
|
|
||||||
|
r.Use(middleware.Logger)
|
||||||
|
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"},
|
||||||
|
AllowCredentials: false,
|
||||||
|
MaxAge: 86400,
|
||||||
|
}))
|
||||||
|
|
||||||
|
templates.Init()
|
||||||
|
|
||||||
|
r.Get("/", app.Dashboard)
|
||||||
|
|
||||||
|
r.Route("/auth", func(r chi.Router) {
|
||||||
|
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("/", 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("/", 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; 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; charset=utf-8")
|
||||||
|
if waConnector == nil {
|
||||||
|
w.Write([]byte(`{"status":"error","error":"WhatsApp connector not initialized"}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Write([]byte(`{"status":"ok","message":"WhatsApp connector initialized"}`))
|
||||||
|
})
|
||||||
|
|
||||||
|
r.Get("/debug/net-test", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
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() + `}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
w.Write([]byte(`{"status":"ok","code":` + strconv.Itoa(resp.StatusCode) + `}`))
|
||||||
|
})
|
||||||
|
|
||||||
|
r.Route("/leads", func(r chi.Router) {
|
||||||
|
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("/", 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("/", 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("/", 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("/", 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("/", 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
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# WhatsApp CRM - Environment Variables
|
||||||
|
|
||||||
|
# Database
|
||||||
|
DATABASE_URL=./data/crm.db
|
||||||
|
|
||||||
|
# Next.js
|
||||||
|
NODE_ENV=development
|
||||||
|
NEXT_PUBLIC_API_URL=http://localhost:3000/api
|
||||||
|
|
||||||
|
# Optional: Custom port
|
||||||
|
# PORT=3000
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
node_modules/
|
||||||
|
.pnp
|
||||||
|
.pnp.js
|
||||||
|
.next/
|
||||||
|
out/
|
||||||
|
build/
|
||||||
|
dist/
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.production
|
||||||
|
.wwebjs_auth/
|
||||||
|
.wwebjs_auth_crm/
|
||||||
|
.wwebjs_cache/
|
||||||
|
*.db
|
||||||
|
*.sqlite
|
||||||
|
coverage/
|
||||||
|
.nyc_output/
|
||||||
|
test-results/
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/** @type {import('jest').Config} */
|
||||||
|
module.exports = {
|
||||||
|
preset: 'ts-jest',
|
||||||
|
testEnvironment: 'node',
|
||||||
|
setupFilesAfterEnv: ['<rootDir>/tests/setup.ts'],
|
||||||
|
moduleNameMapper: {
|
||||||
|
'^@/(.*)$': '<rootDir>/src/$1',
|
||||||
|
},
|
||||||
|
collectCoverageFrom: [
|
||||||
|
'src/**/*.{ts,tsx}',
|
||||||
|
'!src/**/*.d.ts',
|
||||||
|
'!src/**/*.stories.tsx',
|
||||||
|
],
|
||||||
|
testPathIgnorePatterns: ['/node_modules/', '/dist/'],
|
||||||
|
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
|
||||||
|
}
|
||||||
Vendored
+5
@@ -0,0 +1,5 @@
|
|||||||
|
/// <reference types="next" />
|
||||||
|
/// <reference types="next/image-types/global" />
|
||||||
|
|
||||||
|
// NOTE: This file should not be edited
|
||||||
|
// see https://nextjs.org/docs/basic-features/typescript for more information.
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
/** @type {import('next').NextConfig} */
|
||||||
|
const nextConfig = {
|
||||||
|
reactStrictMode: true,
|
||||||
|
experimental: {
|
||||||
|
serverComponentsExternalPackages: ['sql.js', 'better-sqlite3'],
|
||||||
|
},
|
||||||
|
webpack: (config) => {
|
||||||
|
config.resolve.fallback = { fs: false, path: false, crypto: false };
|
||||||
|
return config;
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = nextConfig
|
||||||
Generated
+11853
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,47 @@
|
|||||||
|
{
|
||||||
|
"name": "whatsapp-crm",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "WhatsApp CRM with Kanban board",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"dev": "next dev -H 0.0.0.0",
|
||||||
|
"build": "next build",
|
||||||
|
"start": "next start -H 0.0.0.0",
|
||||||
|
"lint": "next lint",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"test:coverage": "jest --coverage"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@dnd-kit/core": "6.1.0",
|
||||||
|
"@dnd-kit/sortable": "8.0.0",
|
||||||
|
"@dnd-kit/utilities": "3.2.2",
|
||||||
|
"@tanstack/react-query": "5.28.0",
|
||||||
|
"@types/qrcode": "^1.5.6",
|
||||||
|
"date-fns": "3.6.0",
|
||||||
|
"next": "14.2.0",
|
||||||
|
"qrcode": "^1.5.4",
|
||||||
|
"react": "18.2.0",
|
||||||
|
"react-dom": "18.2.0",
|
||||||
|
"react-hook-form": "7.51.0",
|
||||||
|
"sql.js": "1.10.2",
|
||||||
|
"whatsapp-web.js": "^1.34.6",
|
||||||
|
"zod": "3.22.4"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@testing-library/jest-dom": "6.4.2",
|
||||||
|
"@testing-library/react": "14.2.0",
|
||||||
|
"@testing-library/user-event": "14.5.2",
|
||||||
|
"@types/jest": "29.5.12",
|
||||||
|
"@types/node": "20.11.0",
|
||||||
|
"@types/react": "18.2.0",
|
||||||
|
"@types/react-dom": "18.2.0",
|
||||||
|
"@types/sql.js": "1.4.9",
|
||||||
|
"eslint": "8.57.0",
|
||||||
|
"eslint-config-next": "14.2.0",
|
||||||
|
"jest": "29.7.0",
|
||||||
|
"ts-jest": "29.1.2",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
|
"typescript": "5.3.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
|
import { initDB, createContact, getContactById, getContactByPhone, getContactsByStage, getAllContacts, updateContact, deleteContact, searchContacts, getContactsByPaymentStatus, getTaskCountByContactId } from '@/lib/db'
|
||||||
|
import { STAGES } from '@/lib/types'
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
const searchParams = request.nextUrl.searchParams
|
||||||
|
const id = searchParams.get('id')
|
||||||
|
const phone = searchParams.get('phone')
|
||||||
|
const stage = searchParams.get('stage')
|
||||||
|
const search = searchParams.get('search')
|
||||||
|
const payment_status = searchParams.get('payment_status')
|
||||||
|
|
||||||
|
try {
|
||||||
|
await initDB()
|
||||||
|
|
||||||
|
let contacts: any[] = []
|
||||||
|
|
||||||
|
if (id) {
|
||||||
|
const contact = getContactById(parseInt(id))
|
||||||
|
if (!contact) {
|
||||||
|
return NextResponse.json({ error: 'Contact not found' }, { status: 404 })
|
||||||
|
}
|
||||||
|
const taskCount = getTaskCountByContactId(contact.id)
|
||||||
|
return NextResponse.json({ ...contact, taskCount })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (phone) {
|
||||||
|
const contact = getContactByPhone(phone)
|
||||||
|
if (!contact) {
|
||||||
|
return NextResponse.json({ error: 'Contact not found' }, { status: 404 })
|
||||||
|
}
|
||||||
|
return NextResponse.json(contact)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stage) {
|
||||||
|
contacts = getContactsByStage(stage as any)
|
||||||
|
} else if (search) {
|
||||||
|
contacts = searchContacts(search)
|
||||||
|
} else if (payment_status) {
|
||||||
|
contacts = getContactsByPaymentStatus(payment_status as any)
|
||||||
|
} else {
|
||||||
|
contacts = getAllContacts()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Array.isArray(contacts)) {
|
||||||
|
contacts = []
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json(contacts)
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('API Error:', error)
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
await initDB()
|
||||||
|
const body = await request.json()
|
||||||
|
|
||||||
|
const { name, phone, notes, schedule_date, follow_up_date } = body
|
||||||
|
|
||||||
|
if (!name || !phone) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Name and phone are required' },
|
||||||
|
{ status: 400 }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingContact = getContactByPhone(phone)
|
||||||
|
if (existingContact) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Contact with this phone already exists' },
|
||||||
|
{ status: 409 }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const contact = createContact({ name, phone, notes, schedule_date, follow_up_date })
|
||||||
|
return NextResponse.json(contact, { status: 201 })
|
||||||
|
} catch (error: any) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PUT(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
await initDB()
|
||||||
|
const body = await request.json()
|
||||||
|
|
||||||
|
const { id, name, stage, notes, schedule_date, follow_up_date, payment_status } = body
|
||||||
|
|
||||||
|
if (!id) {
|
||||||
|
return NextResponse.json({ error: 'Contact ID is required' }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stage && !Object.values(STAGES).includes(stage)) {
|
||||||
|
return NextResponse.json({ error: 'Invalid stage' }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = updateContact(id, { name, stage, notes, schedule_date, follow_up_date, payment_status })
|
||||||
|
if (!updated) {
|
||||||
|
return NextResponse.json({ error: 'Contact not found' }, { status: 404 })
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json(updated)
|
||||||
|
} catch (error: any) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
await initDB()
|
||||||
|
const searchParams = request.nextUrl.searchParams
|
||||||
|
const id = searchParams.get('id')
|
||||||
|
|
||||||
|
if (!id) {
|
||||||
|
return NextResponse.json({ error: 'Contact ID is required' }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteContact(parseInt(id))
|
||||||
|
return NextResponse.json({ success: true })
|
||||||
|
} catch (error: any) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
|
import { initDB, createMessage, getMessagesByContactId } from '@/lib/db'
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
const searchParams = request.nextUrl.searchParams
|
||||||
|
const contactId = searchParams.get('contact_id')
|
||||||
|
|
||||||
|
try {
|
||||||
|
await initDB()
|
||||||
|
|
||||||
|
if (!contactId) {
|
||||||
|
return NextResponse.json({ error: 'contact_id is required' }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const messages = getMessagesByContactId(parseInt(contactId))
|
||||||
|
return NextResponse.json(messages)
|
||||||
|
} catch (error: any) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
await initDB()
|
||||||
|
const body = await request.json()
|
||||||
|
|
||||||
|
const { contact_id, external_id, body: messageBody, from_phone, timestamp, has_media } = body
|
||||||
|
|
||||||
|
if (!contact_id || !external_id || !messageBody || !from_phone || !timestamp) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'contact_id, external_id, body, from_phone, and timestamp are required' },
|
||||||
|
{ status: 400 }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = createMessage({
|
||||||
|
contact_id,
|
||||||
|
external_id,
|
||||||
|
body: messageBody,
|
||||||
|
from_phone,
|
||||||
|
timestamp,
|
||||||
|
has_media
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!message) {
|
||||||
|
return NextResponse.json({ error: 'Contact not found or message already exists' }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json(message, { status: 201 })
|
||||||
|
} catch (error: any) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
|
import { initDB, createContact, createTask, updateContact, closeDB, getAllContacts } from '@/lib/db'
|
||||||
|
import { STAGES } from '@/lib/types'
|
||||||
|
|
||||||
|
export async function POST() {
|
||||||
|
try {
|
||||||
|
await initDB()
|
||||||
|
|
||||||
|
const existing = getAllContacts()
|
||||||
|
if (existing.length > 0) {
|
||||||
|
return NextResponse.json({ message: 'Database already seeded', seeded: false })
|
||||||
|
}
|
||||||
|
|
||||||
|
createContact({ name: 'João Silva', phone: '+5511999999001' })
|
||||||
|
createContact({ name: 'Maria Santos', phone: '+5511999999002' })
|
||||||
|
createContact({ name: 'Pedro Oliveira', phone: '+5511999999003' })
|
||||||
|
|
||||||
|
const c1 = createContact({ name: 'Ana Costa', phone: '+5511999999004', notes: 'Interessado em pacote premium' })
|
||||||
|
const c2 = createContact({ name: 'Carlos Lima', phone: '+5511999999005', notes: 'Ligou pedindo orçamento' })
|
||||||
|
const c3 = createContact({ name: 'Juliana Alves', phone: '+5511999999006', notes: 'Cliente antigo, muito bom' })
|
||||||
|
|
||||||
|
updateContact(c1.id, { stage: STAGES.DECIDINDO, payment_status: 'paid' })
|
||||||
|
updateContact(c2.id, { stage: STAGES.DISCUSSAO_DE_CONTRATO, schedule_date: '2026-04-15' })
|
||||||
|
updateContact(c3.id, { stage: STAGES.DECISAO_FINAL })
|
||||||
|
|
||||||
|
createTask({ contact_id: c1.id, title: 'Enviar proposta', due_date: '2026-04-10' })
|
||||||
|
createTask({ contact_id: c2.id, title: 'Agendar reunião', due_date: '2026-04-08' })
|
||||||
|
|
||||||
|
closeDB()
|
||||||
|
|
||||||
|
return NextResponse.json({ message: 'Database seeded successfully', seeded: true })
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('Seed error:', error)
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
|
import { initDB, createTask, getTaskById, getTasksByContactId, updateTask, deleteTask, getPendingTasksByContactId, getOverdueTasks } from '@/lib/db'
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
const searchParams = request.nextUrl.searchParams
|
||||||
|
const contactId = searchParams.get('contact_id')
|
||||||
|
const taskId = searchParams.get('id')
|
||||||
|
const pending = searchParams.get('pending')
|
||||||
|
const overdue = searchParams.get('overdue')
|
||||||
|
|
||||||
|
try {
|
||||||
|
await initDB()
|
||||||
|
|
||||||
|
if (taskId) {
|
||||||
|
const task = getTaskById(parseInt(taskId))
|
||||||
|
if (!task) {
|
||||||
|
return NextResponse.json({ error: 'Task not found' }, { status: 404 })
|
||||||
|
}
|
||||||
|
return NextResponse.json(task)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (overdue === 'true') {
|
||||||
|
const tasks = getOverdueTasks()
|
||||||
|
return NextResponse.json(tasks)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (contactId) {
|
||||||
|
if (pending === 'true') {
|
||||||
|
const tasks = getPendingTasksByContactId(parseInt(contactId))
|
||||||
|
return NextResponse.json(tasks)
|
||||||
|
}
|
||||||
|
const tasks = getTasksByContactId(parseInt(contactId))
|
||||||
|
return NextResponse.json(tasks)
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ error: 'Missing required parameter' }, { status: 400 })
|
||||||
|
} catch (error: any) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
await initDB()
|
||||||
|
const body = await request.json()
|
||||||
|
|
||||||
|
const { contact_id, title, due_date } = body
|
||||||
|
|
||||||
|
if (!contact_id || !title || !due_date) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'contact_id, title, and due_date are required' },
|
||||||
|
{ status: 400 }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const task = createTask({ contact_id, title, due_date })
|
||||||
|
return NextResponse.json(task, { status: 201 })
|
||||||
|
} catch (error: any) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PUT(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
await initDB()
|
||||||
|
const body = await request.json()
|
||||||
|
|
||||||
|
const { id, title, due_date, status } = body
|
||||||
|
|
||||||
|
if (!id) {
|
||||||
|
return NextResponse.json({ error: 'Task ID is required' }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = updateTask(id, { title, due_date, status })
|
||||||
|
if (!updated) {
|
||||||
|
return NextResponse.json({ error: 'Task not found' }, { status: 404 })
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json(updated)
|
||||||
|
} catch (error: any) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
await initDB()
|
||||||
|
const searchParams = request.nextUrl.searchParams
|
||||||
|
const id = searchParams.get('id')
|
||||||
|
|
||||||
|
if (!id) {
|
||||||
|
return NextResponse.json({ error: 'Task ID is required' }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteTask(parseInt(id))
|
||||||
|
return NextResponse.json({ success: true })
|
||||||
|
} catch (error: any) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
|
import { Client, LocalAuth } from 'whatsapp-web.js'
|
||||||
|
import * as fs from 'fs'
|
||||||
|
import * as path from 'path'
|
||||||
|
|
||||||
|
let client: Client | null = null
|
||||||
|
let qrCode: string | null = null
|
||||||
|
let status: 'disconnected' | 'loading' | 'qr' | 'ready' = 'disconnected'
|
||||||
|
let syncedContacts = 0
|
||||||
|
const MAX_CONTACTS = 5
|
||||||
|
|
||||||
|
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'
|
||||||
|
const clientDir = path.join(process.cwd(), '.wwebjs_auth_crm')
|
||||||
|
|
||||||
|
function isAuthenticated(): boolean {
|
||||||
|
const sessionDir = path.join(clientDir, 'session')
|
||||||
|
if (!fs.existsSync(sessionDir)) return false
|
||||||
|
const files = fs.readdirSync(sessionDir)
|
||||||
|
return files.length > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
function killExistingBrowser(): void {
|
||||||
|
try {
|
||||||
|
const { execSync } = require('child_process')
|
||||||
|
execSync(`pkill -f "wwebjs"`, { stdio: 'ignore' })
|
||||||
|
execSync(`pkill -f "chromium"`, { stdio: 'ignore' })
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function startClient() {
|
||||||
|
if (client) return
|
||||||
|
|
||||||
|
killExistingBrowser()
|
||||||
|
|
||||||
|
if (!fs.existsSync(clientDir)) {
|
||||||
|
fs.mkdirSync(clientDir, { recursive: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
status = 'loading'
|
||||||
|
qrCode = null
|
||||||
|
|
||||||
|
client = new Client({
|
||||||
|
authStrategy: new LocalAuth({ dataPath: clientDir }),
|
||||||
|
puppeteer: {
|
||||||
|
executablePath: '/usr/sbin/chromium',
|
||||||
|
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
client.on('qr', (qr) => {
|
||||||
|
status = 'qr'
|
||||||
|
qrCode = qr
|
||||||
|
console.log('QR Code received')
|
||||||
|
})
|
||||||
|
|
||||||
|
client.on('ready', async () => {
|
||||||
|
status = 'ready'
|
||||||
|
qrCode = null
|
||||||
|
console.log('WhatsApp client ready')
|
||||||
|
|
||||||
|
const chats = await client!.getChats()
|
||||||
|
syncedContacts = 0
|
||||||
|
const existingPhones = new Set<string>()
|
||||||
|
|
||||||
|
for (const chat of chats) {
|
||||||
|
if (chat.isGroup) continue
|
||||||
|
if (syncedContacts >= MAX_CONTACTS) break
|
||||||
|
|
||||||
|
const msgs = await chat.fetchMessages({ limit: 10 })
|
||||||
|
for (const msg of msgs) {
|
||||||
|
if (syncedContacts >= MAX_CONTACTS) break
|
||||||
|
if (!msg.body || !msg.body.trim()) continue
|
||||||
|
|
||||||
|
const phone = msg.from.split('@')[0]
|
||||||
|
if (existingPhones.has(phone)) continue
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${apiUrl}/api/contacts`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ name: chat.name, phone })
|
||||||
|
})
|
||||||
|
if (res.ok) {
|
||||||
|
syncedContacts++
|
||||||
|
existingPhones.add(phone)
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(`Synced ${syncedContacts} contacts`)
|
||||||
|
})
|
||||||
|
|
||||||
|
client.on('message', async (msg) => {
|
||||||
|
if (syncedContacts >= MAX_CONTACTS) return
|
||||||
|
|
||||||
|
const chat = await msg.getChat()
|
||||||
|
if (chat.isGroup) return
|
||||||
|
if (!msg.body || !msg.body.trim()) return
|
||||||
|
|
||||||
|
const phone = msg.from.split('@')[0]
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${apiUrl}/api/contacts`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ name: chat.name, phone })
|
||||||
|
})
|
||||||
|
if (res.ok) syncedContacts++
|
||||||
|
} catch (e) {}
|
||||||
|
})
|
||||||
|
|
||||||
|
client.on('disconnected', () => {
|
||||||
|
status = 'disconnected'
|
||||||
|
client = null
|
||||||
|
})
|
||||||
|
|
||||||
|
client.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
if (!client && isAuthenticated()) {
|
||||||
|
startClient()
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 5000))
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentStatus = client ? (status === 'loading' ? 'connecting' : status) : 'disconnected'
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
status: currentStatus,
|
||||||
|
qrCode,
|
||||||
|
syncedContacts,
|
||||||
|
isAuthenticated: isAuthenticated(),
|
||||||
|
clientReady: client !== null
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST() {
|
||||||
|
if (!client) {
|
||||||
|
startClient()
|
||||||
|
}
|
||||||
|
return NextResponse.json({ success: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE() {
|
||||||
|
if (client) {
|
||||||
|
client.destroy()
|
||||||
|
client = null
|
||||||
|
}
|
||||||
|
if (fs.existsSync(clientDir)) {
|
||||||
|
fs.rmSync(clientDir, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
status = 'disconnected'
|
||||||
|
qrCode = null
|
||||||
|
syncedContacts = 0
|
||||||
|
return NextResponse.json({ success: true })
|
||||||
|
}
|
||||||
@@ -0,0 +1,393 @@
|
|||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
html,
|
||||||
|
body {
|
||||||
|
max-width: 100vw;
|
||||||
|
overflow-x: hidden;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
|
||||||
|
Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
|
||||||
|
background-color: #f5f5f5;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-header {
|
||||||
|
padding: 16px 24px;
|
||||||
|
background: white;
|
||||||
|
border-bottom: 1px solid #ddd;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-header h1 {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-controls {
|
||||||
|
display: flex;
|
||||||
|
gap: 12px;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-input {
|
||||||
|
padding: 8px 12px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 4px;
|
||||||
|
width: 200px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-select {
|
||||||
|
padding: 8px 12px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 14px;
|
||||||
|
background: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kanban-board {
|
||||||
|
display: flex;
|
||||||
|
gap: 16px;
|
||||||
|
padding: 24px;
|
||||||
|
min-height: calc(100vh - 80px);
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kanban-column {
|
||||||
|
flex: 0 0 300px;
|
||||||
|
background: #ebecf0;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 12px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kanban-column-header {
|
||||||
|
font-weight: 600;
|
||||||
|
padding: 8px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kanban-column-count {
|
||||||
|
background: #0079bf;
|
||||||
|
color: white;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 2px 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
margin-left: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kanban-cards {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
overflow-y: auto;
|
||||||
|
min-height: 100px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.contact-card {
|
||||||
|
background: white;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 12px;
|
||||||
|
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: box-shadow 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.contact-card:hover {
|
||||||
|
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.contact-card.paid {
|
||||||
|
border-left: 4px solid #4caf50;
|
||||||
|
}
|
||||||
|
|
||||||
|
.contact-card.pending {
|
||||||
|
border-left: 4px solid #ff9800;
|
||||||
|
}
|
||||||
|
|
||||||
|
.contact-card.overdue {
|
||||||
|
border-left-color: #f44336;
|
||||||
|
}
|
||||||
|
|
||||||
|
.contact-card-name {
|
||||||
|
font-weight: 500;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.contact-card-phone {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #666;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.contact-card-preview {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #888;
|
||||||
|
display: -webkit-box;
|
||||||
|
-webkit-line-clamp: 2;
|
||||||
|
-webkit-box-orient: vertical;
|
||||||
|
overflow: hidden;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.contact-card-meta {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: center;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.task-badge {
|
||||||
|
background: #0079bf;
|
||||||
|
color: white;
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 2px 6px;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.schedule-date {
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.schedule-date.overdue {
|
||||||
|
color: #f44336;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-column {
|
||||||
|
text-align: center;
|
||||||
|
color: #888;
|
||||||
|
padding: 24px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
min-height: 200px;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Modal styles */
|
||||||
|
.modal-overlay {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.5);
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
z-index: 1000;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content {
|
||||||
|
background: white;
|
||||||
|
border-radius: 8px;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 600px;
|
||||||
|
max-height: 80vh;
|
||||||
|
overflow-y: auto;
|
||||||
|
position: relative;
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-close {
|
||||||
|
position: absolute;
|
||||||
|
top: 12px;
|
||||||
|
right: 12px;
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
font-size: 24px;
|
||||||
|
cursor: pointer;
|
||||||
|
color: #666;
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-close:hover {
|
||||||
|
background: #f0f0f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-header {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-header h2 {
|
||||||
|
font-size: 20px;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-phone {
|
||||||
|
color: #666;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-tabs {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
border-bottom: 1px solid #eee;
|
||||||
|
padding-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-tabs .tab {
|
||||||
|
padding: 8px 16px;
|
||||||
|
border: none;
|
||||||
|
background: none;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 14px;
|
||||||
|
border-radius: 4px;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-tabs .tab.active {
|
||||||
|
background: #0079bf;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-body {
|
||||||
|
min-height: 200px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
text-align: center;
|
||||||
|
color: #888;
|
||||||
|
padding: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.messages-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-item {
|
||||||
|
padding: 12px;
|
||||||
|
background: #f9f9f9;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-time {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #888;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-body {
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tasks-section .add-task-form {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tasks-section .add-task-form input {
|
||||||
|
padding: 8px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tasks-section .add-task-form input[type="text"] {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tasks-section .add-task-form button {
|
||||||
|
padding: 8px 16px;
|
||||||
|
background: #0079bf;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tasks-section .add-task-form button:hover {
|
||||||
|
background: #005a8c;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tasks-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.task-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 12px;
|
||||||
|
background: #f9f9f9;
|
||||||
|
border-radius: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.task-item.completed {
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.task-item.completed .completed {
|
||||||
|
text-decoration: line-through;
|
||||||
|
}
|
||||||
|
|
||||||
|
.task-item input[type="checkbox"] {
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.task-item .task-due {
|
||||||
|
margin-left: auto;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #888;
|
||||||
|
}
|
||||||
|
|
||||||
|
.details-form .form-group {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.details-form .form-group label {
|
||||||
|
display: block;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.details-form .form-group select,
|
||||||
|
.details-form .form-group textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: 8px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.details-form .form-group textarea {
|
||||||
|
min-height: 100px;
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
import { KanbanBoard } from '@/components/Kanban'
|
||||||
|
import { Contact, Stage, Message, Task } from '@/lib/types'
|
||||||
|
import ContactDetailModal from '@/components/Modal/ContactDetailModal'
|
||||||
|
|
||||||
|
export default function KanbanPage() {
|
||||||
|
const [contacts, setContacts] = useState<Contact[]>([])
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const [selectedContact, setSelectedContact] = useState<Contact | null>(null)
|
||||||
|
const [messages, setMessages] = useState<Message[]>([])
|
||||||
|
const [tasks, setTasks] = useState<Task[]>([])
|
||||||
|
const [modalOpen, setModalOpen] = useState(false)
|
||||||
|
|
||||||
|
const fetchContacts = async () => {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/contacts')
|
||||||
|
const data = await res.json()
|
||||||
|
if (Array.isArray(data)) {
|
||||||
|
setContacts(data)
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
setError(e.message)
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchMessages = async (contactId: number) => {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/messages?contact_id=${contactId}`)
|
||||||
|
const data = await res.json()
|
||||||
|
if (Array.isArray(data)) {
|
||||||
|
setMessages(data)
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchTasks = async (contactId: number) => {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/tasks?contact_id=${contactId}`)
|
||||||
|
const data = await res.json()
|
||||||
|
if (Array.isArray(data)) {
|
||||||
|
setTasks(data)
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchContacts()
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleContactClick = async (contact: Contact) => {
|
||||||
|
setSelectedContact(contact)
|
||||||
|
await Promise.all([fetchMessages(contact.id), fetchTasks(contact.id)])
|
||||||
|
setModalOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleStageChange = async (contactId: number, newStage: Stage) => {
|
||||||
|
try {
|
||||||
|
await fetch('/api/contacts', {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ id: contactId, stage: newStage })
|
||||||
|
})
|
||||||
|
setContacts(prev => prev.map(c =>
|
||||||
|
c.id === contactId ? { ...c, stage: newStage } : c
|
||||||
|
))
|
||||||
|
} catch (e: any) {
|
||||||
|
alert(e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleUpdateStage = async (stage: Stage) => {
|
||||||
|
if (!selectedContact) return
|
||||||
|
try {
|
||||||
|
await fetch('/api/contacts', {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ id: selectedContact.id, stage })
|
||||||
|
})
|
||||||
|
const updated = { ...selectedContact, stage }
|
||||||
|
setSelectedContact(updated)
|
||||||
|
setContacts(prev => prev.map(c => c.id === updated.id ? updated : c))
|
||||||
|
} catch (e: any) {
|
||||||
|
alert(e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleAddNote = async (notes: string) => {
|
||||||
|
if (!selectedContact) return
|
||||||
|
try {
|
||||||
|
await fetch('/api/contacts', {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ id: selectedContact.id, notes })
|
||||||
|
})
|
||||||
|
const updated = { ...selectedContact, notes }
|
||||||
|
setSelectedContact(updated)
|
||||||
|
setContacts(prev => prev.map(c => c.id === updated.id ? updated : c))
|
||||||
|
} catch (e: any) {
|
||||||
|
alert(e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleUpdatePaymentStatus = async (payment_status: 'pending' | 'paid') => {
|
||||||
|
if (!selectedContact) return
|
||||||
|
try {
|
||||||
|
await fetch('/api/contacts', {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ id: selectedContact.id, payment_status })
|
||||||
|
})
|
||||||
|
const updated = { ...selectedContact, payment_status }
|
||||||
|
setSelectedContact(updated)
|
||||||
|
setContacts(prev => prev.map(c => c.id === updated.id ? updated : c))
|
||||||
|
} catch (e: any) {
|
||||||
|
alert(e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleAddTask = async (title: string, due_date: string) => {
|
||||||
|
if (!selectedContact) return
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/tasks', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ contact_id: selectedContact.id, title, due_date })
|
||||||
|
})
|
||||||
|
const newTask = await res.json()
|
||||||
|
setTasks(prev => [...prev, newTask])
|
||||||
|
} catch (e: any) {
|
||||||
|
alert(e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleToggleTask = async (taskId: number, status: 'pending' | 'completed') => {
|
||||||
|
try {
|
||||||
|
await fetch(`/api/tasks?id=${taskId}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ status })
|
||||||
|
})
|
||||||
|
setTasks(prev => prev.map(t =>
|
||||||
|
t.id === taskId ? { ...t, status } : t
|
||||||
|
))
|
||||||
|
} catch (e: any) {
|
||||||
|
alert(e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) return <div style={{ padding: 20 }}>Carregando...</div>
|
||||||
|
if (error) return <div style={{ padding: 20, color: 'red' }}>Erro: {error}</div>
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 20 }}>
|
||||||
|
<h1>Kanban - Leads</h1>
|
||||||
|
<KanbanBoard
|
||||||
|
contacts={contacts}
|
||||||
|
onContactClick={handleContactClick}
|
||||||
|
onStageChange={handleStageChange}
|
||||||
|
/>
|
||||||
|
<ContactDetailModal
|
||||||
|
contact={selectedContact!}
|
||||||
|
isOpen={modalOpen}
|
||||||
|
onClose={() => setModalOpen(false)}
|
||||||
|
messages={messages}
|
||||||
|
tasks={tasks}
|
||||||
|
onUpdateStage={handleUpdateStage}
|
||||||
|
onAddNote={handleAddNote}
|
||||||
|
onUpdatePaymentStatus={handleUpdatePaymentStatus}
|
||||||
|
onAddTask={handleAddTask}
|
||||||
|
onToggleTask={handleToggleTask}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import type { Metadata } from 'next'
|
||||||
|
import { Inter } from 'next/font/google'
|
||||||
|
import './globals.css'
|
||||||
|
|
||||||
|
const inter = Inter({ subsets: ['latin'] })
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: 'WhatsApp CRM',
|
||||||
|
description: 'WhatsApp CRM with Kanban board',
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function RootLayout({
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<html lang="pt-BR">
|
||||||
|
<body className={inter.className}>{children}</body>
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
|
||||||
|
export default function HomePage() {
|
||||||
|
const router = useRouter()
|
||||||
|
const [connected, setConnected] = useState(false)
|
||||||
|
const [hasExistingSession, setHasExistingSession] = useState(false)
|
||||||
|
const [syncedContacts, setSyncedContacts] = useState(0)
|
||||||
|
const [showQr, setShowQr] = useState(false)
|
||||||
|
const [qrCode, setQrCode] = useState<string | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const checkStatus = async () => {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/whatsapp')
|
||||||
|
const data = await res.json()
|
||||||
|
setConnected(data.status === 'ready')
|
||||||
|
setHasExistingSession(data.isAuthenticated || false)
|
||||||
|
setSyncedContacts(data.syncedContacts || 0)
|
||||||
|
setQrCode(data.qrCode)
|
||||||
|
setShowQr(data.status === 'qr')
|
||||||
|
} catch (e) {
|
||||||
|
setConnected(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
checkStatus()
|
||||||
|
const interval = setInterval(checkStatus, 3000)
|
||||||
|
return () => clearInterval(interval)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (connected) {
|
||||||
|
router.push('/kanban')
|
||||||
|
}
|
||||||
|
}, [connected, router])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (hasExistingSession && !connected) {
|
||||||
|
fetch('/api/whatsapp', { method: 'POST' })
|
||||||
|
}
|
||||||
|
}, [hasExistingSession, connected])
|
||||||
|
|
||||||
|
const connect = async () => {
|
||||||
|
await fetch('/api/whatsapp', { method: 'POST' })
|
||||||
|
}
|
||||||
|
|
||||||
|
const disconnect = async () => {
|
||||||
|
await fetch('/api/whatsapp', { method: 'DELETE' })
|
||||||
|
setConnected(false)
|
||||||
|
setHasExistingSession(false)
|
||||||
|
setSyncedContacts(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
minHeight: '100vh',
|
||||||
|
fontFamily: 'system-ui, sans-serif',
|
||||||
|
padding: 20
|
||||||
|
}}>
|
||||||
|
<h1 style={{ fontSize: 32, marginBottom: 16 }}>WhatsApp CRM</h1>
|
||||||
|
<p style={{ color: '#666', marginBottom: 32 }}>Conecte seu WhatsApp para começar</p>
|
||||||
|
|
||||||
|
{showQr && qrCode && (
|
||||||
|
<div style={{ textAlign: 'center', marginBottom: 24 }}>
|
||||||
|
<p style={{ marginBottom: 16 }}>Escaneie o QR code com seu WhatsApp:</p>
|
||||||
|
<img src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(qrCode)}`} alt="QR Code" style={{ border: '1px solid #ccc', borderRadius: 8 }} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!connected && (
|
||||||
|
<button
|
||||||
|
onClick={connect}
|
||||||
|
style={{
|
||||||
|
padding: '12px 24px',
|
||||||
|
fontSize: 16,
|
||||||
|
background: '#0079bf',
|
||||||
|
color: 'white',
|
||||||
|
border: 'none',
|
||||||
|
borderRadius: 8,
|
||||||
|
cursor: 'pointer'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Conectar WhatsApp
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{connected && (
|
||||||
|
<div style={{ textAlign: 'center' }}>
|
||||||
|
<p style={{ color: 'green', marginBottom: 16 }}>✓ WhatsApp conectado ({syncedContacts} contatos)</p>
|
||||||
|
<div style={{ display: 'flex', gap: 12 }}>
|
||||||
|
<a
|
||||||
|
href="/kanban"
|
||||||
|
style={{
|
||||||
|
padding: '12px 24px',
|
||||||
|
fontSize: 16,
|
||||||
|
background: '#0079bf',
|
||||||
|
color: 'white',
|
||||||
|
border: 'none',
|
||||||
|
borderRadius: 8,
|
||||||
|
textDecoration: 'none',
|
||||||
|
display: 'inline-block'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Acessar Kanban
|
||||||
|
</a>
|
||||||
|
<button
|
||||||
|
onClick={disconnect}
|
||||||
|
style={{
|
||||||
|
padding: '12px 24px',
|
||||||
|
fontSize: 16,
|
||||||
|
background: '#dc3545',
|
||||||
|
color: 'white',
|
||||||
|
border: 'none',
|
||||||
|
borderRadius: 8,
|
||||||
|
cursor: 'pointer'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Desconectar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { Contact, Stage } from '@/lib/types'
|
||||||
|
|
||||||
|
interface ContactCardProps {
|
||||||
|
contact: Contact
|
||||||
|
onClick: () => void
|
||||||
|
onStageChange?: (contactId: number, newStage: Stage) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ContactCard({ contact, onClick, onStageChange }: ContactCardProps) {
|
||||||
|
const formatPhone = (phone: string) => {
|
||||||
|
const cleaned = phone.replace(/\D/g, '')
|
||||||
|
if (cleaned.length === 13) {
|
||||||
|
return `+${cleaned.slice(0, 2)} (${cleaned.slice(3, 5)}) ${cleaned.slice(5, 10)}-${cleaned.slice(10)}`
|
||||||
|
}
|
||||||
|
if (cleaned.length === 12) {
|
||||||
|
return `+${cleaned.slice(0, 2)} (${cleaned.slice(2, 4)}) ${cleaned.slice(4, 9)}-${cleaned.slice(9)}`
|
||||||
|
}
|
||||||
|
if (cleaned.length === 11) {
|
||||||
|
return `(${cleaned.slice(0, 2)}) ${cleaned.slice(2, 7)}-${cleaned.slice(7)}`
|
||||||
|
}
|
||||||
|
return phone
|
||||||
|
}
|
||||||
|
|
||||||
|
const isOverdue = contact.schedule_date && new Date(contact.schedule_date) < new Date()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`contact-card ${contact.payment_status === 'paid' ? 'paid' : 'pending'} ${isOverdue ? 'overdue' : ''}`}
|
||||||
|
onClick={onClick}
|
||||||
|
>
|
||||||
|
<div className="contact-card-name">{contact.name}</div>
|
||||||
|
<div className="contact-card-phone">{formatPhone(contact.phone)}</div>
|
||||||
|
{contact.notes && (
|
||||||
|
<div className="contact-card-preview">
|
||||||
|
{contact.notes.substring(0, 50)}{contact.notes.length > 50 ? '...' : ''}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="contact-card-meta">
|
||||||
|
{contact.taskCount !== undefined && contact.taskCount > 0 && (
|
||||||
|
<span className="task-badge">{contact.taskCount}</span>
|
||||||
|
)}
|
||||||
|
{contact.schedule_date && (
|
||||||
|
<span className={`schedule-date ${isOverdue ? 'overdue' : ''}`}>
|
||||||
|
{new Date(contact.schedule_date).toLocaleDateString('pt-BR')}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export { default as ContactCard } from './ContactCard'
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState, useMemo } from 'react'
|
||||||
|
import { Stage, STAGES, STAGE_LIST, Contact } from '@/lib/types'
|
||||||
|
import { ContactCard } from '@/components/ContactCard'
|
||||||
|
|
||||||
|
interface KanbanBoardProps {
|
||||||
|
contacts: Contact[]
|
||||||
|
onContactClick: (contact: Contact) => void
|
||||||
|
onStageChange: (contactId: number, newStage: Stage) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function KanbanBoard({ contacts, onContactClick, onStageChange }: KanbanBoardProps) {
|
||||||
|
const safeContacts = useMemo(() => {
|
||||||
|
return Array.isArray(contacts) ? contacts : []
|
||||||
|
}, [contacts])
|
||||||
|
|
||||||
|
const getContactsByStage = (stage: Stage) => {
|
||||||
|
return safeContacts.filter(c => c.stage === stage)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="kanban-board">
|
||||||
|
{STAGE_LIST.map(stage => (
|
||||||
|
<div key={stage} className="kanban-column">
|
||||||
|
<div className="kanban-column-header">
|
||||||
|
{stage}
|
||||||
|
<span className="kanban-column-count">
|
||||||
|
{getContactsByStage(stage).length}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="kanban-cards">
|
||||||
|
{getContactsByStage(stage).length === 0 ? (
|
||||||
|
<div className="empty-column">Nenhum lead</div>
|
||||||
|
) : (
|
||||||
|
getContactsByStage(stage).map(contact => (
|
||||||
|
<ContactCard
|
||||||
|
key={contact.id}
|
||||||
|
contact={contact}
|
||||||
|
onClick={() => onContactClick(contact)}
|
||||||
|
onStageChange={onStageChange}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export { default as KanbanBoard } from './KanbanBoard'
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { Contact, Message, Task, STAGE_LIST, Stage } from '@/lib/types'
|
||||||
|
|
||||||
|
interface ContactDetailModalProps {
|
||||||
|
contact: Contact
|
||||||
|
isOpen: boolean
|
||||||
|
onClose: () => void
|
||||||
|
messages: Message[]
|
||||||
|
tasks: Task[]
|
||||||
|
onUpdateStage: (stage: Stage) => void
|
||||||
|
onAddNote: (notes: string) => void
|
||||||
|
onUpdatePaymentStatus: (status: 'pending' | 'paid') => void
|
||||||
|
onAddTask: (title: string, due_date: string) => void
|
||||||
|
onToggleTask: (taskId: number, status: 'pending' | 'completed') => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ContactDetailModal({
|
||||||
|
contact,
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
messages,
|
||||||
|
tasks,
|
||||||
|
onUpdateStage,
|
||||||
|
onAddNote,
|
||||||
|
onUpdatePaymentStatus,
|
||||||
|
onAddTask,
|
||||||
|
onToggleTask,
|
||||||
|
}: ContactDetailModalProps) {
|
||||||
|
const [noteInput, setNoteInput] = useState('')
|
||||||
|
const [taskTitle, setTaskTitle] = useState('')
|
||||||
|
const [taskDueDate, setTaskDueDate] = useState('')
|
||||||
|
const [activeTab, setActiveTab] = useState<'messages' | 'tasks' | 'details'>('messages')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleEscape = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === 'Escape') onClose()
|
||||||
|
}
|
||||||
|
if (isOpen) {
|
||||||
|
document.addEventListener('keydown', handleEscape)
|
||||||
|
document.body.style.overflow = 'hidden'
|
||||||
|
}
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('keydown', handleEscape)
|
||||||
|
document.body.style.overflow = 'auto'
|
||||||
|
}
|
||||||
|
}, [isOpen, onClose])
|
||||||
|
|
||||||
|
if (!isOpen) return null
|
||||||
|
|
||||||
|
const formatDate = (timestamp: number) => {
|
||||||
|
return new Date(timestamp * 1000).toLocaleString('pt-BR', {
|
||||||
|
day: '2-digit',
|
||||||
|
month: '2-digit',
|
||||||
|
year: 'numeric',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatPhone = (phone: string) => {
|
||||||
|
const cleaned = phone.replace(/\D/g, '')
|
||||||
|
if (cleaned.length === 13) {
|
||||||
|
return `+${cleaned.slice(0, 2)} (${cleaned.slice(3, 5)}) ${cleaned.slice(5, 10)}-${cleaned.slice(10)}`
|
||||||
|
}
|
||||||
|
if (cleaned.length === 12) {
|
||||||
|
return `+${cleaned.slice(0, 2)} (${cleaned.slice(2, 4)}) ${cleaned.slice(4, 9)}-${cleaned.slice(9)}`
|
||||||
|
}
|
||||||
|
if (cleaned.length === 11) {
|
||||||
|
return `(${cleaned.slice(0, 2)}) ${cleaned.slice(2, 7)}-${cleaned.slice(7)}`
|
||||||
|
}
|
||||||
|
return phone
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-overlay" onClick={onClose}>
|
||||||
|
<div className="modal-content" onClick={e => e.stopPropagation()}>
|
||||||
|
<button className="modal-close" onClick={onClose}>×</button>
|
||||||
|
|
||||||
|
<div className="modal-header">
|
||||||
|
<h2>{contact.name}</h2>
|
||||||
|
<p className="modal-phone">{formatPhone(contact.phone)}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-tabs">
|
||||||
|
<button
|
||||||
|
className={`tab ${activeTab === 'messages' ? 'active' : ''}`}
|
||||||
|
onClick={() => setActiveTab('messages')}
|
||||||
|
>
|
||||||
|
Mensagens ({messages.length})
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={`tab ${activeTab === 'tasks' ? 'active' : ''}`}
|
||||||
|
onClick={() => setActiveTab('tasks')}
|
||||||
|
>
|
||||||
|
Tarefas ({tasks.length})
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={`tab ${activeTab === 'details' ? 'active' : ''}`}
|
||||||
|
onClick={() => setActiveTab('details')}
|
||||||
|
>
|
||||||
|
Detalhes
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-body">
|
||||||
|
{activeTab === 'messages' && (
|
||||||
|
<div className="messages-list">
|
||||||
|
{messages.length === 0 ? (
|
||||||
|
<div className="empty-state">Nenhuma mensagem</div>
|
||||||
|
) : (
|
||||||
|
messages.map(msg => (
|
||||||
|
<div key={msg.id} className="message-item">
|
||||||
|
<div className="message-time">{formatDate(msg.timestamp)}</div>
|
||||||
|
<div className="message-body">{msg.body}</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'tasks' && (
|
||||||
|
<div className="tasks-section">
|
||||||
|
<div className="add-task-form">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Nova tarefa..."
|
||||||
|
value={taskTitle}
|
||||||
|
onChange={e => setTaskTitle(e.target.value)}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={taskDueDate}
|
||||||
|
onChange={e => setTaskDueDate(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
if (taskTitle && taskDueDate) {
|
||||||
|
onAddTask(taskTitle, taskDueDate)
|
||||||
|
setTaskTitle('')
|
||||||
|
setTaskDueDate('')
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Adicionar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="tasks-list">
|
||||||
|
{tasks.length === 0 ? (
|
||||||
|
<div className="empty-state">Nenhuma tarefa</div>
|
||||||
|
) : (
|
||||||
|
tasks.map(task => (
|
||||||
|
<div
|
||||||
|
key={task.id}
|
||||||
|
className={`task-item ${task.status}`}
|
||||||
|
onClick={() => onToggleTask(task.id, task.status === 'pending' ? 'completed' : 'pending')}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={task.status === 'completed'}
|
||||||
|
onChange={() => {}}
|
||||||
|
/>
|
||||||
|
<span className={task.status}>{task.title}</span>
|
||||||
|
<span className="task-due">{task.due_date}</span>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'details' && (
|
||||||
|
<div className="details-form">
|
||||||
|
<div className="form-group">
|
||||||
|
<label>Estágio</label>
|
||||||
|
<select
|
||||||
|
value={contact.stage}
|
||||||
|
onChange={e => onUpdateStage(e.target.value as Stage)}
|
||||||
|
>
|
||||||
|
{STAGE_LIST.map(stage => (
|
||||||
|
<option key={stage} value={stage}>{stage}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label>Status de Pagamento</label>
|
||||||
|
<select
|
||||||
|
value={contact.payment_status}
|
||||||
|
onChange={e => onUpdatePaymentStatus(e.target.value as 'pending' | 'paid')}
|
||||||
|
>
|
||||||
|
<option value="pending">Pendente</option>
|
||||||
|
<option value="paid">Pago</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label>Notas</label>
|
||||||
|
<textarea
|
||||||
|
value={contact.notes || ''}
|
||||||
|
onChange={e => onAddNote(e.target.value)}
|
||||||
|
placeholder="Adicione notas sobre este contato..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export { default as ContactDetailModal } from './ContactDetailModal'
|
||||||
@@ -0,0 +1,528 @@
|
|||||||
|
import { Contact, Message, Task, Stage, STAGES } from './types'
|
||||||
|
import * as fs from 'fs'
|
||||||
|
import * as path from 'path'
|
||||||
|
|
||||||
|
const DB_NAME = 'whatsapp-crm.db'
|
||||||
|
|
||||||
|
let db: any = null
|
||||||
|
|
||||||
|
export async function initDB(): Promise<any> {
|
||||||
|
if (db) return db
|
||||||
|
|
||||||
|
const initSqlJs = (await import('sql.js')).default
|
||||||
|
const SQLITE = await initSqlJs()
|
||||||
|
db = new SQLITE.Database()
|
||||||
|
|
||||||
|
const dbPath = path.join(process.cwd(), DB_NAME)
|
||||||
|
if (fs.existsSync(dbPath)) {
|
||||||
|
const fileBuffer = fs.readFileSync(dbPath)
|
||||||
|
db = new SQLITE.Database(fileBuffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
db.run(`
|
||||||
|
CREATE TABLE IF NOT EXISTS contacts (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
phone TEXT NOT NULL UNIQUE,
|
||||||
|
stage TEXT NOT NULL DEFAULT 'LEADS DE ENTRADA',
|
||||||
|
notes TEXT,
|
||||||
|
schedule_date TEXT,
|
||||||
|
follow_up_date TEXT,
|
||||||
|
payment_status TEXT DEFAULT 'pending',
|
||||||
|
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
|
||||||
|
db.run(`
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
contact_id INTEGER NOT NULL,
|
||||||
|
external_id TEXT NOT NULL UNIQUE,
|
||||||
|
body TEXT NOT NULL,
|
||||||
|
from_phone TEXT NOT NULL,
|
||||||
|
timestamp INTEGER NOT NULL,
|
||||||
|
has_media INTEGER DEFAULT 0,
|
||||||
|
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
FOREIGN KEY (contact_id) REFERENCES contacts(id)
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
|
||||||
|
db.run(`
|
||||||
|
CREATE TABLE IF NOT EXISTS tasks (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
contact_id INTEGER NOT NULL,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
due_date TEXT NOT NULL,
|
||||||
|
status TEXT DEFAULT 'pending',
|
||||||
|
completed_at TEXT,
|
||||||
|
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
FOREIGN KEY (contact_id) REFERENCES contacts(id)
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
|
||||||
|
db.run(`CREATE INDEX IF NOT EXISTS idx_contacts_phone ON contacts(phone)`)
|
||||||
|
db.run(`CREATE INDEX IF NOT EXISTS idx_contacts_stage ON contacts(stage)`)
|
||||||
|
db.run(`CREATE INDEX IF NOT EXISTS idx_messages_contact_id ON messages(contact_id)`)
|
||||||
|
db.run(`CREATE INDEX IF NOT EXISTS idx_tasks_contact_id ON tasks(contact_id)`)
|
||||||
|
db.run(`CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status)`)
|
||||||
|
|
||||||
|
const data = db.export()
|
||||||
|
const buffer = Buffer.from(data)
|
||||||
|
fs.writeFileSync(dbPath, buffer)
|
||||||
|
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDB(): any {
|
||||||
|
if (!db) throw new Error('Database not initialized. Call initDB() first.')
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveDB(): void {
|
||||||
|
if (!db) return
|
||||||
|
const dbPath = path.join(process.cwd(), DB_NAME)
|
||||||
|
const data = db.export()
|
||||||
|
const buffer = Buffer.from(data)
|
||||||
|
fs.writeFileSync(dbPath, buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function closeDB(): void {
|
||||||
|
if (db) {
|
||||||
|
db.close()
|
||||||
|
db = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createContact(input: { name: string; phone: string; notes?: string; schedule_date?: string; follow_up_date?: string }): Contact {
|
||||||
|
const database = getDB()
|
||||||
|
|
||||||
|
if (!input.name || !input.phone) {
|
||||||
|
throw new Error('Name and phone are required')
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date().toISOString()
|
||||||
|
|
||||||
|
try {
|
||||||
|
database.run(
|
||||||
|
`INSERT INTO contacts (name, phone, stage, notes, schedule_date, follow_up_date, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
|
[input.name, input.phone, STAGES.LEADS_DE_ENTRADA, input.notes || null, input.schedule_date || null, input.follow_up_date || null, now, now]
|
||||||
|
)
|
||||||
|
saveDB()
|
||||||
|
} catch (err: any) {
|
||||||
|
if (err.message.includes('UNIQUE constraint')) {
|
||||||
|
throw new Error('Contact with this phone already exists')
|
||||||
|
}
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = database.exec('SELECT last_insert_rowid() as id')
|
||||||
|
const id = result[0].values[0][0] as number
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name: input.name,
|
||||||
|
phone: input.phone,
|
||||||
|
stage: STAGES.LEADS_DE_ENTRADA,
|
||||||
|
notes: input.notes || null,
|
||||||
|
schedule_date: input.schedule_date || null,
|
||||||
|
follow_up_date: input.follow_up_date || null,
|
||||||
|
payment_status: 'pending',
|
||||||
|
created_at: now,
|
||||||
|
updated_at: now,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getContactById(id: number): Contact | null {
|
||||||
|
const database = getDB()
|
||||||
|
const result = database.exec('SELECT * FROM contacts WHERE id = ?', [id])
|
||||||
|
|
||||||
|
if (result.length === 0 || result[0].values.length === 0) return null
|
||||||
|
|
||||||
|
const row = result[0].values[0]
|
||||||
|
return {
|
||||||
|
id: row[0] as number,
|
||||||
|
name: row[1] as string,
|
||||||
|
phone: row[2] as string,
|
||||||
|
stage: row[3] as Stage,
|
||||||
|
notes: row[4] as string | null,
|
||||||
|
schedule_date: row[5] as string | null,
|
||||||
|
follow_up_date: row[6] as string | null,
|
||||||
|
payment_status: row[7] as 'pending' | 'paid',
|
||||||
|
created_at: row[8] as string,
|
||||||
|
updated_at: row[9] as string,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getContactByPhone(phone: string): Contact | null {
|
||||||
|
const database = getDB()
|
||||||
|
const result = database.exec('SELECT * FROM contacts WHERE phone = ?', [phone])
|
||||||
|
|
||||||
|
if (result.length === 0 || result[0].values.length === 0) return null
|
||||||
|
|
||||||
|
const row = result[0].values[0]
|
||||||
|
return {
|
||||||
|
id: row[0] as number,
|
||||||
|
name: row[1] as string,
|
||||||
|
phone: row[2] as string,
|
||||||
|
stage: row[3] as Stage,
|
||||||
|
notes: row[4] as string | null,
|
||||||
|
schedule_date: row[5] as string | null,
|
||||||
|
follow_up_date: row[6] as string | null,
|
||||||
|
payment_status: row[7] as 'pending' | 'paid',
|
||||||
|
created_at: row[8] as string,
|
||||||
|
updated_at: row[9] as string,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getContactsByStage(stage: Stage): Contact[] {
|
||||||
|
const database = getDB()
|
||||||
|
const result = database.exec('SELECT * FROM contacts WHERE stage = ? ORDER BY updated_at DESC', [stage])
|
||||||
|
|
||||||
|
if (result.length === 0) return []
|
||||||
|
|
||||||
|
return result[0].values.map((row: any[]) => ({
|
||||||
|
id: row[0] as number,
|
||||||
|
name: row[1] as string,
|
||||||
|
phone: row[2] as string,
|
||||||
|
stage: row[3] as Stage,
|
||||||
|
notes: row[4] as string | null,
|
||||||
|
schedule_date: row[5] as string | null,
|
||||||
|
follow_up_date: row[6] as string | null,
|
||||||
|
payment_status: row[7] as 'pending' | 'paid',
|
||||||
|
created_at: row[8] as string,
|
||||||
|
updated_at: row[9] as string,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAllContacts(): Contact[] {
|
||||||
|
const database = getDB()
|
||||||
|
const result = database.exec('SELECT * FROM contacts ORDER BY stage, updated_at DESC')
|
||||||
|
|
||||||
|
if (result.length === 0) return []
|
||||||
|
|
||||||
|
return result[0].values.map((row: any[]) => ({
|
||||||
|
id: row[0] as number,
|
||||||
|
name: row[1] as string,
|
||||||
|
phone: row[2] as string,
|
||||||
|
stage: row[3] as Stage,
|
||||||
|
notes: row[4] as string | null,
|
||||||
|
schedule_date: row[5] as string | null,
|
||||||
|
follow_up_date: row[6] as string | null,
|
||||||
|
payment_status: row[7] as 'pending' | 'paid',
|
||||||
|
created_at: row[8] as string,
|
||||||
|
updated_at: row[9] as string,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateContact(id: number, input: { name?: string; stage?: Stage; notes?: string; schedule_date?: string; follow_up_date?: string; payment_status?: 'pending' | 'paid' }): Contact | null {
|
||||||
|
const database = getDB()
|
||||||
|
const contact = getContactById(id)
|
||||||
|
if (!contact) return null
|
||||||
|
|
||||||
|
const now = new Date().toISOString()
|
||||||
|
const updates: string[] = []
|
||||||
|
const values: any[] = []
|
||||||
|
|
||||||
|
if (input.name !== undefined) {
|
||||||
|
updates.push('name = ?')
|
||||||
|
values.push(input.name)
|
||||||
|
}
|
||||||
|
if (input.stage !== undefined) {
|
||||||
|
updates.push('stage = ?')
|
||||||
|
values.push(input.stage)
|
||||||
|
}
|
||||||
|
if (input.notes !== undefined) {
|
||||||
|
updates.push('notes = ?')
|
||||||
|
values.push(input.notes)
|
||||||
|
}
|
||||||
|
if (input.schedule_date !== undefined) {
|
||||||
|
updates.push('schedule_date = ?')
|
||||||
|
values.push(input.schedule_date)
|
||||||
|
}
|
||||||
|
if (input.follow_up_date !== undefined) {
|
||||||
|
updates.push('follow_up_date = ?')
|
||||||
|
values.push(input.follow_up_date)
|
||||||
|
}
|
||||||
|
if (input.payment_status !== undefined) {
|
||||||
|
updates.push('payment_status = ?')
|
||||||
|
values.push(input.payment_status)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (updates.length === 0) return contact
|
||||||
|
|
||||||
|
updates.push('updated_at = ?')
|
||||||
|
values.push(now)
|
||||||
|
values.push(id)
|
||||||
|
|
||||||
|
database.run(`UPDATE contacts SET ${updates.join(', ')} WHERE id = ?`, values)
|
||||||
|
saveDB()
|
||||||
|
|
||||||
|
return getContactById(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteContact(id: number): boolean {
|
||||||
|
const database = getDB()
|
||||||
|
database.run('DELETE FROM messages WHERE contact_id = ?', [id])
|
||||||
|
database.run('DELETE FROM tasks WHERE contact_id = ?', [id])
|
||||||
|
database.run('DELETE FROM contacts WHERE id = ?', [id])
|
||||||
|
saveDB()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createMessage(input: { contact_id: number; external_id: string; body: string; from_phone: string; timestamp: number; has_media?: boolean }): Message | null {
|
||||||
|
const database = getDB()
|
||||||
|
|
||||||
|
const existing = database.exec('SELECT id FROM messages WHERE external_id = ?', [input.external_id])
|
||||||
|
if (existing.length > 0 && existing[0].values.length > 0) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const contact = getContactById(input.contact_id)
|
||||||
|
if (!contact) return null
|
||||||
|
|
||||||
|
const now = new Date().toISOString()
|
||||||
|
|
||||||
|
database.run(
|
||||||
|
`INSERT INTO messages (contact_id, external_id, body, from_phone, timestamp, has_media, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||||
|
[input.contact_id, input.external_id, input.body, input.from_phone, input.timestamp, input.has_media ? 1 : 0, now]
|
||||||
|
)
|
||||||
|
saveDB()
|
||||||
|
|
||||||
|
const result = database.exec('SELECT last_insert_rowid() as id')
|
||||||
|
const id = result[0].values[0][0] as number
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
contact_id: input.contact_id,
|
||||||
|
external_id: input.external_id,
|
||||||
|
body: input.body,
|
||||||
|
from: input.from_phone,
|
||||||
|
timestamp: input.timestamp,
|
||||||
|
has_media: input.has_media || false,
|
||||||
|
created_at: now,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMessagesByContactId(contactId: number): Message[] {
|
||||||
|
const database = getDB()
|
||||||
|
const result = database.exec('SELECT * FROM messages WHERE contact_id = ? ORDER BY timestamp DESC', [contactId])
|
||||||
|
|
||||||
|
if (result.length === 0) return []
|
||||||
|
|
||||||
|
return result[0].values.map((row: any[]) => ({
|
||||||
|
id: row[0] as number,
|
||||||
|
contact_id: row[1] as number,
|
||||||
|
external_id: row[2] as string,
|
||||||
|
body: row[3] as string,
|
||||||
|
from: row[4] as string,
|
||||||
|
timestamp: row[5] as number,
|
||||||
|
has_media: Boolean(row[6]),
|
||||||
|
created_at: row[7] as string,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createTask(input: { contact_id: number; title: string; due_date: string }): Task {
|
||||||
|
const database = getDB()
|
||||||
|
|
||||||
|
if (!input.title || !input.due_date) {
|
||||||
|
throw new Error('Title and due date are required')
|
||||||
|
}
|
||||||
|
|
||||||
|
const contact = getContactById(input.contact_id)
|
||||||
|
if (!contact) {
|
||||||
|
throw new Error('Contact not found')
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date().toISOString()
|
||||||
|
|
||||||
|
database.run(
|
||||||
|
`INSERT INTO tasks (contact_id, title, due_date, status, created_at)
|
||||||
|
VALUES (?, ?, ?, 'pending', ?)`,
|
||||||
|
[input.contact_id, input.title, input.due_date, now]
|
||||||
|
)
|
||||||
|
saveDB()
|
||||||
|
|
||||||
|
const result = database.exec('SELECT last_insert_rowid() as id')
|
||||||
|
const id = result[0].values[0][0] as number
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
contact_id: input.contact_id,
|
||||||
|
title: input.title,
|
||||||
|
due_date: input.due_date,
|
||||||
|
status: 'pending',
|
||||||
|
completed_at: null,
|
||||||
|
created_at: now,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTaskById(id: number): Task | null {
|
||||||
|
const database = getDB()
|
||||||
|
const result = database.exec('SELECT * FROM tasks WHERE id = ?', [id])
|
||||||
|
|
||||||
|
if (result.length === 0 || result[0].values.length === 0) return null
|
||||||
|
|
||||||
|
const row = result[0].values[0]
|
||||||
|
return {
|
||||||
|
id: row[0] as number,
|
||||||
|
contact_id: row[1] as number,
|
||||||
|
title: row[2] as string,
|
||||||
|
due_date: row[3] as string,
|
||||||
|
status: row[4] as 'pending' | 'completed',
|
||||||
|
completed_at: row[5] as string | null,
|
||||||
|
created_at: row[6] as string,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTasksByContactId(contactId: number): Task[] {
|
||||||
|
const database = getDB()
|
||||||
|
const result = database.exec('SELECT * FROM tasks WHERE contact_id = ? ORDER BY due_date ASC', [contactId])
|
||||||
|
|
||||||
|
if (result.length === 0) return []
|
||||||
|
|
||||||
|
return result[0].values.map((row: any[]) => ({
|
||||||
|
id: row[0] as number,
|
||||||
|
contact_id: row[1] as number,
|
||||||
|
title: row[2] as string,
|
||||||
|
due_date: row[3] as string,
|
||||||
|
status: row[4] as 'pending' | 'completed',
|
||||||
|
completed_at: row[5] as string | null,
|
||||||
|
created_at: row[6] as string,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPendingTasksByContactId(contactId: number): Task[] {
|
||||||
|
const database = getDB()
|
||||||
|
const result = database.exec("SELECT * FROM tasks WHERE contact_id = ? AND status = 'pending' ORDER BY due_date ASC", [contactId])
|
||||||
|
|
||||||
|
if (result.length === 0) return []
|
||||||
|
|
||||||
|
return result[0].values.map((row: any[]) => ({
|
||||||
|
id: row[0] as number,
|
||||||
|
contact_id: row[1] as number,
|
||||||
|
title: row[2] as string,
|
||||||
|
due_date: row[3] as string,
|
||||||
|
status: row[4] as 'pending' | 'completed',
|
||||||
|
completed_at: row[5] as string | null,
|
||||||
|
created_at: row[6] as string,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getOverdueTasks(): Task[] {
|
||||||
|
const database = getDB()
|
||||||
|
const now = new Date().toISOString()
|
||||||
|
const result = database.exec("SELECT * FROM tasks WHERE status = 'pending' AND due_date < ? ORDER BY due_date ASC", [now.split('T')[0]])
|
||||||
|
|
||||||
|
if (result.length === 0) return []
|
||||||
|
|
||||||
|
return result[0].values.map((row: any[]) => ({
|
||||||
|
id: row[0] as number,
|
||||||
|
contact_id: row[1] as number,
|
||||||
|
title: row[2] as string,
|
||||||
|
due_date: row[3] as string,
|
||||||
|
status: row[4] as 'pending' | 'completed',
|
||||||
|
completed_at: row[5] as string | null,
|
||||||
|
created_at: row[6] as string,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateTask(id: number, input: { title?: string; due_date?: string; status?: 'pending' | 'completed' }): Task | null {
|
||||||
|
const database = getDB()
|
||||||
|
const task = getTaskById(id)
|
||||||
|
if (!task) return null
|
||||||
|
|
||||||
|
const updates: string[] = []
|
||||||
|
const values: any[] = []
|
||||||
|
|
||||||
|
if (input.title !== undefined) {
|
||||||
|
updates.push('title = ?')
|
||||||
|
values.push(input.title)
|
||||||
|
}
|
||||||
|
if (input.due_date !== undefined) {
|
||||||
|
updates.push('due_date = ?')
|
||||||
|
values.push(input.due_date)
|
||||||
|
}
|
||||||
|
if (input.status !== undefined) {
|
||||||
|
updates.push('status = ?')
|
||||||
|
values.push(input.status)
|
||||||
|
if (input.status === 'completed') {
|
||||||
|
updates.push('completed_at = ?')
|
||||||
|
values.push(new Date().toISOString())
|
||||||
|
} else {
|
||||||
|
updates.push('completed_at = ?')
|
||||||
|
values.push(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (updates.length === 0) return task
|
||||||
|
|
||||||
|
values.push(id)
|
||||||
|
|
||||||
|
database.run(`UPDATE tasks SET ${updates.join(', ')} WHERE id = ?`, values)
|
||||||
|
saveDB()
|
||||||
|
|
||||||
|
return getTaskById(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteTask(id: number): boolean {
|
||||||
|
const database = getDB()
|
||||||
|
database.run('DELETE FROM tasks WHERE id = ?', [id])
|
||||||
|
saveDB()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTaskCountByContactId(contactId: number): number {
|
||||||
|
const database = getDB()
|
||||||
|
const result = database.exec("SELECT COUNT(*) as count FROM tasks WHERE contact_id = ? AND status = 'pending'", [contactId])
|
||||||
|
|
||||||
|
if (result.length === 0) return 0
|
||||||
|
|
||||||
|
return result[0].values[0][0] as number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function searchContacts(query: string): Contact[] {
|
||||||
|
const database = getDB()
|
||||||
|
const searchTerm = `%${query}%`
|
||||||
|
const result = database.exec(
|
||||||
|
'SELECT * FROM contacts WHERE name LIKE ? OR phone LIKE ? ORDER BY updated_at DESC',
|
||||||
|
[searchTerm, searchTerm]
|
||||||
|
)
|
||||||
|
|
||||||
|
if (result.length === 0) return []
|
||||||
|
|
||||||
|
return result[0].values.map((row: any[]) => ({
|
||||||
|
id: row[0] as number,
|
||||||
|
name: row[1] as string,
|
||||||
|
phone: row[2] as string,
|
||||||
|
stage: row[3] as Stage,
|
||||||
|
notes: row[4] as string | null,
|
||||||
|
schedule_date: row[5] as string | null,
|
||||||
|
follow_up_date: row[6] as string | null,
|
||||||
|
payment_status: row[7] as 'pending' | 'paid',
|
||||||
|
created_at: row[8] as string,
|
||||||
|
updated_at: row[9] as string,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getContactsByPaymentStatus(status: 'pending' | 'paid'): Contact[] {
|
||||||
|
const database = getDB()
|
||||||
|
const result = database.exec('SELECT * FROM contacts WHERE payment_status = ? ORDER BY updated_at DESC', [status])
|
||||||
|
|
||||||
|
if (result.length === 0) return []
|
||||||
|
|
||||||
|
return result[0].values.map((row: any[]) => ({
|
||||||
|
id: row[0] as number,
|
||||||
|
name: row[1] as string,
|
||||||
|
phone: row[2] as string,
|
||||||
|
stage: row[3] as Stage,
|
||||||
|
notes: row[4] as string | null,
|
||||||
|
schedule_date: row[5] as string | null,
|
||||||
|
follow_up_date: row[6] as string | null,
|
||||||
|
payment_status: row[7] as 'pending' | 'paid',
|
||||||
|
created_at: row[8] as string,
|
||||||
|
updated_at: row[9] as string,
|
||||||
|
}))
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
export const STAGES = {
|
||||||
|
LEADS_DE_ENTRADA: 'LEADS DE ENTRADA',
|
||||||
|
DECIDINDO: 'DECIDINDO',
|
||||||
|
DISCUSSAO_DE_CONTRATO: 'DISCUSSAO DE CONTRATO',
|
||||||
|
DECISAO_FINAL: 'DECISAO FINAL',
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type Stage = typeof STAGES[keyof typeof STAGES]
|
||||||
|
|
||||||
|
export const STAGE_LIST = Object.values(STAGES)
|
||||||
|
|
||||||
|
export interface Contact {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
phone: string
|
||||||
|
stage: Stage
|
||||||
|
notes: string | null
|
||||||
|
schedule_date: string | null
|
||||||
|
follow_up_date: string | null
|
||||||
|
payment_status: 'pending' | 'paid'
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
taskCount?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Message {
|
||||||
|
id: number
|
||||||
|
contact_id: number
|
||||||
|
external_id: string
|
||||||
|
body: string
|
||||||
|
from: string
|
||||||
|
timestamp: number
|
||||||
|
has_media: boolean
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Task {
|
||||||
|
id: number
|
||||||
|
contact_id: number
|
||||||
|
title: string
|
||||||
|
due_date: string
|
||||||
|
status: 'pending' | 'completed'
|
||||||
|
completed_at: string | null
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateContactInput {
|
||||||
|
name: string
|
||||||
|
phone: string
|
||||||
|
notes?: string
|
||||||
|
schedule_date?: string
|
||||||
|
follow_up_date?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateContactInput {
|
||||||
|
name?: string
|
||||||
|
stage?: Stage
|
||||||
|
notes?: string
|
||||||
|
schedule_date?: string
|
||||||
|
follow_up_date?: string
|
||||||
|
payment_status?: 'pending' | 'paid'
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateTaskInput {
|
||||||
|
contact_id: number
|
||||||
|
title: string
|
||||||
|
due_date: string
|
||||||
|
}
|
||||||
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user