Ahsan commited on
Commit
f4656a0
·
1 Parent(s): 64c38dc

Deploy Oxinto backend 2026-04-23 00:01

Browse files
Dockerfile ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:20-alpine
2
+
3
+ # HF Spaces requires UID 1000
4
+ RUN addgroup -g 1000 -S appgroup && adduser -S appuser -u 1000 -G appgroup
5
+
6
+ # Build tools needed for better-sqlite3 native module
7
+ RUN apk add --no-cache python3 make g++
8
+
9
+ WORKDIR /app
10
+
11
+ # Install dependencies first (layer cache)
12
+ COPY package*.json ./
13
+ RUN npm ci --omit=dev
14
+
15
+ # Copy application source
16
+ COPY --chown=appuser:appgroup src/ ./src/
17
+ COPY --chown=appuser:appgroup package.json ./
18
+
19
+ # Create writable directories
20
+ RUN mkdir -p /app/data /app/logs && chown -R appuser:appgroup /app/data /app/logs
21
+
22
+ USER appuser
23
+
24
+ # HF Spaces requires port 7860
25
+ EXPOSE 7860
26
+
27
+ ENV NODE_ENV=production
28
+ ENV PORT=7860
29
+
30
+ CMD ["node", "src/app.js"]
README.md CHANGED
@@ -1,10 +1,28 @@
1
  ---
2
  title: Oxinto Backend
3
- emoji: 🌍
4
- colorFrom: green
5
- colorTo: pink
6
  sdk: docker
7
  pinned: false
 
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Oxinto Backend
3
+ emoji: 🚀
4
+ colorFrom: blue
5
+ colorTo: green
6
  sdk: docker
7
  pinned: false
8
+ license: mit
9
+ app_port: 7860
10
+ short_description: Oxinto AI — Node.js backend API
11
  ---
12
 
13
+ # Oxinto Backend API
14
+
15
+ Node.js/Express backend for authentication, sessions, products, and webhooks.
16
+
17
+ ## Endpoints
18
+
19
+ | Method | Path | Description |
20
+ |--------|------|-------------|
21
+ | GET | `/api/health` | Health check |
22
+ | POST | `/api/auth/send-otp` | Register (step 1) |
23
+ | POST | `/api/auth/verify-otp` | Register (step 2) |
24
+ | POST | `/api/auth/login` | Login |
25
+ | POST | `/api/auth/logout` | Logout |
26
+ | GET | `/api/auth/me` | Get current user |
27
+ | POST | `/api/webhook/web` | Web chat |
28
+ | GET | `/api/products` | Product catalog |
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "smart-ai-recommendation-system",
3
+ "version": "1.0.0",
4
+ "description": "Smart Personalized Product Recommendation System - Multi-channel AI sales assistant",
5
+ "main": "src/app.js",
6
+ "scripts": {
7
+ "start": "node src/app.js",
8
+ "dev": "nodemon src/app.js",
9
+ "dev:all": "run-p dev dev:frontend",
10
+ "dev:frontend": "npm --prefix frontend run dev",
11
+ "build:frontend": "npm --prefix frontend run build",
12
+ "test": "jest --runInBand",
13
+ "test:unit": "jest tests/unit --runInBand",
14
+ "test:integration": "jest tests/integration --runInBand",
15
+ "test:e2e": "playwright test",
16
+ "test:coverage": "jest --coverage --runInBand",
17
+ "lint": "eslint src/ tests/",
18
+ "migrate": "node src/utils/migrate.js",
19
+ "seed": "node src/utils/seed.js"
20
+ },
21
+ "dependencies": {
22
+ "axios": "^1.6.2",
23
+ "better-sqlite3": "^12.8.0",
24
+ "compression": "^1.7.4",
25
+ "cookie-parser": "^1.4.7",
26
+ "cors": "^2.8.5",
27
+ "crypto": "^1.0.1",
28
+ "dotenv": "^16.3.1",
29
+ "express": "^4.18.2",
30
+ "express-rate-limit": "^7.1.5",
31
+ "express-session": "^1.19.0",
32
+ "helmet": "^7.1.0",
33
+ "joi": "^17.11.0",
34
+ "jsonwebtoken": "^9.0.3",
35
+ "morgan": "^1.10.0",
36
+ "node-cron": "^3.0.3",
37
+ "nodemailer": "^8.0.4",
38
+ "passport": "^0.7.0",
39
+ "passport-google-oauth20": "^2.0.0",
40
+ "pg": "^8.11.3",
41
+ "sqlite3": "^6.0.1",
42
+ "twilio": "^4.20.0",
43
+ "uuid": "^9.0.0",
44
+ "winston": "^3.11.0"
45
+ },
46
+ "devDependencies": {
47
+ "@playwright/test": "^1.40.1",
48
+ "eslint": "^8.55.0",
49
+ "jest": "^29.7.0",
50
+ "nodemon": "^3.0.2",
51
+ "npm-run-all2": "^8.0.4",
52
+ "supertest": "^6.3.3"
53
+ },
54
+ "engines": {
55
+ "node": ">=18.0.0"
56
+ },
57
+ "jest": {
58
+ "testEnvironment": "node",
59
+ "testMatch": [
60
+ "**/tests/**/*.test.js"
61
+ ],
62
+ "collectCoverageFrom": [
63
+ "src/**/*.js",
64
+ "!src/app.js"
65
+ ]
66
+ }
67
+ }
src/app.js ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ require('dotenv').config();
4
+
5
+ const express = require('express');
6
+ const cors = require('cors');
7
+ const helmet = require('helmet');
8
+ const morgan = require('morgan');
9
+ const compression = require('compression');
10
+ const cron = require('node-cron');
11
+ const cookieParser = require('cookie-parser');
12
+
13
+ const { initDatabase } = require('./config/database');
14
+ const SessionModel = require('./models/session.model');
15
+ const WebhookController = require('./controllers/webhook.controller');
16
+ const SessionController = require('./controllers/session.controller');
17
+ const { apiKeyAuth, verifyTwilioSignature, verifyMetaSignature, requireAuth } = require('./middleware/auth');
18
+ const AuthController = require('./controllers/auth.controller');
19
+ const { generalLimiter, webhookLimiter } = require('./middleware/rateLimiter');
20
+ const { validate, schemas } = require('./middleware/validation');
21
+ // Passport must be required after dotenv so GOOGLE_* env vars are available
22
+ const passport = require('./config/passport');
23
+ // eslint-disable-next-line no-unused-vars
24
+ const logger = require('./utils/logger');
25
+
26
+ const app = express();
27
+ const PORT = process.env.PORT || 3000;
28
+
29
+ // ─────────────────────────────────────────────
30
+ // Security & Middleware
31
+ // ─────────────────────────────────────────────
32
+
33
+ app.use(helmet({
34
+ contentSecurityPolicy: {
35
+ directives: {
36
+ defaultSrc: ["'self'"],
37
+ scriptSrc: ["'self'", "'unsafe-inline'", 'https://www.gstatic.com', 'https://apis.google.com'],
38
+ scriptSrcElem: ["'self'", "'unsafe-inline'", 'https://www.gstatic.com', 'https://apis.google.com'],
39
+ styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
40
+ fontSrc: ["'self'", 'https://fonts.gstatic.com'],
41
+ imgSrc: ["'self'", 'data:', 'https:'],
42
+ connectSrc: ["'self'"],
43
+ frameSrc: ['https://accounts.google.com'],
44
+ },
45
+ },
46
+ }));
47
+
48
+ const allowedOrigins = (process.env.ALLOWED_ORIGINS || 'http://localhost:3000,http://localhost:3001').split(',').map(o => o.trim());
49
+ app.use(cors({
50
+ origin: (origin, callback) => {
51
+ if (!origin || allowedOrigins.includes(origin) || process.env.NODE_ENV === 'development') {
52
+ callback(null, true);
53
+ } else {
54
+ callback(new Error('Not allowed by CORS'));
55
+ }
56
+ },
57
+ credentials: true,
58
+ }));
59
+
60
+ app.use(compression());
61
+ app.use(cookieParser());
62
+ app.use(morgan('combined', { stream: { write: (msg) => logger.info(msg.trim()) } }));
63
+ // Initialize Passport (no session middleware — stateless JWT only)
64
+ app.use(passport.initialize());
65
+
66
+ // Capture raw body ONLY for signature-verified channels (WhatsApp, Instagram).
67
+ // The web chat route does NOT need this — it uses standard express.json() parsing.
68
+ app.use((req, res, next) => {
69
+ if (req.path === '/api/webhook/whatsapp' || req.path === '/api/webhook/instagram') {
70
+ let data = '';
71
+ req.on('data', (chunk) => { data += chunk; });
72
+ req.on('end', () => {
73
+ req.rawBody = data;
74
+ try { req.body = JSON.parse(data); } catch { /* urlencoded or empty body — ok */ }
75
+ next();
76
+ });
77
+ } else {
78
+ next();
79
+ }
80
+ });
81
+
82
+ app.use(express.json({ limit: '1mb' }));
83
+ app.use(express.urlencoded({ extended: true, limit: '1mb' }));
84
+
85
+ // Apply general rate limiting
86
+ app.use('/api/', generalLimiter);
87
+
88
+ // ─────────────────────────────────────────────
89
+ // Routes
90
+ // ─────────────────────────────────────────────
91
+
92
+ // ── Google OAuth routes (Passport redirect flow, no session) ─────────────────
93
+ app.get('/auth/google', AuthController.redirectToGoogle);
94
+ app.get('/auth/google/callback',
95
+ passport.authenticate('google', { session: false, failWithError: true }),
96
+ AuthController.handleGoogleCallback
97
+ );
98
+
99
+ // ── Auth routes ──────────────────────────────────────────
100
+ app.post('/api/auth/send-otp', validate(schemas.sendOtp), AuthController.sendOtp);
101
+ app.post('/api/auth/verify-otp', validate(schemas.verifyOtp), AuthController.verifyOtp);
102
+ app.post('/api/auth/resend-otp', validate(schemas.resendOtp), AuthController.resendOtp);
103
+ app.post('/api/auth/login', validate(schemas.login), AuthController.login);
104
+ app.post('/api/auth/logout', requireAuth, AuthController.logout);
105
+ app.get('/api/auth/me', requireAuth, AuthController.me);
106
+ app.post('/api/auth/forgot-password', validate(schemas.forgotPassword), AuthController.forgotPassword);
107
+ app.post('/api/auth/reset-password', validate(schemas.resetPassword), AuthController.resetPassword);
108
+
109
+ // Health check (no auth required)
110
+ app.get('/api/health', SessionController.healthCheck);
111
+
112
+ // WhatsApp Webhook (Twilio signature verification)
113
+ app.post(
114
+ '/api/webhook/whatsapp',
115
+ webhookLimiter,
116
+ verifyTwilioSignature,
117
+ WebhookController.handleWhatsApp
118
+ );
119
+
120
+ // Instagram Webhook (Meta verification + signature)
121
+ app.get('/api/webhook/instagram', WebhookController.verifyInstagram);
122
+ app.post(
123
+ '/api/webhook/instagram',
124
+ webhookLimiter,
125
+ verifyMetaSignature,
126
+ WebhookController.handleInstagram
127
+ );
128
+
129
+ // Web Chat (no external auth needed — rate limited)
130
+ app.post(
131
+ '/api/webhook/web',
132
+ validate(schemas.webMessage),
133
+ WebhookController.handleWeb
134
+ );
135
+
136
+ // Session endpoints (require API key)
137
+ app.get('/api/session/:id', apiKeyAuth, validate(schemas.sessionId), SessionController.getSession);
138
+ app.post('/api/session/reset/:id', apiKeyAuth, validate(schemas.sessionId), SessionController.resetSession);
139
+
140
+ // Product catalog (public read)
141
+ app.get('/api/products', validate(schemas.productFilter), SessionController.getProducts);
142
+
143
+ // Unknown API routes — return 404 JSON. UI routing is handled by Next.js frontend.
144
+ app.use((req, res) => {
145
+ res.status(404).json({ error: 'Not found' });
146
+ });
147
+
148
+ // ─────────────────────────────────────────────
149
+ // Global Error Handler
150
+ // ─────────────────────────────────────────────
151
+
152
+ app.use((err, req, res, next) => {
153
+ logger.error('Unhandled error:', err);
154
+ const status = err.status || 500;
155
+ res.status(status).json({
156
+ error: status === 500 ? 'Internal server error' : err.message,
157
+ ...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
158
+ });
159
+ });
160
+
161
+ // ─────────────────────────────────────────────
162
+ // Cron: Session Cleanup
163
+ // ─────────────────────────────────────────────
164
+
165
+ function startCleanupJob() {
166
+ const interval = parseInt(process.env.SESSION_CLEANUP_INTERVAL_MINUTES || '10');
167
+ cron.schedule(`*/${interval} * * * *`, async () => {
168
+ try {
169
+ const deleted = await SessionModel.deleteExpired();
170
+ if (deleted > 0) logger.info(`Session cleanup: removed ${deleted} expired sessions`);
171
+ } catch (err) {
172
+ logger.error('Session cleanup error:', err);
173
+ }
174
+ });
175
+ logger.info(`Session cleanup job scheduled every ${interval} minutes`);
176
+ }
177
+
178
+ // ─────────────────────────────────────────────
179
+ // Startup
180
+ // ─────────────────────────────────────────────
181
+
182
+ async function start() {
183
+ try {
184
+ await initDatabase();
185
+ logger.info('Database initialized');
186
+
187
+ startCleanupJob();
188
+
189
+ const server = app.listen(PORT, () => {
190
+ logger.info(`Smart AI Recommendation System running on port ${PORT}`);
191
+ logger.info(`Environment: ${process.env.NODE_ENV || 'development'}`);
192
+ logger.info(`DB type: ${process.env.DB_TYPE || 'sqlite'}`);
193
+ });
194
+
195
+ // Graceful shutdown
196
+ const shutdown = (signal) => {
197
+ logger.info(`Received ${signal}, shutting down gracefully...`);
198
+ server.close(() => {
199
+ logger.info('Server closed');
200
+ process.exit(0);
201
+ });
202
+ };
203
+
204
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
205
+ process.on('SIGINT', () => shutdown('SIGINT'));
206
+
207
+ } catch (err) {
208
+ logger.error('Failed to start server:', err);
209
+ process.exit(1);
210
+ }
211
+ }
212
+
213
+ // Only auto-start when run directly; tests import and call start() themselves
214
+ if (require.main === module) {
215
+ start();
216
+ }
217
+
218
+ module.exports = app;
219
+ module.exports.start = start;
src/config/database.js ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const fs = require('fs');
5
+ const logger = require('../utils/logger');
6
+
7
+ let db = null;
8
+ let dbType = null;
9
+
10
+ /**
11
+ * Initialize database connection based on DB_TYPE env variable.
12
+ * Uses SQLite for development and PostgreSQL for production.
13
+ */
14
+ async function initDatabase() {
15
+ // Idempotent — safe to call multiple times
16
+ if (db) return db;
17
+
18
+ dbType = process.env.DB_TYPE || 'sqlite';
19
+
20
+ if (dbType === 'sqlite') {
21
+ return initSQLite();
22
+ } else {
23
+ return initPostgres();
24
+ }
25
+ }
26
+
27
+ function initSQLite() {
28
+ const Database = require('better-sqlite3');
29
+ const dbPath = process.env.DB_PATH || './data/database.db';
30
+ const resolvedPath = path.resolve(dbPath);
31
+
32
+ // Ensure data directory exists
33
+ const dir = path.dirname(resolvedPath);
34
+ if (!fs.existsSync(dir)) {
35
+ fs.mkdirSync(dir, { recursive: true });
36
+ }
37
+
38
+ db = new Database(resolvedPath);
39
+ db.pragma('journal_mode = WAL');
40
+ db.pragma('foreign_keys = ON');
41
+
42
+ logger.info(`SQLite database initialized at: ${resolvedPath}`);
43
+ createTables();
44
+ return db;
45
+ }
46
+
47
+ async function initPostgres() {
48
+ const { Pool } = require('pg');
49
+
50
+ const pool = new Pool({
51
+ connectionString: process.env.DATABASE_URL,
52
+ ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false,
53
+ max: 20,
54
+ idleTimeoutMillis: 30000,
55
+ connectionTimeoutMillis: 2000,
56
+ });
57
+
58
+ // Test connection
59
+ const client = await pool.connect();
60
+ await client.query('SELECT NOW()');
61
+ client.release();
62
+
63
+ db = pool;
64
+ logger.info('PostgreSQL database connected');
65
+ await createTablesPg();
66
+ return db;
67
+ }
68
+
69
+ /**
70
+ * Create all tables for SQLite.
71
+ */
72
+ function createTables() {
73
+ db.exec(`
74
+ CREATE TABLE IF NOT EXISTS products (
75
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
76
+ name TEXT NOT NULL,
77
+ description TEXT,
78
+ price REAL NOT NULL,
79
+ category TEXT NOT NULL,
80
+ tags TEXT DEFAULT '[]',
81
+ features TEXT DEFAULT '[]',
82
+ images TEXT DEFAULT '[]',
83
+ stock INTEGER DEFAULT 100,
84
+ active INTEGER DEFAULT 1,
85
+ created_at TEXT DEFAULT (datetime('now')),
86
+ updated_at TEXT DEFAULT (datetime('now'))
87
+ );
88
+
89
+ CREATE TABLE IF NOT EXISTS sessions (
90
+ id TEXT PRIMARY KEY,
91
+ channel TEXT NOT NULL,
92
+ user_id TEXT NOT NULL,
93
+ current_question_index INTEGER DEFAULT 0,
94
+ responses TEXT DEFAULT '[]',
95
+ completed INTEGER DEFAULT 0,
96
+ recommendations TEXT,
97
+ metadata TEXT DEFAULT '{}',
98
+ created_at TEXT DEFAULT (datetime('now')),
99
+ updated_at TEXT DEFAULT (datetime('now')),
100
+ expires_at TEXT NOT NULL
101
+ );
102
+
103
+ CREATE INDEX IF NOT EXISTS idx_sessions_user_channel ON sessions(user_id, channel);
104
+ CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);
105
+ CREATE INDEX IF NOT EXISTS idx_products_category ON products(category);
106
+ CREATE INDEX IF NOT EXISTS idx_products_active ON products(active);
107
+
108
+ CREATE TABLE IF NOT EXISTS users (
109
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
110
+ name TEXT NOT NULL,
111
+ email TEXT UNIQUE NOT NULL,
112
+ password_hash TEXT NOT NULL,
113
+ created_at TEXT DEFAULT (datetime('now')),
114
+ updated_at TEXT DEFAULT (datetime('now')),
115
+ last_seen_at TEXT
116
+ );
117
+
118
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email ON users(email);
119
+
120
+ CREATE TABLE IF NOT EXISTS user_activity (
121
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
122
+ user_id TEXT NOT NULL,
123
+ session_id TEXT,
124
+ action TEXT NOT NULL,
125
+ category TEXT,
126
+ data TEXT DEFAULT '{}',
127
+ created_at TEXT DEFAULT (datetime('now'))
128
+ );
129
+
130
+ CREATE INDEX IF NOT EXISTS idx_activity_user ON user_activity(user_id);
131
+ CREATE INDEX IF NOT EXISTS idx_activity_action ON user_activity(action);
132
+
133
+ CREATE TABLE IF NOT EXISTS temp_users (
134
+ id TEXT PRIMARY KEY,
135
+ name TEXT NOT NULL,
136
+ email TEXT UNIQUE NOT NULL,
137
+ password_hash TEXT NOT NULL,
138
+ otp TEXT NOT NULL,
139
+ otp_expires_at TEXT NOT NULL,
140
+ otp_attempts INTEGER DEFAULT 0,
141
+ created_at TEXT DEFAULT (datetime('now'))
142
+ );
143
+
144
+ CREATE INDEX IF NOT EXISTS idx_temp_users_email ON temp_users(email);
145
+ CREATE INDEX IF NOT EXISTS idx_temp_users_expires ON temp_users(otp_expires_at);
146
+
147
+ CREATE TABLE IF NOT EXISTS password_resets (
148
+ id TEXT PRIMARY KEY,
149
+ email TEXT NOT NULL,
150
+ otp TEXT NOT NULL,
151
+ otp_expires_at TEXT NOT NULL,
152
+ otp_attempts INTEGER DEFAULT 0,
153
+ created_at TEXT DEFAULT (datetime('now'))
154
+ );
155
+
156
+ CREATE INDEX IF NOT EXISTS idx_pw_resets_email ON password_resets(email);
157
+
158
+ CREATE TABLE IF NOT EXISTS google_users (
159
+ id TEXT PRIMARY KEY,
160
+ email TEXT UNIQUE NOT NULL,
161
+ google_uid TEXT UNIQUE NOT NULL,
162
+ name TEXT,
163
+ user_id INTEGER,
164
+ created_at TEXT DEFAULT (datetime('now'))
165
+ );
166
+
167
+ CREATE INDEX IF NOT EXISTS idx_google_users_email ON google_users(email);
168
+ CREATE INDEX IF NOT EXISTS idx_google_users_uid ON google_users(google_uid);
169
+ `);
170
+
171
+ logger.info('SQLite tables created/verified');
172
+ }
173
+
174
+ async function createTablesPg() {
175
+ await db.query(`
176
+ CREATE TABLE IF NOT EXISTS products (
177
+ id SERIAL PRIMARY KEY,
178
+ name VARCHAR(255) NOT NULL,
179
+ description TEXT,
180
+ price DECIMAL(10,2) NOT NULL,
181
+ category VARCHAR(100) NOT NULL,
182
+ tags JSONB DEFAULT '[]',
183
+ features JSONB DEFAULT '[]',
184
+ images JSONB DEFAULT '[]',
185
+ stock INTEGER DEFAULT 100,
186
+ active BOOLEAN DEFAULT true,
187
+ created_at TIMESTAMP DEFAULT NOW(),
188
+ updated_at TIMESTAMP DEFAULT NOW()
189
+ );
190
+
191
+ CREATE TABLE IF NOT EXISTS sessions (
192
+ id UUID PRIMARY KEY,
193
+ channel VARCHAR(50) NOT NULL,
194
+ user_id VARCHAR(255) NOT NULL,
195
+ current_question_index INTEGER DEFAULT 0,
196
+ responses JSONB DEFAULT '[]',
197
+ completed BOOLEAN DEFAULT false,
198
+ recommendations JSONB,
199
+ metadata JSONB DEFAULT '{}',
200
+ created_at TIMESTAMP DEFAULT NOW(),
201
+ updated_at TIMESTAMP DEFAULT NOW(),
202
+ expires_at TIMESTAMP NOT NULL
203
+ );
204
+
205
+ CREATE INDEX IF NOT EXISTS idx_sessions_user_channel ON sessions(user_id, channel);
206
+ CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);
207
+ CREATE INDEX IF NOT EXISTS idx_products_category ON products(category);
208
+ CREATE INDEX IF NOT EXISTS idx_products_active ON products(active);
209
+
210
+ CREATE TABLE IF NOT EXISTS users (
211
+ id SERIAL PRIMARY KEY,
212
+ name VARCHAR(255) NOT NULL,
213
+ email VARCHAR(255) UNIQUE NOT NULL,
214
+ password_hash TEXT NOT NULL,
215
+ created_at TIMESTAMP DEFAULT NOW(),
216
+ updated_at TIMESTAMP DEFAULT NOW(),
217
+ last_seen_at TIMESTAMP
218
+ );
219
+
220
+ CREATE TABLE IF NOT EXISTS user_activity (
221
+ id SERIAL PRIMARY KEY,
222
+ user_id VARCHAR(255) NOT NULL,
223
+ session_id VARCHAR(255),
224
+ action VARCHAR(100) NOT NULL,
225
+ category VARCHAR(100),
226
+ data JSONB DEFAULT '{}',
227
+ created_at TIMESTAMP DEFAULT NOW()
228
+ );
229
+
230
+ CREATE INDEX IF NOT EXISTS idx_activity_user ON user_activity(user_id);
231
+ CREATE INDEX IF NOT EXISTS idx_activity_action ON user_activity(action);
232
+ `);
233
+
234
+ logger.info('PostgreSQL tables created/verified');
235
+ }
236
+
237
+ function getDb() {
238
+ if (!db) throw new Error('Database not initialized. Call initDatabase() first.');
239
+ return db;
240
+ }
241
+
242
+ function getDbType() {
243
+ return dbType || process.env.DB_TYPE || 'sqlite';
244
+ }
245
+
246
+ module.exports = { initDatabase, getDb, getDbType };
src/config/passport.js ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const passport = require('passport');
4
+ const { Strategy: GoogleStrategy } = require('passport-google-oauth20');
5
+ const UserModel = require('../models/user.model');
6
+ const logger = require('../utils/logger');
7
+
8
+ /**
9
+ * Configure Passport.js with Google OAuth 2.0 strategy.
10
+ * Sessions are disabled — stateless JWT flow only.
11
+ * Required env vars: GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_CALLBACK_URL
12
+ *
13
+ * Strategy registration is skipped when env vars are absent (e.g. in tests)
14
+ * so the process does not crash. Requests to /auth/google will return 500
15
+ * if the vars are genuinely missing in production.
16
+ */
17
+ if (process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET && process.env.GOOGLE_CALLBACK_URL) {
18
+ passport.use(
19
+ new GoogleStrategy(
20
+ {
21
+ clientID: process.env.GOOGLE_CLIENT_ID,
22
+ clientSecret: process.env.GOOGLE_CLIENT_SECRET,
23
+ callbackURL: process.env.GOOGLE_CALLBACK_URL,
24
+ },
25
+ async (accessToken, refreshToken, profile, done) => {
26
+ try {
27
+ const googleId = profile.id;
28
+ const emailEntry = profile.emails && profile.emails[0];
29
+ const email = emailEntry ? emailEntry.value : null;
30
+ const name = profile.displayName || (email ? email.split('@')[0] : 'User');
31
+
32
+ if (!email) {
33
+ return done(new Error('No email provided by Google account'), null);
34
+ }
35
+
36
+ const lowerEmail = email.toLowerCase();
37
+
38
+ // 1. Check if user already linked via Google ID in google_users table
39
+ let user = await UserModel.findByGoogleId(googleId);
40
+
41
+ if (!user) {
42
+ // 2. Check if an email/password account already exists for this email
43
+ user = await UserModel.findByEmail(lowerEmail);
44
+
45
+ if (!user) {
46
+ // 3. Brand-new user — create account and link Google ID
47
+ user = await UserModel.createGoogleUser({ email: lowerEmail, name, googleId });
48
+ logger.info(`New Google OAuth user created: ${lowerEmail}`);
49
+ } else {
50
+ // 4. Link existing email/password account to this Google ID
51
+ await UserModel.linkGoogleId(user.id, lowerEmail, name, googleId);
52
+ logger.info(`Existing user linked to Google OAuth: ${lowerEmail}`);
53
+ }
54
+ }
55
+
56
+ return done(null, user);
57
+ } catch (err) {
58
+ logger.error('Google OAuth strategy error:', err);
59
+ return done(err, null);
60
+ }
61
+ }
62
+ )
63
+ );
64
+ } else {
65
+ logger.warn('Google OAuth not configured: GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, or GOOGLE_CALLBACK_URL is missing');
66
+ }
67
+
68
+ module.exports = passport;
src/config/questionnaire.js ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ /**
4
+ * Multi-category questionnaire.
5
+ * Flow: Category → 3 category-specific branch questions → Budget → Urgency → Freetext
6
+ */
7
+ const questionnaire = {
8
+ version: '2.0',
9
+
10
+ questions: [
11
+ // ── ENTRY: Category ──────────────────────────────────────────
12
+ {
13
+ id: 'q_category',
14
+ text: { en: 'What are you shopping for today?' },
15
+ type: 'multiple_choice',
16
+ options: {
17
+ en: [
18
+ 'Electronics & Gadgets',
19
+ 'Fashion & Accessories',
20
+ 'Home & Kitchen',
21
+ 'Health & Beauty',
22
+ 'Entertainment & Hobbies',
23
+ 'Grocery & Daily Essentials',
24
+ ],
25
+ },
26
+ tags: {
27
+ 0: ['electronics'], 1: ['fashion'], 2: ['home'],
28
+ 3: ['health'], 4: ['entertainment'], 5: ['grocery'],
29
+ },
30
+ branchOn: {
31
+ 0: ['q_elec_sub', 'q_elec_use', 'q_elec_brand'],
32
+ 1: ['q_fashion_sub', 'q_fashion_style', 'q_fashion_fit'],
33
+ 2: ['q_home_sub', 'q_home_size', 'q_home_style'],
34
+ 3: ['q_health_sub', 'q_health_concern', 'q_health_type'],
35
+ 4: ['q_entertain_sub','q_entertain_setting','q_entertain_level'],
36
+ 5: ['q_grocery_sub', 'q_grocery_diet', 'q_grocery_freq'],
37
+ },
38
+ },
39
+
40
+ // ── ELECTRONICS ──────────────────────────────────────────────
41
+ {
42
+ id: 'q_elec_sub',
43
+ text: { en: 'Which electronics category are you interested in?' },
44
+ type: 'multiple_choice',
45
+ options: { en: ['Smartphones, Laptops & Tablets', 'Headphones, Earbuds & Smartwatches', 'Gaming Consoles & VR', 'Cameras & Drones'] },
46
+ tags: { 0: ['mobile', 'computing'], 1: ['audio', 'wearables'], 2: ['gaming', 'vr'], 3: ['photography', 'drones'] },
47
+ },
48
+ {
49
+ id: 'q_elec_use',
50
+ text: { en: 'What will you mainly use it for?' },
51
+ type: 'multiple_choice',
52
+ options: { en: ['Work & Productivity', 'Gaming & Entertainment', 'Casual & Social', 'Professional / Creative'] },
53
+ tags: { 0: ['professional', 'productivity'], 1: ['gaming'], 2: ['casual'], 3: ['creative', 'professional'] },
54
+ },
55
+ {
56
+ id: 'q_elec_brand',
57
+ text: { en: 'Do you have a brand or ecosystem preference?' },
58
+ type: 'multiple_choice',
59
+ options: { en: ['Apple / iOS ecosystem', 'Samsung / Android', 'Best value — any brand', 'Best specs — any brand'] },
60
+ tags: { 0: ['apple', 'ios'], 1: ['samsung', 'android'], 2: ['value'], 3: ['premium', 'specs'] },
61
+ },
62
+
63
+ // ── FASHION & ACCESSORIES ────────────────────────────────────
64
+ {
65
+ id: 'q_fashion_sub',
66
+ text: { en: 'What type of fashion item are you looking for?' },
67
+ type: 'multiple_choice',
68
+ options: { en: ['Clothing (T-shirts, Jackets, Jeans)', 'Shoes & Sneakers', 'Watches & Jewelry', 'Bags & Wallets'] },
69
+ tags: { 0: ['clothing'], 1: ['footwear'], 2: ['accessories', 'jewelry'], 3: ['bags', 'accessories'] },
70
+ },
71
+ {
72
+ id: 'q_fashion_style',
73
+ text: { en: 'Which style best matches you?' },
74
+ type: 'multiple_choice',
75
+ options: { en: ['Casual & Everyday', 'Formal & Business', 'Sportswear & Athletic', 'Streetwear & Trendy'] },
76
+ tags: { 0: ['casual'], 1: ['formal'], 2: ['sport', 'athletic'], 3: ['streetwear', 'trendy'] },
77
+ },
78
+ {
79
+ id: 'q_fashion_fit',
80
+ text: { en: 'What fit or size do you prefer?' },
81
+ type: 'multiple_choice',
82
+ options: { en: ['Slim / Fitted', 'Regular / Standard', 'Oversized / Relaxed', 'Not sure — help me choose'] },
83
+ tags: { 0: ['slim'], 1: ['regular'], 2: ['oversized'], 3: [] },
84
+ },
85
+
86
+ // ── HOME & KITCHEN ───────────────────────────────────────────
87
+ {
88
+ id: 'q_home_sub',
89
+ text: { en: 'Which home category are you browsing?' },
90
+ type: 'multiple_choice',
91
+ options: { en: ['Kitchen Appliances', 'Furniture (Sofa, Desk, Bed)', 'Home Decor (Lamps, Rugs, Art)'] },
92
+ tags: { 0: ['appliances', 'kitchen'], 1: ['furniture'], 2: ['decor'] },
93
+ },
94
+ {
95
+ id: 'q_home_size',
96
+ text: { en: 'How much space do you have?' },
97
+ type: 'multiple_choice',
98
+ options: { en: ['Small / Compact', 'Medium', 'Large / Spacious', 'Not sure'] },
99
+ tags: { 0: ['compact', 'small'], 1: ['medium'], 2: ['large', 'spacious'], 3: [] },
100
+ },
101
+ {
102
+ id: 'q_home_style',
103
+ text: { en: 'Which interior style do you prefer?' },
104
+ type: 'multiple_choice',
105
+ options: { en: ['Modern & Minimalist', 'Rustic & Classic', 'Industrial & Bold', 'Scandinavian & Cosy'] },
106
+ tags: { 0: ['modern', 'minimalist'], 1: ['rustic', 'classic'], 2: ['industrial'], 3: ['scandinavian', 'cosy'] },
107
+ },
108
+
109
+ // ── HEALTH & BEAUTY ─────────���────────────────────────────────
110
+ {
111
+ id: 'q_health_sub',
112
+ text: { en: 'Which health & beauty area interests you?' },
113
+ type: 'multiple_choice',
114
+ options: { en: ['Skincare (Cleansers, Moisturizers)', 'Haircare (Shampoo, Conditioner, Oils)', 'Fitness Gear (Mats, Dumbbells)', 'Vitamins & Supplements'] },
115
+ tags: { 0: ['skincare'], 1: ['haircare'], 2: ['fitness', 'gym'], 3: ['supplements', 'vitamins'] },
116
+ },
117
+ {
118
+ id: 'q_health_concern',
119
+ text: { en: 'What is your main concern or goal?' },
120
+ type: 'multiple_choice',
121
+ options: { en: ['Anti-aging & Glow', 'Acne & Oily Skin', 'Dry or Sensitive Skin / Hair', 'Performance & Strength'] },
122
+ tags: { 0: ['anti-aging', 'glow'], 1: ['acne', 'oily'], 2: ['dry', 'sensitive'], 3: ['performance', 'strength'] },
123
+ },
124
+ {
125
+ id: 'q_health_type',
126
+ text: { en: 'Do you prefer natural/organic or science-based products?' },
127
+ type: 'multiple_choice',
128
+ options: { en: ['Natural & Organic', 'Science-based & Clinical', 'Most effective wins', 'Cruelty-free & Vegan only'] },
129
+ tags: { 0: ['natural', 'organic'], 1: ['clinical', 'science'], 2: ['effective'], 3: ['vegan', 'cruelty-free'] },
130
+ },
131
+
132
+ // ── ENTERTAINMENT & HOBBIES ──────────────────────────────────
133
+ {
134
+ id: 'q_entertain_sub',
135
+ text: { en: 'What type of entertainment or hobby product?' },
136
+ type: 'multiple_choice',
137
+ options: { en: ['Books, eBooks & Comics', 'Board Games & Puzzles', 'Musical Instruments', 'Sports Equipment'] },
138
+ tags: { 0: ['books', 'reading'], 1: ['games', 'puzzles'], 2: ['music', 'instruments'], 3: ['sports', 'outdoor'] },
139
+ },
140
+ {
141
+ id: 'q_entertain_setting',
142
+ text: { en: 'Do you prefer indoor or outdoor activities?' },
143
+ type: 'multiple_choice',
144
+ options: { en: ['Indoor only', 'Outdoor only', 'Both indoor & outdoor', "Doesn't matter"] },
145
+ tags: { 0: ['indoor'], 1: ['outdoor'], 2: ['indoor', 'outdoor'], 3: [] },
146
+ },
147
+ {
148
+ id: 'q_entertain_level',
149
+ text: { en: "What's your experience level?" },
150
+ type: 'multiple_choice',
151
+ options: { en: ['Complete beginner', 'Intermediate', 'Advanced / Expert', 'Buying as a gift'] },
152
+ tags: { 0: ['beginner', 'starter'], 1: ['intermediate'], 2: ['advanced', 'expert'], 3: ['gift'] },
153
+ },
154
+
155
+ // ── GROCERY & DAILY ESSENTIALS ───────────────────────────────
156
+ {
157
+ id: 'q_grocery_sub',
158
+ text: { en: 'Which grocery category?' },
159
+ type: 'multiple_choice',
160
+ options: { en: ['Snacks & Beverages', 'Organic & Health Foods', 'Household Cleaning Products', 'Pet Supplies'] },
161
+ tags: { 0: ['snacks', 'beverages'], 1: ['organic', 'health-food'], 2: ['cleaning', 'household'], 3: ['pets'] },
162
+ },
163
+ {
164
+ id: 'q_grocery_diet',
165
+ text: { en: 'Do you have any dietary restrictions?' },
166
+ type: 'multiple_choice',
167
+ options: { en: ['None — anything goes', 'Vegan / Vegetarian', 'Gluten-free', 'Dairy-free'] },
168
+ tags: { 0: [], 1: ['vegan', 'vegetarian'], 2: ['gluten-free'], 3: ['dairy-free'] },
169
+ },
170
+ {
171
+ id: 'q_grocery_freq',
172
+ text: { en: 'How often do you need this product?' },
173
+ type: 'multiple_choice',
174
+ options: { en: ['Daily', 'Weekly', 'Monthly / Bulk buy', 'One-time purchase'] },
175
+ tags: { 0: ['daily', 'frequent'], 1: ['weekly'], 2: ['bulk'], 3: ['one-time'] },
176
+ },
177
+
178
+ // ── COMMON (always shown) ────────────────────────────────────
179
+ {
180
+ id: 'q_budget',
181
+ text: { en: 'What is your budget range?' },
182
+ type: 'multiple_choice',
183
+ options: { en: ['Under $25', '$25 – $75', '$75 – $200', '$200+'] },
184
+ budgetRanges: [
185
+ { min: 0, max: 25 },
186
+ { min: 25, max: 75 },
187
+ { min: 75, max: 200 },
188
+ { min: 200, max: Infinity },
189
+ ],
190
+ tags: { 0: ['budget'], 1: ['mid-range'], 2: ['premium'], 3: ['luxury'] },
191
+ branchOn: { 3: 'q_bundle' },
192
+ },
193
+ {
194
+ id: 'q_bundle',
195
+ text: { en: 'Since your budget is $200+, would you like a complete bundle (product + accessories)?' },
196
+ type: 'multiple_choice',
197
+ optional: true,
198
+ options: { en: ['Yes, bundle me up!', 'No, just the main product'] },
199
+ tags: { 0: ['bundle', 'luxury'], 1: ['luxury'] },
200
+ },
201
+ {
202
+ id: 'q_urgency',
203
+ text: { en: 'How soon do you need this?' },
204
+ type: 'multiple_choice',
205
+ options: { en: ['Today (express delivery)', 'This week', 'Next month', 'Just browsing'] },
206
+ tags: { 0: ['urgent', 'express'], 1: ['standard'], 2: ['flexible'], 3: ['browsing'] },
207
+ },
208
+ {
209
+ id: 'q_specific',
210
+ text: { en: 'Any specific requirements or preferences? (optional)' },
211
+ type: 'text',
212
+ optional: true,
213
+ placeholder: { en: 'e.g., waterproof, specific color, certain brand, size...' },
214
+ },
215
+ ],
216
+
217
+ /**
218
+ * Build ordered question flow, inserting category-specific branch questions.
219
+ * Supports single branch ID (string) or multiple (array) per answer index.
220
+ */
221
+ getFlow(responses = []) {
222
+ const branchIds = new Set();
223
+ for (const q of this.questions) {
224
+ if (q.branchOn) {
225
+ Object.values(q.branchOn).forEach((v) => [].concat(v).forEach((id) => branchIds.add(id)));
226
+ }
227
+ }
228
+
229
+ const base = this.questions.filter((q) => !branchIds.has(q.id));
230
+ const flow = [];
231
+
232
+ for (const q of base) {
233
+ flow.push(q);
234
+ if (q.branchOn) {
235
+ const answer = responses.find((r) => r.questionId === q.id);
236
+ if (answer !== undefined && answer.answerIndex !== null) {
237
+ const branchVal = q.branchOn[answer.answerIndex];
238
+ if (branchVal !== undefined) {
239
+ [].concat(branchVal).forEach((id) => {
240
+ const bq = this.questions.find((bq) => bq.id === id);
241
+ if (bq) flow.push(bq);
242
+ });
243
+ }
244
+ }
245
+ }
246
+ }
247
+
248
+ return flow;
249
+ },
250
+ };
251
+
252
+ module.exports = questionnaire;
src/controllers/auth.controller.js ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const jwt = require('jsonwebtoken');
4
+ const passport = require('passport');
5
+ const { v4: uuidv4 } = require('uuid');
6
+ const UserModel = require('../models/user.model');
7
+ const { hashPassword, verifyPassword } = require('../models/user.model');
8
+ const EmailService = require('../services/email.service');
9
+ const { getDb, getDbType } = require('../config/database');
10
+ const logger = require('../utils/logger');
11
+
12
+ const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret-change-in-production';
13
+ const JWT_EXPIRES = process.env.JWT_EXPIRES || '7d';
14
+ const OTP_TTL_MS = 10 * 60 * 1000; // 10 minutes
15
+ const MAX_OTP_ATTEMPTS = 5;
16
+ // Max 3 OTP requests per email per hour (enforced in-process; use Redis for multi-instance)
17
+ const otpRateMap = new Map(); // email → { count, resetAt }
18
+
19
+ function signToken(user) {
20
+ return jwt.sign(
21
+ { id: user.id, email: user.email, name: user.name },
22
+ JWT_SECRET,
23
+ { expiresIn: JWT_EXPIRES }
24
+ );
25
+ }
26
+
27
+ function generateOtp() {
28
+ return String(Math.floor(100000 + Math.random() * 900000));
29
+ }
30
+
31
+ function checkOtpRate(email) {
32
+ const now = Date.now();
33
+ const rec = otpRateMap.get(email);
34
+ if (!rec || now > rec.resetAt) {
35
+ otpRateMap.set(email, { count: 1, resetAt: now + 3600_000 });
36
+ return true;
37
+ }
38
+ if (rec.count >= 3) return false;
39
+ rec.count++;
40
+ return true;
41
+ }
42
+
43
+ function setAuthCookie(res, token) {
44
+ res.cookie('smart_token', token, {
45
+ httpOnly: true,
46
+ secure: process.env.NODE_ENV === 'production',
47
+ sameSite: 'lax',
48
+ maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
49
+ });
50
+ }
51
+
52
+ function clearAuthCookie(res) {
53
+ res.clearCookie('smart_token', { httpOnly: true, sameSite: 'lax' });
54
+ }
55
+
56
+ // ── DB helpers for temp_users ─────────────────────────────────────────────────
57
+
58
+ function dbRun(sql, params = []) {
59
+ const db = getDb();
60
+ if (getDbType() === 'sqlite') {
61
+ db.prepare(sql).run(...params);
62
+ }
63
+ }
64
+
65
+ function dbGet(sql, params = []) {
66
+ const db = getDb();
67
+ if (getDbType() === 'sqlite') {
68
+ return db.prepare(sql).get(...params);
69
+ }
70
+ return null;
71
+ }
72
+
73
+ // ─────────────────────────────────────────────
74
+ // Controller
75
+ // ─────────────────────────────────────────────
76
+
77
+ const AuthController = {
78
+
79
+ /**
80
+ * POST /api/auth/signup (legacy — direct signup without OTP, kept for backward compat)
81
+ */
82
+ async signup(req, res) {
83
+ const { name, email, password } = req.body;
84
+ try {
85
+ const existing = await UserModel.findByEmail(email);
86
+ if (existing) return res.status(409).json({ error: 'Email already registered' });
87
+
88
+ const passwordHash = await hashPassword(password);
89
+ const user = await UserModel.create({ name, email, passwordHash });
90
+
91
+ await UserModel.trackActivity({ userId: String(user.id), action: 'signup', data: { email: user.email } });
92
+
93
+ const token = signToken(user);
94
+ logger.info(`New user registered (direct): ${email}`);
95
+ setAuthCookie(res, token);
96
+ return res.status(201).json({ token, user: { id: user.id, name: user.name, email: user.email } });
97
+ } catch (err) {
98
+ logger.error('Signup error:', err);
99
+ return res.status(500).json({ error: 'Internal server error' });
100
+ }
101
+ },
102
+
103
+ /**
104
+ * POST /api/auth/send-otp
105
+ * Step 1 of OTP signup: store temp user, send OTP email.
106
+ */
107
+ async sendOtp(req, res) {
108
+ const { name, email, password } = req.body;
109
+ try {
110
+ // Rate limit
111
+ if (!checkOtpRate(email.toLowerCase())) {
112
+ return res.status(429).json({ error: 'Too many OTP requests. Try again in an hour.' });
113
+ }
114
+
115
+ // Check if already permanently registered
116
+ const existing = await UserModel.findByEmail(email);
117
+ if (existing) return res.status(409).json({ error: 'Email already registered. Please sign in.' });
118
+
119
+ const passwordHash = await hashPassword(password);
120
+ const otp = generateOtp();
121
+ const otpExpiresAt = new Date(Date.now() + OTP_TTL_MS).toISOString();
122
+ const tempId = uuidv4();
123
+
124
+ // Upsert temp_users (overwrite if same email retried)
125
+ dbRun(
126
+ `INSERT INTO temp_users (id, name, email, password_hash, otp, otp_expires_at, otp_attempts)
127
+ VALUES (?, ?, ?, ?, ?, ?, 0)
128
+ ON CONFLICT(email) DO UPDATE SET
129
+ id=excluded.id, name=excluded.name, password_hash=excluded.password_hash,
130
+ otp=excluded.otp, otp_expires_at=excluded.otp_expires_at, otp_attempts=0`,
131
+ [tempId, name, email.toLowerCase(), passwordHash, otp, otpExpiresAt]
132
+ );
133
+
134
+ // Get the actual stored id (may differ if email already existed)
135
+ const stored = dbGet('SELECT id FROM temp_users WHERE email = ?', [email.toLowerCase()]);
136
+
137
+ await EmailService.sendOtp(email, otp, name);
138
+ logger.info(`OTP sent for signup: ${email}`);
139
+
140
+ return res.status(200).json({ success: true, tempUserId: stored.id });
141
+ } catch (err) {
142
+ logger.error('send-otp error:', err);
143
+ return res.status(500).json({ error: 'Failed to send OTP. Please try again.' });
144
+ }
145
+ },
146
+
147
+ /**
148
+ * POST /api/auth/verify-otp
149
+ * Step 2: verify OTP, create permanent user, return JWT.
150
+ */
151
+ async verifyOtp(req, res) {
152
+ const { tempUserId, otp } = req.body;
153
+ try {
154
+ const temp = dbGet('SELECT * FROM temp_users WHERE id = ?', [tempUserId]);
155
+ if (!temp) return res.status(400).json({ error: 'Session expired. Please start again.' });
156
+
157
+ // Check expiry
158
+ if (new Date(temp.otp_expires_at) < new Date()) {
159
+ dbRun('DELETE FROM temp_users WHERE id = ?', [tempUserId]);
160
+ return res.status(400).json({ error: 'OTP expired. Please request a new one.' });
161
+ }
162
+
163
+ // Check attempts
164
+ if (temp.otp_attempts >= MAX_OTP_ATTEMPTS) {
165
+ dbRun('DELETE FROM temp_users WHERE id = ?', [tempUserId]);
166
+ return res.status(400).json({ error: 'Too many failed attempts. Please start again.' });
167
+ }
168
+
169
+ // Verify OTP
170
+ if (temp.otp !== otp) {
171
+ dbRun('UPDATE temp_users SET otp_attempts = otp_attempts + 1 WHERE id = ?', [tempUserId]);
172
+ const remaining = MAX_OTP_ATTEMPTS - (temp.otp_attempts + 1);
173
+ return res.status(400).json({ error: `Incorrect code. ${remaining} attempt(s) remaining.` });
174
+ }
175
+
176
+ // Check email not taken (race condition guard)
177
+ const existing = await UserModel.findByEmail(temp.email);
178
+ if (existing) {
179
+ dbRun('DELETE FROM temp_users WHERE id = ?', [tempUserId]);
180
+ return res.status(409).json({ error: 'Email already registered. Please sign in.' });
181
+ }
182
+
183
+ // Create permanent user
184
+ const user = await UserModel.create({ name: temp.name, email: temp.email, passwordHash: temp.password_hash });
185
+ dbRun('DELETE FROM temp_users WHERE id = ?', [tempUserId]);
186
+
187
+ await UserModel.trackActivity({ userId: String(user.id), action: 'signup', data: { email: user.email, method: 'otp' } });
188
+
189
+ const token = signToken(user);
190
+ logger.info(`New user verified & created: ${temp.email}`);
191
+ setAuthCookie(res, token);
192
+ return res.status(201).json({ success: true, token, user: { id: user.id, name: user.name, email: user.email } });
193
+ } catch (err) {
194
+ logger.error('verify-otp error:', err);
195
+ return res.status(500).json({ error: 'Internal server error' });
196
+ }
197
+ },
198
+
199
+ /**
200
+ * POST /api/auth/resend-otp
201
+ * Regenerate and resend OTP for an existing temp session.
202
+ */
203
+ async resendOtp(req, res) {
204
+ const { tempUserId } = req.body;
205
+ try {
206
+ const temp = dbGet('SELECT * FROM temp_users WHERE id = ?', [tempUserId]);
207
+ if (!temp) return res.status(400).json({ error: 'Session not found. Please start again.' });
208
+
209
+ if (!checkOtpRate(temp.email)) {
210
+ return res.status(429).json({ error: 'Too many OTP requests. Try again in an hour.' });
211
+ }
212
+
213
+ const otp = generateOtp();
214
+ const otpExpiresAt = new Date(Date.now() + OTP_TTL_MS).toISOString();
215
+ dbRun('UPDATE temp_users SET otp = ?, otp_expires_at = ?, otp_attempts = 0 WHERE id = ?', [otp, otpExpiresAt, tempUserId]);
216
+
217
+ await EmailService.sendOtp(temp.email, otp, temp.name);
218
+ logger.info(`OTP resent for: ${temp.email}`);
219
+ return res.status(200).json({ success: true });
220
+ } catch (err) {
221
+ logger.error('resend-otp error:', err);
222
+ return res.status(500).json({ error: 'Failed to resend OTP.' });
223
+ }
224
+ },
225
+
226
+ /**
227
+ * POST /api/auth/login
228
+ */
229
+ async login(req, res) {
230
+ const { email, password } = req.body;
231
+ try {
232
+ const user = await UserModel.findByEmail(email);
233
+ if (!user) return res.status(401).json({ error: 'Invalid email or password' });
234
+
235
+ const valid = await verifyPassword(password, user.password_hash);
236
+ if (!valid) return res.status(401).json({ error: 'Invalid email or password' });
237
+
238
+ await UserModel.updateLastSeen(user.id);
239
+ await UserModel.trackActivity({ userId: String(user.id), action: 'login', data: { email: user.email } });
240
+
241
+ const token = signToken(user);
242
+ logger.info(`User logged in: ${email}`);
243
+ setAuthCookie(res, token);
244
+ return res.status(200).json({ token, user: { id: user.id, name: user.name, email: user.email } });
245
+ } catch (err) {
246
+ logger.error('Login error:', err);
247
+ return res.status(500).json({ error: 'Internal server error' });
248
+ }
249
+ },
250
+
251
+ /**
252
+ * POST /api/auth/logout
253
+ */
254
+ async logout(req, res) {
255
+ try {
256
+ if (req.user) {
257
+ await UserModel.trackActivity({ userId: String(req.user.id), action: 'logout' });
258
+ }
259
+ clearAuthCookie(res);
260
+ return res.status(200).json({ message: 'Logged out successfully' });
261
+ } catch {
262
+ clearAuthCookie(res);
263
+ return res.status(200).json({ message: 'Logged out' });
264
+ }
265
+ },
266
+
267
+ /**
268
+ * GET /api/auth/me
269
+ */
270
+ async me(req, res) {
271
+ try {
272
+ const user = await UserModel.findById(req.user.id);
273
+ if (!user) return res.status(404).json({ error: 'User not found' });
274
+
275
+ const activity = await UserModel.getActivitySummary(String(user.id));
276
+ return res.status(200).json({
277
+ user: { id: user.id, name: user.name, email: user.email, createdAt: user.created_at, lastSeen: user.last_seen_at },
278
+ recentActivity: activity.slice(0, 10),
279
+ });
280
+ } catch (err) {
281
+ logger.error('me error:', err);
282
+ return res.status(500).json({ error: 'Internal server error' });
283
+ }
284
+ },
285
+
286
+ /**
287
+ * POST /api/auth/forgot-password
288
+ * Send OTP to registered email for password reset.
289
+ */
290
+ async forgotPassword(req, res) {
291
+ const { email } = req.body;
292
+ try {
293
+ // Always return success to prevent email enumeration
294
+ const user = await UserModel.findByEmail(email);
295
+ if (!user) {
296
+ return res.status(200).json({ success: true, message: 'If this email is registered, you will receive a reset code.' });
297
+ }
298
+
299
+ if (!checkOtpRate(email.toLowerCase())) {
300
+ return res.status(429).json({ error: 'Too many requests. Try again in an hour.' });
301
+ }
302
+
303
+ const otp = generateOtp();
304
+ const otpExpiresAt = new Date(Date.now() + OTP_TTL_MS).toISOString();
305
+ const resetId = uuidv4();
306
+
307
+ dbRun(
308
+ `INSERT INTO password_resets (id, email, otp, otp_expires_at, otp_attempts) VALUES (?, ?, ?, ?, 0)`,
309
+ [resetId, email.toLowerCase(), otp, otpExpiresAt]
310
+ );
311
+
312
+ await EmailService.sendPasswordResetOtp(email, otp);
313
+ logger.info(`Password reset OTP sent to: ${email}`);
314
+
315
+ return res.status(200).json({ success: true, resetId });
316
+ } catch (err) {
317
+ logger.error('forgot-password error:', err);
318
+ return res.status(500).json({ error: 'Failed to send reset email.' });
319
+ }
320
+ },
321
+
322
+ /**
323
+ * GET /auth/google
324
+ * Initiates the Google OAuth 2.0 redirect flow via Passport.
325
+ * No session created — stateless JWT only.
326
+ */
327
+ redirectToGoogle(req, res, next) {
328
+ return passport.authenticate('google', {
329
+ scope: ['profile', 'email'],
330
+ session: false,
331
+ })(req, res, next);
332
+ },
333
+
334
+ /**
335
+ * GET /auth/google/callback
336
+ * Called by Google after user grants/denies access.
337
+ * Passport has already verified the code and populated req.user.
338
+ * Generates a JWT, sets an httpOnly cookie, then redirects to the frontend
339
+ * /auth/callback page which persists the token in localStorage.
340
+ */
341
+ handleGoogleCallback(req, res) {
342
+ if (!req.user) {
343
+ logger.warn('Google OAuth callback reached without req.user');
344
+ const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3001';
345
+ return res.redirect(`${frontendUrl}/auth/callback?error=auth_failed`);
346
+ }
347
+
348
+ const user = req.user;
349
+
350
+ // Fire-and-forget activity tracking (non-blocking)
351
+ UserModel.updateLastSeen(user.id).catch((e) => logger.error('updateLastSeen error:', e));
352
+ UserModel.trackActivity({
353
+ userId: String(user.id),
354
+ action: 'login',
355
+ data: { method: 'google_oauth', email: user.email },
356
+ }).catch((e) => logger.error('trackActivity error:', e));
357
+
358
+ const token = signToken(user);
359
+ logger.info(`Google OAuth login: ${user.email}`);
360
+ setAuthCookie(res, token);
361
+
362
+ const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3001';
363
+ return res.redirect(`${frontendUrl}/auth/callback?token=${token}`);
364
+ },
365
+
366
+ /**
367
+ * POST /api/auth/reset-password
368
+ * Verify OTP and update password.
369
+ */
370
+ async resetPassword(req, res) {
371
+ const { resetId, otp, newPassword } = req.body;
372
+ try {
373
+ const record = dbGet('SELECT * FROM password_resets WHERE id = ?', [resetId]);
374
+ if (!record) return res.status(400).json({ error: 'Reset session expired. Please request again.' });
375
+
376
+ if (new Date(record.otp_expires_at) < new Date()) {
377
+ dbRun('DELETE FROM password_resets WHERE id = ?', [resetId]);
378
+ return res.status(400).json({ error: 'OTP expired. Please request a new one.' });
379
+ }
380
+
381
+ if (record.otp_attempts >= MAX_OTP_ATTEMPTS) {
382
+ dbRun('DELETE FROM password_resets WHERE id = ?', [resetId]);
383
+ return res.status(400).json({ error: 'Too many failed attempts. Please request a new reset.' });
384
+ }
385
+
386
+ if (record.otp !== otp) {
387
+ dbRun('UPDATE password_resets SET otp_attempts = otp_attempts + 1 WHERE id = ?', [resetId]);
388
+ const remaining = MAX_OTP_ATTEMPTS - (record.otp_attempts + 1);
389
+ return res.status(400).json({ error: `Incorrect code. ${remaining} attempt(s) remaining.` });
390
+ }
391
+
392
+ // Update user password
393
+ const newHash = await hashPassword(newPassword);
394
+ const db = getDb();
395
+ db.prepare(`UPDATE users SET password_hash = ?, updated_at = datetime('now') WHERE email = ?`).run(newHash, record.email);
396
+ dbRun('DELETE FROM password_resets WHERE id = ?', [resetId]);
397
+
398
+ logger.info(`Password reset successful: ${record.email}`);
399
+ return res.status(200).json({ success: true, message: 'Password updated successfully.' });
400
+ } catch (err) {
401
+ logger.error('reset-password error:', err);
402
+ return res.status(500).json({ error: 'Internal server error' });
403
+ }
404
+ },
405
+ };
406
+
407
+ module.exports = AuthController;
src/controllers/session.controller.js ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const SessionModel = require('../models/session.model');
4
+ const ProductModel = require('../models/product.model');
5
+ const logger = require('../utils/logger');
6
+
7
+ const SessionController = {
8
+ /**
9
+ * GET /api/session/:id
10
+ * Returns full session state including responses and recommendations.
11
+ */
12
+ async getSession(req, res) {
13
+ try {
14
+ const session = await SessionModel.findById(req.params.id);
15
+ if (!session) return res.status(404).json({ error: 'Session not found' });
16
+
17
+ return res.status(200).json({
18
+ id: session.id,
19
+ channel: session.channel,
20
+ userId: session.user_id,
21
+ currentQuestionIndex: session.current_question_index,
22
+ responses: session.responses,
23
+ completed: session.completed,
24
+ recommendations: session.recommendations,
25
+ metadata: session.metadata,
26
+ createdAt: session.created_at,
27
+ updatedAt: session.updated_at,
28
+ expiresAt: session.expires_at,
29
+ });
30
+ } catch (err) {
31
+ logger.error('getSession error:', err);
32
+ return res.status(500).json({ error: 'Internal server error' });
33
+ }
34
+ },
35
+
36
+ /**
37
+ * POST /api/session/reset/:id
38
+ * Deletes the session so the user can start fresh.
39
+ */
40
+ async resetSession(req, res) {
41
+ try {
42
+ const session = await SessionModel.findById(req.params.id);
43
+ if (!session) return res.status(404).json({ error: 'Session not found' });
44
+
45
+ await SessionModel.delete(req.params.id);
46
+ logger.info(`Session manually reset: ${req.params.id}`);
47
+
48
+ return res.status(200).json({ success: true, message: 'Session reset successfully' });
49
+ } catch (err) {
50
+ logger.error('resetSession error:', err);
51
+ return res.status(500).json({ error: 'Internal server error' });
52
+ }
53
+ },
54
+
55
+ /**
56
+ * GET /api/products
57
+ * Returns product catalog with optional category filter.
58
+ */
59
+ async getProducts(req, res) {
60
+ try {
61
+ const { category, limit = 50, offset = 0 } = req.query;
62
+ const products = await ProductModel.findAll({ category, limit: parseInt(limit), offset: parseInt(offset) });
63
+ return res.status(200).json({ products, count: products.length });
64
+ } catch (err) {
65
+ logger.error('getProducts error:', err);
66
+ return res.status(500).json({ error: 'Internal server error' });
67
+ }
68
+ },
69
+
70
+ /**
71
+ * GET /api/health
72
+ * Health check — verifies app and DB are running.
73
+ */
74
+ async healthCheck(req, res) {
75
+ try {
76
+ // Quick DB probe
77
+ await ProductModel.findAll({ limit: 1 });
78
+ return res.status(200).json({
79
+ status: 'ok',
80
+ timestamp: new Date().toISOString(),
81
+ uptime: Math.floor(process.uptime()),
82
+ environment: process.env.NODE_ENV || 'development',
83
+ });
84
+ } catch (err) {
85
+ logger.error('Health check failed:', err);
86
+ return res.status(503).json({ status: 'error', message: err.message });
87
+ }
88
+ },
89
+ };
90
+
91
+ module.exports = SessionController;
src/controllers/webhook.controller.js ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const twilio = require('twilio');
4
+ const axios = require('axios');
5
+ const QuestionnaireService = require('../services/questionnaire.service');
6
+ const OfferService = require('../services/offer.service');
7
+ const SessionModel = require('../models/session.model');
8
+ const formatter = require('../utils/whatsappFormatter');
9
+ const logger = require('../utils/logger');
10
+
11
+ const WebhookController = {
12
+ // ─────────────────────────────────────────────
13
+ // WhatsApp (Twilio)
14
+ // ─────────────────────────────────────────────
15
+
16
+ /**
17
+ * Handle incoming WhatsApp messages via Twilio webhook.
18
+ * POST /api/webhook/whatsapp
19
+ */
20
+ async handleWhatsApp(req, res) {
21
+ const { From: from, Body: body, ProfileName: name } = req.body;
22
+ if (!from || !body) return res.status(200).send('<Response/>');
23
+
24
+ const userId = from.replace('whatsapp:', '');
25
+ const userInput = (body || '').trim();
26
+ const lang = 'en'; // TODO: detect from user locale
27
+
28
+ logger.info(`WhatsApp incoming [${userId}]: "${userInput}"`);
29
+
30
+ try {
31
+ const responseText = await WebhookController._processMessage(userId, 'whatsapp', userInput, lang, { name });
32
+ await WebhookController._sendWhatsApp(from, responseText);
33
+ } catch (err) {
34
+ logger.error('WhatsApp handler error:', err);
35
+ await WebhookController._sendWhatsApp(from, formatter.formatMessage('Sorry, something went wrong. Please try again.', '⚠️'));
36
+ }
37
+
38
+ // Always respond 200 to Twilio immediately
39
+ res.status(200).send('<Response/>');
40
+ },
41
+
42
+ // ─────────────────────────────────────────────
43
+ // Instagram / Meta Messenger
44
+ // ─────────────────────────────────────────────
45
+
46
+ /**
47
+ * Handle Meta webhook verification challenge.
48
+ * GET /api/webhook/instagram
49
+ */
50
+ verifyInstagram(req, res) {
51
+ const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;
52
+
53
+ if (mode === 'subscribe' && token === process.env.META_VERIFY_TOKEN) {
54
+ logger.info('Instagram webhook verified');
55
+ return res.status(200).send(challenge);
56
+ }
57
+
58
+ res.status(403).json({ error: 'Verification failed' });
59
+ },
60
+
61
+ /**
62
+ * Handle incoming Instagram messages.
63
+ * POST /api/webhook/instagram
64
+ */
65
+ async handleInstagram(req, res) {
66
+ // Acknowledge immediately (Meta requires < 20s response)
67
+ res.status(200).json({ status: 'ok' });
68
+
69
+ const body = req.body;
70
+ if (body.object !== 'page') return;
71
+
72
+ for (const entry of body.entry || []) {
73
+ for (const event of entry.messaging || []) {
74
+ if (!event.message || event.message.is_echo) continue;
75
+
76
+ const userId = event.sender.id;
77
+ const userInput = (event.message.text || '').trim();
78
+ const lang = 'en';
79
+
80
+ logger.info(`Instagram incoming [${userId}]: "${userInput}"`);
81
+
82
+ try {
83
+ const responseText = await WebhookController._processMessage(userId, 'instagram', userInput, lang, {});
84
+ await WebhookController._sendInstagram(userId, responseText);
85
+ } catch (err) {
86
+ logger.error('Instagram handler error:', err);
87
+ await WebhookController._sendInstagram(userId, 'Sorry, something went wrong. Please try again.');
88
+ }
89
+ }
90
+ }
91
+ },
92
+
93
+ // ─────────────────────────────────────────────
94
+ // Web Chat
95
+ // ─────────────────────────────────────────────
96
+
97
+ /**
98
+ * Handle web chat messages.
99
+ * POST /api/webhook/web
100
+ */
101
+ async handleWeb(req, res) {
102
+ const { userId, message: userInput, sessionId, language: lang = 'en' } = req.body;
103
+
104
+ logger.info(`Web chat [${userId}]: "${userInput}"`);
105
+
106
+ try {
107
+ // If sessionId provided, check if it's valid
108
+ let session = null;
109
+ if (sessionId) {
110
+ session = await SessionModel.findById(sessionId);
111
+ if (session && session.user_id !== userId) session = null; // security check
112
+ }
113
+
114
+ const overrideSession = session;
115
+
116
+ const result = await WebhookController._processMessageFull(
117
+ userId, 'web', userInput, lang, {}, overrideSession
118
+ );
119
+
120
+ return res.status(200).json({
121
+ sessionId: result.sessionId,
122
+ response: result.text,
123
+ isComplete: result.isComplete,
124
+ offers: result.offers || null,
125
+ question: result.question || null,
126
+ questionNumber: result.questionNumber,
127
+ totalQuestions: result.totalQuestions,
128
+ });
129
+ } catch (err) {
130
+ logger.error('Web handler error:', err);
131
+ return res.status(500).json({ error: 'Internal server error' });
132
+ }
133
+ },
134
+
135
+ // ─────────────────────────────────────────────
136
+ // Shared Processing Logic
137
+ // ─────────────────────────────────────────────
138
+
139
+ /**
140
+ * Shared message processing — returns formatted text for channel delivery.
141
+ */
142
+ async _processMessage(userId, channel, userInput, lang, metadata) {
143
+ const result = await WebhookController._processMessageFull(userId, channel, userInput, lang, metadata);
144
+ return result.text;
145
+ },
146
+
147
+ async _processMessageFull(userId, channel, userInput, lang, metadata, existingSession = null) {
148
+ const lowerInput = userInput.toLowerCase();
149
+ const isStartCommand = /^(start|iniciar|hi|hello|olá|ola|hey)$/i.test(lowerInput);
150
+ const isResetCommand = /^(reset|restart|recomeçar|recomecar|new)$/i.test(lowerInput);
151
+
152
+ // Handle reset
153
+ if (isResetCommand) {
154
+ const current = existingSession || await SessionModel.findActiveByUserChannel(userId, channel);
155
+ if (current) await QuestionnaireService.resetSession(current.id);
156
+
157
+ const state = await QuestionnaireService.startOrResume(userId, channel, { ...metadata, language: lang });
158
+ const text = formatter.formatWelcome(lang);
159
+ return { sessionId: state.session.id, text, isComplete: false, question: state.question, questionNumber: 1, totalQuestions: state.totalQuestions };
160
+ }
161
+
162
+ // If no active session or start command, create/resume
163
+ if (isStartCommand || !existingSession) {
164
+ const state = await QuestionnaireService.startOrResume(userId, channel, { ...metadata, language: lang });
165
+
166
+ if (state.isComplete && state.recommendations) {
167
+ // Already completed — show offers again
168
+ const text = formatter.formatOffers(state.recommendations, lang);
169
+ return { sessionId: state.session.id, text, isComplete: true, offers: state.recommendations, questionNumber: state.questionNumber, totalQuestions: state.totalQuestions };
170
+ }
171
+
172
+ const text = isStartCommand
173
+ ? formatter.formatWelcome(lang) + '\n\n' + formatter.formatQuestion(state.question, state.questionNumber, state.totalQuestions, lang)
174
+ : formatter.formatQuestion(state.question, state.questionNumber, state.totalQuestions, lang);
175
+
176
+ return { sessionId: state.session.id, text, isComplete: false, question: state.question, questionNumber: state.questionNumber, totalQuestions: state.totalQuestions };
177
+ }
178
+
179
+ // Process answer for existing session
180
+ const result = await QuestionnaireService.processAnswer(existingSession.id, userInput);
181
+
182
+ if (result.invalidInput) {
183
+ const text = formatter.formatInvalidInput(result.optionCount, lang);
184
+ return { sessionId: existingSession.id, text, isComplete: false, question: result.question, questionNumber: result.questionNumber, totalQuestions: result.totalQuestions };
185
+ }
186
+
187
+ if (result.isComplete) {
188
+ // Generate recommendations
189
+ const offers = await OfferService.generate(existingSession.id, lang);
190
+ const text = formatter.formatOffers(offers, lang);
191
+ return { sessionId: existingSession.id, text, isComplete: true, offers, questionNumber: result.questionNumber, totalQuestions: result.totalQuestions };
192
+ }
193
+
194
+ const text = formatter.formatQuestion(result.question, result.questionNumber, result.totalQuestions, lang);
195
+ return { sessionId: existingSession.id, text, isComplete: false, question: result.question, questionNumber: result.questionNumber, totalQuestions: result.totalQuestions };
196
+ },
197
+
198
+ // ─────────────────────────────────────────────
199
+ // Channel Delivery
200
+ // ─────────────────────────────────────────────
201
+
202
+ async _sendWhatsApp(to, message) {
203
+ if (!process.env.TWILIO_ACCOUNT_SID || process.env.NODE_ENV === 'test') {
204
+ logger.info(`[MOCK WhatsApp -> ${to}]: ${message.substring(0, 80)}...`);
205
+ return;
206
+ }
207
+
208
+ const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
209
+ await client.messages.create({
210
+ from: process.env.TWILIO_WHATSAPP_FROM,
211
+ to,
212
+ body: message,
213
+ });
214
+ },
215
+
216
+ async _sendInstagram(recipientId, message) {
217
+ if (!process.env.META_PAGE_ACCESS_TOKEN || process.env.NODE_ENV === 'test') {
218
+ logger.info(`[MOCK Instagram -> ${recipientId}]: ${message.substring(0, 80)}...`);
219
+ return;
220
+ }
221
+
222
+ await axios.post(
223
+ `https://graph.facebook.com/v18.0/me/messages`,
224
+ {
225
+ recipient: { id: recipientId },
226
+ message: { text: message },
227
+ messaging_type: 'RESPONSE',
228
+ },
229
+ {
230
+ params: { access_token: process.env.META_PAGE_ACCESS_TOKEN },
231
+ timeout: 10000,
232
+ }
233
+ );
234
+ },
235
+ };
236
+
237
+ module.exports = WebhookController;
src/middleware/auth.js ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const jwt = require('jsonwebtoken');
5
+ const logger = require('../utils/logger');
6
+
7
+ const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret-change-in-production';
8
+
9
+ /**
10
+ * Require valid JWT — checks Authorization header OR smart_token cookie.
11
+ * Returns 401 JSON if missing or invalid (for API routes).
12
+ */
13
+ function requireAuth(req, res, next) {
14
+ const header = req.headers['authorization'];
15
+ const cookieToken = req.cookies && req.cookies.smart_token;
16
+ const token = (header && header.startsWith('Bearer ') ? header.slice(7) : null) || cookieToken;
17
+
18
+ if (!token) {
19
+ return res.status(401).json({ error: 'Authentication required' });
20
+ }
21
+ try {
22
+ req.user = jwt.verify(token, JWT_SECRET);
23
+ next();
24
+ } catch (err) {
25
+ return res.status(401).json({ error: 'Invalid or expired token' });
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Auth guard for HTML pages — redirects to /login.html if no valid token.
31
+ * Checks Authorization header OR smart_token cookie.
32
+ */
33
+ function requireAuthPage(req, res, next) {
34
+ const cookieToken = req.cookies && req.cookies.smart_token;
35
+ const header = req.headers['authorization'];
36
+ const token = (header && header.startsWith('Bearer ') ? header.slice(7) : null) || cookieToken;
37
+
38
+ if (!token) {
39
+ return res.redirect('/login.html');
40
+ }
41
+ try {
42
+ req.user = jwt.verify(token, JWT_SECRET);
43
+ next();
44
+ } catch (err) {
45
+ res.clearCookie('smart_token');
46
+ return res.redirect('/login.html');
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Optional JWT — attaches req.user if token present; never blocks.
52
+ */
53
+ function optionalAuth(req, res, next) {
54
+ const header = req.headers['authorization'];
55
+ if (header && header.startsWith('Bearer ')) {
56
+ try {
57
+ req.user = jwt.verify(header.slice(7), JWT_SECRET);
58
+ } catch {
59
+ // ignore invalid token in optional context
60
+ }
61
+ }
62
+ next();
63
+ }
64
+
65
+ /**
66
+ * API key authentication middleware for internal endpoints.
67
+ */
68
+ function apiKeyAuth(req, res, next) {
69
+ const apiKey = req.headers['x-api-key'] || req.query.api_key;
70
+
71
+ if (!apiKey || apiKey !== process.env.API_KEY) {
72
+ logger.warn(`Unauthorized request from ${req.ip} to ${req.path}`);
73
+ return res.status(401).json({ error: 'Unauthorized', message: 'Valid API key required' });
74
+ }
75
+
76
+ next();
77
+ }
78
+
79
+ /**
80
+ * Twilio webhook signature verification.
81
+ * Validates that incoming requests are genuinely from Twilio.
82
+ */
83
+ function verifyTwilioSignature(req, res, next) {
84
+ // Skip in test/development if no auth token is set
85
+ if (!process.env.TWILIO_AUTH_TOKEN || process.env.NODE_ENV === 'test') {
86
+ return next();
87
+ }
88
+
89
+ const twilioSignature = req.headers['x-twilio-signature'];
90
+ if (!twilioSignature) {
91
+ return res.status(403).json({ error: 'Missing Twilio signature' });
92
+ }
93
+
94
+ try {
95
+ const { validateRequest } = require('twilio');
96
+ const url = `${process.env.APP_URL}${req.originalUrl}`;
97
+ const isValid = validateRequest(process.env.TWILIO_AUTH_TOKEN, twilioSignature, url, req.body || {});
98
+
99
+ if (!isValid) {
100
+ logger.warn(`Invalid Twilio signature from ${req.ip}`);
101
+ return res.status(403).json({ error: 'Invalid Twilio signature' });
102
+ }
103
+
104
+ next();
105
+ } catch (err) {
106
+ logger.error('Twilio signature verification error:', err);
107
+ return res.status(403).json({ error: 'Signature verification failed' });
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Meta/Instagram webhook signature verification.
113
+ * Uses HMAC-SHA256 with APP_SECRET to validate X-Hub-Signature-256 header.
114
+ */
115
+ function verifyMetaSignature(req, res, next) {
116
+ if (!process.env.META_APP_SECRET || process.env.NODE_ENV === 'test') {
117
+ return next();
118
+ }
119
+
120
+ const signature = req.headers['x-hub-signature-256'];
121
+ if (!signature) {
122
+ return res.status(403).json({ error: 'Missing Meta signature' });
123
+ }
124
+
125
+ const rawBody = req.rawBody || JSON.stringify(req.body);
126
+ const expectedSig = 'sha256=' + crypto
127
+ .createHmac('sha256', process.env.META_APP_SECRET)
128
+ .update(rawBody)
129
+ .digest('hex');
130
+
131
+ if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSig))) {
132
+ logger.warn(`Invalid Meta signature from ${req.ip}`);
133
+ return res.status(403).json({ error: 'Invalid Meta signature' });
134
+ }
135
+
136
+ next();
137
+ }
138
+
139
+ /**
140
+ * Capture raw body for signature verification before JSON parsing.
141
+ */
142
+ function captureRawBody(req, res, next) {
143
+ let data = '';
144
+ req.on('data', (chunk) => { data += chunk; });
145
+ req.on('end', () => { req.rawBody = data; next(); });
146
+ }
147
+
148
+ module.exports = { apiKeyAuth, verifyTwilioSignature, verifyMetaSignature, captureRawBody, requireAuth, optionalAuth, requireAuthPage };
src/middleware/rateLimiter.js ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const rateLimit = require('express-rate-limit');
4
+ const logger = require('../utils/logger');
5
+
6
+ /**
7
+ * General API rate limiter: 100 requests per minute per IP.
8
+ */
9
+ const generalLimiter = rateLimit({
10
+ windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS || '60000'),
11
+ max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS || '100'),
12
+ standardHeaders: true,
13
+ legacyHeaders: false,
14
+ message: {
15
+ error: 'Too many requests',
16
+ message: 'Rate limit exceeded. Please try again later.',
17
+ retryAfter: 60,
18
+ },
19
+ handler(req, res, next, options) {
20
+ logger.warn(`Rate limit exceeded for IP: ${req.ip}`);
21
+ res.status(options.statusCode).json(options.message);
22
+ },
23
+ });
24
+
25
+ /**
26
+ * Stricter limiter for webhook endpoints: 200 req/min (higher volume expected).
27
+ */
28
+ const webhookLimiter = rateLimit({
29
+ windowMs: 60000,
30
+ max: 200,
31
+ standardHeaders: true,
32
+ legacyHeaders: false,
33
+ message: { error: 'Too many requests', message: 'Webhook rate limit exceeded.' },
34
+ });
35
+
36
+ module.exports = { generalLimiter, webhookLimiter };
src/middleware/validation.js ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const Joi = require('joi');
4
+
5
+ /**
6
+ * Generic Joi validation middleware factory.
7
+ * @param {Object} schema - Joi schema with optional { body, query, params } keys
8
+ */
9
+ function validate(schema) {
10
+ return (req, res, next) => {
11
+ const toValidate = {};
12
+ if (schema.body) toValidate.body = req.body;
13
+ if (schema.query) toValidate.query = req.query;
14
+ if (schema.params) toValidate.params = req.params;
15
+
16
+ const fullSchema = Joi.object(
17
+ Object.fromEntries(
18
+ Object.entries(toValidate).map(([key, val]) => [key, schema[key]])
19
+ )
20
+ );
21
+
22
+ const { error, value } = fullSchema.validate(toValidate, { abortEarly: false, stripUnknown: true });
23
+
24
+ if (error) {
25
+ return res.status(400).json({
26
+ error: 'Validation error',
27
+ details: error.details.map((d) => ({ field: d.path.join('.'), message: d.message })),
28
+ });
29
+ }
30
+
31
+ // Merge validated values back
32
+ if (value.body) req.body = value.body;
33
+ if (value.query) req.query = value.query;
34
+ if (value.params) req.params = value.params;
35
+
36
+ next();
37
+ };
38
+ }
39
+
40
+ // --- Schemas ---
41
+
42
+ const schemas = {
43
+ login: {
44
+ body: Joi.object({
45
+ email: Joi.string().email().required(),
46
+ password: Joi.string().min(1).max(128).required(),
47
+ }),
48
+ },
49
+
50
+ webMessage: {
51
+ body: Joi.object({
52
+ userId: Joi.string().max(255).required(),
53
+ message: Joi.string().max(1000).required(),
54
+ sessionId: Joi.string().uuid().optional().allow(null),
55
+ language: Joi.string().valid('en', 'pt').default('en'),
56
+ }),
57
+ },
58
+
59
+ sessionId: {
60
+ params: Joi.object({
61
+ id: Joi.string().uuid().required(),
62
+ }),
63
+ },
64
+
65
+ productFilter: {
66
+ query: Joi.object({
67
+ category: Joi.string().max(100).optional(),
68
+ limit: Joi.number().integer().min(1).max(100).default(50),
69
+ offset: Joi.number().integer().min(0).default(0),
70
+ }),
71
+ },
72
+
73
+ sendOtp: {
74
+ body: Joi.object({
75
+ name: Joi.string().min(2).max(100).required(),
76
+ email: Joi.string().email().required(),
77
+ password: Joi.string().min(8).max(128).required(),
78
+ }),
79
+ },
80
+
81
+ verifyOtp: {
82
+ body: Joi.object({
83
+ tempUserId: Joi.string().required(),
84
+ otp: Joi.string().length(6).pattern(/^\d+$/).required(),
85
+ }),
86
+ },
87
+
88
+ resendOtp: {
89
+ body: Joi.object({
90
+ tempUserId: Joi.string().required(),
91
+ }),
92
+ },
93
+
94
+ forgotPassword: {
95
+ body: Joi.object({
96
+ email: Joi.string().email().required(),
97
+ }),
98
+ },
99
+
100
+ resetPassword: {
101
+ body: Joi.object({
102
+ resetId: Joi.string().required(),
103
+ otp: Joi.string().length(6).pattern(/^\d+$/).required(),
104
+ newPassword: Joi.string().min(8).max(128).required(),
105
+ }),
106
+ },
107
+ };
108
+
109
+ module.exports = { validate, schemas };
src/models/product.model.js ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const { getDb, getDbType } = require('../config/database');
4
+
5
+ /**
6
+ * Product model — abstracts SQLite and PostgreSQL operations.
7
+ */
8
+ const ProductModel = {
9
+ /**
10
+ * Get all active products, optionally filtered by category.
11
+ */
12
+ async findAll({ category, limit = 100, offset = 0 } = {}) {
13
+ const db = getDb();
14
+
15
+ if (getDbType() === 'sqlite') {
16
+ let sql = 'SELECT * FROM products WHERE active = 1';
17
+ const params = [];
18
+ if (category) {
19
+ sql += ' AND category = ?';
20
+ params.push(category);
21
+ }
22
+ sql += ' ORDER BY price ASC LIMIT ? OFFSET ?';
23
+ params.push(limit, offset);
24
+ const rows = db.prepare(sql).all(...params);
25
+ return rows.map(parseProduct);
26
+ } else {
27
+ let sql = 'SELECT * FROM products WHERE active = true';
28
+ const params = [];
29
+ let i = 1;
30
+ if (category) {
31
+ sql += ` AND category = $${i++}`;
32
+ params.push(category);
33
+ }
34
+ sql += ` ORDER BY price ASC LIMIT $${i++} OFFSET $${i++}`;
35
+ params.push(limit, offset);
36
+ const { rows } = await db.query(sql, params);
37
+ return rows;
38
+ }
39
+ },
40
+
41
+ /**
42
+ * Find a product by ID.
43
+ */
44
+ async findById(id) {
45
+ const db = getDb();
46
+
47
+ if (getDbType() === 'sqlite') {
48
+ const row = db.prepare('SELECT * FROM products WHERE id = ? AND active = 1').get(id);
49
+ return row ? parseProduct(row) : null;
50
+ } else {
51
+ const { rows } = await db.query('SELECT * FROM products WHERE id = $1 AND active = true', [id]);
52
+ return rows[0] || null;
53
+ }
54
+ },
55
+
56
+ /**
57
+ * Create a new product.
58
+ */
59
+ async create(product) {
60
+ const db = getDb();
61
+ const { name, description, price, category, tags = [], features = [], images = [], stock = 100 } = product;
62
+
63
+ if (getDbType() === 'sqlite') {
64
+ const stmt = db.prepare(`
65
+ INSERT INTO products (name, description, price, category, tags, features, images, stock)
66
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
67
+ `);
68
+ const result = stmt.run(
69
+ name, description, price, category,
70
+ JSON.stringify(tags), JSON.stringify(features), JSON.stringify(images), stock
71
+ );
72
+ return { id: result.lastInsertRowid, ...product };
73
+ } else {
74
+ const { rows } = await db.query(
75
+ `INSERT INTO products (name, description, price, category, tags, features, images, stock)
76
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *`,
77
+ [name, description, price, category, JSON.stringify(tags), JSON.stringify(features), JSON.stringify(images), stock]
78
+ );
79
+ return rows[0];
80
+ }
81
+ },
82
+
83
+ /**
84
+ * Get all active products for recommendation engine (no pagination).
85
+ */
86
+ async findAllForRecommendation() {
87
+ const db = getDb();
88
+
89
+ if (getDbType() === 'sqlite') {
90
+ const rows = db.prepare('SELECT * FROM products WHERE active = 1 AND stock > 0').all();
91
+ return rows.map(parseProduct);
92
+ } else {
93
+ const { rows } = await db.query('SELECT * FROM products WHERE active = true AND stock > 0');
94
+ return rows;
95
+ }
96
+ },
97
+ };
98
+
99
+ /**
100
+ * Parse SQLite row (JSON fields stored as strings).
101
+ */
102
+ function parseProduct(row) {
103
+ return {
104
+ ...row,
105
+ tags: typeof row.tags === 'string' ? JSON.parse(row.tags) : row.tags,
106
+ features: typeof row.features === 'string' ? JSON.parse(row.features) : row.features,
107
+ images: typeof row.images === 'string' ? JSON.parse(row.images) : row.images,
108
+ active: row.active === 1 || row.active === true,
109
+ };
110
+ }
111
+
112
+ module.exports = ProductModel;
src/models/session.model.js ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const { getDb, getDbType } = require('../config/database');
4
+ const { v4: uuidv4 } = require('uuid');
5
+
6
+ const SESSION_TIMEOUT_MINUTES = parseInt(process.env.SESSION_TIMEOUT_MINUTES || '30');
7
+
8
+ /**
9
+ * Session model — manages conversation sessions across channels.
10
+ * Each session is isolated per user+channel combination.
11
+ */
12
+ const SessionModel = {
13
+ /**
14
+ * Create a new session for a user on a given channel.
15
+ */
16
+ async create({ userId, channel, metadata = {} }) {
17
+ const db = getDb();
18
+ const id = uuidv4();
19
+ const expiresAt = new Date(Date.now() + SESSION_TIMEOUT_MINUTES * 60 * 1000);
20
+
21
+ if (getDbType() === 'sqlite') {
22
+ db.prepare(`
23
+ INSERT INTO sessions (id, channel, user_id, responses, metadata, expires_at)
24
+ VALUES (?, ?, ?, ?, ?, ?)
25
+ `).run(id, channel, userId, '[]', JSON.stringify(metadata), expiresAt.toISOString());
26
+ } else {
27
+ await db.query(
28
+ `INSERT INTO sessions (id, channel, user_id, responses, metadata, expires_at)
29
+ VALUES ($1, $2, $3, $4, $5, $6)`,
30
+ [id, channel, userId, '[]', JSON.stringify(metadata), expiresAt]
31
+ );
32
+ }
33
+
34
+ return this.findById(id);
35
+ },
36
+
37
+ /**
38
+ * Find session by ID.
39
+ */
40
+ async findById(id) {
41
+ const db = getDb();
42
+
43
+ if (getDbType() === 'sqlite') {
44
+ const row = db.prepare('SELECT * FROM sessions WHERE id = ?').get(id);
45
+ return row ? parseSession(row) : null;
46
+ } else {
47
+ const { rows } = await db.query('SELECT * FROM sessions WHERE id = $1', [id]);
48
+ return rows[0] ? parseSession(rows[0]) : null;
49
+ }
50
+ },
51
+
52
+ /**
53
+ * Find the most recent active (non-expired) session for a user+channel.
54
+ */
55
+ async findActiveByUserChannel(userId, channel) {
56
+ const db = getDb();
57
+ const now = new Date().toISOString();
58
+
59
+ if (getDbType() === 'sqlite') {
60
+ const row = db.prepare(`
61
+ SELECT * FROM sessions
62
+ WHERE user_id = ? AND channel = ? AND expires_at > ?
63
+ ORDER BY created_at DESC LIMIT 1
64
+ `).get(userId, channel, now);
65
+ return row ? parseSession(row) : null;
66
+ } else {
67
+ const { rows } = await db.query(
68
+ `SELECT * FROM sessions
69
+ WHERE user_id = $1 AND channel = $2 AND expires_at > NOW()
70
+ ORDER BY created_at DESC LIMIT 1`,
71
+ [userId, channel]
72
+ );
73
+ return rows[0] ? parseSession(rows[0]) : null;
74
+ }
75
+ },
76
+
77
+ /**
78
+ * Update session state after each question answer.
79
+ */
80
+ async update(id, updates) {
81
+ const db = getDb();
82
+ const expiresAt = new Date(Date.now() + SESSION_TIMEOUT_MINUTES * 60 * 1000);
83
+
84
+ const fields = { ...updates, expires_at: expiresAt };
85
+
86
+ if (getDbType() === 'sqlite') {
87
+ const setClauses = [];
88
+ const values = [];
89
+
90
+ for (const [key, val] of Object.entries(fields)) {
91
+ const col = camelToSnake(key);
92
+ setClauses.push(`${col} = ?`);
93
+ values.push(toSQLiteValue(val));
94
+ }
95
+ values.push(id);
96
+
97
+ db.prepare(`UPDATE sessions SET ${setClauses.join(', ')}, updated_at = datetime('now') WHERE id = ?`).run(...values);
98
+ } else {
99
+ const setClauses = [];
100
+ const values = [];
101
+ let i = 1;
102
+
103
+ for (const [key, val] of Object.entries(fields)) {
104
+ const col = camelToSnake(key);
105
+ setClauses.push(`${col} = $${i++}`);
106
+ values.push(typeof val === 'object' && val !== null ? JSON.stringify(val) : val);
107
+ }
108
+ values.push(id);
109
+
110
+ await db.query(
111
+ `UPDATE sessions SET ${setClauses.join(', ')}, updated_at = NOW() WHERE id = $${i}`,
112
+ values
113
+ );
114
+ }
115
+
116
+ return this.findById(id);
117
+ },
118
+
119
+ /**
120
+ * Delete a session (used for reset).
121
+ */
122
+ async delete(id) {
123
+ const db = getDb();
124
+
125
+ if (getDbType() === 'sqlite') {
126
+ db.prepare('DELETE FROM sessions WHERE id = ?').run(id);
127
+ } else {
128
+ await db.query('DELETE FROM sessions WHERE id = $1', [id]);
129
+ }
130
+ },
131
+
132
+ /**
133
+ * Remove all expired sessions (called by cleanup cron job).
134
+ */
135
+ async deleteExpired() {
136
+ const db = getDb();
137
+ const now = new Date().toISOString();
138
+
139
+ if (getDbType() === 'sqlite') {
140
+ const result = db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(now);
141
+ return result.changes;
142
+ } else {
143
+ const { rowCount } = await db.query('DELETE FROM sessions WHERE expires_at < NOW()');
144
+ return rowCount;
145
+ }
146
+ },
147
+ };
148
+
149
+ /**
150
+ * Convert a JS value to a SQLite-compatible type.
151
+ * Booleans → integer, Date → ISO string, objects → JSON string.
152
+ */
153
+ function toSQLiteValue(val) {
154
+ if (val === null || val === undefined) return null;
155
+ if (typeof val === 'boolean') return val ? 1 : 0;
156
+ if (val instanceof Date) return val.toISOString();
157
+ if (typeof val === 'object') return JSON.stringify(val);
158
+ return val;
159
+ }
160
+
161
+ function parseSession(row) {
162
+ return {
163
+ ...row,
164
+ responses: typeof row.responses === 'string' ? JSON.parse(row.responses) : row.responses || [],
165
+ recommendations: row.recommendations
166
+ ? typeof row.recommendations === 'string'
167
+ ? JSON.parse(row.recommendations)
168
+ : row.recommendations
169
+ : null,
170
+ metadata: typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata || {},
171
+ completed: row.completed === 1 || row.completed === true,
172
+ };
173
+ }
174
+
175
+ function camelToSnake(str) {
176
+ return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
177
+ }
178
+
179
+ module.exports = SessionModel;
src/models/user.model.js ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const { getDb, getDbType } = require('../config/database');
5
+
6
+ /**
7
+ * User model — authentication and profile management.
8
+ * Passwords hashed with Node.js crypto.scrypt (no extra deps).
9
+ */
10
+ const UserModel = {
11
+ async create({ name, email, passwordHash }) {
12
+ const db = getDb();
13
+ if (getDbType() === 'sqlite') {
14
+ const stmt = db.prepare(
15
+ `INSERT INTO users (name, email, password_hash) VALUES (?, ?, ?)`
16
+ );
17
+ const result = stmt.run(name, email.toLowerCase(), passwordHash);
18
+ return this.findById(result.lastInsertRowid);
19
+ } else {
20
+ const { rows } = await db.query(
21
+ `INSERT INTO users (name, email, password_hash) VALUES ($1, $2, $3) RETURNING *`,
22
+ [name, email.toLowerCase(), passwordHash]
23
+ );
24
+ return rows[0];
25
+ }
26
+ },
27
+
28
+ async findById(id) {
29
+ const db = getDb();
30
+ if (getDbType() === 'sqlite') {
31
+ return db.prepare('SELECT * FROM users WHERE id = ?').get(id) || null;
32
+ } else {
33
+ const { rows } = await db.query('SELECT * FROM users WHERE id = $1', [id]);
34
+ return rows[0] || null;
35
+ }
36
+ },
37
+
38
+ async findByEmail(email) {
39
+ const db = getDb();
40
+ const e = email.toLowerCase();
41
+ if (getDbType() === 'sqlite') {
42
+ return db.prepare('SELECT * FROM users WHERE email = ?').get(e) || null;
43
+ } else {
44
+ const { rows } = await db.query('SELECT * FROM users WHERE email = $1', [e]);
45
+ return rows[0] || null;
46
+ }
47
+ },
48
+
49
+ async updateLastSeen(id) {
50
+ const db = getDb();
51
+ if (getDbType() === 'sqlite') {
52
+ db.prepare(`UPDATE users SET last_seen_at = datetime('now') WHERE id = ?`).run(id);
53
+ } else {
54
+ await db.query(`UPDATE users SET last_seen_at = NOW() WHERE id = $1`, [id]);
55
+ }
56
+ },
57
+
58
+ async trackActivity({ userId, sessionId, action, category, data = {} }) {
59
+ const db = getDb();
60
+ if (getDbType() === 'sqlite') {
61
+ db.prepare(
62
+ `INSERT INTO user_activity (user_id, session_id, action, category, data) VALUES (?, ?, ?, ?, ?)`
63
+ ).run(userId, sessionId || null, action, category || null, JSON.stringify(data));
64
+ } else {
65
+ await db.query(
66
+ `INSERT INTO user_activity (user_id, session_id, action, category, data) VALUES ($1,$2,$3,$4,$5)`,
67
+ [userId, sessionId || null, action, category || null, JSON.stringify(data)]
68
+ );
69
+ }
70
+ },
71
+
72
+ /**
73
+ * Find a user by their Google OAuth ID via the google_users join table.
74
+ * Returns the full users row, or null if not found.
75
+ */
76
+ async findByGoogleId(googleId) {
77
+ const db = getDb();
78
+ if (getDbType() === 'sqlite') {
79
+ const link = db.prepare('SELECT user_id FROM google_users WHERE google_uid = ?').get(googleId);
80
+ if (!link) return null;
81
+ return db.prepare('SELECT * FROM users WHERE id = ?').get(link.user_id) || null;
82
+ }
83
+ return null;
84
+ },
85
+
86
+ /**
87
+ * Create a new user for Google OAuth sign-in (no usable password).
88
+ * Inserts into users then links via google_users table.
89
+ */
90
+ async createGoogleUser({ email, name, googleId }) {
91
+ // Random unusable password so NOT NULL constraint is satisfied
92
+ const passwordHash = await hashPassword(crypto.randomUUID());
93
+ const user = await this.create({ name, email, passwordHash });
94
+ const db = getDb();
95
+ if (getDbType() === 'sqlite') {
96
+ db.prepare(
97
+ 'INSERT OR IGNORE INTO google_users (id, email, google_uid, name, user_id) VALUES (?, ?, ?, ?, ?)'
98
+ ).run(crypto.randomUUID(), email, googleId, name, user.id);
99
+ }
100
+ return user;
101
+ },
102
+
103
+ /**
104
+ * Link an existing email/password user to a Google OAuth ID.
105
+ * Inserts into google_users if not already present.
106
+ */
107
+ async linkGoogleId(userId, email, name, googleId) {
108
+ const db = getDb();
109
+ if (getDbType() === 'sqlite') {
110
+ db.prepare(
111
+ 'INSERT OR IGNORE INTO google_users (id, email, google_uid, name, user_id) VALUES (?, ?, ?, ?, ?)'
112
+ ).run(crypto.randomUUID(), email, googleId, name, userId);
113
+ }
114
+ },
115
+
116
+ async getActivitySummary(userId) {
117
+ const db = getDb();
118
+ if (getDbType() === 'sqlite') {
119
+ const rows = db.prepare(
120
+ `SELECT action, category, data, created_at FROM user_activity WHERE user_id = ? ORDER BY created_at DESC LIMIT 50`
121
+ ).all(userId);
122
+ return rows.map((r) => ({ ...r, data: JSON.parse(r.data || '{}') }));
123
+ } else {
124
+ const { rows } = await db.query(
125
+ `SELECT action, category, data, created_at FROM user_activity WHERE user_id = $1 ORDER BY created_at DESC LIMIT 50`,
126
+ [userId]
127
+ );
128
+ return rows;
129
+ }
130
+ },
131
+ };
132
+
133
+ // ── Password utilities ───────────────────────────────────
134
+ async function hashPassword(password) {
135
+ return new Promise((resolve, reject) => {
136
+ const salt = crypto.randomBytes(16).toString('hex');
137
+ crypto.scrypt(password, salt, 64, (err, hash) => {
138
+ if (err) return reject(err);
139
+ resolve(`${salt}:${hash.toString('hex')}`);
140
+ });
141
+ });
142
+ }
143
+
144
+ async function verifyPassword(password, stored) {
145
+ return new Promise((resolve, reject) => {
146
+ const [salt, hash] = stored.split(':');
147
+ crypto.scrypt(password, salt, 64, (err, derivedKey) => {
148
+ if (err) return reject(err);
149
+ try {
150
+ resolve(crypto.timingSafeEqual(Buffer.from(hash, 'hex'), derivedKey));
151
+ } catch {
152
+ resolve(false);
153
+ }
154
+ });
155
+ });
156
+ }
157
+
158
+ module.exports = UserModel;
159
+ module.exports.hashPassword = hashPassword;
160
+ module.exports.verifyPassword = verifyPassword;
src/services/email.service.js ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const nodemailer = require('nodemailer');
4
+ const logger = require('../utils/logger');
5
+
6
+ let transporter = null;
7
+
8
+ function isEmailConfigured() {
9
+ const user = process.env.EMAIL_USER;
10
+ const pass = process.env.EMAIL_PASS;
11
+ return user && pass && !user.includes('your-gmail') && !pass.includes('your-gmail') && !pass.includes('your_');
12
+ }
13
+
14
+ function getTransporter() {
15
+ if (transporter) return transporter;
16
+
17
+ if (!isEmailConfigured()) {
18
+ return null;
19
+ }
20
+
21
+ transporter = nodemailer.createTransport({
22
+ service: 'gmail',
23
+ auth: {
24
+ user: process.env.EMAIL_USER,
25
+ pass: process.env.EMAIL_PASS,
26
+ },
27
+ });
28
+
29
+ return transporter;
30
+ }
31
+
32
+ const EmailService = {
33
+ /**
34
+ * Send a 6-digit OTP verification email.
35
+ */
36
+ async sendOtp(to, otp, name = '') {
37
+ // Dev mode: if email is not configured, log OTP to console and skip sending
38
+ if (!isEmailConfigured()) {
39
+ logger.warn(`[DEV] OTP email not sent — EMAIL_USER/EMAIL_PASS not configured.`);
40
+ logger.warn(`[DEV] OTP for ${to}: ${otp}`);
41
+ return { messageId: 'dev-mode-skipped' };
42
+ }
43
+
44
+ const transporter = getTransporter();
45
+ if (!transporter) {
46
+ logger.warn(`[DEV] OTP for ${to}: ${otp}`);
47
+ return { messageId: 'dev-mode-skipped' };
48
+ }
49
+
50
+ const from = process.env.EMAIL_FROM || `Smart Product Advisor <${process.env.EMAIL_USER}>`;
51
+ const greeting = name ? `Hi ${name},` : 'Hi,';
52
+
53
+ const mailOptions = {
54
+ from,
55
+ to,
56
+ subject: 'Your verification code — Smart Product Advisor',
57
+ html: `
58
+ <div style="font-family:'Helvetica Neue',Arial,sans-serif;max-width:480px;margin:0 auto;background:#0a0b0f;color:#f0f2ff;border-radius:16px;overflow:hidden;">
59
+ <div style="background:linear-gradient(135deg,#6366f1,#7c3aed);padding:32px 40px;">
60
+ <div style="font-size:22px;font-weight:800;letter-spacing:-0.02em;">✦ Smart Product Advisor</div>
61
+ </div>
62
+ <div style="padding:40px;">
63
+ <p style="margin:0 0 8px;font-size:14px;color:#9ca3af;">${greeting}</p>
64
+ <h2 style="margin:0 0 24px;font-size:22px;font-weight:700;">Your verification code</h2>
65
+ <div style="background:#1e2130;border:1px solid rgba(99,102,241,0.3);border-radius:12px;padding:28px;text-align:center;margin:0 0 24px;">
66
+ <div style="font-size:42px;font-weight:900;letter-spacing:12px;color:#818cf8;">${otp}</div>
67
+ <div style="font-size:12px;color:#6b7280;margin-top:10px;">Expires in 10 minutes</div>
68
+ </div>
69
+ <p style="font-size:13px;color:#6b7280;line-height:1.6;margin:0;">
70
+ Enter this code on the verification page to complete your sign-up.<br/>
71
+ If you didn't request this, you can safely ignore this email.
72
+ </p>
73
+ </div>
74
+ <div style="padding:20px 40px;border-top:1px solid rgba(255,255,255,0.06);font-size:11px;color:#4b5563;">
75
+ Smart Product Advisor — AI-powered recommendations
76
+ </div>
77
+ </div>
78
+ `,
79
+ text: `${greeting}\n\nYour verification code is: ${otp}\n\nThis code expires in 10 minutes.\n\nIf you didn't request this, ignore this email.`,
80
+ };
81
+
82
+ const info = await getTransporter().sendMail(mailOptions);
83
+ logger.info(`OTP email sent to ${to} (messageId: ${info.messageId})`);
84
+ return info;
85
+ },
86
+
87
+ /**
88
+ * Send a password reset OTP email.
89
+ */
90
+ async sendPasswordResetOtp(to, otp) {
91
+ if (!isEmailConfigured()) {
92
+ logger.warn(`[DEV] Password reset OTP for ${to}: ${otp}`);
93
+ return { messageId: 'dev-mode-skipped' };
94
+ }
95
+
96
+ const transporter = getTransporter();
97
+ if (!transporter) {
98
+ logger.warn(`[DEV] Password reset OTP for ${to}: ${otp}`);
99
+ return { messageId: 'dev-mode-skipped' };
100
+ }
101
+
102
+ const from = process.env.EMAIL_FROM || `Smart Product Advisor <${process.env.EMAIL_USER}>`;
103
+
104
+ const mailOptions = {
105
+ from,
106
+ to,
107
+ subject: 'Reset your password — Smart Product Advisor',
108
+ html: `
109
+ <div style="font-family:'Helvetica Neue',Arial,sans-serif;max-width:480px;margin:0 auto;background:#0a0b0f;color:#f0f2ff;border-radius:16px;overflow:hidden;">
110
+ <div style="background:linear-gradient(135deg,#6366f1,#7c3aed);padding:32px 40px;">
111
+ <div style="font-size:22px;font-weight:800;letter-spacing:-0.02em;">✦ Smart Product Advisor</div>
112
+ </div>
113
+ <div style="padding:40px;">
114
+ <h2 style="margin:0 0 24px;font-size:22px;font-weight:700;">Reset your password</h2>
115
+ <p style="font-size:14px;color:#9ca3af;margin:0 0 20px;">Use this code to reset your password:</p>
116
+ <div style="background:#1e2130;border:1px solid rgba(244,63,94,0.3);border-radius:12px;padding:28px;text-align:center;margin:0 0 24px;">
117
+ <div style="font-size:42px;font-weight:900;letter-spacing:12px;color:#fb7185;">${otp}</div>
118
+ <div style="font-size:12px;color:#6b7280;margin-top:10px;">Expires in 10 minutes</div>
119
+ </div>
120
+ <p style="font-size:13px;color:#6b7280;line-height:1.6;margin:0;">
121
+ If you didn't request a password reset, your account is safe — ignore this email.
122
+ </p>
123
+ </div>
124
+ <div style="padding:20px 40px;border-top:1px solid rgba(255,255,255,0.06);font-size:11px;color:#4b5563;">
125
+ Smart Product Advisor — AI-powered recommendations
126
+ </div>
127
+ </div>
128
+ `,
129
+ text: `Your password reset code is: ${otp}\n\nThis code expires in 10 minutes.\n\nIf you didn't request this, ignore this email.`,
130
+ };
131
+
132
+ const info = await getTransporter().sendMail(mailOptions);
133
+ logger.info(`Password reset OTP sent to ${to}`);
134
+ return info;
135
+ },
136
+ };
137
+
138
+ module.exports = EmailService;
src/services/offer.service.js ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const RecommendationService = require('./recommendation.service');
4
+ const SessionModel = require('../models/session.model');
5
+ const logger = require('../utils/logger');
6
+
7
+ /**
8
+ * Offer Service — generates 3-tier recommendations and persists them to the session.
9
+ *
10
+ * Tiers:
11
+ * Basic: top 1-2 products with >= 50% score match
12
+ * Intermediate: top 3-4 products with contextual reasoning
13
+ * Premium: best match (>= 85%) + optional bundle with 10% discount
14
+ */
15
+ const TIER_THRESHOLDS = {
16
+ basic: 50,
17
+ premium: 85,
18
+ };
19
+
20
+ const BUNDLE_DISCOUNT_PERCENT = 10;
21
+
22
+ const ACCESSORIES = {
23
+ en: ['Premium carry case', '3-year extended warranty', 'Extra cable set', 'Audio adapter kit'],
24
+ pt: ['Estojo de transporte premium', 'Garantia estendida 3 anos', 'Kit de cabos extras', 'Kit adaptador de áudio'],
25
+ };
26
+
27
+ const OfferService = {
28
+ /**
29
+ * Generate and store 3-tier offers for a completed session.
30
+ * @param {string} sessionId
31
+ * @param {string} lang - 'en' | 'pt'
32
+ * @returns {Object} { basic, intermediate, premium }
33
+ */
34
+ async generate(sessionId, lang = 'en') {
35
+ const session = await SessionModel.findById(sessionId);
36
+ if (!session) throw new Error(`Session not found: ${sessionId}`);
37
+
38
+ const scored = await RecommendationService.score(session.responses);
39
+ const context = RecommendationService.buildContext(session.responses);
40
+
41
+ // Track used product IDs across tiers so no product appears in more than one tier
42
+ const usedIds = new Set();
43
+
44
+ const basic = this.buildBasicTier(scored, lang, usedIds);
45
+ basic.forEach((p) => usedIds.add(p.id));
46
+
47
+ const intermediate = this.buildIntermediateTier(scored, context, lang, usedIds);
48
+ intermediate.forEach((p) => usedIds.add(p.id));
49
+
50
+ const premium = this.buildPremiumTier(scored, context, lang, usedIds);
51
+
52
+ const offers = { basic, intermediate, premium };
53
+
54
+ // Persist recommendations to session
55
+ await SessionModel.update(sessionId, { recommendations: offers, completed: true });
56
+
57
+ logger.info(`Offers generated for session ${sessionId}: basic=${offers.basic.length}, premium=${!!offers.premium}`);
58
+ return offers;
59
+ },
60
+
61
+ /**
62
+ * Basic tier: top 2 CHEAPEST products with score >= 50.
63
+ */
64
+ buildBasicTier(scored, lang, usedIds = new Set()) {
65
+ return scored
66
+ .filter((p) => p.score >= TIER_THRESHOLDS.basic)
67
+ .sort((a, b) => a.price - b.price) // cheapest first for basic
68
+ .slice(0, 2)
69
+ .map((p) => ({
70
+ id: p.id,
71
+ name: p.name,
72
+ description: p.description,
73
+ price: p.price,
74
+ score: p.score,
75
+ tags: p.tags,
76
+ features: p.features,
77
+ images: p.images,
78
+ }));
79
+ },
80
+
81
+ /**
82
+ * Intermediate tier: top 4 products by score, excluding Basic products.
83
+ */
84
+ buildIntermediateTier(scored, context, lang, usedIds = new Set()) {
85
+ const top = scored
86
+ .filter((p) => p.score >= TIER_THRESHOLDS.basic && !usedIds.has(p.id))
87
+ .slice(0, 4);
88
+
89
+ return top.map((p) => ({
90
+ id: p.id,
91
+ name: p.name,
92
+ description: p.description,
93
+ price: p.price,
94
+ score: p.score,
95
+ tags: p.tags,
96
+ features: p.features,
97
+ images: p.images,
98
+ reason: RecommendationService.generateReason(p, context, lang),
99
+ }));
100
+ },
101
+
102
+ /**
103
+ * Premium tier: highest scorer not in Basic or Intermediate + bundle suggestion.
104
+ * Returns null if no eligible product exists.
105
+ */
106
+ buildPremiumTier(scored, context, lang, usedIds = new Set()) {
107
+ const best = scored.find((p) => !usedIds.has(p.id));
108
+ if (!best) return null;
109
+
110
+ // If no product is ≥85%, still recommend best available but flag it
111
+ const isHighConfidence = best.score >= TIER_THRESHOLDS.premium;
112
+
113
+ const accessories = ACCESSORIES[lang] || ACCESSORIES.en;
114
+ const bundleItems = accessories.slice(0, 2);
115
+
116
+ const bundleBasePrice = best.price;
117
+ const accessoryValue = bundleBasePrice * 0.3; // accessories ~30% of product value
118
+ const bundleTotal = bundleBasePrice + accessoryValue;
119
+ const discountedTotal = parseFloat((bundleTotal * (1 - BUNDLE_DISCOUNT_PERCENT / 100)).toFixed(2));
120
+
121
+ const premium = {
122
+ product: {
123
+ id: best.id,
124
+ name: best.name,
125
+ description: best.description,
126
+ price: best.price,
127
+ score: best.score,
128
+ tags: best.tags,
129
+ features: best.features,
130
+ images: best.images,
131
+ reason: RecommendationService.generateReason(best, context, lang),
132
+ isHighConfidence,
133
+ },
134
+ };
135
+
136
+ // Only add bundle if user wants it OR score is high-confidence
137
+ if (context.wantsBundle || isHighConfidence) {
138
+ premium.bundle = {
139
+ items: bundleItems,
140
+ originalPrice: parseFloat(bundleTotal.toFixed(2)),
141
+ discountPercent: BUNDLE_DISCOUNT_PERCENT,
142
+ totalPrice: discountedTotal,
143
+ savings: parseFloat((bundleTotal - discountedTotal).toFixed(2)),
144
+ };
145
+ }
146
+
147
+ return premium;
148
+ },
149
+ };
150
+
151
+ module.exports = OfferService;
src/services/questionnaire.service.js ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const config = require('../config/questionnaire');
4
+ const SessionModel = require('../models/session.model');
5
+ const logger = require('../utils/logger');
6
+
7
+ const MAX_INVALID_ATTEMPTS = 3;
8
+
9
+ /**
10
+ * Questionnaire Service — manages the dynamic question flow and session state.
11
+ */
12
+ const QuestionnaireService = {
13
+ /**
14
+ * Get or create a session, return the current question.
15
+ * @param {string} userId - Platform-specific user ID
16
+ * @param {string} channel - 'whatsapp' | 'instagram' | 'web'
17
+ * @param {Object} metadata - Optional extra data (e.g., phone number, username)
18
+ * @returns {{ session, question, questionNumber, totalQuestions, isComplete }}
19
+ */
20
+ async startOrResume(userId, channel, metadata = {}) {
21
+ let session = await SessionModel.findActiveByUserChannel(userId, channel);
22
+
23
+ if (!session) {
24
+ session = await SessionModel.create({ userId, channel, metadata });
25
+ logger.info(`New session created: ${session.id} [${channel}] user=${userId}`);
26
+ } else {
27
+ logger.info(`Resumed session: ${session.id} [${channel}] user=${userId}`);
28
+ }
29
+
30
+ return this.getCurrentState(session);
31
+ },
32
+
33
+ /**
34
+ * Process a user's answer to the current question.
35
+ * Handles validation, re-prompting (max 3 attempts), and progression.
36
+ * @param {string} sessionId
37
+ * @param {string} userInput - Raw text input from the user
38
+ * @returns {{ session, nextQuestion, questionNumber, totalQuestions, isComplete, invalidInput, recommendations }}
39
+ */
40
+ async processAnswer(sessionId, userInput) {
41
+ const session = await SessionModel.findById(sessionId);
42
+ if (!session) throw new Error(`Session not found: ${sessionId}`);
43
+
44
+ if (session.completed) {
45
+ return { isComplete: true, session, recommendations: session.recommendations };
46
+ }
47
+
48
+ const flow = config.getFlow(session.responses);
49
+ const currentQ = flow[session.current_question_index];
50
+
51
+ if (!currentQ) {
52
+ return { isComplete: true, session, recommendations: session.recommendations };
53
+ }
54
+
55
+ // Validate and parse the answer
56
+ const parsed = this.parseAnswer(currentQ, userInput, session.metadata.language || 'en');
57
+
58
+ if (parsed.invalid) {
59
+ // Track invalid attempts in metadata
60
+ const attempts = (session.metadata.invalidAttempts || 0) + 1;
61
+
62
+ if (attempts >= MAX_INVALID_ATTEMPTS) {
63
+ // Skip optional question after max attempts, fail on required
64
+ if (currentQ.optional) {
65
+ return this.advanceQuestion(session, { questionId: currentQ.id, answerText: null, answerIndex: null, skipped: true });
66
+ }
67
+ // Reset attempt count but re-ask
68
+ await SessionModel.update(sessionId, { metadata: { ...session.metadata, invalidAttempts: 0 } });
69
+ } else {
70
+ await SessionModel.update(sessionId, { metadata: { ...session.metadata, invalidAttempts: attempts } });
71
+ }
72
+
73
+ return {
74
+ invalidInput: true,
75
+ optionCount: currentQ.options ? (currentQ.options.en || currentQ.options).length : 0,
76
+ attemptsRemaining: MAX_INVALID_ATTEMPTS - attempts,
77
+ session,
78
+ question: currentQ,
79
+ questionNumber: session.current_question_index + 1,
80
+ totalQuestions: flow.length,
81
+ };
82
+ }
83
+
84
+ // Valid input — advance
85
+ return this.advanceQuestion(session, {
86
+ questionId: currentQ.id,
87
+ answerText: parsed.text,
88
+ answerIndex: parsed.index,
89
+ skipped: parsed.skipped || false,
90
+ });
91
+ },
92
+
93
+ /**
94
+ * Advance session to next question after a valid answer.
95
+ */
96
+ async advanceQuestion(session, answerData) {
97
+ const newResponses = [...session.responses, answerData];
98
+
99
+ // Recompute flow with updated responses (branching may add questions)
100
+ const flow = config.getFlow(newResponses);
101
+ const nextIndex = session.current_question_index + 1;
102
+ const isComplete = nextIndex >= flow.length;
103
+
104
+ const updates = {
105
+ responses: newResponses,
106
+ current_question_index: nextIndex,
107
+ completed: isComplete,
108
+ metadata: { ...session.metadata, invalidAttempts: 0 },
109
+ };
110
+
111
+ if (isComplete) {
112
+ updates.completed = true;
113
+ }
114
+
115
+ const updatedSession = await SessionModel.update(session.id, updates);
116
+ const state = this.getCurrentState(updatedSession);
117
+
118
+ return { ...state, justAnswered: answerData };
119
+ },
120
+
121
+ /**
122
+ * Reset a session (user wants to start over).
123
+ */
124
+ async resetSession(sessionId) {
125
+ await SessionModel.delete(sessionId);
126
+ logger.info(`Session reset: ${sessionId}`);
127
+ },
128
+
129
+ /**
130
+ * Get current state summary for a session.
131
+ */
132
+ getCurrentState(session) {
133
+ const flow = config.getFlow(session.responses);
134
+ const currentQ = flow[session.current_question_index];
135
+ const isComplete = session.completed || session.current_question_index >= flow.length;
136
+
137
+ return {
138
+ session,
139
+ question: currentQ || null,
140
+ questionNumber: session.current_question_index + 1,
141
+ totalQuestions: flow.length,
142
+ isComplete,
143
+ recommendations: session.recommendations || null,
144
+ };
145
+ },
146
+
147
+ /**
148
+ * Parse and validate user input for a question.
149
+ * @returns {{ index, text, invalid, skipped }}
150
+ */
151
+ parseAnswer(question, input, lang = 'en') {
152
+ const trimmed = (input || '').trim();
153
+
154
+ if (question.optional && /^(skip|pular|no|não|nao)$/i.test(trimmed)) {
155
+ return { skipped: true, text: null, index: null, invalid: false };
156
+ }
157
+
158
+ if (question.type === 'text') {
159
+ if (!trimmed && !question.optional) return { invalid: true };
160
+ return { text: trimmed || null, index: null, invalid: false };
161
+ }
162
+
163
+ if (question.type === 'multiple_choice') {
164
+ const options = question.options[lang] || question.options.en;
165
+ const num = parseInt(trimmed);
166
+
167
+ if (!isNaN(num) && num >= 1 && num <= options.length) {
168
+ return { index: num - 1, text: options[num - 1], invalid: false };
169
+ }
170
+
171
+ // Accept full option text (case-insensitive)
172
+ const idx = options.findIndex((o) => o.toLowerCase() === trimmed.toLowerCase());
173
+ if (idx !== -1) {
174
+ return { index: idx, text: options[idx], invalid: false };
175
+ }
176
+
177
+ return { invalid: true };
178
+ }
179
+
180
+ return { text: trimmed, index: null, invalid: false };
181
+ },
182
+ };
183
+
184
+ module.exports = QuestionnaireService;
src/services/recommendation.service.js ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const ProductModel = require('../models/product.model');
4
+ const questionnaireConfig = require('../config/questionnaire');
5
+ const logger = require('../utils/logger');
6
+
7
+ /**
8
+ * Recommendation Engine — rule-based tag scoring with per-user differentiation.
9
+ *
10
+ * Scoring weights:
11
+ * Category match: 35 pts
12
+ * Budget compat: 25 pts
13
+ * Tag overlap: 25 pts (+10 bonus if overlap > 60%)
14
+ * Feature keywords: 15 pts (0 if user skipped free-text question)
15
+ *
16
+ * Penalties:
17
+ * Price > 30% over budget ceiling: -20 pts
18
+ */
19
+ const WEIGHTS = {
20
+ category: 35,
21
+ budget: 25,
22
+ tag: 25,
23
+ feature: 15,
24
+ };
25
+
26
+ /**
27
+ * Minimal suffix stemmer so "running" matches "runner", "run", etc.
28
+ */
29
+ function stem(word) {
30
+ return word
31
+ .replace(/ners?$/, 'n')
32
+ .replace(/ing$/, '')
33
+ .replace(/ers?$/, '')
34
+ .replace(/tion$/, '')
35
+ .replace(/s$/, '');
36
+ }
37
+
38
+ const RecommendationService = {
39
+ /**
40
+ * Generate scored product recommendations from session responses.
41
+ * @param {Array} responses - Array of { questionId, answerIndex, answerText, skipped }
42
+ * @returns {Array} products sorted by score descending
43
+ */
44
+ async score(responses) {
45
+ const context = this.buildContext(responses);
46
+ let products = await ProductModel.findAllForRecommendation();
47
+
48
+ // Filter to selected category when known — keeps recommendations relevant
49
+ if (context.category) {
50
+ const filtered = products.filter((p) => p.category === context.category);
51
+ if (filtered.length > 0) products = filtered;
52
+ }
53
+
54
+ logger.info(`Scoring ${products.length} products for context:`, { category: context.category, tags: context.tags.slice(0, 5) });
55
+
56
+ const scored = products.map((product) => ({
57
+ ...product,
58
+ score: this.calculateMatchScore(product, context),
59
+ }));
60
+
61
+ return scored.sort((a, b) => b.score - a.score);
62
+ },
63
+
64
+ /**
65
+ * Build a scoring context from user responses.
66
+ * Extracts: budget range, collected tags, text keywords, category.
67
+ */
68
+ buildContext(responses) {
69
+ const CATEGORY_MAP = ['electronics', 'fashion', 'home', 'health', 'entertainment', 'grocery'];
70
+ const context = {
71
+ tags: new Set(),
72
+ budgetMin: 0,
73
+ budgetMax: Infinity,
74
+ keywords: [],
75
+ wantsBundle: false,
76
+ category: null,
77
+ hasFreetextResponse: false,
78
+ };
79
+
80
+ for (const response of responses) {
81
+ if (response.skipped) continue;
82
+
83
+ const question = questionnaireConfig.questions.find((q) => q.id === response.questionId);
84
+ if (!question) continue;
85
+
86
+ // Collect tags from option selection
87
+ if (response.answerIndex !== null && question.tags) {
88
+ const tagList = question.tags[response.answerIndex] || [];
89
+ tagList.forEach((t) => context.tags.add(t));
90
+ }
91
+
92
+ // Extract primary category from q_category answer
93
+ if (question.id === 'q_category' && response.answerIndex !== null) {
94
+ context.category = CATEGORY_MAP[response.answerIndex] || null;
95
+ }
96
+
97
+ // Extract budget range
98
+ if (question.id === 'q_budget' && response.answerIndex !== null && question.budgetRanges) {
99
+ const range = question.budgetRanges[response.answerIndex];
100
+ if (range) {
101
+ context.budgetMin = range.min;
102
+ context.budgetMax = range.max === Infinity ? Infinity : range.max;
103
+ }
104
+ }
105
+
106
+ // Bundle preference from q_bundle
107
+ if (question.id === 'q_bundle' && response.answerIndex === 0) {
108
+ context.wantsBundle = true;
109
+ }
110
+
111
+ // Free-text keyword extraction with stemming
112
+ if (question.type === 'text' && response.answerText) {
113
+ context.hasFreetextResponse = true;
114
+ const words = response.answerText.toLowerCase().split(/\s+/).filter((w) => w.length > 2);
115
+ context.keywords.push(...words.map(stem));
116
+ }
117
+ }
118
+
119
+ return {
120
+ tags: [...context.tags],
121
+ budgetMin: context.budgetMin,
122
+ budgetMax: context.budgetMax,
123
+ keywords: context.keywords,
124
+ wantsBundle: context.wantsBundle,
125
+ category: context.category,
126
+ hasFreetextResponse: context.hasFreetextResponse,
127
+ };
128
+ },
129
+
130
+ /**
131
+ * Score a single product against the user context (0-100).
132
+ */
133
+ calculateMatchScore(product, context) {
134
+ let score = 0;
135
+
136
+ // 1. Category match (35 pts)
137
+ if (context.category) {
138
+ if (product.category === context.category) {
139
+ score += WEIGHTS.category;
140
+ }
141
+ // No category match → 0 pts (category filter usually handles this already)
142
+ } else {
143
+ // No category expressed — award half as neutral
144
+ score += Math.round(WEIGHTS.category * 0.5);
145
+ }
146
+
147
+ // 2. Budget compatibility (25 pts) with penalty for expensive items
148
+ if (product.price >= context.budgetMin && product.price <= context.budgetMax) {
149
+ score += WEIGHTS.budget;
150
+ } else if (product.price < context.budgetMin) {
151
+ // Product is cheaper than the user's stated minimum — no budget points
152
+ } else if (context.budgetMax !== Infinity && product.price > context.budgetMax) {
153
+ const overflow = (product.price - context.budgetMax) / context.budgetMax;
154
+ if (overflow > 0.3) {
155
+ // More than 30% over budget ceiling — apply penalty
156
+ score -= 20;
157
+ } else if (overflow <= 0.2) {
158
+ // Partial credit for being within 20% over
159
+ score += Math.round(WEIGHTS.budget * (1 - overflow / 0.2));
160
+ }
161
+ // Between 20-30% over: no points, no penalty
162
+ }
163
+
164
+ // 3. Tag overlap (25 pts) with bonus for high overlap
165
+ if (context.tags.length > 0 && product.tags && product.tags.length > 0) {
166
+ const productTagSet = new Set(product.tags.map((t) => t.toLowerCase()));
167
+ const matchCount = context.tags.filter((t) => productTagSet.has(t.toLowerCase())).length;
168
+ const overlap = matchCount / context.tags.length;
169
+ score += Math.round(WEIGHTS.tag * Math.min(overlap, 1));
170
+ if (overlap > 0.6) {
171
+ score += 10; // bonus for strong tag alignment
172
+ }
173
+ } else if (context.tags.length === 0) {
174
+ score += Math.round(WEIGHTS.tag * 0.5);
175
+ }
176
+
177
+ // 4. Feature keyword match (15 pts) — 0 if user skipped free-text (q_specific)
178
+ if (context.hasFreetextResponse && context.keywords.length > 0) {
179
+ if (product.features && product.features.length > 0) {
180
+ const featureText = product.features.join(' ').toLowerCase();
181
+ const nameText = (product.name + ' ' + (product.description || '')).toLowerCase();
182
+ const combined = featureText + ' ' + nameText;
183
+ const stemmedTokens = combined.split(/\s+/).map(stem);
184
+
185
+ const matchCount = context.keywords.filter((kw) => stemmedTokens.includes(stem(kw))).length;
186
+ const keywordScore = matchCount / context.keywords.length;
187
+ score += Math.round(WEIGHTS.feature * Math.min(keywordScore, 1));
188
+ }
189
+ }
190
+ // If no free-text response: fall back to category + tag scoring only (feature = 0)
191
+
192
+ return Math.min(Math.max(Math.round(score), 0), 100);
193
+ },
194
+
195
+ /**
196
+ * Generate reasoning text for a product recommendation.
197
+ */
198
+ generateReason(product, context, lang = 'en') {
199
+ const reasons = {
200
+ en: [],
201
+ pt: [],
202
+ };
203
+
204
+ if (product.tags.includes('budget') || product.tags.includes('value')) {
205
+ reasons.en.push('great value for money');
206
+ reasons.pt.push('ótimo custo-benefício');
207
+ }
208
+ if (product.tags.includes('premium') || product.tags.includes('audiophile')) {
209
+ reasons.en.push('premium audio quality');
210
+ reasons.pt.push('qualidade de áudio premium');
211
+ }
212
+ if (product.tags.includes('portable')) {
213
+ reasons.en.push('perfect for on-the-go');
214
+ reasons.pt.push('perfeito para usar em movimento');
215
+ }
216
+ if (product.tags.includes('professional')) {
217
+ reasons.en.push('ideal for professionals');
218
+ reasons.pt.push('ideal para profissionais');
219
+ }
220
+ if (product.features.includes('noise-canceling')) {
221
+ reasons.en.push('noise-canceling for focus');
222
+ reasons.pt.push('cancelamento de ruído para foco');
223
+ }
224
+ if (product.features.includes('waterproof') || product.tags.includes('sports')) {
225
+ reasons.en.push('built for active use');
226
+ reasons.pt.push('feito para uso ativo');
227
+ }
228
+
229
+ const list = reasons[lang] || reasons.en;
230
+ if (list.length === 0) return lang === 'pt' ? 'boa opção geral' : 'solid overall option';
231
+ return list.slice(0, 2).join(', ');
232
+ },
233
+ };
234
+
235
+ module.exports = RecommendationService;
src/utils/logger.js ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const winston = require('winston');
4
+ const path = require('path');
5
+ const fs = require('fs');
6
+
7
+ const { combine, timestamp, printf, colorize, errors } = winston.format;
8
+
9
+ const logFormat = printf(({ level, message, timestamp, stack, ...meta }) => {
10
+ const metaStr = Object.keys(meta).length ? ` ${JSON.stringify(meta)}` : '';
11
+ return `${timestamp} [${level}]: ${stack || message}${metaStr}`;
12
+ });
13
+
14
+ const transports = [
15
+ new winston.transports.Console({
16
+ format: combine(colorize(), timestamp({ format: 'HH:mm:ss' }), logFormat),
17
+ }),
18
+ ];
19
+
20
+ // Add file transports only when the logs directory is writable (not on serverless)
21
+ const logDir = path.resolve('./logs');
22
+ let fileLoggingEnabled = false;
23
+ try {
24
+ if (!fs.existsSync(logDir)) {
25
+ fs.mkdirSync(logDir, { recursive: true });
26
+ }
27
+ fileLoggingEnabled = true;
28
+ } catch (_) {
29
+ // Read-only filesystem (e.g. serverless) — log to console only
30
+ }
31
+
32
+ if (fileLoggingEnabled) {
33
+ transports.push(
34
+ new winston.transports.File({
35
+ filename: process.env.LOG_FILE || './logs/app.log',
36
+ maxsize: 10 * 1024 * 1024,
37
+ maxFiles: 5,
38
+ tailable: true,
39
+ }),
40
+ new winston.transports.File({
41
+ filename: './logs/error.log',
42
+ level: 'error',
43
+ maxsize: 10 * 1024 * 1024,
44
+ maxFiles: 3,
45
+ })
46
+ );
47
+ }
48
+
49
+ const logger = winston.createLogger({
50
+ level: process.env.LOG_LEVEL || 'info',
51
+ format: combine(
52
+ errors({ stack: true }),
53
+ timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
54
+ logFormat
55
+ ),
56
+ transports,
57
+ });
58
+
59
+ module.exports = logger;
src/utils/migrate.js ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ require('dotenv').config();
4
+ const { initDatabase } = require('../config/database');
5
+ const logger = require('./logger');
6
+
7
+ async function migrate() {
8
+ logger.info('Running database migration...');
9
+ await initDatabase();
10
+ logger.info('Migration complete.');
11
+ process.exit(0);
12
+ }
13
+
14
+ migrate().catch((err) => {
15
+ logger.error('Migration failed:', err);
16
+ process.exit(1);
17
+ });
src/utils/seed.js ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ require('dotenv').config();
4
+ const path = require('path');
5
+ const { initDatabase } = require('../config/database');
6
+ const ProductModel = require('../models/product.model');
7
+ const logger = require('./logger');
8
+
9
+ const sampleProducts = require(path.join(__dirname, '../../data/products.json'));
10
+
11
+ async function seed() {
12
+ logger.info('Seeding database with sample products...');
13
+ const { getDb, getDbType } = require('../config/database');
14
+ await initDatabase();
15
+
16
+ // Clear existing products before seeding to prevent duplicates on re-run
17
+ const db = getDb();
18
+ if (getDbType() === 'sqlite') {
19
+ db.prepare('DELETE FROM products').run();
20
+ } else {
21
+ await db.query('DELETE FROM products');
22
+ }
23
+ logger.info('Cleared existing products.');
24
+
25
+ for (const product of sampleProducts) {
26
+ try {
27
+ await ProductModel.create(product);
28
+ logger.info(`Seeded: ${product.name}`);
29
+ } catch (err) {
30
+ logger.error(`Failed to seed ${product.name}:`, err.message);
31
+ }
32
+ }
33
+
34
+ logger.info('Seeding complete.');
35
+ process.exit(0);
36
+ }
37
+
38
+ seed().catch((err) => {
39
+ logger.error('Seeding failed:', err);
40
+ process.exit(1);
41
+ });
src/utils/whatsappFormatter.js ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ /**
4
+ * Formats messages and recommendation offers for WhatsApp/Twilio.
5
+ * WhatsApp supports basic markdown: *bold*, _italic_, ~strikethrough~
6
+ */
7
+
8
+ /**
9
+ * Format a question for WhatsApp delivery.
10
+ * @param {Object} question - Question object from questionnaire config
11
+ * @param {number} questionNumber - Current question number (1-based)
12
+ * @param {number} totalQuestions - Total questions in flow
13
+ * @param {string} lang - Language code ('en' | 'pt')
14
+ * @returns {string} Formatted message body
15
+ */
16
+ function formatQuestion(question, questionNumber, totalQuestions, lang = 'en') {
17
+ const text = question.text[lang] || question.text.en;
18
+ const options = question.options ? question.options[lang] || question.options.en : null;
19
+
20
+ let message = `📋 *Question ${questionNumber}/${totalQuestions}*\n\n${text}`;
21
+
22
+ if (question.type === 'multiple_choice' && options) {
23
+ message += '\n\n';
24
+ options.forEach((option, idx) => {
25
+ message += `${idx + 1}. ${option}\n`;
26
+ });
27
+ message += '\n_Reply with the number of your choice_';
28
+ } else if (question.type === 'text') {
29
+ const placeholder = question.placeholder ? question.placeholder[lang] || question.placeholder.en : '';
30
+ if (placeholder) {
31
+ message += `\n\n_${placeholder}_`;
32
+ }
33
+ if (question.optional) {
34
+ message += '\n_(You can skip this by typing "skip")_';
35
+ }
36
+ }
37
+
38
+ return message;
39
+ }
40
+
41
+ /**
42
+ * Format 3-tier recommendation offers for WhatsApp.
43
+ * @param {Object} offers - { basic, intermediate, premium } tier objects
44
+ * @param {string} lang - Language code
45
+ * @returns {string} Formatted message
46
+ */
47
+ function formatOffers(offers, lang = 'en') {
48
+ const labels = {
49
+ en: {
50
+ header: '🎯 *Your Personalized Recommendations*',
51
+ basic: '🟢 *BASIC OPTION*',
52
+ intermediate: '🔵 *INTERMEDIATE OPTIONS*',
53
+ premium: '⭐ *PREMIUM RECOMMENDATION*',
54
+ price: 'Price',
55
+ score: 'Match',
56
+ bundle: '🎁 Bundle includes',
57
+ discount: 'Bundle discount',
58
+ contact: 'To order, reply with *ORDER [product name]* or visit our website.',
59
+ },
60
+ pt: {
61
+ header: '🎯 *Suas Recomendações Personalizadas*',
62
+ basic: '🟢 *OPÇÃO BÁSICA*',
63
+ intermediate: '🔵 *OPÇÕES INTERMEDIÁRIAS*',
64
+ premium: '⭐ *RECOMENDAÇÃO PREMIUM*',
65
+ price: 'Preço',
66
+ score: 'Compatibilidade',
67
+ bundle: '🎁 Pacote inclui',
68
+ discount: 'Desconto do pacote',
69
+ contact: 'Para pedir, responda com *PEDIR [nome do produto]* ou visite nosso site.',
70
+ },
71
+ };
72
+
73
+ const t = labels[lang] || labels.en;
74
+ let message = `${t.header}\n\n`;
75
+
76
+ // Basic tier
77
+ if (offers.basic && offers.basic.length > 0) {
78
+ message += `${t.basic}\n`;
79
+ offers.basic.forEach((p) => {
80
+ message += `• *${p.name}* - $${p.price}\n`;
81
+ if (p.description) message += ` ${p.description}\n`;
82
+ });
83
+ message += '\n';
84
+ }
85
+
86
+ // Intermediate tier
87
+ if (offers.intermediate && offers.intermediate.length > 0) {
88
+ message += `${t.intermediate}\n`;
89
+ offers.intermediate.forEach((p) => {
90
+ message += `• *${p.name}* - $${p.price} (${t.score}: ${p.score}%)\n`;
91
+ if (p.reason) message += ` _${p.reason}_\n`;
92
+ });
93
+ message += '\n';
94
+ }
95
+
96
+ // Premium tier
97
+ if (offers.premium) {
98
+ message += `${t.premium}\n`;
99
+ message += `🏆 *${offers.premium.product.name}* - $${offers.premium.product.price}\n`;
100
+ if (offers.premium.product.description) {
101
+ message += `${offers.premium.product.description}\n`;
102
+ }
103
+ if (offers.premium.bundle) {
104
+ message += `\n${t.bundle}:\n`;
105
+ offers.premium.bundle.items.forEach((item) => {
106
+ message += ` + ${item}\n`;
107
+ });
108
+ message += `💰 ${t.discount}: ${offers.premium.bundle.discountPercent}% OFF\n`;
109
+ message += `Total: $${offers.premium.bundle.totalPrice}\n`;
110
+ }
111
+ message += '\n';
112
+ }
113
+
114
+ message += `---\n${t.contact}`;
115
+ return message;
116
+ }
117
+
118
+ /**
119
+ * Format a simple text message with optional emoji prefix.
120
+ */
121
+ function formatMessage(text, emoji = '') {
122
+ return emoji ? `${emoji} ${text}` : text;
123
+ }
124
+
125
+ /**
126
+ * Format welcome/greeting message.
127
+ */
128
+ function formatWelcome(lang = 'en') {
129
+ const messages = {
130
+ en: `👋 *Welcome to Smart Product Advisor!*\n\nI'll help you find the perfect product by asking a few quick questions.\n\nThis will take about 2 minutes. Ready? Type *START* to begin!`,
131
+ pt: `👋 *Bem-vindo ao Smart Product Advisor!*\n\nVou ajudá-lo a encontrar o produto perfeito fazendo algumas perguntas rápidas.\n\nIsso levará cerca de 2 minutos. Pronto? Digite *INICIAR* para começar!`,
132
+ };
133
+ return messages[lang] || messages.en;
134
+ }
135
+
136
+ /**
137
+ * Format session timeout message.
138
+ */
139
+ function formatTimeout(lang = 'en') {
140
+ const messages = {
141
+ en: `⏰ Your session has expired due to inactivity.\n\nType *START* to begin a new product search!`,
142
+ pt: `⏰ Sua sessão expirou por inatividade.\n\nDigite *INICIAR* para começar uma nova busca de produto!`,
143
+ };
144
+ return messages[lang] || messages.en;
145
+ }
146
+
147
+ /**
148
+ * Format error/invalid input message.
149
+ */
150
+ function formatInvalidInput(optionCount, lang = 'en') {
151
+ const messages = {
152
+ en: `❌ Invalid choice. Please reply with a number between 1 and ${optionCount}.`,
153
+ pt: `❌ Escolha inválida. Por favor, responda com um número entre 1 e ${optionCount}.`,
154
+ };
155
+ return messages[lang] || messages.en;
156
+ }
157
+
158
+ module.exports = {
159
+ formatQuestion,
160
+ formatOffers,
161
+ formatMessage,
162
+ formatWelcome,
163
+ formatTimeout,
164
+ formatInvalidInput,
165
+ };