74 lines
1.7 KiB
Go
74 lines
1.7 KiB
Go
package db
|
|
|
|
import (
|
|
"database/sql"
|
|
|
|
_ "modernc.org/sqlite"
|
|
)
|
|
|
|
var Conn *sql.DB
|
|
|
|
func Init() {
|
|
var err error
|
|
Conn, err = sql.Open("sqlite", "./data/bot.db")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
schema := `
|
|
CREATE TABLE IF NOT EXISTS clients (
|
|
id TEXT PRIMARY KEY,
|
|
name TEXT,
|
|
tier TEXT,
|
|
msg_count INTEGER DEFAULT 0
|
|
);
|
|
CREATE TABLE IF NOT EXISTS appointments (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
client_id TEXT,
|
|
customer_phone TEXT,
|
|
appointment_date TEXT,
|
|
status TEXT DEFAULT 'confirmed'
|
|
);
|
|
CREATE TABLE IF NOT EXISTS chats (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
title TEXT DEFAULT 'New Chat',
|
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS messages (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
chat_id INTEGER,
|
|
role TEXT, -- 'user' or 'assistant'
|
|
content TEXT,
|
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
FOREIGN KEY(chat_id) REFERENCES chats(id)
|
|
);`
|
|
Conn.Exec(schema)
|
|
}
|
|
|
|
func SaveAppointment(phone string, date string) error {
|
|
_, err := Conn.Exec(
|
|
"INSERT INTO appointments (customer_phone, appointment_date, status) VALUES (?, ?, ?)",
|
|
phone, date, "confirmed",
|
|
)
|
|
return err
|
|
}
|
|
|
|
// GetOrCreateChatByPhone finds a chat for this phone number or creates one
|
|
func GetOrCreateChatByPhone(phone string) int {
|
|
// 1. Check if we already have a chat for this phone
|
|
// (Note: You might want to add a 'phone' column to 'chats' table if you haven't yet.
|
|
// For now, I'll cheat and put the phone in the title if it's new)
|
|
var id int
|
|
err := Conn.QueryRow("SELECT id FROM chats WHERE title = ?", phone).Scan(&id)
|
|
|
|
if err == nil {
|
|
return id
|
|
}
|
|
|
|
// 2. If not found, create one
|
|
res, _ := Conn.Exec("INSERT INTO chats (title) VALUES (?)", phone)
|
|
newId, _ := res.LastInsertId()
|
|
return int(newId)
|
|
}
|