feat: initial setup with WhatsApp CRM apps and sync services
This commit is contained in:
1 parent
d983027450
commit
e8bb767884
57 files changed
+26156
No files matched your search
@@ -1,3 +1,6 @@
|
|||||||
|
# Plans
|
||||||
|
plans/
|
||||||
|
|
||||||
# Byte-compiled / cache files
|
# Byte-compiled / cache files
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
|
|||||||
@@ -0,0 +1,191 @@
|
|||||||
|
# AGENTS.md - Agent Coding Guidelines
|
||||||
|
|
||||||
|
This workspace is a monorepo containing data engineering projects and WhatsApp CRM applications.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
workspace/
|
||||||
|
├── apps/
|
||||||
|
│ ├── whatsapp-crm/ # Next.js CRM with Kanban board
|
||||||
|
│ ├── whatsapp-sync/ # WhatsApp message sync service
|
||||||
|
│ ├── whatsapp-reader/ # WhatsApp message reader
|
||||||
|
│ └── timesfm-forecast/ # Time series forecasting app
|
||||||
|
├── data-engineering/ # Udacity DE portfolio projects
|
||||||
|
└── skills/ # dbt reference templates
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Build / Lint / Test Commands
|
||||||
|
|
||||||
|
### whatsapp-crm (primary app)
|
||||||
|
```bash
|
||||||
|
cd apps/whatsapp-crm
|
||||||
|
|
||||||
|
# Development
|
||||||
|
npm run dev # Start Next.js dev server on 0.0.0.0:3000
|
||||||
|
npm run build # Production build
|
||||||
|
npm run start # Production server
|
||||||
|
|
||||||
|
# Linting
|
||||||
|
npm run lint # ESLint with Next.js config
|
||||||
|
|
||||||
|
# Testing
|
||||||
|
npm run test # Run all Jest tests
|
||||||
|
npm run test:watch # Run tests in watch mode
|
||||||
|
npm run test:coverage # Run tests with coverage
|
||||||
|
|
||||||
|
# Single test file
|
||||||
|
npm run test -- tests/kanban.test.ts
|
||||||
|
npm run test -- --testPathPattern=kanban
|
||||||
|
```
|
||||||
|
|
||||||
|
### whatsapp-sync
|
||||||
|
```bash
|
||||||
|
cd apps/whatsapp-sync
|
||||||
|
|
||||||
|
npm run start # node src/index.js
|
||||||
|
npm run dev # node --watch src/index.js
|
||||||
|
npm run sync # node src/sync.js
|
||||||
|
npm run test # Jest
|
||||||
|
npm run test:watch # Jest watch mode
|
||||||
|
```
|
||||||
|
|
||||||
|
### whatsapp-reader
|
||||||
|
```bash
|
||||||
|
cd apps/whatsapp-reader
|
||||||
|
# No test script defined
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Code Style Guidelines
|
||||||
|
|
||||||
|
### TypeScript
|
||||||
|
- `strict: true` enabled in tsconfig.json
|
||||||
|
- Always use explicit types for function parameters and return values
|
||||||
|
- Use `interface` for objects, `type` for unions/aliases
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Good
|
||||||
|
interface Contact {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
stage: Stage
|
||||||
|
}
|
||||||
|
|
||||||
|
function getContactById(id: number): Contact | null
|
||||||
|
|
||||||
|
// Avoid
|
||||||
|
const contact = { id: 1, name: 'Test' } // implicit any
|
||||||
|
```
|
||||||
|
|
||||||
|
### Imports
|
||||||
|
- Use path alias `@/*` for internal imports (configured in tsconfig.json)
|
||||||
|
- Order: external → internal → relative
|
||||||
|
- Group by: React imports → other imports → types → components
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { useState, useMemo } from 'react'
|
||||||
|
import { Stage, STAGES, Contact } from '@/lib/types'
|
||||||
|
import { ContactCard } from '@/components/ContactCard'
|
||||||
|
```
|
||||||
|
|
||||||
|
### Naming Conventions
|
||||||
|
- **Components**: PascalCase (e.g., `KanbanBoard`, `ContactCard`)
|
||||||
|
- **Files**: PascalCase for components (`.tsx`), camelCase for utilities (`.ts`)
|
||||||
|
- **Interfaces/Types**: PascalCase (e.g., `Contact`, `Task`, `CreateContactInput`)
|
||||||
|
- **Constants**: UPPER_SNAKE_CASE (e.g., `STAGES`, `STAGE_LIST`)
|
||||||
|
- **React hooks**: camelCase with `use` prefix (e.g., `useContacts`, `useTask`)
|
||||||
|
- **Boolean variables**: prefix with `is`, `has`, `should` (e.g., `isLoading`, `hasError`)
|
||||||
|
|
||||||
|
### Error Handling
|
||||||
|
- Use Zod for input validation with react-hook-form
|
||||||
|
- Always wrap async operations in try/catch
|
||||||
|
- Return proper HTTP status codes in API routes
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// API route error handling
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
try {
|
||||||
|
const body = await request.json()
|
||||||
|
const validated = CreateContactInput.parse(body)
|
||||||
|
// ... process
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof ZodError) {
|
||||||
|
return Response.json({ error: error.errors }, { status: 400 })
|
||||||
|
}
|
||||||
|
return Response.json({ error: 'Internal server error' }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Component Structure
|
||||||
|
- Use `'use client'` directive for client-side components
|
||||||
|
- Destructure props with explicit typing
|
||||||
|
- Keep components focused and small
|
||||||
|
- Extract reusable logic to custom hooks
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
'use client'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
contacts: Contact[]
|
||||||
|
onContactClick: (contact: Contact) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ComponentName({ contacts, onContactClick }: Props) {
|
||||||
|
// hooks first, then effects, then render
|
||||||
|
const [state, setState] = useState(false)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{/* JSX */}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Database (sql.js)
|
||||||
|
- Use Zod schemas for table definitions
|
||||||
|
- Always validate data before insert/update
|
||||||
|
- Use transactions for multi-step operations
|
||||||
|
|
||||||
|
### Testing
|
||||||
|
- Test files: `tests/*.test.ts` or `*.test.tsx`
|
||||||
|
- Use `@testing-library/react` for component tests
|
||||||
|
- Use `@testing-library/user-event` for user interactions
|
||||||
|
- Follow AAA pattern: Arrange, Act, Assert
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
test('should update contact stage', async () => {
|
||||||
|
const user = userEvent.setup()
|
||||||
|
render(<KanbanBoard {...props} />)
|
||||||
|
|
||||||
|
await user.click(screen.getByText('Move to Next Stage'))
|
||||||
|
|
||||||
|
expect(onStageChange).toHaveBeenCalledWith(1, 'DECIDINDO')
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### CSS / Styling
|
||||||
|
- This project uses CSS modules or global CSS
|
||||||
|
- Follow BEM-like naming: `block-element--modifier`
|
||||||
|
- Keep styles co-located when possible
|
||||||
|
|
||||||
|
### Git Conventions
|
||||||
|
- Use meaningful commit messages
|
||||||
|
- Branch naming: `feature/description` or `fix/description`
|
||||||
|
- Run `npm run lint` and `npm run test` before committing
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Important Notes
|
||||||
|
|
||||||
|
- whatsapp-crm uses Next.js 14 App Router
|
||||||
|
- Database is sql.js (WebAssembly SQLite) - runs in browser
|
||||||
|
- Authentication uses WhatsApp Web.js QR code scanning
|
||||||
|
- STAGES constant defines the Kanban pipeline (defined in `src/lib/types.ts`)
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
import { initDB, createContact, createTask, createMessage, getContactById, getTasksByContactId, getMessagesByContactId, updateContact, updateTask, closeDB } from '@/lib/db'
|
||||||
|
import { STAGES } from '@/lib/types'
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
await initDB()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(() => {
|
||||||
|
closeDB()
|
||||||
|
})
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
const db = require('@/lib/db').getDB()
|
||||||
|
db.run('DELETE FROM tasks')
|
||||||
|
db.run('DELETE FROM messages')
|
||||||
|
db.run('DELETE FROM contacts')
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Integration Tests', () => {
|
||||||
|
describe('10.1 Full Pipeline Tests', () => {
|
||||||
|
it('test_full_contact_lifecycle', async () => {
|
||||||
|
const contact = createContact({ name: 'Test User', phone: '+5511999999991' })
|
||||||
|
expect(contact.id).toBeGreaterThan(0)
|
||||||
|
|
||||||
|
const updated = updateContact(contact.id, { stage: STAGES.DECIDINDO })
|
||||||
|
expect(updated?.stage).toBe(STAGES.DECIDINDO)
|
||||||
|
|
||||||
|
const fetched = getContactById(contact.id)
|
||||||
|
expect(fetched?.name).toBe('Test User')
|
||||||
|
expect(fetched?.stage).toBe(STAGES.DECIDINDO)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_contact_with_tasks_lifecycle', async () => {
|
||||||
|
const contact = createContact({ name: 'Task User', phone: '+5511999999992' })
|
||||||
|
|
||||||
|
const task1 = createTask({ contact_id: contact.id, title: 'Task 1', due_date: '2026-04-10' })
|
||||||
|
const task2 = createTask({ contact_id: contact.id, title: 'Task 2', due_date: '2026-04-15' })
|
||||||
|
|
||||||
|
const tasks = getTasksByContactId(contact.id)
|
||||||
|
expect(tasks).toHaveLength(2)
|
||||||
|
|
||||||
|
updateTask(task1.id, { status: 'completed' })
|
||||||
|
|
||||||
|
const allTasks = getTasksByContactId(contact.id)
|
||||||
|
const pending = allTasks.filter(t => t.status === 'pending')
|
||||||
|
expect(pending).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_contact_with_messages_lifecycle', async () => {
|
||||||
|
const contact = createContact({ name: 'Message User', phone: '+5511999999993' })
|
||||||
|
|
||||||
|
const msg1 = createMessage({
|
||||||
|
contact_id: contact.id,
|
||||||
|
external_id: 'msg-1',
|
||||||
|
body: 'Hello',
|
||||||
|
from_phone: contact.phone,
|
||||||
|
timestamp: 1704067200,
|
||||||
|
has_media: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
const msg2 = createMessage({
|
||||||
|
contact_id: contact.id,
|
||||||
|
external_id: 'msg-2',
|
||||||
|
body: 'How are you?',
|
||||||
|
from_phone: contact.phone,
|
||||||
|
timestamp: 1704070800,
|
||||||
|
has_media: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
const messages = getMessagesByContactId(contact.id)
|
||||||
|
expect(messages).toHaveLength(2)
|
||||||
|
expect(messages[0].body).toBe('How are you?')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_duplicate_message_filtered', async () => {
|
||||||
|
const contact = createContact({ name: 'Dupe User', phone: '+5511999999994' })
|
||||||
|
|
||||||
|
createMessage({
|
||||||
|
contact_id: contact.id,
|
||||||
|
external_id: 'same-id',
|
||||||
|
body: 'First message',
|
||||||
|
from_phone: contact.phone,
|
||||||
|
timestamp: 1704067200,
|
||||||
|
})
|
||||||
|
|
||||||
|
const duplicate = createMessage({
|
||||||
|
contact_id: contact.id,
|
||||||
|
external_id: 'same-id',
|
||||||
|
body: 'Duplicate message',
|
||||||
|
from_phone: contact.phone,
|
||||||
|
timestamp: 1704070800,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(duplicate).toBeNull()
|
||||||
|
|
||||||
|
const messages = getMessagesByContactId(contact.id)
|
||||||
|
expect(messages).toHaveLength(1)
|
||||||
|
expect(messages[0].body).toBe('First message')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('10.2 Multi-Feature Tests', () => {
|
||||||
|
it('test_search_finds_contact_with_tasks', async () => {
|
||||||
|
createContact({ name: 'Searchable Contact', phone: '+5511999999991' })
|
||||||
|
const contact2 = createContact({ name: 'Other Contact', phone: '+5511999999992' })
|
||||||
|
|
||||||
|
createTask({ contact_id: contact2.id, title: 'Important Task', due_date: '2026-04-10' })
|
||||||
|
|
||||||
|
const { searchContacts } = require('@/lib/db')
|
||||||
|
const results = searchContacts('Searchable')
|
||||||
|
expect(results).toHaveLength(1)
|
||||||
|
expect(results[0].name).toBe('Searchable Contact')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_filter_stage_preserves_tasks', async () => {
|
||||||
|
const contact1 = createContact({ name: 'Lead 1', phone: '+5511999999991' })
|
||||||
|
const contact2 = createContact({ name: 'Lead 2', phone: '+5511999999992' })
|
||||||
|
|
||||||
|
updateContact(contact1.id, { stage: STAGES.DECIDINDO })
|
||||||
|
|
||||||
|
createTask({ contact_id: contact1.id, title: 'Task for Decidindo', due_date: '2026-04-10' })
|
||||||
|
createTask({ contact_id: contact2.id, title: 'Task for Leads', due_date: '2026-04-10' })
|
||||||
|
|
||||||
|
const { getContactsByStage } = require('@/lib/db')
|
||||||
|
const leads = getContactsByStage(STAGES.LEADS_DE_ENTRADA)
|
||||||
|
const decidindo = getContactsByStage(STAGES.DECIDINDO)
|
||||||
|
|
||||||
|
expect(leads).toHaveLength(1)
|
||||||
|
expect(decidindo).toHaveLength(1)
|
||||||
|
|
||||||
|
const decidindoTasks = getTasksByContactId(decidindo[0].id)
|
||||||
|
expect(decidindoTasks).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_payment_status_update_preserves_all_data', async () => {
|
||||||
|
const contact = createContact({ name: 'Payment User', phone: '+5511999999991', notes: 'Initial note' })
|
||||||
|
|
||||||
|
createTask({ contact_id: contact.id, title: 'Task 1', due_date: '2026-04-10' })
|
||||||
|
createMessage({
|
||||||
|
contact_id: contact.id,
|
||||||
|
external_id: 'msg-1',
|
||||||
|
body: 'Message 1',
|
||||||
|
from_phone: contact.phone,
|
||||||
|
timestamp: 1704067200,
|
||||||
|
})
|
||||||
|
|
||||||
|
updateContact(contact.id, { payment_status: 'paid', notes: 'Updated note' })
|
||||||
|
|
||||||
|
const updated = getContactById(contact.id)
|
||||||
|
expect(updated?.payment_status).toBe('paid')
|
||||||
|
expect(updated?.notes).toBe('Updated note')
|
||||||
|
|
||||||
|
const tasks = getTasksByContactId(contact.id)
|
||||||
|
expect(tasks).toHaveLength(1)
|
||||||
|
|
||||||
|
const messages = getMessagesByContactId(contact.id)
|
||||||
|
expect(messages).toHaveLength(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('10.3 Performance Tests', () => {
|
||||||
|
it('test_bulk_contact_creation', async () => {
|
||||||
|
const startTime = Date.now()
|
||||||
|
|
||||||
|
for (let i = 0; i < 50; i++) {
|
||||||
|
createContact({ name: `Contact ${i}`, phone: `+551199999${String(i).padStart(4, '0')}` })
|
||||||
|
}
|
||||||
|
|
||||||
|
const elapsed = Date.now() - startTime
|
||||||
|
expect(elapsed).toBeLessThan(2000)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_bulk_task_creation', async () => {
|
||||||
|
const contact = createContact({ name: 'Bulk User', phone: '+5511999999991' })
|
||||||
|
|
||||||
|
for (let i = 0; i < 20; i++) {
|
||||||
|
createTask({ contact_id: contact.id, title: `Task ${i}`, due_date: '2026-04-10' })
|
||||||
|
}
|
||||||
|
|
||||||
|
const tasks = getTasksByContactId(contact.id)
|
||||||
|
expect(tasks).toHaveLength(20)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_bulk_message_creation', async () => {
|
||||||
|
const contact = createContact({ name: 'Bulk Msg User', phone: '+5511999999991' })
|
||||||
|
|
||||||
|
for (let i = 0; i < 20; i++) {
|
||||||
|
createMessage({
|
||||||
|
contact_id: contact.id,
|
||||||
|
external_id: `msg-${i}`,
|
||||||
|
body: `Message ${i}`,
|
||||||
|
from_phone: contact.phone,
|
||||||
|
timestamp: 1704067200 + i * 3600,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const messages = getMessagesByContactId(contact.id)
|
||||||
|
expect(messages).toHaveLength(20)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('10.4 Edge Cases', () => {
|
||||||
|
it('test_delete_contact_cascades_tasks_and_messages', async () => {
|
||||||
|
const contact = createContact({ name: 'To Delete', phone: '+5511999999991' })
|
||||||
|
|
||||||
|
createTask({ contact_id: contact.id, title: 'Task', due_date: '2026-04-10' })
|
||||||
|
createMessage({
|
||||||
|
contact_id: contact.id,
|
||||||
|
external_id: 'msg-1',
|
||||||
|
body: 'Message',
|
||||||
|
from_phone: contact.phone,
|
||||||
|
timestamp: 1704067200,
|
||||||
|
})
|
||||||
|
|
||||||
|
const { deleteContact } = require('@/lib/db')
|
||||||
|
deleteContact(contact.id)
|
||||||
|
|
||||||
|
const tasks = getTasksByContactId(contact.id)
|
||||||
|
const messages = getMessagesByContactId(contact.id)
|
||||||
|
|
||||||
|
expect(tasks).toHaveLength(0)
|
||||||
|
expect(messages).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_stage_transitions_all_stages', async () => {
|
||||||
|
const contact = createContact({ name: 'Stage User', phone: '+5511999999991' })
|
||||||
|
|
||||||
|
expect(contact.stage).toBe(STAGES.LEADS_DE_ENTRADA)
|
||||||
|
|
||||||
|
let updated = updateContact(contact.id, { stage: STAGES.DECIDINDO })
|
||||||
|
expect(updated?.stage).toBe(STAGES.DECIDINDO)
|
||||||
|
|
||||||
|
updated = updateContact(contact.id, { stage: STAGES.DISCUSSAO_DE_CONTRATO })
|
||||||
|
expect(updated?.stage).toBe(STAGES.DISCUSSAO_DE_CONTRATO)
|
||||||
|
|
||||||
|
updated = updateContact(contact.id, { stage: STAGES.DECISAO_FINAL })
|
||||||
|
expect(updated?.stage).toBe(STAGES.DECISAO_FINAL)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_task_completion_updates_correctly', async () => {
|
||||||
|
const contact = createContact({ name: 'Task User', phone: '+5511999999991' })
|
||||||
|
const task = createTask({ contact_id: contact.id, title: 'To Complete', due_date: '2026-04-10' })
|
||||||
|
|
||||||
|
const completed = updateTask(task.id, { status: 'completed' })
|
||||||
|
expect(completed?.status).toBe('completed')
|
||||||
|
expect(completed?.completed_at).not.toBeNull()
|
||||||
|
|
||||||
|
const reOpened = updateTask(task.id, { status: 'pending' })
|
||||||
|
expect(reOpened?.status).toBe('pending')
|
||||||
|
expect(reOpened?.completed_at).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
import { STAGES, Stage, Contact } from '@/lib/types'
|
||||||
|
|
||||||
|
describe('Kanban Board', () => {
|
||||||
|
describe('3.1 Column Component Tests', () => {
|
||||||
|
it('test_renders_four_columns', () => {
|
||||||
|
const { STAGE_LIST } = require('@/lib/types')
|
||||||
|
expect(STAGE_LIST).toHaveLength(4)
|
||||||
|
expect(STAGE_LIST).toContain('LEADS DE ENTRADA')
|
||||||
|
expect(STAGE_LIST).toContain('DECIDINDO')
|
||||||
|
expect(STAGE_LIST).toContain('DISCUSSAO DE CONTRATO')
|
||||||
|
expect(STAGE_LIST).toContain('DECISAO FINAL')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_column_displays_contact_count', () => {
|
||||||
|
const contacts: Contact[] = [
|
||||||
|
{ id: 1, name: 'Contact 1', phone: '+5511999999991', stage: STAGES.LEADS_DE_ENTRADA, notes: null, schedule_date: null, follow_up_date: null, payment_status: 'pending', created_at: '', updated_at: '' },
|
||||||
|
{ id: 2, name: 'Contact 2', phone: '+5511999999992', stage: STAGES.LEADS_DE_ENTRADA, notes: null, schedule_date: null, follow_up_date: null, payment_status: 'pending', created_at: '', updated_at: '' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const leadsContacts = contacts.filter(c => c.stage === STAGES.LEADS_DE_ENTRADA)
|
||||||
|
expect(leadsContacts.length).toBe(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_empty_column_shows_placeholder', () => {
|
||||||
|
const contacts: Contact[] = []
|
||||||
|
const leadsContacts = contacts.filter(c => c.stage === STAGES.LEADS_DE_ENTRADA)
|
||||||
|
|
||||||
|
const shouldShowEmpty = leadsContacts.length === 0
|
||||||
|
expect(shouldShowEmpty).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('3.2 Contact Card Tests', () => {
|
||||||
|
it('test_card_displays_contact_name', () => {
|
||||||
|
const contact: Contact = {
|
||||||
|
id: 1,
|
||||||
|
name: 'John Doe',
|
||||||
|
phone: '+5511999999999',
|
||||||
|
stage: STAGES.LEADS_DE_ENTRADA,
|
||||||
|
notes: null,
|
||||||
|
schedule_date: null,
|
||||||
|
follow_up_date: null,
|
||||||
|
payment_status: 'pending',
|
||||||
|
created_at: '',
|
||||||
|
updated_at: ''
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(contact.name).toBe('John Doe')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_card_displays_formatted_phone', () => {
|
||||||
|
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 formatted = formatPhone('+5511999999999')
|
||||||
|
expect(formatted).toContain('+55')
|
||||||
|
expect(formatted).toContain('99999')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_card_displays_message_preview', () => {
|
||||||
|
const contact: Contact = {
|
||||||
|
id: 1,
|
||||||
|
name: 'John Doe',
|
||||||
|
phone: '+5511999999999',
|
||||||
|
stage: STAGES.LEADS_DE_ENTRADA,
|
||||||
|
notes: 'This is a very long note that should be truncated when displayed in the card preview area',
|
||||||
|
schedule_date: null,
|
||||||
|
follow_up_date: null,
|
||||||
|
payment_status: 'pending',
|
||||||
|
created_at: '',
|
||||||
|
updated_at: ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const preview = contact.notes ? contact.notes.substring(0, 50) + (contact.notes.length > 50 ? '...' : '') : ''
|
||||||
|
expect(preview.length).toBe(53)
|
||||||
|
expect(preview).toContain('...')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_card_displays_task_count_badge', () => {
|
||||||
|
const contact: Contact = {
|
||||||
|
id: 1,
|
||||||
|
name: 'John Doe',
|
||||||
|
phone: '+5511999999999',
|
||||||
|
stage: STAGES.LEADS_DE_ENTRADA,
|
||||||
|
notes: null,
|
||||||
|
schedule_date: null,
|
||||||
|
follow_up_date: null,
|
||||||
|
payment_status: 'pending',
|
||||||
|
created_at: '',
|
||||||
|
updated_at: '',
|
||||||
|
taskCount: 3
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(contact.taskCount).toBe(3)
|
||||||
|
expect(contact.taskCount! > 0).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_card_displays_overdue_indicator', () => {
|
||||||
|
const pastDate = '2020-01-01'
|
||||||
|
const futureDate = '2030-01-01'
|
||||||
|
|
||||||
|
const isPastOverdue = pastDate && new Date(pastDate) < new Date()
|
||||||
|
const isFutureOverdue = futureDate && new Date(futureDate) < new Date()
|
||||||
|
|
||||||
|
expect(isPastOverdue).toBe(true)
|
||||||
|
expect(isFutureOverdue).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('3.3 Drag and Drop Tests', () => {
|
||||||
|
it('test_drag_card_to_different_stage', () => {
|
||||||
|
const contact: Contact = {
|
||||||
|
id: 1,
|
||||||
|
name: 'John Doe',
|
||||||
|
phone: '+5511999999999',
|
||||||
|
stage: STAGES.LEADS_DE_ENTRADA,
|
||||||
|
notes: null,
|
||||||
|
schedule_date: null,
|
||||||
|
follow_up_date: null,
|
||||||
|
payment_status: 'pending',
|
||||||
|
created_at: '',
|
||||||
|
updated_at: ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const newStage = STAGES.DECIDINDO
|
||||||
|
const updatedContact = { ...contact, stage: newStage }
|
||||||
|
|
||||||
|
expect(updatedContact.stage).toBe(STAGES.DECIDINDO)
|
||||||
|
expect(updatedContact.stage).not.toBe(contact.stage)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_cannot_drag_to_same_column', () => {
|
||||||
|
const contact: Contact = {
|
||||||
|
id: 1,
|
||||||
|
name: 'John Doe',
|
||||||
|
phone: '+5511999999999',
|
||||||
|
stage: STAGES.LEADS_DE_ENTRADA,
|
||||||
|
notes: null,
|
||||||
|
schedule_date: null,
|
||||||
|
follow_up_date: null,
|
||||||
|
payment_status: 'pending',
|
||||||
|
created_at: '',
|
||||||
|
updated_at: ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const sameStage = STAGES.LEADS_DE_ENTRADA
|
||||||
|
const updatedContact = { ...contact, stage: sameStage }
|
||||||
|
|
||||||
|
expect(updatedContact.stage).toBe(contact.stage)
|
||||||
|
expect(updatedContact.stage).not.toBe(STAGES.DECIDINDO)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_drag_cancelled_returns_card', () => {
|
||||||
|
const contact: Contact = {
|
||||||
|
id: 1,
|
||||||
|
name: 'John Doe',
|
||||||
|
phone: '+5511999999999',
|
||||||
|
stage: STAGES.LEADS_DE_ENTRADA,
|
||||||
|
notes: null,
|
||||||
|
schedule_date: null,
|
||||||
|
follow_up_date: null,
|
||||||
|
payment_status: 'pending',
|
||||||
|
created_at: '',
|
||||||
|
updated_at: ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const originalContact = { ...contact }
|
||||||
|
|
||||||
|
expect(contact.stage).toBe(originalContact.stage)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import { Stage, STAGES } from '@/lib/types'
|
||||||
|
|
||||||
|
describe('Contact Detail View', () => {
|
||||||
|
describe('4.1 Modal Tests', () => {
|
||||||
|
it('test_modal_opens_on_card_click', () => {
|
||||||
|
const isModalOpen = true
|
||||||
|
expect(isModalOpen).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_modal_displays_all_fields', () => {
|
||||||
|
const contact = {
|
||||||
|
id: 1,
|
||||||
|
name: 'John Doe',
|
||||||
|
phone: '+5511999999999',
|
||||||
|
stage: STAGES.LEADS_DE_ENTRADA,
|
||||||
|
notes: 'Test note',
|
||||||
|
schedule_date: '2026-04-10',
|
||||||
|
follow_up_date: null,
|
||||||
|
payment_status: 'pending' as const,
|
||||||
|
created_at: '2026-04-01',
|
||||||
|
updated_at: '2026-04-01',
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(contact.name).toBeDefined()
|
||||||
|
expect(contact.phone).toBeDefined()
|
||||||
|
expect(contact.stage).toBeDefined()
|
||||||
|
expect(contact.notes).toBeDefined()
|
||||||
|
expect(contact.payment_status).toBeDefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_modal_close_on_overlay_click', () => {
|
||||||
|
const handleClose = jest.fn()
|
||||||
|
const event = { target: { classList: { contains: (cls: string) => cls === 'modal-overlay' } } }
|
||||||
|
|
||||||
|
if (event.target.classList.contains('modal-overlay')) {
|
||||||
|
handleClose()
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(handleClose).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_modal_close_on_escape_key', () => {
|
||||||
|
const handleClose = jest.fn()
|
||||||
|
const event = { key: 'Escape' }
|
||||||
|
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
handleClose()
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(handleClose).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('4.2 Message History Tests', () => {
|
||||||
|
it('test_displays_message_history_sorted_by_date', () => {
|
||||||
|
const messages = [
|
||||||
|
{ id: 1, timestamp: 1000, body: 'First' },
|
||||||
|
{ id: 2, timestamp: 2000, body: 'Second' },
|
||||||
|
{ id: 3, timestamp: 500, body: 'Third' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const sorted = [...messages].sort((a, b) => b.timestamp - a.timestamp)
|
||||||
|
expect(sorted[0].body).toBe('Second')
|
||||||
|
expect(sorted[1].body).toBe('First')
|
||||||
|
expect(sorted[2].body).toBe('Third')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_message_shows_content_and_time', () => {
|
||||||
|
const message = {
|
||||||
|
id: 1,
|
||||||
|
timestamp: 1704067200,
|
||||||
|
body: 'Hello world',
|
||||||
|
}
|
||||||
|
|
||||||
|
const date = new Date(message.timestamp * 1000)
|
||||||
|
expect(message.body).toBe('Hello world')
|
||||||
|
expect(date.getTime()).toBeGreaterThan(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_pagination_loads_more_messages', () => {
|
||||||
|
const allMessages = Array.from({ length: 100 }, (_, i) => ({ id: i, body: `Message ${i}` }))
|
||||||
|
const pageSize = 20
|
||||||
|
let currentPage = 0
|
||||||
|
|
||||||
|
const getPage = (page: number) => {
|
||||||
|
const start = page * pageSize
|
||||||
|
return allMessages.slice(start, start + pageSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
const firstPage = getPage(currentPage)
|
||||||
|
expect(firstPage).toHaveLength(pageSize)
|
||||||
|
|
||||||
|
currentPage++
|
||||||
|
const secondPage = getPage(currentPage)
|
||||||
|
expect(secondPage).toHaveLength(pageSize)
|
||||||
|
expect(secondPage[0].body).toBe('Message 20')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('4.3 Notes and Fields Tests', () => {
|
||||||
|
it('test_add_note_to_contact', () => {
|
||||||
|
let notes = ''
|
||||||
|
|
||||||
|
const addNote = (newNote: string) => {
|
||||||
|
notes = newNote
|
||||||
|
}
|
||||||
|
|
||||||
|
addNote('This is a new note')
|
||||||
|
expect(notes).toBe('This is a new note')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_update_payment_status', () => {
|
||||||
|
let paymentStatus: 'pending' | 'paid' = 'pending'
|
||||||
|
|
||||||
|
const updateStatus = (status: 'pending' | 'paid') => {
|
||||||
|
paymentStatus = status
|
||||||
|
}
|
||||||
|
|
||||||
|
updateStatus('paid')
|
||||||
|
expect(paymentStatus).toBe('paid')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
describe('Project Setup', () => {
|
||||||
|
it('should have types defined', () => {
|
||||||
|
expect(true).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should have STAGES constant', () => {
|
||||||
|
const { STAGES, STAGE_LIST } = require('@/lib/types')
|
||||||
|
expect(STAGES.LEADS_DE_ENTRADA).toBe('LEADS DE ENTRADA')
|
||||||
|
expect(STAGES.DECIDINDO).toBe('DECIDINDO')
|
||||||
|
expect(STAGES.DISCUSSAO_DE_CONTRATO).toBe('DISCUSSAO DE CONTRATO')
|
||||||
|
expect(STAGES.DECISAO_FINAL).toBe('DECISAO FINAL')
|
||||||
|
expect(STAGE_LIST).toHaveLength(4)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should have stage list exported', () => {
|
||||||
|
const { STAGE_LIST } = require('@/lib/types')
|
||||||
|
expect(STAGE_LIST).toContain('LEADS DE ENTRADA')
|
||||||
|
expect(STAGE_LIST).toContain('DECIDINDO')
|
||||||
|
expect(STAGE_LIST).toContain('DISCUSSAO DE CONTRATO')
|
||||||
|
expect(STAGE_LIST).toContain('DECISAO FINAL')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { initDB, createContact, searchContacts, getContactsByStage, getContactsByPaymentStatus, closeDB } from '@/lib/db'
|
||||||
|
import { STAGES } from '@/lib/types'
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
await initDB()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(() => {
|
||||||
|
closeDB()
|
||||||
|
})
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
const db = require('@/lib/db').getDB()
|
||||||
|
db.run('DELETE FROM tasks')
|
||||||
|
db.run('DELETE FROM messages')
|
||||||
|
db.run('DELETE FROM contacts')
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Search & Filter', () => {
|
||||||
|
describe('6.1 Search Tests', () => {
|
||||||
|
it('test_search_contacts_by_name', async () => {
|
||||||
|
createContact({ name: 'John Doe', phone: '+5511999999991' })
|
||||||
|
createContact({ name: 'Jane Smith', phone: '+5511999999992' })
|
||||||
|
createContact({ name: 'Alice Brown', phone: '+5511999999993' })
|
||||||
|
|
||||||
|
const results = searchContacts('John')
|
||||||
|
|
||||||
|
expect(results).toHaveLength(1)
|
||||||
|
expect(results[0].name).toBe('John Doe')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_search_contacts_by_phone', async () => {
|
||||||
|
createContact({ name: 'Contact One', phone: '+5511999999991' })
|
||||||
|
createContact({ name: 'Contact Two', phone: '+5511888888888' })
|
||||||
|
|
||||||
|
const results = searchContacts('19999')
|
||||||
|
|
||||||
|
expect(results).toHaveLength(1)
|
||||||
|
expect(results[0].phone).toBe('+5511999999991')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_search_returns_empty_for_no_match', async () => {
|
||||||
|
createContact({ name: 'John Doe', phone: '+5511999999991' })
|
||||||
|
|
||||||
|
const results = searchContacts('nonexistent')
|
||||||
|
|
||||||
|
expect(results).toHaveLength(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('6.2 Filter Tests', () => {
|
||||||
|
it('test_filter_by_stage', async () => {
|
||||||
|
const c1 = createContact({ name: 'Lead 1', phone: '+5511999999991' })
|
||||||
|
const c2 = createContact({ name: 'Lead 2', phone: '+5511999999992' })
|
||||||
|
const c3 = createContact({ name: 'Deciding', phone: '+5511999999993' })
|
||||||
|
|
||||||
|
const { updateContact } = require('@/lib/db')
|
||||||
|
updateContact(c1.id, { stage: STAGES.LEADS_DE_ENTRADA })
|
||||||
|
updateContact(c2.id, { stage: STAGES.LEADS_DE_ENTRADA })
|
||||||
|
updateContact(c3.id, { stage: STAGES.DECIDINDO })
|
||||||
|
|
||||||
|
const leads = getContactsByStage(STAGES.LEADS_DE_ENTRADA)
|
||||||
|
const decidindo = getContactsByStage(STAGES.DECIDINDO)
|
||||||
|
|
||||||
|
expect(leads).toHaveLength(2)
|
||||||
|
expect(decidindo).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_filter_by_payment_status', async () => {
|
||||||
|
const c1 = createContact({ name: 'Paid Contact', phone: '+5511999999991' })
|
||||||
|
const c2 = createContact({ name: 'Pending Contact', phone: '+5511999999992' })
|
||||||
|
|
||||||
|
const { updateContact } = require('@/lib/db')
|
||||||
|
updateContact(c1.id, { payment_status: 'paid' })
|
||||||
|
updateContact(c2.id, { payment_status: 'pending' })
|
||||||
|
|
||||||
|
const paid = getContactsByPaymentStatus('paid')
|
||||||
|
const pending = getContactsByPaymentStatus('pending')
|
||||||
|
|
||||||
|
expect(paid).toHaveLength(1)
|
||||||
|
expect(pending).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_filter_combined_stage_and_payment', async () => {
|
||||||
|
const c1 = createContact({ name: 'Lead Paid', phone: '+5511999999991' })
|
||||||
|
const c2 = createContact({ name: 'Lead Pending', phone: '+5511999999992' })
|
||||||
|
const c3 = createContact({ name: 'Deciding Paid', phone: '+5511999999993' })
|
||||||
|
|
||||||
|
const { updateContact } = require('@/lib/db')
|
||||||
|
updateContact(c1.id, { stage: STAGES.LEADS_DE_ENTRADA, payment_status: 'paid' })
|
||||||
|
updateContact(c2.id, { stage: STAGES.LEADS_DE_ENTRADA, payment_status: 'pending' })
|
||||||
|
updateContact(c3.id, { stage: STAGES.DECIDINDO, payment_status: 'paid' })
|
||||||
|
|
||||||
|
const leadsByStage = getContactsByStage(STAGES.LEADS_DE_ENTRADA)
|
||||||
|
const paidByStatus = getContactsByPaymentStatus('paid')
|
||||||
|
const combined = leadsByStage.filter(c => c.payment_status === 'paid')
|
||||||
|
|
||||||
|
expect(leadsByStage).toHaveLength(2)
|
||||||
|
expect(paidByStatus).toHaveLength(2)
|
||||||
|
expect(combined).toHaveLength(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import '@testing-library/jest-dom'
|
||||||
|
import { cleanup } from '@testing-library/react'
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup()
|
||||||
|
})
|
||||||
|
|
||||||
|
const mockRouter = {
|
||||||
|
push: jest.fn(),
|
||||||
|
replace: jest.fn(),
|
||||||
|
prefetch: jest.fn(),
|
||||||
|
back: jest.fn(),
|
||||||
|
}
|
||||||
|
|
||||||
|
jest.mock('next/navigation', () => ({
|
||||||
|
useRouter: () => mockRouter,
|
||||||
|
useSearchParams: () => new URLSearchParams(),
|
||||||
|
usePathname: () => '/',
|
||||||
|
}))
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
import { initDB, createContact, createTask, getTaskById, getTasksByContactId, getPendingTasksByContactId, getOverdueTasks, updateTask, deleteTask, closeDB } from '@/lib/db'
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
await initDB()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(() => {
|
||||||
|
closeDB()
|
||||||
|
})
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
const db = require('@/lib/db').getDB()
|
||||||
|
db.run('DELETE FROM tasks')
|
||||||
|
db.run('DELETE FROM messages')
|
||||||
|
db.run('DELETE FROM contacts')
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Task Management', () => {
|
||||||
|
describe('5.1 Task Creation Tests', () => {
|
||||||
|
it('test_create_task_with_required_fields', async () => {
|
||||||
|
const contact = createContact({ name: 'Test Contact', phone: '+5511999999999' })
|
||||||
|
|
||||||
|
const task = createTask({
|
||||||
|
contact_id: contact.id,
|
||||||
|
title: 'Follow up call',
|
||||||
|
due_date: '2026-04-10',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(task).toBeDefined()
|
||||||
|
expect(task.id).toBeGreaterThan(0)
|
||||||
|
expect(task.contact_id).toBe(contact.id)
|
||||||
|
expect(task.title).toBe('Follow up call')
|
||||||
|
expect(task.due_date).toBe('2026-04-10')
|
||||||
|
expect(task.status).toBe('pending')
|
||||||
|
expect(task.completed_at).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_create_task_missing_due_date', async () => {
|
||||||
|
const contact = createContact({ name: 'Test Contact', phone: '+5511999999998' })
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
createTask({
|
||||||
|
contact_id: contact.id,
|
||||||
|
title: 'Follow up call',
|
||||||
|
due_date: '',
|
||||||
|
})
|
||||||
|
}).toThrow('Title and due date are required')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_create_task_missing_title', async () => {
|
||||||
|
const contact = createContact({ name: 'Test Contact', phone: '+5511999999997' })
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
createTask({
|
||||||
|
contact_id: contact.id,
|
||||||
|
title: '',
|
||||||
|
due_date: '2026-04-10',
|
||||||
|
})
|
||||||
|
}).toThrow('Title and due date are required')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('5.2 Task Updates Tests', () => {
|
||||||
|
it('test_mark_task_completed', async () => {
|
||||||
|
const contact = createContact({ name: 'Test Contact', phone: '+5511999999996' })
|
||||||
|
const task = createTask({
|
||||||
|
contact_id: contact.id,
|
||||||
|
title: 'Follow up call',
|
||||||
|
due_date: '2026-04-10',
|
||||||
|
})
|
||||||
|
|
||||||
|
const updated = updateTask(task.id, { status: 'completed' })
|
||||||
|
|
||||||
|
expect(updated).toBeDefined()
|
||||||
|
expect(updated?.status).toBe('completed')
|
||||||
|
expect(updated?.completed_at).not.toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_update_task_due_date', async () => {
|
||||||
|
const contact = createContact({ name: 'Test Contact', phone: '+5511999999995' })
|
||||||
|
const task = createTask({
|
||||||
|
contact_id: contact.id,
|
||||||
|
title: 'Follow up call',
|
||||||
|
due_date: '2026-04-10',
|
||||||
|
})
|
||||||
|
|
||||||
|
const updated = updateTask(task.id, { due_date: '2026-04-15' })
|
||||||
|
|
||||||
|
expect(updated).toBeDefined()
|
||||||
|
expect(updated?.due_date).toBe('2026-04-15')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('5.3 Task Queries Tests', () => {
|
||||||
|
it('test_list_pending_tasks_for_contact', async () => {
|
||||||
|
const contact = createContact({ name: 'Test Contact', phone: '+5511999999994' })
|
||||||
|
|
||||||
|
createTask({ contact_id: contact.id, title: 'Task 1', due_date: '2026-04-10' })
|
||||||
|
createTask({ contact_id: contact.id, title: 'Task 2', due_date: '2026-04-12' })
|
||||||
|
|
||||||
|
const completedTask = createTask({ contact_id: contact.id, title: 'Task 3', due_date: '2026-04-08' })
|
||||||
|
updateTask(completedTask.id, { status: 'completed' })
|
||||||
|
|
||||||
|
const pendingTasks = getPendingTasksByContactId(contact.id)
|
||||||
|
|
||||||
|
expect(pendingTasks).toHaveLength(2)
|
||||||
|
expect(pendingTasks.every(t => t.status === 'pending')).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_list_overdue_tasks', async () => {
|
||||||
|
const contact = createContact({ name: 'Test Contact', phone: '+5511999999993' })
|
||||||
|
|
||||||
|
createTask({ contact_id: contact.id, title: 'Overdue Task', due_date: '2020-01-01' })
|
||||||
|
createTask({ contact_id: contact.id, title: 'Future Task', due_date: '2030-01-01' })
|
||||||
|
|
||||||
|
const overdueTasks = getOverdueTasks()
|
||||||
|
|
||||||
|
expect(overdueTasks.length).toBeGreaterThan(0)
|
||||||
|
expect(overdueTasks.every(t => t.status === 'pending' && t.due_date < new Date().toISOString().split('T')[0])).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_create_task_without_contact', async () => {
|
||||||
|
expect(() => {
|
||||||
|
createTask({
|
||||||
|
contact_id: 99999,
|
||||||
|
title: 'Follow up call',
|
||||||
|
due_date: '2026-04-10',
|
||||||
|
})
|
||||||
|
}).toThrow('Contact not found')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('test_get_task_by_id', async () => {
|
||||||
|
const contact = createContact({ name: 'Test Contact', phone: '+5511999999992' })
|
||||||
|
const task = createTask({
|
||||||
|
contact_id: contact.id,
|
||||||
|
title: 'Test Task',
|
||||||
|
due_date: '2026-04-15',
|
||||||
|
})
|
||||||
|
|
||||||
|
const found = getTaskById(task.id)
|
||||||
|
|
||||||
|
expect(found).toBeDefined()
|
||||||
|
expect(found?.id).toBe(task.id)
|
||||||
|
expect(found?.title).toBe('Test Task')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"lib": ["dom", "dom.iterable", "esnext"],
|
||||||
|
"allowJs": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strict": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"jsx": "preserve",
|
||||||
|
"incremental": true,
|
||||||
|
"plugins": [
|
||||||
|
{
|
||||||
|
"name": "next"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||||
|
"exclude": ["node_modules"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
node_modules/
|
||||||
|
.wwebjs_auth/
|
||||||
|
.wwebjs_cache/
|
||||||
|
data/
|
||||||
|
*.db
|
||||||
|
*.sqlite
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.production
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
const { Client, LocalAuth } = require('whatsapp-web.js');
|
||||||
|
const qrcode = require('qrcode-terminal');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const BASE_DIR = path.join(__dirname);
|
||||||
|
const DATA_DIR = path.join(BASE_DIR, 'data');
|
||||||
|
const MESSAGES_FILE = path.join(DATA_DIR, 'messages.jsonl');
|
||||||
|
|
||||||
|
console.log('Data directory:', DATA_DIR);
|
||||||
|
|
||||||
|
const client = new Client({
|
||||||
|
authStrategy: new LocalAuth(),
|
||||||
|
puppeteer: {
|
||||||
|
executablePath: '/usr/sbin/chromium',
|
||||||
|
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('Creating data dir:', DATA_DIR);
|
||||||
|
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||||
|
console.log('Data dir created');
|
||||||
|
|
||||||
|
function formatMessage(msg, chat) {
|
||||||
|
const phoneNumber = msg.from ? msg.from.split('@')[0] : '';
|
||||||
|
return {
|
||||||
|
id: msg.id._serialized,
|
||||||
|
chatId: chat.id._serialized,
|
||||||
|
chatName: chat.name,
|
||||||
|
from: phoneNumber,
|
||||||
|
fromName: msg.author || phoneNumber,
|
||||||
|
body: msg.body || '',
|
||||||
|
timestamp: msg.timestamp,
|
||||||
|
type: msg.type,
|
||||||
|
hasMedia: msg.hasMedia,
|
||||||
|
isGroup: chat.isGroup,
|
||||||
|
isMe: msg.fromMe
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOTE: Limited to top 5 messages for testing - remove/comment this block to collect all messages
|
||||||
|
// CHANGES:
|
||||||
|
// - Added messageCount to track messages
|
||||||
|
// - Added MAX_MESSAGES = 5 limit
|
||||||
|
// - Added MAX_MESSAGES_REACHED check
|
||||||
|
// - Modified saveMessage to count and stop at limit
|
||||||
|
let messageCount = 0;
|
||||||
|
const MAX_MESSAGES = 5;
|
||||||
|
const MAX_MESSAGES_REACHED = () => {
|
||||||
|
if (messageCount >= MAX_MESSAGES) {
|
||||||
|
console.log(`\n📝 Reached limit of ${MAX_MESSAGES} messages - stopping collection`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
function saveMessage(msgData) {
|
||||||
|
// DEBUG: Limited message collection for testing
|
||||||
|
messageCount++;
|
||||||
|
console.log(` (${messageCount}/${MAX_MESSAGES} messages collected)`);
|
||||||
|
|
||||||
|
if (MAX_MESSAGES_REACHED()) return; // Stop after reaching limit
|
||||||
|
|
||||||
|
const line = JSON.stringify(msgData) + '\n';
|
||||||
|
fs.appendFileSync(MESSAGES_FILE, line);
|
||||||
|
}
|
||||||
|
|
||||||
|
client.on('qr', (qr) => {
|
||||||
|
qrcode.generate(qr, { small: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
client.on('ready', async () => {
|
||||||
|
console.log('✅ Connected!');
|
||||||
|
|
||||||
|
const chats = await client.getChats();
|
||||||
|
console.log(`\n📱 ${chats.length} conversations loaded:\n`);
|
||||||
|
chats.forEach((chat, i) => {
|
||||||
|
console.log(`[${i}] ${chat.name} (${chat.unreadCount} unread)`);
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const chat of chats) {
|
||||||
|
const msgs = await chat.fetchMessages({ limit: 10 });
|
||||||
|
for (const msg of msgs) {
|
||||||
|
if (msg.body && msg.body.trim().length > 0) {
|
||||||
|
const msgData = formatMessage(msg, chat);
|
||||||
|
const contact = {
|
||||||
|
phone: msgData.from,
|
||||||
|
name: chat.name
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const res = await fetch('http://localhost:3000/api/contacts', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(contact)
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
console.log(` 📇 Contact synced: ${chat.name}`);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// skip duplicates/errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
client.on('message', async (msg) => {
|
||||||
|
const chat = await msg.getChat();
|
||||||
|
const msgData = formatMessage(msg, chat);
|
||||||
|
|
||||||
|
console.log(`💬 [${chat.name}] ${msg.from}: ${msg.body.substring(0, 50)}`);
|
||||||
|
|
||||||
|
saveMessage(msgData);
|
||||||
|
|
||||||
|
// Only create contact if there's actual message content (not system notifications)
|
||||||
|
if (msg.body && msg.body.trim().length > 0) {
|
||||||
|
const contact = {
|
||||||
|
phone: msgData.from,
|
||||||
|
name: chat.name
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch('http://localhost:3000/api/contacts', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(contact)
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
console.log(` 📇 Contact created in CRM`);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.log(' (CRM sync skipped)');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
client.initialize();
|
||||||
Generated
+2110
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"name": "whatsapp-reader",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "",
|
||||||
|
"main": "index.js",
|
||||||
|
"scripts": {
|
||||||
|
"test": "echo \"Error: no test specified\" && exit 1"
|
||||||
|
},
|
||||||
|
"keywords": [],
|
||||||
|
"author": "",
|
||||||
|
"license": "ISC",
|
||||||
|
"type": "commonjs",
|
||||||
|
"dependencies": {
|
||||||
|
"qrcode-terminal": "^0.12.0",
|
||||||
|
"whatsapp-web.js": "^1.34.6"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
const { Client, LocalAuth } = require('whatsapp-web.js');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const DATA_DIR = './data';
|
||||||
|
const MESSAGES_FILE = path.join(DATA_DIR, 'messages.jsonl');
|
||||||
|
const CHATS_FILE = path.join(DATA_DIR, 'chats.json');
|
||||||
|
const LIMIT_PER_CHAT = 50; // messages to fetch per chat per run
|
||||||
|
|
||||||
|
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||||
|
|
||||||
|
// Load already saved message IDs to avoid duplicates
|
||||||
|
function loadSavedIds() {
|
||||||
|
if (!fs.existsSync(MESSAGES_FILE)) return new Set();
|
||||||
|
const lines = fs.readFileSync(MESSAGES_FILE, 'utf8').trim().split('\n').filter(Boolean);
|
||||||
|
return new Set(lines.map(l => JSON.parse(l).id));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Append new messages to jsonl
|
||||||
|
function saveMessages(messages) {
|
||||||
|
const lines = messages.map(m => JSON.stringify(m)).join('\n') + '\n';
|
||||||
|
fs.appendFileSync(MESSAGES_FILE, lines);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save chat index
|
||||||
|
function saveChats(chats) {
|
||||||
|
fs.writeFileSync(CHATS_FILE, JSON.stringify(chats, null, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = new Client({
|
||||||
|
authStrategy: new LocalAuth(),
|
||||||
|
puppeteer: {
|
||||||
|
executablePath: '/usr/sbin/chromium',
|
||||||
|
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
client.on('qr', (qr) => {
|
||||||
|
// Only needed first time — after that LocalAuth handles it
|
||||||
|
const qrcode = require('qrcode-terminal');
|
||||||
|
qrcode.generate(qr, { small: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
client.on('ready', async () => {
|
||||||
|
console.log('✅ Connected — starting sync...');
|
||||||
|
|
||||||
|
const savedIds = loadSavedIds();
|
||||||
|
const chats = await client.getChats();
|
||||||
|
const chatIndex = [];
|
||||||
|
const newMessages = [];
|
||||||
|
|
||||||
|
for (const chat of chats) {
|
||||||
|
console.log(`📥 Fetching: ${chat.name}`);
|
||||||
|
chatIndex.push({
|
||||||
|
id: chat.id._serialized,
|
||||||
|
name: chat.name,
|
||||||
|
isGroup: chat.isGroup,
|
||||||
|
lastSync: new Date().toISOString()
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const messages = await chat.fetchMessages({ limit: LIMIT_PER_CHAT });
|
||||||
|
for (const msg of messages) {
|
||||||
|
if (savedIds.has(msg.id._serialized)) continue; // skip duplicates
|
||||||
|
newMessages.push({
|
||||||
|
id: msg.id._serialized,
|
||||||
|
chat: chat.name,
|
||||||
|
chatId: chat.id._serialized,
|
||||||
|
from: msg.from,
|
||||||
|
fromName: msg.author || msg.from,
|
||||||
|
timestamp: msg.timestamp,
|
||||||
|
date: new Date(msg.timestamp * 1000).toISOString(),
|
||||||
|
body: msg.body,
|
||||||
|
type: msg.type,
|
||||||
|
isGroup: chat.isGroup,
|
||||||
|
hasMedia: msg.hasMedia
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`❌ Failed on ${chat.name}:`, err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
saveChats(chatIndex);
|
||||||
|
saveMessages(newMessages);
|
||||||
|
console.log(`✅ Sync done — ${newMessages.length} new messages saved.`);
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
client.initialize();
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# WhatsApp Sync Service - Environment Variables
|
||||||
|
|
||||||
|
# Database
|
||||||
|
DATABASE_URL=./data/crm.db
|
||||||
|
|
||||||
|
# Sync settings
|
||||||
|
SYNC_INTERVAL_MINUTES=5
|
||||||
|
MESSAGES_LIMIT_PER_CHAT=50
|
||||||
|
|
||||||
|
# Optional: JSONL source path
|
||||||
|
# MESSAGES_JSONL_PATH=../whatsapp-reader/data/messages.jsonl
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
node_modules/
|
||||||
|
.pnp
|
||||||
|
.pnp.js
|
||||||
|
dist/
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.production
|
||||||
|
.wwebjs_auth/
|
||||||
|
.wwebjs_cache/
|
||||||
|
*.db
|
||||||
|
*.sqlite
|
||||||
|
coverage/
|
||||||
|
.nyc_output/
|
||||||
|
test-results/
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
module.exports = {
|
||||||
|
presets: [
|
||||||
|
['@babel/preset-env', { targets: { node: 'current' } }],
|
||||||
|
],
|
||||||
|
};
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/** @type {import('jest').Config} */
|
||||||
|
module.exports = {
|
||||||
|
testEnvironment: 'node',
|
||||||
|
setupFilesAfterEnv: [],
|
||||||
|
collectCoverageFrom: [
|
||||||
|
'src/**/*.{ts,js}',
|
||||||
|
'!src/**/*.d.ts',
|
||||||
|
],
|
||||||
|
testPathIgnorePatterns: ['/node_modules/', '/dist/'],
|
||||||
|
moduleFileExtensions: ['ts', 'js', 'json'],
|
||||||
|
transform: {
|
||||||
|
'^.+\\.jsx?$': 'babel-jest',
|
||||||
|
},
|
||||||
|
transformIgnorePatterns: [
|
||||||
|
'/node_modules/',
|
||||||
|
],
|
||||||
|
moduleNameMapper: {
|
||||||
|
'^qrcode-terminal$': '<rootDir>/tests/__mocks__/qrcode-terminal.js',
|
||||||
|
'^whatsapp-web.js$': '<rootDir>/tests/__mocks__/whatsapp-web.js',
|
||||||
|
},
|
||||||
|
};
|
||||||
Generated
+7473
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"name": "whatsapp-sync",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "WhatsApp message sync service",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"start": "node src/index.js",
|
||||||
|
"dev": "node --watch src/index.js",
|
||||||
|
"sync": "node src/sync.js",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"test:coverage": "jest --coverage"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"better-sqlite3": "^12.8.0",
|
||||||
|
"node-cron": "3.0.3",
|
||||||
|
"qrcode-terminal": "0.12.0",
|
||||||
|
"sql.js": "1.10.2",
|
||||||
|
"whatsapp-web.js": "1.23.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@babel/preset-env": "^7.29.2",
|
||||||
|
"@types/jest": "29.5.12",
|
||||||
|
"@types/node": "20.11.0",
|
||||||
|
"@types/sql.js": "1.4.9",
|
||||||
|
"eslint": "8.57.0",
|
||||||
|
"jest": "29.7.0",
|
||||||
|
"ts-jest": "29.1.2",
|
||||||
|
"typescript": "5.3.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
var Database;
|
||||||
|
|
||||||
|
try {
|
||||||
|
Database = require('better-sqlite3');
|
||||||
|
} catch (e) {
|
||||||
|
Database = function() {
|
||||||
|
throw new Error('better-sqlite3 not available');
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
var STAGES = [
|
||||||
|
'LEADS DE ENTRADA',
|
||||||
|
'DECIDINDO',
|
||||||
|
'DISCUSSAO DE CONTRATO',
|
||||||
|
'DECISAO FINAL',
|
||||||
|
];
|
||||||
|
|
||||||
|
function initialize(dbPath) {
|
||||||
|
var db = new Database(dbPath);
|
||||||
|
|
||||||
|
db.exec("\n CREATE TABLE IF NOT EXISTS contacts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n phone TEXT UNIQUE NOT NULL,\n name TEXT,\n stage TEXT DEFAULT 'LEADS DE ENTRADA',\n payment_status TEXT DEFAULT 'pending',\n schedule_date INTEGER,\n notes TEXT,\n created_at INTEGER DEFAULT (strftime('%s', 'now')),\n updated_at INTEGER DEFAULT (strftime('%s', 'now'))\n )\n ");
|
||||||
|
|
||||||
|
db.exec("\n CREATE TABLE IF NOT EXISTS messages (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n message_id TEXT UNIQUE NOT NULL,\n contact_phone TEXT NOT NULL,\n body TEXT,\n timestamp INTEGER,\n has_media INTEGER DEFAULT 0,\n created_at INTEGER DEFAULT (strftime('%s', 'now')),\n FOREIGN KEY (contact_phone) REFERENCES contacts(phone)\n )\n ");
|
||||||
|
|
||||||
|
db.exec("\n CREATE TABLE IF NOT EXISTS tasks (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n contact_phone TEXT NOT NULL,\n title TEXT NOT NULL,\n due_date INTEGER,\n status TEXT DEFAULT 'pending',\n created_at INTEGER DEFAULT (strftime('%s', 'now')),\n FOREIGN KEY (contact_phone) REFERENCES contacts(phone)\n )\n ");
|
||||||
|
|
||||||
|
db.exec("CREATE INDEX IF NOT EXISTS idx_messages_contact ON messages(contact_phone)");
|
||||||
|
db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_contact ON tasks(contact_phone)");
|
||||||
|
db.exec("CREATE INDEX IF NOT EXISTS idx_contacts_phone ON contacts(phone)");
|
||||||
|
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertContact(db, contact) {
|
||||||
|
var stmt = db.prepare("\n INSERT INTO contacts (phone, name, stage, payment_status, schedule_date, notes)\n VALUES (@phone, @name, @stage, @paymentStatus, @scheduleDate, @notes)\n ");
|
||||||
|
|
||||||
|
var result = stmt.run({
|
||||||
|
phone: contact.phone,
|
||||||
|
name: contact.name || null,
|
||||||
|
stage: contact.stage || 'LEADS DE ENTRADA',
|
||||||
|
paymentStatus: contact.paymentStatus || 'pending',
|
||||||
|
scheduleDate: contact.scheduleDate || null,
|
||||||
|
notes: contact.notes || null,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { id: result.lastInsertRowid, phone: contact.phone };
|
||||||
|
}
|
||||||
|
|
||||||
|
function findContactByPhone(db, phone) {
|
||||||
|
var stmt = db.prepare('SELECT * FROM contacts WHERE phone = ?');
|
||||||
|
return stmt.get(phone);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateContactStage(db, phone, stage) {
|
||||||
|
if (STAGES.indexOf(stage) === -1) {
|
||||||
|
throw new Error('Invalid stage: ' + stage);
|
||||||
|
}
|
||||||
|
|
||||||
|
var stmt = db.prepare("\n UPDATE contacts\n SET stage = ?, updated_at = strftime('%s', 'now')\n WHERE phone = ?\n ");
|
||||||
|
|
||||||
|
return stmt.run(stage, phone);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateContactPaymentStatus(db, phone, status) {
|
||||||
|
var stmt = db.prepare("\n UPDATE contacts\n SET payment_status = ?, updated_at = strftime('%s', 'now')\n WHERE phone = ?\n ");
|
||||||
|
|
||||||
|
return stmt.run(status, phone);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateContactScheduleDate(db, phone, date) {
|
||||||
|
var stmt = db.prepare("\n UPDATE contacts\n SET schedule_date = ?, updated_at = strftime('%s', 'now')\n WHERE phone = ?\n ");
|
||||||
|
|
||||||
|
return stmt.run(date, phone);
|
||||||
|
}
|
||||||
|
|
||||||
|
function listContactsByStage(db, stage) {
|
||||||
|
var stmt = db.prepare('SELECT * FROM contacts WHERE stage = ? ORDER BY updated_at DESC');
|
||||||
|
return stmt.all(stage);
|
||||||
|
}
|
||||||
|
|
||||||
|
function listContactsByPaymentStatus(db, status) {
|
||||||
|
var stmt = db.prepare('SELECT * FROM contacts WHERE payment_status = ? ORDER BY updated_at DESC');
|
||||||
|
return stmt.all(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
function listAllContacts(db) {
|
||||||
|
var stmt = db.prepare('SELECT * FROM contacts ORDER BY updated_at DESC');
|
||||||
|
return stmt.all();
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertMessage(db, message) {
|
||||||
|
var stmt = db.prepare("\n INSERT OR IGNORE INTO messages (message_id, contact_phone, body, timestamp, has_media)\n VALUES (@id, @contactPhone, @body, @timestamp, @hasMedia)\n ");
|
||||||
|
|
||||||
|
return stmt.run({
|
||||||
|
id: message.id,
|
||||||
|
contactPhone: message.contactPhone,
|
||||||
|
body: message.body || '',
|
||||||
|
timestamp: message.timestamp || null,
|
||||||
|
hasMedia: message.hasMedia ? 1 : 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function findMessagesByContact(db, phone) {
|
||||||
|
var stmt = db.prepare("\n SELECT * FROM messages\n WHERE contact_phone = ?\n ORDER BY timestamp DESC\n ");
|
||||||
|
return stmt.all(phone);
|
||||||
|
}
|
||||||
|
|
||||||
|
function messageExists(db, messageId) {
|
||||||
|
var stmt = db.prepare('SELECT 1 FROM messages WHERE message_id = ?');
|
||||||
|
return stmt.get(messageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertTask(db, task) {
|
||||||
|
var stmt = db.prepare("\n INSERT INTO tasks (contact_phone, title, due_date, status)\n VALUES (@contactPhone, @title, @dueDate, @status)\n ");
|
||||||
|
|
||||||
|
return stmt.run({
|
||||||
|
contactPhone: task.contactPhone,
|
||||||
|
title: task.title,
|
||||||
|
dueDate: task.dueDate || null,
|
||||||
|
status: task.status || 'pending',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function findTasksByContact(db, phone, status) {
|
||||||
|
var sql = 'SELECT * FROM tasks WHERE contact_phone = ?';
|
||||||
|
var params = [phone];
|
||||||
|
|
||||||
|
if (status) {
|
||||||
|
sql += ' AND status = ?';
|
||||||
|
params.push(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
sql += ' ORDER BY due_date ASC';
|
||||||
|
|
||||||
|
var stmt = db.prepare(sql);
|
||||||
|
return stmt.all.apply(stmt, params);
|
||||||
|
}
|
||||||
|
|
||||||
|
function findOverdueTasks(db) {
|
||||||
|
var now = Math.floor(Date.now() / 1000);
|
||||||
|
var stmt = db.prepare("\n SELECT * FROM tasks\n WHERE status = 'pending' AND due_date < ?\n ORDER BY due_date ASC\n ");
|
||||||
|
return stmt.all(now);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateTaskStatus(db, taskId, status) {
|
||||||
|
var stmt = db.prepare('UPDATE tasks SET status = ? WHERE id = ?');
|
||||||
|
return stmt.run(status, taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateTaskDueDate(db, taskId, dueDate) {
|
||||||
|
var stmt = db.prepare('UPDATE tasks SET due_date = ? WHERE id = ?');
|
||||||
|
return stmt.run(dueDate, taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteContact(db, phone) {
|
||||||
|
var stmt = db.prepare('DELETE FROM contacts WHERE phone = ?');
|
||||||
|
return stmt.run(phone);
|
||||||
|
}
|
||||||
|
|
||||||
|
function close(db) {
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
initialize: initialize,
|
||||||
|
insertContact: insertContact,
|
||||||
|
findContactByPhone: findContactByPhone,
|
||||||
|
updateContactStage: updateContactStage,
|
||||||
|
updateContactPaymentStatus: updateContactPaymentStatus,
|
||||||
|
updateContactScheduleDate: updateContactScheduleDate,
|
||||||
|
listContactsByStage: listContactsByStage,
|
||||||
|
listContactsByPaymentStatus: listContactsByPaymentStatus,
|
||||||
|
listAllContacts: listAllContacts,
|
||||||
|
insertMessage: insertMessage,
|
||||||
|
findMessagesByContact: findMessagesByContact,
|
||||||
|
messageExists: messageExists,
|
||||||
|
insertTask: insertTask,
|
||||||
|
findTasksByContact: findTasksByContact,
|
||||||
|
findOverdueTasks: findOverdueTasks,
|
||||||
|
updateTaskStatus: updateTaskStatus,
|
||||||
|
updateTaskDueDate: updateTaskDueDate,
|
||||||
|
deleteContact: deleteContact,
|
||||||
|
close: close,
|
||||||
|
STAGES: STAGES,
|
||||||
|
};
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
var fs = require('fs');
|
||||||
|
var path = require('path');
|
||||||
|
|
||||||
|
function ParseError(message) {
|
||||||
|
this.message = message;
|
||||||
|
}
|
||||||
|
ParseError.prototype = new Error();
|
||||||
|
|
||||||
|
function parseMessageLine(line) {
|
||||||
|
if (!line || typeof line !== 'string') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var trimmed = line.trim();
|
||||||
|
if (!trimmed) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
var parsed = JSON.parse(trimmed);
|
||||||
|
return {
|
||||||
|
id: parsed.id,
|
||||||
|
from: parsed.from,
|
||||||
|
body: parsed.body || '',
|
||||||
|
timestamp: parsed.timestamp,
|
||||||
|
hasMedia: parsed.hasMedia || false,
|
||||||
|
chatId: parsed.chatId,
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
throw new ParseError('Invalid JSON: ' + trimmed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseFile(content) {
|
||||||
|
if (!content || typeof content !== 'string') {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
var lines = content.split('\n');
|
||||||
|
var messages = [];
|
||||||
|
|
||||||
|
for (var i = 0; i < lines.length; i++) {
|
||||||
|
var parsed = parseMessageLine(lines[i]);
|
||||||
|
if (parsed) {
|
||||||
|
messages.push(parsed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
function filterNewMessages(messageIds, existingMessages) {
|
||||||
|
var newMessages = [];
|
||||||
|
|
||||||
|
for (var i = 0; i < messageIds.length; i++) {
|
||||||
|
if (!existingMessages.has(messageIds[i])) {
|
||||||
|
newMessages.push(messageIds[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return newMessages;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getOrCreateContact(phone, contactsMap) {
|
||||||
|
var existing = contactsMap.get(phone);
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
|
||||||
|
var newContact = {
|
||||||
|
phone: phone,
|
||||||
|
name: null,
|
||||||
|
stage: 'LEADS DE ENTRADA',
|
||||||
|
paymentStatus: 'pending',
|
||||||
|
createdAt: Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
contactsMap.set(phone, newContact);
|
||||||
|
return newContact;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
parseMessageLine: parseMessageLine,
|
||||||
|
parseFile: parseFile,
|
||||||
|
filterNewMessages: filterNewMessages,
|
||||||
|
getOrCreateContact: getOrCreateContact,
|
||||||
|
ParseError: ParseError,
|
||||||
|
};
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
var fs = require('fs');
|
||||||
|
var path = require('path');
|
||||||
|
|
||||||
|
var DATA_DIR = process.env.DATA_DIR || path.join(__dirname, '..', 'data');
|
||||||
|
var MESSAGES_FILE = path.join(DATA_DIR, 'messages.jsonl');
|
||||||
|
|
||||||
|
function ensureDataDir() {
|
||||||
|
if (!fs.existsSync(DATA_DIR)) {
|
||||||
|
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatMessageForJsonl(message) {
|
||||||
|
var phoneNumber = message.from ? message.from.split('@')[0] : '';
|
||||||
|
|
||||||
|
return JSON.stringify({
|
||||||
|
id: message.id ? message.id._serialized || message.id.id : message.id,
|
||||||
|
from: phoneNumber,
|
||||||
|
body: message.body || '',
|
||||||
|
timestamp: message.timestamp,
|
||||||
|
hasMedia: message.hasMedia || false,
|
||||||
|
chatId: message.chatId ? message.chatId._serialized || message.chatId : message.chatId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncMessages(client) {
|
||||||
|
ensureDataDir();
|
||||||
|
|
||||||
|
return client.getChats().then(function(chats) {
|
||||||
|
var writeStream = fs.createWriteStream(MESSAGES_FILE, { flags: 'a' });
|
||||||
|
|
||||||
|
var messagePromises = chats.map(function(chat) {
|
||||||
|
return chat.fetchMessages({ limit: 100 }).then(function(messages) {
|
||||||
|
var writePromises = messages
|
||||||
|
.filter(function(message) { return !message.fromMe; })
|
||||||
|
.map(function(message) {
|
||||||
|
var jsonlLine = formatMessageForJsonl(message);
|
||||||
|
writeStream.write(jsonlLine + '\n');
|
||||||
|
});
|
||||||
|
return Promise.all(writePromises);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return Promise.all(messagePromises).then(function() {
|
||||||
|
return new Promise(function(resolve, reject) {
|
||||||
|
writeStream.end(resolve);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
syncMessages: syncMessages,
|
||||||
|
formatMessageForJsonl: formatMessageForJsonl,
|
||||||
|
DATA_DIR: DATA_DIR,
|
||||||
|
MESSAGES_FILE: MESSAGES_FILE,
|
||||||
|
};
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
var generate = jest.fn();
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
__esModule: true,
|
||||||
|
default: {
|
||||||
|
generate: generate,
|
||||||
|
},
|
||||||
|
generate: generate,
|
||||||
|
};
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
var MockClient = function() {
|
||||||
|
this.on = jest.fn();
|
||||||
|
this.initialize = jest.fn().mockResolvedValue(undefined);
|
||||||
|
this.getChats = jest.fn().mockResolvedValue([]);
|
||||||
|
this.destroy = jest.fn().mockResolvedValue(undefined);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
Client: MockClient,
|
||||||
|
LocalAuth: function() {},
|
||||||
|
};
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
var MockDatabase = function() {
|
||||||
|
this.contacts = [];
|
||||||
|
this.messages = [];
|
||||||
|
this.tasks = [];
|
||||||
|
};
|
||||||
|
|
||||||
|
MockDatabase.prototype.exec = function(sql) {
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
|
||||||
|
MockDatabase.prototype.prepare = function(sql) {
|
||||||
|
var self = this;
|
||||||
|
|
||||||
|
return {
|
||||||
|
run: function() { return { lastInsertRowid: 1, changes: 1 }; },
|
||||||
|
get: function() { return undefined; },
|
||||||
|
all: function() { return []; },
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
MockDatabase.prototype.close = function() {};
|
||||||
|
|
||||||
|
jest.mock('better-sqlite3', function() {
|
||||||
|
return function() {
|
||||||
|
return new MockDatabase();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('5. Contact Management', function() {
|
||||||
|
var db;
|
||||||
|
var database;
|
||||||
|
|
||||||
|
beforeEach(function() {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
database = require('../src/database');
|
||||||
|
db = database.initialize(':memory:');
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(function() {
|
||||||
|
if (db && db.close) {
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('5.1 Contact Creation', function() {
|
||||||
|
test('test_create_contact_with_required_fields - name, phone required', function() {
|
||||||
|
var contact = {
|
||||||
|
phone: '5511999999999',
|
||||||
|
name: 'John Doe',
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = database.insertContact(db, contact);
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
expect(result.phone).toBe('5511999999999');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_create_contact_with_optional_fields - notes, schedule_date optional', function() {
|
||||||
|
var contact = {
|
||||||
|
phone: '5511888888888',
|
||||||
|
name: 'Jane Doe',
|
||||||
|
notes: 'Interested in product A',
|
||||||
|
scheduleDate: 1700000000,
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = database.insertContact(db, contact);
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_create_contact_missing_name - throws ValidationError', function() {
|
||||||
|
var contact = {
|
||||||
|
phone: '5511777777777',
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(function() {
|
||||||
|
database.insertContact(db, contact);
|
||||||
|
}).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_create_contact_missing_phone - throws ValidationError', function() {
|
||||||
|
var contact = {
|
||||||
|
name: 'Test User',
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
database.insertContact(db, contact);
|
||||||
|
} catch (e) {
|
||||||
|
expect(e).toBeDefined();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('5.2 Contact Updates', function() {
|
||||||
|
test('test_update_contact_stage_to_decidindo - stage change works', function() {
|
||||||
|
var contact = {
|
||||||
|
phone: '5511999999999',
|
||||||
|
name: 'John Doe',
|
||||||
|
stage: 'LEADS DE ENTRADA',
|
||||||
|
};
|
||||||
|
|
||||||
|
database.insertContact(db, contact);
|
||||||
|
var result = database.updateContactStage(db, '5511999999999', 'DECIDINDO');
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_update_contact_payment_status_to_paid - payment status update', function() {
|
||||||
|
var contact = {
|
||||||
|
phone: '5511999999999',
|
||||||
|
name: 'John Doe',
|
||||||
|
};
|
||||||
|
|
||||||
|
database.insertContact(db, contact);
|
||||||
|
var result = database.updateContactPaymentStatus(db, '5511999999999', 'paid');
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_update_schedule_date - schedule date update', function() {
|
||||||
|
var contact = {
|
||||||
|
phone: '5511999999999',
|
||||||
|
name: 'John Doe',
|
||||||
|
};
|
||||||
|
|
||||||
|
database.insertContact(db, contact);
|
||||||
|
var newDate = 1800000000;
|
||||||
|
var result = database.updateContactScheduleDate(db, '5511999999999', newDate);
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('5.3 Contact Queries', function() {
|
||||||
|
test('test_list_contacts_by_stage - filter by stage', function() {
|
||||||
|
var contacts = database.listContactsByStage(db, 'LEADS DE ENTRADA');
|
||||||
|
|
||||||
|
expect(Array.isArray(contacts)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_list_contacts_with_payment_pending - filter by payment status', function() {
|
||||||
|
var contacts = database.listContactsByPaymentStatus(db, 'pending');
|
||||||
|
|
||||||
|
expect(Array.isArray(contacts)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
var MockDatabase = function() {
|
||||||
|
this.contacts = [];
|
||||||
|
this.messages = [];
|
||||||
|
this.tasks = [];
|
||||||
|
this._prepared = {};
|
||||||
|
};
|
||||||
|
|
||||||
|
MockDatabase.prototype.exec = function(sql) {
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
|
||||||
|
MockDatabase.prototype.prepare = function(sql) {
|
||||||
|
var self = this;
|
||||||
|
var stmt = {
|
||||||
|
_sql: sql,
|
||||||
|
run: function() { return { lastInsertRowid: 1, changes: 1 }; },
|
||||||
|
get: function() { return undefined; },
|
||||||
|
all: function() { return []; },
|
||||||
|
};
|
||||||
|
|
||||||
|
if (sql.indexOf('INSERT INTO contacts') !== -1) {
|
||||||
|
stmt.run = function(params) {
|
||||||
|
self.contacts.push(params);
|
||||||
|
return { lastInsertRowid: self.contacts.length, changes: 1 };
|
||||||
|
};
|
||||||
|
} else if (sql.indexOf('SELECT * FROM contacts WHERE phone') !== -1) {
|
||||||
|
stmt.get = function(phone) {
|
||||||
|
return self.contacts.find(function(c) { return c.phone === phone; });
|
||||||
|
};
|
||||||
|
} else if (sql.indexOf('SELECT * FROM contacts WHERE stage =') !== -1) {
|
||||||
|
stmt.all = function(stage) {
|
||||||
|
return self.contacts.filter(function(c) { return c.stage === stage; });
|
||||||
|
};
|
||||||
|
} else if (sql.indexOf('SELECT * FROM contacts WHERE payment_status') !== -1) {
|
||||||
|
stmt.all = function(status) {
|
||||||
|
return self.contacts.filter(function(c) { return c.payment_status === status; });
|
||||||
|
};
|
||||||
|
} else if (sql.indexOf('SELECT * FROM messages WHERE contact_phone') !== -1) {
|
||||||
|
stmt.all = function(phone) {
|
||||||
|
return self.messages.filter(function(m) { return m.contact_phone === phone; });
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return stmt;
|
||||||
|
};
|
||||||
|
|
||||||
|
MockDatabase.prototype.close = function() {};
|
||||||
|
|
||||||
|
jest.mock('better-sqlite3', function() {
|
||||||
|
return function() {
|
||||||
|
return new MockDatabase();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('4. SQLite Database Layer', function() {
|
||||||
|
var db;
|
||||||
|
var database;
|
||||||
|
|
||||||
|
beforeEach(function() {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
database = require('../src/database');
|
||||||
|
db = database.initialize(':memory:');
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(function() {
|
||||||
|
if (db && db.close) {
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Database Initialization', function() {
|
||||||
|
test('test_database_schema_created_on_init - creates contacts table', function() {
|
||||||
|
expect(db).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_database_creates_messages_table - messages table exists', function() {
|
||||||
|
expect(db).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_database_creates_tasks_table - tasks table exists', function() {
|
||||||
|
expect(db).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Contact Operations', function() {
|
||||||
|
test('test_insert_contact - creates new contact', function() {
|
||||||
|
var contact = {
|
||||||
|
phone: '5511999999999',
|
||||||
|
name: 'John Doe',
|
||||||
|
stage: 'LEADS DE ENTRADA',
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = database.insertContact(db, contact);
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_find_contact_by_phone - retrieves contact by phone', function() {
|
||||||
|
var contact = {
|
||||||
|
phone: '5511999999999',
|
||||||
|
name: 'John Doe',
|
||||||
|
stage: 'LEADS DE ENTRADA',
|
||||||
|
};
|
||||||
|
|
||||||
|
database.insertContact(db, contact);
|
||||||
|
var found = database.findContactByPhone(db, '5511999999999');
|
||||||
|
|
||||||
|
expect(found).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_update_contact_stage - updates contact stage', function() {
|
||||||
|
var contact = {
|
||||||
|
phone: '5511999999999',
|
||||||
|
name: 'John Doe',
|
||||||
|
stage: 'LEADS DE ENTRADA',
|
||||||
|
};
|
||||||
|
|
||||||
|
database.insertContact(db, contact);
|
||||||
|
var result = database.updateContactStage(db, '5511999999999', 'DECIDINDO');
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_list_contacts_by_stage - filters contacts by stage', function() {
|
||||||
|
var contacts = database.listContactsByStage(db, 'LEADS DE ENTRADA');
|
||||||
|
|
||||||
|
expect(Array.isArray(contacts)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Message Operations', function() {
|
||||||
|
test('test_insert_message - creates message record', function() {
|
||||||
|
var message = {
|
||||||
|
id: 'msg_123',
|
||||||
|
contactPhone: '5511999999999',
|
||||||
|
body: 'Hello world',
|
||||||
|
timestamp: 1234567890,
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = database.insertMessage(db, message);
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_find_messages_by_contact - retrieves messages for contact', function() {
|
||||||
|
var messages = database.findMessagesByContact(db, '5511999999999');
|
||||||
|
|
||||||
|
expect(Array.isArray(messages)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
var fs = require('fs');
|
||||||
|
var path = require('path');
|
||||||
|
var jsonlParser = require('../src/jsonl-parser');
|
||||||
|
|
||||||
|
describe('1.1 JSONL Parser Tests', function() {
|
||||||
|
describe('parseValidMessageLine', function() {
|
||||||
|
test('test_parse_valid_message_line - parses valid JSONL correctly', function() {
|
||||||
|
var validLine = JSON.stringify({
|
||||||
|
id: 'msg_123',
|
||||||
|
from: '5511999999999',
|
||||||
|
body: 'Hello world',
|
||||||
|
timestamp: 1234567890,
|
||||||
|
hasMedia: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
var result = jsonlParser.parseMessageLine(validLine);
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
expect(result.id).toBe('msg_123');
|
||||||
|
expect(result.from).toBe('5511999999999');
|
||||||
|
expect(result.body).toBe('Hello world');
|
||||||
|
expect(result.timestamp).toBe(1234567890);
|
||||||
|
expect(result.hasMedia).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_parse_message_with_missing_optional_fields - handles missing fields', function() {
|
||||||
|
var lineWithMissingFields = JSON.stringify({
|
||||||
|
id: 'msg_456',
|
||||||
|
from: '5511888888888',
|
||||||
|
body: 'Test',
|
||||||
|
});
|
||||||
|
|
||||||
|
var result = jsonlParser.parseMessageLine(lineWithMissingFields);
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
expect(result.id).toBe('msg_456');
|
||||||
|
expect(result.from).toBe('5511888888888');
|
||||||
|
expect(result.body).toBe('Test');
|
||||||
|
expect(result.timestamp).toBeUndefined();
|
||||||
|
expect(result.hasMedia).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_parse_invalid_json - throws ParseError for bad JSON', function() {
|
||||||
|
var invalidLine = 'not valid json {';
|
||||||
|
|
||||||
|
expect(function() {
|
||||||
|
jsonlParser.parseMessageLine(invalidLine);
|
||||||
|
}).toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_parse_empty_file - returns empty array for empty file', function() {
|
||||||
|
var result = jsonlParser.parseFile('');
|
||||||
|
|
||||||
|
expect(Array.isArray(result)).toBe(true);
|
||||||
|
expect(result.length).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('1.2 Sync Logic Tests', function() {
|
||||||
|
var mockDb;
|
||||||
|
|
||||||
|
beforeEach(function() {
|
||||||
|
mockDb = {
|
||||||
|
contacts: new Map(),
|
||||||
|
messages: new Map(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_deduplication_filters_known_ids - skips already-synced messages', function() {
|
||||||
|
mockDb.messages.set('msg_123', true);
|
||||||
|
|
||||||
|
var result = jsonlParser.filterNewMessages(['msg_123', 'msg_456'], mockDb.messages);
|
||||||
|
|
||||||
|
expect(result).toEqual(['msg_456']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_new_phone_creates_new_contact - new phone creates new contact', function() {
|
||||||
|
var newPhone = '5511999999999';
|
||||||
|
|
||||||
|
var result = jsonlParser.getOrCreateContact(newPhone, mockDb.contacts);
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
expect(result.phone).toBe(newPhone);
|
||||||
|
expect(mockDb.contacts.size).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_known_phone_updates_existing_contact - existing phone updates contact', function() {
|
||||||
|
var existingPhone = '5511999999999';
|
||||||
|
mockDb.contacts.set(existingPhone, { phone: existingPhone, name: 'John' });
|
||||||
|
|
||||||
|
var result = jsonlParser.getOrCreateContact(existingPhone, mockDb.contacts);
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
expect(result.phone).toBe(existingPhone);
|
||||||
|
expect(mockDb.contacts.size).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('1.3 Database Integration Tests', function() {
|
||||||
|
test('test_insert_contact_unique_by_phone - prevents duplicates', function() {
|
||||||
|
var contactsDb = {
|
||||||
|
insert: function(contact) {
|
||||||
|
if (this.findByPhone(contact.phone)) {
|
||||||
|
throw new Error('Duplicate');
|
||||||
|
}
|
||||||
|
this.contacts.push(contact);
|
||||||
|
},
|
||||||
|
findByPhone: function(phone) {
|
||||||
|
return this.contacts.find(function(c) { return c.phone === phone; });
|
||||||
|
},
|
||||||
|
contacts: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
contactsDb.insert({ phone: '5511999999999', name: 'John' });
|
||||||
|
|
||||||
|
expect(function() {
|
||||||
|
contactsDb.insert({ phone: '5511999999999', name: 'Jane' });
|
||||||
|
}).toThrow('Duplicate');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_find_contact_by_phone_returns_contact - retrieves by phone', function() {
|
||||||
|
var contactsDb = {
|
||||||
|
findByPhone: function(phone) {
|
||||||
|
return this.contacts.find(function(c) { return c.phone === phone; });
|
||||||
|
},
|
||||||
|
contacts: [
|
||||||
|
{ id: 1, phone: '5511999999999', name: 'John' },
|
||||||
|
{ id: 2, phone: '5511888888888', name: 'Jane' },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = contactsDb.findByPhone('5511999999999');
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
expect(result.name).toBe('John');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_link_message_to_contact - associates message with contact', function() {
|
||||||
|
var messagesDb = {
|
||||||
|
insert: function(message, contactPhone) {
|
||||||
|
message.contactPhone = contactPhone;
|
||||||
|
this.messages.push(message);
|
||||||
|
},
|
||||||
|
messages: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
messagesDb.insert({ id: 'msg_123', body: 'Hello' }, '5511999999999');
|
||||||
|
|
||||||
|
expect(messagesDb.messages[0].contactPhone).toBe('5511999999999');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
var fs = require('fs');
|
||||||
|
|
||||||
|
var mockWriteStream = {
|
||||||
|
write: jest.fn(),
|
||||||
|
end: jest.fn(function(cb) { if (cb) cb(); }),
|
||||||
|
};
|
||||||
|
|
||||||
|
var originalCreateWriteStream = fs.createWriteStream;
|
||||||
|
|
||||||
|
jest.mock('fs', function() {
|
||||||
|
return {
|
||||||
|
__esModule: true,
|
||||||
|
default: {
|
||||||
|
existsSync: jest.fn().mockReturnValue(true),
|
||||||
|
mkdirSync: jest.fn(),
|
||||||
|
createWriteStream: jest.fn(function() { return mockWriteStream; }),
|
||||||
|
},
|
||||||
|
existsSync: jest.fn().mockReturnValue(true),
|
||||||
|
mkdirSync: jest.fn(),
|
||||||
|
createWriteStream: jest.fn(function() { return mockWriteStream; }),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('0.4 Sync Service Integration', function() {
|
||||||
|
var mockClient;
|
||||||
|
|
||||||
|
beforeEach(function() {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
jest.resetModules();
|
||||||
|
|
||||||
|
mockClient = {
|
||||||
|
on: jest.fn(),
|
||||||
|
getChats: jest.fn().mockResolvedValue([]),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_sync_runs_after_connection - messages fetched from all chats', function() {
|
||||||
|
var mockChats = [
|
||||||
|
{ id: 'chat1', fetchMessages: jest.fn().mockResolvedValue([]) },
|
||||||
|
{ id: 'chat2', fetchMessages: jest.fn().mockResolvedValue([]) },
|
||||||
|
];
|
||||||
|
mockClient.getChats.mockResolvedValue(mockChats);
|
||||||
|
|
||||||
|
return require('../src/sync').syncMessages(mockClient).then(function() {
|
||||||
|
expect(mockClient.getChats).toHaveBeenCalled();
|
||||||
|
expect(mockChats[0].fetchMessages).toHaveBeenCalled();
|
||||||
|
expect(mockChats[1].fetchMessages).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_sync_saves_to_jsonl - messages.jsonl contains correct lines', function() {
|
||||||
|
var mockMessages = [
|
||||||
|
{
|
||||||
|
id: { _serialized: 'msg_1' },
|
||||||
|
from: '[email protected]',
|
||||||
|
body: 'Hello',
|
||||||
|
timestamp: 1234567890,
|
||||||
|
hasMedia: false,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
var mockChat = {
|
||||||
|
id: 'chat1',
|
||||||
|
fetchMessages: jest.fn().mockResolvedValue(mockMessages),
|
||||||
|
};
|
||||||
|
mockClient.getChats.mockResolvedValue([mockChat]);
|
||||||
|
|
||||||
|
return require('../src/sync').syncMessages(mockClient).then(function() {
|
||||||
|
expect(mockWriteStream.write).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('0.5 End-to-End Integration', function() {
|
||||||
|
test('test_qr_code_flow_to_sqlite_ingestion - full pipeline test', function() {
|
||||||
|
expect(true).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_full_message_ingestion_pipeline - 10 messages, 5 unique phones', function() {
|
||||||
|
expect(true).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_message_ingestion_with_media - hasMedia flag handled', function() {
|
||||||
|
expect(true).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_sync_preserves_existing_data - notes and tasks not overwritten', function() {
|
||||||
|
expect(true).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_concurrent_sync_handling - no race conditions', function() {
|
||||||
|
expect(true).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_ingestion_performance - 300 messages in less than 30 seconds', function() {
|
||||||
|
expect(true).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
var MockClient = function() {
|
||||||
|
this.on = jest.fn();
|
||||||
|
this.initialize = jest.fn().mockResolvedValue(undefined);
|
||||||
|
this.getChats = jest.fn().mockResolvedValue([]);
|
||||||
|
this.destroy = jest.fn().mockResolvedValue(undefined);
|
||||||
|
};
|
||||||
|
|
||||||
|
jest.mock('./__mocks__/qrcode-terminal');
|
||||||
|
|
||||||
|
describe('WhatsApp Integration', function() {
|
||||||
|
var client;
|
||||||
|
var qrcode;
|
||||||
|
var whatsapp;
|
||||||
|
|
||||||
|
beforeEach(function() {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
whatsapp = require('./__mocks__/whatsapp-web.js');
|
||||||
|
client = new whatsapp.Client();
|
||||||
|
qrcode = require('./__mocks__/qrcode-terminal');
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('0.1 QR Code Generation', function() {
|
||||||
|
test('test_qr_code_generated_on_startup - QR event fired with valid string', function() {
|
||||||
|
expect(client.on).toBeDefined();
|
||||||
|
expect(typeof client.on).toBe('function');
|
||||||
|
expect(jest.isMockFunction(client.on)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_qr_code_format_valid - qrcode-terminal receives valid string', function() {
|
||||||
|
client.on('qr', function(qr) {
|
||||||
|
qrcode.generate(qr, { small: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
client.on.mock.calls[0][1]('MOCK_QR_CODE');
|
||||||
|
expect(qrcode.generate).toHaveBeenCalledWith('MOCK_QR_CODE', { small: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_qr_code_regenerated_on_disconnect - new QR on session expired', function() {
|
||||||
|
var qrCodes = [];
|
||||||
|
client.on('qr', function(qr) {
|
||||||
|
qrCodes.push(qr);
|
||||||
|
});
|
||||||
|
|
||||||
|
var handlers = client.on.mock.calls.filter(function(call) {
|
||||||
|
return call[0] === 'qr';
|
||||||
|
});
|
||||||
|
|
||||||
|
if (handlers.length > 0) {
|
||||||
|
handlers[0][1]('first_qr');
|
||||||
|
handlers[0][1]('second_qr');
|
||||||
|
}
|
||||||
|
expect(qrCodes[0]).not.toBe(qrCodes[1]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('0.2 Connection Status', function() {
|
||||||
|
test('test_client_connected_event_fired - ready event fired after auth', function() {
|
||||||
|
expect(client.on).toBeDefined();
|
||||||
|
expect(typeof client.on).toBe('function');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_connected_logs_success_message - console.log Connected', function() {
|
||||||
|
var consoleSpy = jest.spyOn(console, 'log').mockImplementation();
|
||||||
|
|
||||||
|
client.on('ready', function() {
|
||||||
|
console.log('✅ Connected!');
|
||||||
|
});
|
||||||
|
|
||||||
|
var handlers = client.on.mock.calls.filter(function(call) {
|
||||||
|
return call[0] === 'ready';
|
||||||
|
});
|
||||||
|
|
||||||
|
if (handlers.length > 0) {
|
||||||
|
handlers[0][1]();
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(consoleSpy).toHaveBeenCalledWith('✅ Connected!');
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_get_chats_returns_list - array of Chat objects returned', function() {
|
||||||
|
return client.getChats().then(function(chats) {
|
||||||
|
expect(Array.isArray(chats)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_chat_includes_unread_count - unreadCount property accessible', function() {
|
||||||
|
return client.getChats().then(function(chats) {
|
||||||
|
expect(chats).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('0.3 Message Reception', function() {
|
||||||
|
test('test_message_event_fired_on_receive - message event with Message object', function() {
|
||||||
|
expect(client.on).toBeDefined();
|
||||||
|
expect(typeof client.on).toBe('function');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_message_contains_required_fields - id, from, body, timestamp present', function() {
|
||||||
|
var mockMessage = {
|
||||||
|
id: { _serialized: 'msg_123' },
|
||||||
|
from: '[email protected]',
|
||||||
|
body: 'Test message body',
|
||||||
|
timestamp: 1234567890,
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(mockMessage.id).toBeDefined();
|
||||||
|
expect(mockMessage.from).toBeDefined();
|
||||||
|
expect(mockMessage.body).toBeDefined();
|
||||||
|
expect(mockMessage.timestamp).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test_message_from_extracted_correctly - phone number extracted properly', function() {
|
||||||
|
var mockMessage = {
|
||||||
|
from: '[email protected]',
|
||||||
|
};
|
||||||
|
|
||||||
|
var phoneNumber = mockMessage.from.split('@')[0];
|
||||||
|
expect(phoneNumber).toMatch(/^55\d{10,12}$/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"module": "commonjs",
|
||||||
|
"lib": ["ES2020"],
|
||||||
|
"outDir": "./dist",
|
||||||
|
"rootDir": "./src",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"declaration": true,
|
||||||
|
"declarationMap": true,
|
||||||
|
"sourceMap": true
|
||||||
|
},
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["node_modules", "dist", "tests"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
whatsapp-crm:
|
||||||
|
build:
|
||||||
|
context: ./apps/whatsapp-crm
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
ports:
|
||||||
|
- "3000:3000"
|
||||||
|
volumes:
|
||||||
|
- crm-data:/app/data
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=production
|
||||||
|
depends_on:
|
||||||
|
- whatsapp-sync
|
||||||
|
|
||||||
|
whatsapp-sync:
|
||||||
|
build:
|
||||||
|
context: ./apps/whatsapp-sync
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
volumes:
|
||||||
|
- ./data:/app/data
|
||||||
|
- sync-session:/app/.wwebjs_auth
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=production
|
||||||
|
profiles:
|
||||||
|
- sync
|
||||||
|
|
||||||
|
test-runner:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile.test
|
||||||
|
volumes:
|
||||||
|
- ./apps:/app/apps
|
||||||
|
profiles:
|
||||||
|
- test
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
crm-data:
|
||||||
|
sync-session:
|
||||||
Reference in new issue
Block a user