File size: 4,942 Bytes
6980b1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const database_1 = require("../db/database");
const router = express_1.default.Router();
// Get current tenant info
router.get('/me', async (req, res) => {
    try {
        const { tenantId } = req.user;
        const tenant = await database_1.database.get('SELECT id, name, subdomain, plan, settings, created_at FROM tenants WHERE id = ?', [tenantId]);
        if (!tenant) {
            return res.status(404).json({ error: 'Tenant not found' });
        }
        // Get domains
        const domains = await database_1.database.query('SELECT id, domain, verified, created_at FROM domains WHERE tenant_id = ?', [tenantId]);
        res.json({
            ...tenant,
            settings: JSON.parse(tenant.settings || '{}'),
            domains
        });
    }
    catch (error) {
        console.error('Get tenant error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});
// Update tenant settings
router.put('/me', async (req, res) => {
    try {
        const { tenantId } = req.user;
        const { name, settings } = req.body;
        const updates = [];
        const params = [];
        if (name) {
            updates.push('name = ?');
            params.push(name);
        }
        if (settings) {
            updates.push('settings = ?');
            params.push(JSON.stringify(settings));
        }
        if (updates.length === 0) {
            return res.status(400).json({ error: 'No valid fields to update' });
        }
        updates.push('updated_at = CURRENT_TIMESTAMP');
        params.push(tenantId);
        await database_1.database.run(`UPDATE tenants SET ${updates.join(', ')} WHERE id = ?`, params);
        res.json({ message: 'Tenant updated successfully' });
    }
    catch (error) {
        console.error('Update tenant error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});
// Add domain
router.post('/domains', async (req, res) => {
    try {
        const { tenantId } = req.user;
        const { domain } = req.body;
        if (!domain) {
            return res.status(400).json({ error: 'Domain is required' });
        }
        // Check if domain already exists
        const existingDomain = await database_1.database.get('SELECT id FROM domains WHERE domain = ?', [domain]);
        if (existingDomain) {
            return res.status(400).json({ error: 'Domain already exists' });
        }
        // Add domain
        const result = await database_1.database.run('INSERT INTO domains (tenant_id, domain) VALUES (?, ?)', [tenantId, domain]);
        res.status(201).json({
            id: result.lastID,
            domain,
            verified: false,
            message: 'Domain added successfully'
        });
    }
    catch (error) {
        console.error('Add domain error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});
// Remove domain
router.delete('/domains/:domainId', async (req, res) => {
    try {
        const { tenantId } = req.user;
        const { domainId } = req.params;
        await database_1.database.run('DELETE FROM domains WHERE id = ? AND tenant_id = ?', [domainId, tenantId]);
        res.json({ message: 'Domain removed successfully' });
    }
    catch (error) {
        console.error('Remove domain error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});
// Get tenant analytics summary
router.get('/analytics/summary', async (req, res) => {
    try {
        const { tenantId } = req.user;
        // Get basic stats
        const totalConversations = await database_1.database.get('SELECT COUNT(*) as count FROM chat_sessions WHERE tenant_id = ?', [tenantId]);
        const totalMessages = await database_1.database.get('SELECT COUNT(*) as count FROM chat_messages cm JOIN chat_sessions cs ON cm.session_id = cs.id WHERE cs.tenant_id = ?', [tenantId]);
        const avgRating = await database_1.database.get('SELECT AVG(rating) as avg FROM chat_sessions WHERE tenant_id = ? AND rating IS NOT NULL', [tenantId]);
        const knowledgeBaseCount = await database_1.database.get('SELECT COUNT(*) as count FROM knowledge_base WHERE tenant_id = ?', [tenantId]);
        res.json({
            totalConversations: totalConversations.count,
            totalMessages: totalMessages.count,
            averageRating: avgRating.avg || 0,
            knowledgeBaseDocuments: knowledgeBaseCount.count
        });
    }
    catch (error) {
        console.error('Get analytics summary error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});
exports.default = router;
//# sourceMappingURL=tenants.js.map