Compare commits

...

1 Commits

Author SHA1 Message Date
Flatlogic Bot
9e5a382aa8 Autosave: 20260312-030310 2026-03-12 03:03:10 +00:00
16 changed files with 775 additions and 567 deletions

49
admin.php Normal file
View File

@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/twilio.php';
if (!check_admin_auth()) {
header('Location: admin/login.php');
exit;
}
$pdo = db();
$tab = $_GET['tab'] ?? 'dashboard';
?>
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>后台管理 - Twilio Console</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.admin-layout { display: flex; min-height: 100vh; }
.sidebar { width: 250px; background: #212529; color: #fff; padding: 20px; flex-shrink: 0; }
.sidebar a { color: #adb5bd; display: block; padding: 12px 15px; text-decoration: none; border-radius: 4px; margin-bottom: 5px; transition: 0.3s; }
.sidebar a:hover, .sidebar a.active { color: #fff; background: #0d6efd; }
.content { flex: 1; padding: 30px; background: #f8f9fa; }
</style>
</head>
<body>
<div class="admin-layout">
<nav class="sidebar">
<h5 class="mb-4 text-center">管理控制台</h5>
<a class="<?= $tab === 'dashboard' ? 'active' : '' ?>" href="admin.php?tab=dashboard">仪表盘</a>
<a class="<?= $tab === 'twilio' ? 'active' : '' ?>" href="admin.php?tab=twilio">Twilio 配置</a>
<a class="<?= $tab === 'messages' ? 'active' : '' ?>" href="admin.php?tab=messages">消息日志</a>
<a class="<?= $tab === 'billing' ? 'active' : '' ?>" href="admin.php?tab=billing">计费报表</a>
<hr>
<a href="admin.php?logout=1" class="text-danger">退出登录</a>
</nav>
<main class="content">
<div class="card p-4 shadow-sm">
<h1 class="h4 mb-4">当前模块:<?= ucfirst($tab) ?></h1>
<p>系统已就绪,正在进行双向通信管理。</p>
</div>
</main>
</div>
</body>
</html>

33
admin/login.php Normal file
View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/bootstrap.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ($_POST['password'] === 'admin') {
session_start();
$_SESSION['user_type'] = 'admin';
header('Location: admin.php');
exit;
}
}
?>
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>后台登录</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light d-flex align-items-center justify-content-center" style="height:100vh;">
<div class="card p-4" style="width: 300px;">
<h4 class="mb-3">后台管理登录</h4>
<form method="post">
<div class="mb-3">
<label>密码</label>
<input type="password" name="password" class="form-control" required>
</div>
<button class="btn btn-primary w-100">登录后台</button>
</form>
</div>
</body>
</html>

51
api/add_contact.php Normal file
View File

@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/bootstrap.php';
header('Content-Type: application/json');
$name = trim($_POST['name'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$twilioId = (int)($_POST['twilio_number_id'] ?? 0);
if ($phone === '' || $twilioId <= 0) {
echo json_encode(['success' => false, 'error' => '号码与发送账号不能为空。']);
exit;
}
$pdo = db();
$pdo->beginTransaction();
try {
$stmt = $pdo->prepare("SELECT id FROM contacts WHERE phone = :phone");
$stmt->bindValue(':phone', $phone);
$stmt->execute();
$contactId = (int)($stmt->fetchColumn() ?: 0);
if ($contactId === 0) {
$stmt = $pdo->prepare("INSERT INTO contacts (name, phone) VALUES (:name, :phone)");
$stmt->bindValue(':name', $name !== '' ? $name : null);
$stmt->bindValue(':phone', $phone);
$stmt->execute();
$contactId = (int)$pdo->lastInsertId();
}
$stmt = $pdo->prepare("SELECT id FROM conversations WHERE contact_id = :cid AND twilio_number_id = :tid");
$stmt->bindValue(':cid', $contactId, PDO::PARAM_INT);
$stmt->bindValue(':tid', $twilioId, PDO::PARAM_INT);
$stmt->execute();
$conversationId = (int)($stmt->fetchColumn() ?: 0);
if ($conversationId === 0) {
$stmt = $pdo->prepare("INSERT INTO conversations (contact_id, twilio_number_id) VALUES (:cid, :tid)");
$stmt->bindValue(':cid', $contactId, PDO::PARAM_INT);
$stmt->bindValue(':tid', $twilioId, PDO::PARAM_INT);
$stmt->execute();
$conversationId = (int)$pdo->lastInsertId();
}
$pdo->commit();
echo json_encode(['success' => true, 'conversation_id' => $conversationId]);
} catch (Throwable $e) {
$pdo->rollBack();
echo json_encode(['success' => false, 'error' => '保存失败,请稍后再试。']);
}

32
api/conversations.php Normal file
View File

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/bootstrap.php';
header('Content-Type: application/json');
$twilioId = (int)($_GET['twilio_number_id'] ?? 0);
if ($twilioId <= 0) {
echo json_encode(['items' => []]);
exit;
}
$stmt = db()->prepare("
SELECT c.id, ct.name, ct.phone,
m.body AS last_message,
c.last_message_at AS last_time
FROM conversations c
JOIN contacts ct ON ct.id = c.contact_id
LEFT JOIN messages m ON m.id = (
SELECT id FROM messages
WHERE conversation_id = c.id
ORDER BY created_at DESC
LIMIT 1
)
WHERE c.twilio_number_id = :twilio
ORDER BY c.last_message_at DESC, c.created_at DESC
");
$stmt->bindValue(':twilio', $twilioId, PDO::PARAM_INT);
$stmt->execute();
$items = $stmt->fetchAll();
echo json_encode(['items' => $items]);

18
api/messages.php Normal file
View File

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/bootstrap.php';
header('Content-Type: application/json');
$conversationId = (int)($_GET['conversation_id'] ?? 0);
if ($conversationId <= 0) {
echo json_encode(['items' => []]);
exit;
}
$stmt = db()->prepare("SELECT id, direction, body, status, created_at FROM messages WHERE conversation_id = :cid ORDER BY created_at ASC");
$stmt->bindValue(':cid', $conversationId, PDO::PARAM_INT);
$stmt->execute();
$items = $stmt->fetchAll();
echo json_encode(['items' => $items]);

54
api/send_message.php Normal file
View File

@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/twilio.php';
header('Content-Type: application/json');
$payload = json_decode((string)file_get_contents('php://input'), true);
$conversationId = (int)($payload['conversation_id'] ?? 0);
$body = trim($payload['body'] ?? '');
if ($conversationId <= 0 || $body === '') {
echo json_encode(['success' => false, 'error' => '会话与内容不能为空。']);
exit;
}
$pdo = db();
$stmt = $pdo->prepare("
SELECT c.id, ct.phone, t.account_sid, t.auth_token, t.from_number, t.label, t.is_active
FROM conversations c
JOIN contacts ct ON ct.id = c.contact_id
JOIN twilio_numbers t ON t.id = c.twilio_number_id
WHERE c.id = :cid
");
$stmt->bindValue(':cid', $conversationId, PDO::PARAM_INT);
$stmt->execute();
$twilio = $stmt->fetch();
if (!$twilio) {
echo json_encode(['success' => false, 'error' => '找不到会话。']);
exit;
}
$status = 'stored';
if ((int)$twilio['is_active'] === 1 && $twilio['account_sid'] && $twilio['auth_token']) {
$sendResult = twilio_send_sms($twilio, $twilio['phone'], $body);
if (!empty($sendResult['success'])) {
$status = 'sent';
} else {
$status = 'failed';
}
}
$stmt = $pdo->prepare("INSERT INTO messages (conversation_id, direction, body, status) VALUES (:cid, 'outbound', :body, :status)");
$stmt->bindValue(':cid', $conversationId, PDO::PARAM_INT);
$stmt->bindValue(':body', $body);
$stmt->bindValue(':status', $status);
$stmt->execute();
$stmt = $pdo->prepare("UPDATE conversations SET last_message_at = NOW() WHERE id = :cid");
$stmt->bindValue(':cid', $conversationId, PDO::PARAM_INT);
$stmt->execute();
echo json_encode(['success' => true, 'status' => $status]);

69
api/twilio_webhook.php Normal file
View File

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/bootstrap.php';
header('Content-Type: text/xml');
$from = trim($_POST['From'] ?? '');
$to = trim($_POST['To'] ?? '');
$body = trim($_POST['Body'] ?? '');
if ($from === '' || $to === '' || $body === '') {
echo "<Response></Response>";
exit;
}
$pdo = db();
$stmt = $pdo->prepare("SELECT id FROM twilio_numbers WHERE from_number = :to LIMIT 1");
$stmt->bindValue(':to', $to);
$stmt->execute();
$twilioId = (int)($stmt->fetchColumn() ?: 0);
if ($twilioId === 0) {
echo "<Response></Response>";
exit;
}
$pdo->beginTransaction();
try {
$stmt = $pdo->prepare("SELECT id FROM contacts WHERE phone = :phone");
$stmt->bindValue(':phone', $from);
$stmt->execute();
$contactId = (int)($stmt->fetchColumn() ?: 0);
if ($contactId === 0) {
$stmt = $pdo->prepare("INSERT INTO contacts (phone) VALUES (:phone)");
$stmt->bindValue(':phone', $from);
$stmt->execute();
$contactId = (int)$pdo->lastInsertId();
}
$stmt = $pdo->prepare("SELECT id FROM conversations WHERE contact_id = :cid AND twilio_number_id = :tid");
$stmt->bindValue(':cid', $contactId, PDO::PARAM_INT);
$stmt->bindValue(':tid', $twilioId, PDO::PARAM_INT);
$stmt->execute();
$conversationId = (int)($stmt->fetchColumn() ?: 0);
if ($conversationId === 0) {
$stmt = $pdo->prepare("INSERT INTO conversations (contact_id, twilio_number_id) VALUES (:cid, :tid)");
$stmt->bindValue(':cid', $contactId, PDO::PARAM_INT);
$stmt->bindValue(':tid', $twilioId, PDO::PARAM_INT);
$stmt->execute();
$conversationId = (int)$pdo->lastInsertId();
}
$stmt = $pdo->prepare("INSERT INTO messages (conversation_id, direction, body, status) VALUES (:cid, 'inbound', :body, 'received')");
$stmt->bindValue(':cid', $conversationId, PDO::PARAM_INT);
$stmt->bindValue(':body', $body);
$stmt->execute();
$stmt = $pdo->prepare("UPDATE conversations SET last_message_at = NOW() WHERE id = :cid");
$stmt->bindValue(':cid', $conversationId, PDO::PARAM_INT);
$stmt->execute();
$pdo->commit();
} catch (Throwable $e) {
$pdo->rollBack();
}
echo "<Response></Response>";

View File

@ -1,403 +1,33 @@
body { /* WhatsApp-like theme */
background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab); :root {
background-size: 400% 400%; --whatsapp-green: #075E54;
animation: gradient 15s ease infinite; --whatsapp-bg: #e5ddd5;
color: #212529; --whatsapp-sidebar: #ffffff;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; --whatsapp-input: #f0f2f5;
font-size: 14px; --whatsapp-bubble-me: #dcf8c6;
margin: 0; --whatsapp-bubble-other: #ffffff;
min-height: 100vh;
} }
.main-wrapper { body, html { height: 100%; margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
width: 100%;
padding: 20px;
box-sizing: border-box;
position: relative;
z-index: 1;
}
@keyframes gradient { .whatsapp-app { display: flex; height: 100vh; overflow: hidden; background: white; }
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
.chat-container { .sidebar { width: 350px; background: var(--whatsapp-sidebar); border-right: 1px solid #ddd; display: flex; flex-direction: column; }
width: 100%; .sidebar-header { background: var(--whatsapp-input); padding: 15px; display: flex; align-items: center; }
max-width: 600px;
background: rgba(255, 255, 255, 0.85);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 20px;
display: flex;
flex-direction: column;
height: 85vh;
box-shadow: 0 20px 40px rgba(0,0,0,0.2);
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
overflow: hidden;
}
.chat-header { .chat-area { flex: 1; background: var(--whatsapp-bg); display: flex; flex-direction: column; }
padding: 1.5rem; .chat-header { background: var(--whatsapp-input); padding: 10px 20px; display: flex; align-items: center; border-left: 1px solid #ddd; }
border-bottom: 1px solid rgba(0, 0, 0, 0.05);
background: rgba(255, 255, 255, 0.5);
font-weight: 700;
font-size: 1.1rem;
display: flex;
justify-content: space-between;
align-items: center;
}
.chat-messages { .message-list { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; }
flex: 1; .bubble { background: var(--whatsapp-bubble-other); padding: 8px 12px; border-radius: 8px; margin-bottom: 5px; max-width: 60%; position: relative; font-size: 0.95rem; box-shadow: 0 1px 0.5px rgba(0,0,0,0.1); }
overflow-y: auto; .bubble.me { background: var(--whatsapp-bubble-me); align-self: flex-end; }
padding: 1.5rem;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
/* Custom Scrollbar */ .chat-input { background: var(--whatsapp-input); padding: 10px 20px; display: flex; align-items: center; gap: 15px; }
::-webkit-scrollbar { .chat-input input { border-radius: 20px; border: none; padding: 10px 15px; }
width: 6px;
}
::-webkit-scrollbar-track { /* Admin layout */
background: transparent; .admin-layout { display: flex; min-height: 100vh; }
} .admin-sidebar { width: 250px; background: #343a40; color: #fff; padding: 20px; }
.admin-sidebar a { color: #ccc; display: block; padding: 10px; text-decoration: none; border-bottom: 1px solid #444; }
::-webkit-scrollbar-thumb { .admin-sidebar a.active { color: #fff; background: #495057; }
background: rgba(255, 255, 255, 0.3); .admin-content { flex: 1; padding: 20px; background: #f8f9fa; }
border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5);
}
.message {
max-width: 85%;
padding: 0.85rem 1.1rem;
border-radius: 16px;
line-height: 1.5;
font-size: 0.95rem;
box-shadow: 0 4px 15px rgba(0,0,0,0.05);
animation: fadeIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px) scale(0.95); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
.message.visitor {
align-self: flex-end;
background: linear-gradient(135deg, #212529 0%, #343a40 100%);
color: #fff;
border-bottom-right-radius: 4px;
}
.message.bot {
align-self: flex-start;
background: #ffffff;
color: #212529;
border-bottom-left-radius: 4px;
}
.chat-input-area {
padding: 1.25rem;
background: rgba(255, 255, 255, 0.5);
border-top: 1px solid rgba(0, 0, 0, 0.05);
}
.chat-input-area form {
display: flex;
gap: 0.75rem;
}
.chat-input-area input {
flex: 1;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 12px;
padding: 0.75rem 1rem;
outline: none;
background: rgba(255, 255, 255, 0.9);
transition: all 0.3s ease;
}
.chat-input-area input:focus {
border-color: #23a6d5;
box-shadow: 0 0 0 3px rgba(35, 166, 213, 0.2);
}
.chat-input-area button {
background: #212529;
color: #fff;
border: none;
padding: 0.75rem 1.5rem;
border-radius: 12px;
cursor: pointer;
font-weight: 600;
transition: all 0.3s ease;
}
.chat-input-area button:hover {
background: #000;
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}
/* Background Animations */
.bg-animations {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 0;
overflow: hidden;
pointer-events: none;
}
.blob {
position: absolute;
width: 500px;
height: 500px;
background: rgba(255, 255, 255, 0.2);
border-radius: 50%;
filter: blur(80px);
animation: move 20s infinite alternate cubic-bezier(0.45, 0, 0.55, 1);
}
.blob-1 {
top: -10%;
left: -10%;
background: rgba(238, 119, 82, 0.4);
}
.blob-2 {
bottom: -10%;
right: -10%;
background: rgba(35, 166, 213, 0.4);
animation-delay: -7s;
width: 600px;
height: 600px;
}
.blob-3 {
top: 40%;
left: 30%;
background: rgba(231, 60, 126, 0.3);
animation-delay: -14s;
width: 450px;
height: 450px;
}
@keyframes move {
0% { transform: translate(0, 0) rotate(0deg) scale(1); }
33% { transform: translate(150px, 100px) rotate(120deg) scale(1.1); }
66% { transform: translate(-50px, 200px) rotate(240deg) scale(0.9); }
100% { transform: translate(0, 0) rotate(360deg) scale(1); }
}
.header-link {
font-size: 14px;
color: #fff;
text-decoration: none;
background: rgba(0, 0, 0, 0.2);
padding: 0.5rem 1rem;
border-radius: 8px;
transition: all 0.3s ease;
}
.header-link:hover {
background: rgba(0, 0, 0, 0.4);
text-decoration: none;
}
/* Admin Styles */
.admin-container {
max-width: 900px;
margin: 3rem auto;
padding: 2.5rem;
background: rgba(255, 255, 255, 0.85);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border-radius: 24px;
box-shadow: 0 20px 50px rgba(0,0,0,0.15);
border: 1px solid rgba(255, 255, 255, 0.4);
position: relative;
z-index: 1;
}
.admin-container h1 {
margin-top: 0;
color: #212529;
font-weight: 800;
}
.table {
width: 100%;
border-collapse: separate;
border-spacing: 0 8px;
margin-top: 1.5rem;
}
.table th {
background: transparent;
border: none;
padding: 1rem;
color: #6c757d;
font-weight: 600;
text-transform: uppercase;
font-size: 0.75rem;
letter-spacing: 1px;
}
.table td {
background: #fff;
padding: 1rem;
border: none;
}
.table tr td:first-child { border-radius: 12px 0 0 12px; }
.table tr td:last-child { border-radius: 0 12px 12px 0; }
.form-group {
margin-bottom: 1.25rem;
}
.form-group label {
display: block;
margin-bottom: 0.5rem;
font-weight: 600;
font-size: 0.9rem;
}
.form-control {
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 12px;
background: #fff;
transition: all 0.3s ease;
box-sizing: border-box;
}
.form-control:focus {
outline: none;
border-color: #23a6d5;
box-shadow: 0 0 0 3px rgba(35, 166, 213, 0.1);
}
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
}
.header-links {
display: flex;
gap: 1rem;
}
.admin-card {
background: rgba(255, 255, 255, 0.6);
padding: 2rem;
border-radius: 20px;
border: 1px solid rgba(255, 255, 255, 0.5);
margin-bottom: 2.5rem;
box-shadow: 0 10px 30px rgba(0,0,0,0.05);
}
.admin-card h3 {
margin-top: 0;
margin-bottom: 1.5rem;
font-weight: 700;
}
.btn-delete {
background: #dc3545;
color: white;
border: none;
padding: 0.25rem 0.5rem;
border-radius: 4px;
cursor: pointer;
}
.btn-add {
background: #212529;
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
margin-top: 1rem;
}
.btn-save {
background: #0088cc;
color: white;
border: none;
padding: 0.8rem 1.5rem;
border-radius: 12px;
cursor: pointer;
font-weight: 600;
width: 100%;
transition: all 0.3s ease;
}
.webhook-url {
font-size: 0.85em;
color: #555;
margin-top: 0.5rem;
}
.history-table-container {
overflow-x: auto;
background: rgba(255, 255, 255, 0.4);
padding: 1rem;
border-radius: 12px;
border: 1px solid rgba(255, 255, 255, 0.3);
}
.history-table {
width: 100%;
}
.history-table-time {
width: 15%;
white-space: nowrap;
font-size: 0.85em;
color: #555;
}
.history-table-user {
width: 35%;
background: rgba(255, 255, 255, 0.3);
border-radius: 8px;
padding: 8px;
}
.history-table-ai {
width: 50%;
background: rgba(255, 255, 255, 0.5);
border-radius: 8px;
padding: 8px;
}
.no-messages {
text-align: center;
color: #777;
}

View File

@ -1,39 +1,185 @@
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
const chatForm = document.getElementById('chat-form'); const app = document.getElementById('chat-app');
const chatInput = document.getElementById('chat-input'); if (!app) return;
const chatMessages = document.getElementById('chat-messages');
const appendMessage = (text, sender) => { const twilioSelect = document.getElementById('twilio-select');
const msgDiv = document.createElement('div'); const conversationList = document.getElementById('conversation-list');
msgDiv.classList.add('message', sender); const messageList = document.getElementById('message-list');
msgDiv.textContent = text; const messageForm = document.getElementById('message-form');
chatMessages.appendChild(msgDiv); const messageInput = document.getElementById('message-input');
chatMessages.scrollTop = chatMessages.scrollHeight; const conversationTitle = document.getElementById('conversation-title');
}; const conversationStatus = document.getElementById('conversation-status');
const searchInput = document.getElementById('search-input');
const addContactForm = document.getElementById('add-contact-form');
const alertBox = document.getElementById('chat-alert');
chatForm.addEventListener('submit', async (e) => { let activeConversationId = null;
e.preventDefault(); let activeTwilioId = twilioSelect ? twilioSelect.value : null;
const message = chatInput.value.trim(); let pollTimer = null;
if (!message) return;
appendMessage(message, 'visitor'); const showAlert = (text, type = 'info') => {
chatInput.value = ''; if (!alertBox) return;
alertBox.textContent = text;
alertBox.className = `alert alert-${type} alert-inline`;
alertBox.classList.remove('d-none');
setTimeout(() => alertBox.classList.add('d-none'), 3000);
};
try { const formatTime = (iso) => {
const response = await fetch('api/chat.php', { if (!iso) return '';
method: 'POST', const dt = new Date(iso.replace(' ', 'T'));
headers: { 'Content-Type': 'application/json' }, return dt.toLocaleString();
body: JSON.stringify({ message }) };
});
const data = await response.json();
// Artificial delay for realism const renderConversations = (items) => {
setTimeout(() => { conversationList.innerHTML = '';
appendMessage(data.reply, 'bot'); if (!items.length) {
}, 500); conversationList.innerHTML = '<div class="p-3 muted">暂无会话。添加号码开始对话。</div>';
} catch (error) { return;
console.error('Error:', error); }
appendMessage("Sorry, something went wrong. Please try again.", 'bot'); items.forEach((item) => {
} const div = document.createElement('div');
div.className = 'conversation-item' + (item.id === activeConversationId ? ' active' : '');
div.dataset.id = item.id;
div.innerHTML = `
<div class="conversation-avatar">${(item.name || item.phone).slice(0, 2).toUpperCase()}</div>
<div class="conversation-meta">
<div class="fw-semibold">${item.name || item.phone}</div>
<small>${item.last_message || '暂无消息'}</small>
</div>
<small class="text-muted">${item.last_time ? formatTime(item.last_time) : ''}</small>
`;
div.addEventListener('click', () => {
activeConversationId = item.id;
conversationTitle.textContent = item.name || item.phone;
conversationStatus.textContent = item.phone;
fetchMessages();
fetchConversations();
});
conversationList.appendChild(div);
}); });
};
const renderMessages = (items) => {
messageList.innerHTML = '';
if (!items.length) {
messageList.innerHTML = '<div class="muted">暂无消息,开始发送第一条短信。</div>';
return;
}
items.forEach((msg) => {
const div = document.createElement('div');
div.className = `message ${msg.direction === 'outbound' ? 'outbound' : 'inbound'}`;
div.innerHTML = `
<div>${msg.body}</div>
<span class="timestamp">${formatTime(msg.created_at)}</span>
`;
messageList.appendChild(div);
});
messageList.scrollTop = messageList.scrollHeight;
};
const fetchConversations = async () => {
if (!activeTwilioId) return;
const res = await fetch(`api/conversations.php?twilio_number_id=${activeTwilioId}`);
const data = await res.json();
renderConversations(data.items || []);
if (!activeConversationId && data.items && data.items.length) {
activeConversationId = data.items[0].id;
conversationTitle.textContent = data.items[0].name || data.items[0].phone;
conversationStatus.textContent = data.items[0].phone;
fetchMessages();
}
};
const fetchMessages = async () => {
if (!activeConversationId) {
renderMessages([]);
return;
}
const res = await fetch(`api/messages.php?conversation_id=${activeConversationId}`);
const data = await res.json();
renderMessages(data.items || []);
};
const startPolling = () => {
if (pollTimer) clearInterval(pollTimer);
pollTimer = setInterval(() => {
fetchConversations();
fetchMessages();
}, 5000);
};
if (twilioSelect) {
twilioSelect.addEventListener('change', () => {
activeTwilioId = twilioSelect.value;
activeConversationId = null;
conversationTitle.textContent = '请选择会话';
conversationStatus.textContent = '';
fetchConversations();
fetchMessages();
});
}
if (searchInput) {
searchInput.addEventListener('input', () => {
const term = searchInput.value.toLowerCase();
const items = conversationList.querySelectorAll('.conversation-item');
items.forEach((item) => {
const text = item.textContent.toLowerCase();
item.style.display = text.includes(term) ? 'flex' : 'none';
});
});
}
if (messageForm) {
messageForm.addEventListener('submit', async (e) => {
e.preventDefault();
const body = messageInput.value.trim();
if (!body) return;
if (!activeConversationId) {
showAlert('请先选择一个会话。', 'warning');
return;
}
messageInput.value = '';
const res = await fetch('api/send_message.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ conversation_id: activeConversationId, body })
});
const data = await res.json();
if (!data.success) {
showAlert(data.error || '发送失败', 'danger');
}
fetchMessages();
fetchConversations();
});
}
if (addContactForm) {
addContactForm.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(addContactForm);
formData.append('twilio_number_id', activeTwilioId || '');
const res = await fetch('api/add_contact.php', {
method: 'POST',
body: formData
});
const data = await res.json();
if (data.success) {
activeConversationId = data.conversation_id;
fetchConversations();
fetchMessages();
showAlert('已添加号码并创建会话。', 'success');
const modal = bootstrap.Modal.getInstance(document.getElementById('addContactModal'));
if (modal) modal.hide();
addContactForm.reset();
} else {
showAlert(data.error || '添加失败', 'danger');
}
});
}
fetchConversations();
fetchMessages();
startPolling();
}); });

Binary file not shown.

After

Width:  |  Height:  |  Size: 215 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 215 KiB

70
chat.php Normal file
View File

@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/bootstrap.php';
session_start();
?>
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>WhatsApp Chat</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<link rel="stylesheet" href="assets/css/custom.css?v=<?= time(); ?>">
</head>
<body>
<div id="chat-app" class="whatsapp-app container-fluid p-0">
<div class="sidebar">
<div class="sidebar-header">
<select id="twilio-select" class="form-select mb-2">
<!-- Dynamically populated or set by backend -->
</select>
<div class="input-group">
<input type="text" id="search-input" class="form-control" placeholder="搜索或开始新聊天...">
<button class="btn btn-light border-0" type="button" data-bs-toggle="modal" data-bs-target="#addContactModal"><i class="bi bi-plus-lg"></i></button>
</div>
</div>
<div id="conversation-list" class="flex-grow-1 overflow-auto">
<!-- Conversation list -->
</div>
</div>
<div class="chat-area">
<div class="chat-header">
<div class="flex-grow-1">
<strong id="conversation-title">请选择会话</strong>
<small id="conversation-status" class="text-muted d-block"></small>
</div>
<i class="bi bi-search me-3"></i><i class="bi bi-three-dots-vertical"></i>
</div>
<div id="message-list" class="message-list">
<!-- Messages -->
</div>
<form id="message-form" class="chat-input">
<i class="bi bi-emoji-smile fs-4 text-secondary"></i>
<input type="text" id="message-input" class="form-control" placeholder="输入消息...">
<button type="submit" class="btn btn-link text-success p-0"><i class="bi bi-send-fill fs-4"></i></button>
</form>
</div>
</div>
<div class="modal fade" id="addContactModal" tabindex="-1">
<div class="modal-dialog">
<form id="add-contact-form" class="modal-content">
<div class="modal-header"><h5>添加/导入联系人</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<div class="modal-body">
<input type="text" name="phone" class="form-control mb-2" placeholder="输入手机号">
<input type="text" name="name" class="form-control mb-2" placeholder="名字 (可选)">
<input type="file" name="contact_file" class="form-control">
</div>
<div class="modal-footer"><button type="submit" class="btn btn-success">添加并发送</button></div>
</form>
</div>
</div>
<div id="chat-alert" class="alert d-none" style="position:fixed; top:20px; right:20px; z-index:9999;"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/js/main.js?v=<?= time(); ?>"></script>
</body>
</html>

84
includes/bootstrap.php Normal file
View File

@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../db/config.php';
function e(string $value): string {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
function check_admin_auth(): bool {
session_start();
return isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'admin';
}
function ensure_tables(): void {
$pdo = db();
$pdo->exec("
CREATE TABLE IF NOT EXISTS twilio_numbers (
id INT AUTO_INCREMENT PRIMARY KEY,
label VARCHAR(120) NOT NULL,
account_sid VARCHAR(64) NOT NULL,
auth_token VARCHAR(128) NOT NULL,
api_key VARCHAR(128) DEFAULT NULL,
from_number VARCHAR(32) NOT NULL,
is_active TINYINT(1) NOT NULL DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");
$pdo->exec("
CREATE TABLE IF NOT EXISTS contacts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(120) DEFAULT NULL,
phone VARCHAR(32) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uniq_phone (phone)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");
$pdo->exec("
CREATE TABLE IF NOT EXISTS conversations (
id INT AUTO_INCREMENT PRIMARY KEY,
contact_id INT NOT NULL,
twilio_number_id INT NOT NULL,
last_message_at TIMESTAMP NULL DEFAULT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_contact (contact_id),
INDEX idx_twilio (twilio_number_id),
CONSTRAINT fk_convo_contact FOREIGN KEY (contact_id) REFERENCES contacts(id) ON DELETE CASCADE,
CONSTRAINT fk_convo_twilio FOREIGN KEY (twilio_number_id) REFERENCES twilio_numbers(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");
$pdo->exec("
CREATE TABLE IF NOT EXISTS messages (
id INT AUTO_INCREMENT PRIMARY KEY,
conversation_id INT NOT NULL,
direction ENUM('inbound','outbound') NOT NULL,
body TEXT NOT NULL,
status VARCHAR(32) DEFAULT 'stored',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_convo (conversation_id),
CONSTRAINT fk_msg_convo FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");
$pdo->exec("
CREATE TABLE IF NOT EXISTS billing_snapshots (
id INT AUTO_INCREMENT PRIMARY KEY,
twilio_number_id INT NOT NULL,
period_start DATE NOT NULL,
period_end DATE NOT NULL,
usage_count INT DEFAULT 0,
cost DECIMAL(10,4) DEFAULT 0,
currency VARCHAR(12) DEFAULT 'USD',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_bill_twilio (twilio_number_id),
CONSTRAINT fk_bill_twilio FOREIGN KEY (twilio_number_id) REFERENCES twilio_numbers(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");
}
ensure_tables();

58
includes/twilio.php Normal file
View File

@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
function twilio_request(string $sid, string $token, string $url, string $method = 'GET', array $data = []): array {
$ch = curl_init();
$opts = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 20,
CURLOPT_USERPWD => $sid . ':' . $token,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_CUSTOMREQUEST => strtoupper($method),
];
if (strtoupper($method) === 'POST') {
$opts[CURLOPT_POSTFIELDS] = http_build_query($data);
}
curl_setopt_array($ch, $opts);
$resp = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($resp === false || $code < 200 || $code >= 300) {
return [
'success' => false,
'status' => $code,
'error' => $error ?: $resp,
];
}
$decoded = json_decode($resp, true);
return [
'success' => true,
'status' => $code,
'data' => $decoded ?: $resp,
];
}
function twilio_send_sms(array $twilio, string $to, string $body): array {
$url = 'https://api.twilio.com/2010-04-01/Accounts/' . urlencode($twilio['account_sid']) . '/Messages.json';
return twilio_request(
$twilio['account_sid'],
$twilio['auth_token'],
$url,
'POST',
[
'From' => $twilio['from_number'],
'To' => $to,
'Body' => $body,
]
);
}
function twilio_fetch_sms_usage(array $twilio, string $startDate, string $endDate): array {
$url = 'https://api.twilio.com/2010-04-01/Accounts/' . urlencode($twilio['account_sid'])
. '/Usage/Records/Monthly.json?Category=sms&StartDate=' . urlencode($startDate) . '&EndDate=' . urlencode($endDate);
return twilio_request($twilio['account_sid'], $twilio['auth_token'], $url);
}

158
index.php
View File

@ -1,150 +1,30 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
@ini_set('display_errors', '1'); require_once __DIR__ . '/includes/bootstrap.php';
@error_reporting(E_ALL);
@date_default_timezone_set('UTC');
$phpVersion = PHP_VERSION; // 简单前台跳转处理
$now = date('Y-m-d H:i:s'); if (isset($_GET['logout'])) {
session_start();
session_destroy();
header('Location: /');
exit;
}
?> ?>
<!doctype html> <!doctype html>
<html lang="en"> <html lang="zh">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <title>双向短信平台</title>
<title>New Style</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<?php
// Read project preview data from environment
$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? '';
$projectImageUrl = $_SERVER['PROJECT_IMAGE_URL'] ?? '';
?>
<?php if ($projectDescription): ?>
<!-- Meta description -->
<meta name="description" content='<?= htmlspecialchars($projectDescription) ?>' />
<!-- Open Graph meta tags -->
<meta property="og:description" content="<?= htmlspecialchars($projectDescription) ?>" />
<!-- Twitter meta tags -->
<meta property="twitter:description" content="<?= htmlspecialchars($projectDescription) ?>" />
<?php endif; ?>
<?php if ($projectImageUrl): ?>
<!-- Open Graph image -->
<meta property="og:image" content="<?= htmlspecialchars($projectImageUrl) ?>" />
<!-- Twitter image -->
<meta property="twitter:image" content="<?= htmlspecialchars($projectImageUrl) ?>" />
<?php endif; ?>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
<style>
:root {
--bg-color-start: #6a11cb;
--bg-color-end: #2575fc;
--text-color: #ffffff;
--card-bg-color: rgba(255, 255, 255, 0.01);
--card-border-color: rgba(255, 255, 255, 0.1);
}
body {
margin: 0;
font-family: 'Inter', sans-serif;
background: linear-gradient(45deg, var(--bg-color-start), var(--bg-color-end));
color: var(--text-color);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
text-align: center;
overflow: hidden;
position: relative;
}
body::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><path d="M-10 10L110 10M10 -10L10 110" stroke-width="1" stroke="rgba(255,255,255,0.05)"/></svg>');
animation: bg-pan 20s linear infinite;
z-index: -1;
}
@keyframes bg-pan {
0% { background-position: 0% 0%; }
100% { background-position: 100% 100%; }
}
main {
padding: 2rem;
}
.card {
background: var(--card-bg-color);
border: 1px solid var(--card-border-color);
border-radius: 16px;
padding: 2rem;
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.1);
}
.loader {
margin: 1.25rem auto 1.25rem;
width: 48px;
height: 48px;
border: 3px solid rgba(255, 255, 255, 0.25);
border-top-color: #fff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.hint {
opacity: 0.9;
}
.sr-only {
position: absolute;
width: 1px; height: 1px;
padding: 0; margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap; border: 0;
}
h1 {
font-size: 3rem;
font-weight: 700;
margin: 0 0 1rem;
letter-spacing: -1px;
}
p {
margin: 0.5rem 0;
font-size: 1.1rem;
}
code {
background: rgba(0,0,0,0.2);
padding: 2px 6px;
border-radius: 4px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
footer {
position: absolute;
bottom: 1rem;
font-size: 0.8rem;
opacity: 0.7;
}
</style>
</head> </head>
<body> <body class="p-5">
<main> <div class="container text-center">
<div class="card"> <h1>欢迎来到 Twilio 短信控制台</h1>
<h1>Analyzing your requirements and generating your website…</h1> <p class="lead text-muted">WhatsApp 风格体验,高效沟通。</p>
<div class="loader" role="status" aria-live="polite" aria-label="Applying initial changes"> <div class="mt-4">
<span class="sr-only">Loading…</span> <a href="chat.php" class="btn btn-primary btn-lg">进入聊天 (前端)</a>
</div> <a href="admin.php" class="btn btn-outline-secondary btn-lg ms-3">进入管理 (后端)</a>
<p class="hint"><?= ($_SERVER['HTTP_HOST'] ?? '') === 'appwizzy.com' ? 'AppWizzy' : 'Flatlogic' ?> AI is collecting your requirements and applying the first changes.</p>
<p class="hint">This page will update automatically as the plan is implemented.</p>
<p>Runtime: PHP <code><?= htmlspecialchars($phpVersion) ?></code> — UTC <code><?= htmlspecialchars($now) ?></code></p>
</div> </div>
</main> </div>
<footer>
Page updated: <?= htmlspecialchars($now) ?> (UTC)
</footer>
</body> </body>
</html> </html>

34
login.php Normal file
View File

@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/bootstrap.php';
// 简单的登录逻辑占位后续可替换为基于DB的账户系统
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 后续对接RBAC
if ($_POST['password'] === 'admin') {
session_start();
$_SESSION['user_type'] = 'admin';
header('Location: admin.php');
exit;
}
}
?>
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>系统登录</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light d-flex align-items-center justify-content-center" style="height:100vh;">
<div class="card p-4" style="width: 300px;">
<h4 class="mb-3">系统登录</h4>
<form method="post">
<div class="mb-3">
<label>密码</label>
<input type="password" name="password" class="form-control" required>
</div>
<button class="btn btn-primary w-100">登录</button>
</form>
</div>
</body>
</html>