tam add chat

This commit is contained in:
2026-06-30 10:53:51 +07:00
parent 6e284e66fa
commit dc86524ff0
6 changed files with 298 additions and 176 deletions

View File

@@ -975,18 +975,21 @@ func (a *App) connectWS() {
case "chat:message":
senderRole, _ := msg.Data["senderRole"].(string)
if senderRole == "staff" {
from := "Giảng viên"
if n, ok := msg.Data["staffName"].(string); ok && n != "" {
from = n
}
preview := ""
if b, ok := msg.Data["body"].(string); ok {
preview = b
}
if staffVal, ok := msg.Data["staffId"].(float64); ok {
a.mu.Lock()
a.replyStaffID = uint(staffVal)
a.chatUnread++
unread := a.chatUnread
a.mu.Unlock()
runtime.EventsEmit(a.ctx, "chat:notify", map[string]any{
"unread": unread,
"preview": msg.Data["body"],
"from": msg.Data["staffName"],
})
}
a.alertChatIncoming(from, preview)
}
runtime.EventsEmit(a.ctx, "chat:message", msg.Data)
}
@@ -1059,6 +1062,32 @@ func (a *App) stopScreenshotStream() {
log.Println("[WS] Screenshot screen-streaming stopped.")
}
func (a *App) alertChatIncoming(from, preview string) {
if preview == "" {
preview = "Bạn có tin nhắn mới"
}
if len(preview) > 120 {
preview = preview[:120] + "…"
}
winapi.PlayNotifySound()
winapi.ActivateAppWindow("Simple Care")
runtime.WindowUnminimise(a.ctx)
runtime.WindowShow(a.ctx)
a.mu.Lock()
unread := a.chatUnread
staffID := a.replyStaffID
a.mu.Unlock()
runtime.EventsEmit(a.ctx, "chat:notify", map[string]any{
"unread": unread,
"preview": preview,
"from": from,
"staffId": staffID,
})
}
// UnlockChatAudio — gọi từ UI sau lần click đầu để mở khóa Web Audio (dự phòng)
func (a *App) UnlockChatAudio() {}
func (a *App) GetChatUnread() int {
a.mu.Lock()
defer a.mu.Unlock()

View File

@@ -490,127 +490,148 @@ body {
white-space: nowrap;
}
/* Student chat messenger */
/* Student chat — modal 2 panel giống web */
.student-chat-dock {
position: fixed;
right: 12px;
bottom: 12px;
z-index: 1000;
right: 16px;
bottom: 16px;
z-index: 2000;
pointer-events: none;
}
.student-chat-toast {
position: absolute;
right: 0;
bottom: 64px;
width: 260px;
padding: 0.65rem 0.75rem;
border-radius: 10px;
background: #1e293b;
color: #fff;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.28);
font-size: 0.78rem;
display: flex;
flex-direction: column;
gap: 0.2rem;
.student-chat-dock > * {
pointer-events: auto;
}
.student-chat-fab {
position: relative;
width: 48px;
height: 48px;
width: 50px;
height: 50px;
border-radius: 50%;
border: none;
background: var(--accent);
color: #fff;
font-size: 1.15rem;
cursor: pointer;
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.25);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.28);
}
.student-chat-fab.is-hidden {
display: none;
}
.student-chat-fab--pulse {
animation: chat-fab-pulse 0.6s ease 2;
}
@keyframes chat-fab-pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.1); box-shadow: 0 0 0 8px rgba(187, 33, 38, 0.25); }
}
.student-chat-badge {
position: absolute;
top: -2px;
right: -2px;
min-width: 16px;
height: 16px;
padding: 0 4px;
border-radius: 8px;
top: -3px;
right: -3px;
min-width: 18px;
height: 18px;
padding: 0 5px;
border-radius: 9px;
background: #ef4444;
color: #fff;
font-size: 0.62rem;
font-weight: 700;
line-height: 16px;
line-height: 18px;
}
.student-chat-messenger {
.student-chat-modal {
display: none;
position: absolute;
right: 0;
bottom: 58px;
width: min(520px, calc(100vw - 24px));
height: min(400px, calc(100vh - 80px));
bottom: 60px;
width: min(560px, calc(100vw - 32px));
height: min(440px, calc(100vh - 100px));
background: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: 12px;
box-shadow: 0 12px 36px rgba(0, 0, 0, 0.3);
display: flex;
box-shadow: 0 16px 48px rgba(0, 0, 0, 0.38);
flex-direction: column;
overflow: hidden;
}
.student-chat-messenger-head {
.student-chat-modal.is-open {
display: flex;
}
.student-chat-modal-head {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.55rem 0.7rem;
justify-content: space-between;
padding: 0.65rem 0.85rem;
border-bottom: 1px solid var(--border-color);
font-size: 0.82rem;
flex-shrink: 0;
font-size: 0.88rem;
}
.student-chat-close {
border: none;
background: none;
background: transparent;
color: var(--text-muted);
font-size: 1.1rem;
width: 30px;
height: 30px;
border-radius: 6px;
cursor: pointer;
font-size: 1.25rem;
line-height: 1;
}
.student-chat-messenger-body {
display: flex;
.student-chat-close:hover {
background: rgba(187, 33, 38, 0.12);
color: var(--accent);
}
.student-chat-modal-body {
flex: 1;
min-height: 0;
display: flex;
overflow: hidden;
}
.student-chat-sidebar {
width: 150px;
width: 200px;
flex-shrink: 0;
border-right: 1px solid var(--border-color);
overflow-y: auto;
background: rgba(255, 255, 255, 0.02);
display: flex;
flex-direction: column;
overscroll-behavior: contain;
background: rgba(0, 0, 0, 0.06);
}
.student-chat-conv-btn {
.student-chat-conv-row {
width: 100%;
text-align: left;
border: none;
background: transparent;
padding: 0.55rem 0.5rem;
padding: 0.7rem 0.75rem;
cursor: pointer;
border-bottom: 1px solid var(--border-color);
color: var(--text-primary);
}
.student-chat-conv-btn.active {
.student-chat-conv-row:hover {
background: rgba(255, 255, 255, 0.04);
}
.student-chat-conv-row.active {
background: rgba(187, 33, 38, 0.12);
border-left: 2px solid var(--accent);
border-left: 3px solid var(--accent);
}
.student-chat-conv-name {
display: flex;
justify-content: space-between;
font-size: 0.72rem;
align-items: center;
gap: 0.35rem;
font-size: 0.78rem;
font-weight: 600;
}
@@ -621,29 +642,32 @@ body {
border-radius: 8px;
padding: 0 5px;
font-size: 0.6rem;
font-weight: 700;
flex-shrink: 0;
}
.student-chat-conv-preview {
display: block;
font-size: 0.65rem;
font-size: 0.7rem;
color: var(--text-muted);
margin-top: 0.2rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-top: 0.15rem;
}
.student-chat-thread {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
min-width: 0;
overflow: hidden;
}
.student-chat-thread-head {
padding: 0.45rem 0.65rem;
padding: 0.55rem 0.75rem;
border-bottom: 1px solid var(--border-color);
font-size: 0.75rem;
font-size: 0.8rem;
font-weight: 600;
flex-shrink: 0;
}
@@ -651,43 +675,38 @@ body {
.student-chat-messages {
flex: 1;
overflow-y: auto;
padding: 0.55rem;
overscroll-behavior: contain;
padding: 0.65rem 0.75rem;
display: flex;
flex-direction: column;
gap: 0.4rem;
background: rgba(0, 0, 0, 0.12);
background: rgba(0, 0, 0, 0.06);
}
.student-chat-empty {
font-size: 0.72rem;
font-size: 0.78rem;
color: var(--text-muted);
text-align: center;
padding: 1rem 0.5rem;
padding: 1.5rem 0.75rem;
}
.student-chat-bubble {
max-width: 88%;
font-size: 0.76rem;
max-width: 82%;
font-size: 0.8rem;
}
.student-chat-bubble--staff { align-self: flex-start; }
.student-chat-bubble--student { align-self: flex-end; }
.student-chat-label {
font-size: 0.6rem;
color: var(--text-muted);
margin-bottom: 0.1rem;
}
.student-chat-body {
padding: 0.4rem 0.55rem;
border-radius: 10px;
line-height: 1.35;
padding: 0.45rem 0.6rem;
border-radius: 12px;
line-height: 1.4;
word-break: break-word;
}
.student-chat-bubble--staff .student-chat-body {
background: rgba(255, 255, 255, 0.06);
background: rgba(255, 255, 255, 0.08);
border: 1px solid var(--border-color);
}
@@ -697,33 +716,31 @@ body {
}
.student-chat-time {
font-size: 0.58rem;
font-size: 0.6rem;
color: var(--text-muted);
margin-top: 0.1rem;
margin-top: 0.12rem;
padding: 0 0.2rem;
}
.student-chat-compose {
display: flex;
gap: 0.35rem;
padding: 0.45rem 0.55rem;
gap: 0.45rem;
padding: 0.55rem 0.7rem;
border-top: 1px solid var(--border-color);
flex-shrink: 0;
background: var(--bg-card);
}
.student-chat-compose input {
flex: 1;
font-size: 0.74rem;
padding: 0.4rem 0.5rem;
font-size: 0.8rem;
padding: 0.5rem 0.6rem;
border-radius: 8px;
border: 1px solid var(--border-color);
background: var(--bg-base);
color: var(--text-primary);
}
.student-chat-compose input:disabled {
opacity: 0.5;
}
.shifts-wrap {
flex: 1;
min-height: 0;

View File

@@ -27,34 +27,8 @@ let chatOpen = false;
let chatMessages = [];
let chatConversations = [];
let activeStaffId = 0;
let chatAudioCtx = null;
function playChatSound() {
try {
const Ctx = window.AudioContext || window.webkitAudioContext;
if (!chatAudioCtx) chatAudioCtx = new Ctx();
const ctx = chatAudioCtx;
if (ctx.state === 'suspended') ctx.resume();
const tone = (freq, start, dur) => {
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.type = 'sine';
osc.frequency.value = freq;
gain.gain.setValueAtTime(0.0001, start);
gain.gain.exponentialRampToValueAtTime(0.15, start + 0.02);
gain.gain.exponentialRampToValueAtTime(0.0001, start + dur);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start(start);
osc.stop(start + dur + 0.02);
};
const t = ctx.currentTime;
tone(880, t, 0.12);
tone(1174, t + 0.14, 0.14);
} catch {
/* ignore */
}
}
let lastRenderedMsgCount = 0;
let bannerStaffId = 0;
// Quản lý webcam
let webcamStream = null;
@@ -82,15 +56,14 @@ function init() {
window.runtime.EventsOn('chat:message', (data) => {
updateChatBadge();
loadChatConversations().catch(console.error);
if (chatOpen && activeStaffId) loadChatMessages(activeStaffId).catch(console.error);
if (data?.senderRole === 'staff') {
playChatSound();
if (chatOpen && activeStaffId) {
loadChatMessages(activeStaffId, true).catch(console.error);
}
});
window.runtime.EventsOn('chat:notify', (data) => {
updateChatBadge();
showChatToast(data);
playChatSound();
if (data?.staffId) bannerStaffId = Number(data.staffId);
pulseChatFab();
});
checkLogin();
}
@@ -310,71 +283,85 @@ function ensureChatWidget() {
wrap.id = 'student-chat-widget';
wrap.className = 'student-chat-dock';
wrap.innerHTML = `
<div class="student-chat-toast" id="student-chat-toast" hidden></div>
<button type="button" class="student-chat-fab" id="student-chat-fab" title="Tin nhắn">
💬<span class="student-chat-badge" id="student-chat-badge" hidden>0</span>
</button>
<div class="student-chat-messenger" id="student-chat-messenger" hidden>
<header class="student-chat-messenger-head">
<div class="student-chat-modal" id="student-chat-modal">
<header class="student-chat-modal-head">
<strong>Tin nhắn</strong>
<button type="button" class="student-chat-close" id="student-chat-close">×</button>
<button type="button" class="student-chat-close" id="student-chat-close" aria-label="Đóng">×</button>
</header>
<div class="student-chat-messenger-body">
<aside class="student-chat-sidebar" id="student-chat-conv-list"></aside>
<div class="student-chat-modal-body">
<aside class="student-chat-sidebar" id="student-chat-sidebar"></aside>
<section class="student-chat-thread">
<div class="student-chat-thread-head" id="student-chat-thread-head">Chọn hội thoại</div>
<div class="student-chat-messages" id="student-chat-messages"></div>
<div class="student-chat-messages" id="student-chat-messages">
<div class="student-chat-empty">Chọn giảng viên bên trái để xem tin nhắn</div>
</div>
<div class="student-chat-compose">
<input id="student-chat-input" placeholder="Nhập tin nhắn..." disabled />
<button type="button" class="btn btn-primary btn-sm" id="student-chat-send" disabled>Gửi</button>
<input id="student-chat-input" placeholder="Nhập tin nhắn..." />
<button type="button" class="btn btn-primary btn-sm" id="student-chat-send">Gửi</button>
</div>
</section>
</div>
</div>
`;
document.body.appendChild(wrap);
document.getElementById('student-chat-fab').addEventListener('click', toggleChat);
document.getElementById('student-chat-close').addEventListener('click', () => setChatOpen(false));
document.getElementById('student-chat-fab').addEventListener('click', () => setChatOpen(true));
document.getElementById('student-chat-close').addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
setChatOpen(false);
});
document.getElementById('student-chat-send').addEventListener('click', sendStudentChat);
document.getElementById('student-chat-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter') { e.preventDefault(); sendStudentChat(); }
});
}
function showChatToast(data) {
const toast = document.getElementById('student-chat-toast');
if (!toast) return;
const from = data?.from || 'Giảng viên';
const preview = data?.preview || 'Bạn có tin nhắn mới';
toast.innerHTML = `<strong>${escapeHtml(from)}</strong><span>${escapeHtml(preview)}</span>`;
toast.hidden = false;
clearTimeout(showChatToast._t);
showChatToast._t = setTimeout(() => { toast.hidden = true; }, 5000);
function pulseChatFab() {
const fab = document.getElementById('student-chat-fab');
if (!fab) return;
fab.classList.remove('student-chat-fab--pulse');
void fab.offsetWidth;
fab.classList.add('student-chat-fab--pulse');
}
function setChatOpen(open) {
chatOpen = open;
const panel = document.getElementById('student-chat-messenger');
if (panel) panel.hidden = !open;
const modal = document.getElementById('student-chat-modal');
const fab = document.getElementById('student-chat-fab');
if (modal) modal.classList.toggle('is-open', open);
if (fab) fab.classList.toggle('is-hidden', open);
if (open) {
loadChatConversations().catch(console.error);
if (activeStaffId) loadChatMessages(activeStaffId).catch(console.error);
loadChatConversations().then(() => {
const sid = bannerStaffId || activeStaffId || Number(chatConversations[0]?.staffId || 0);
if (sid) selectStaffChat(sid);
}).catch(console.error);
}
}
function toggleChat() {
setChatOpen(!chatOpen);
function selectStaffChat(staffId) {
if (!staffId) return;
activeStaffId = staffId;
const conv = chatConversations.find((c) => Number(c.staffId) === staffId);
const head = document.getElementById('student-chat-thread-head');
if (head) head.textContent = conv?.staffName || conv?.staffEmail || 'Giảng viên';
renderChatConversations();
loadChatMessages(staffId).catch(console.error);
}
async function loadChatConversations() {
const rows = await window.go.main.App.GetChatConversations();
chatConversations = Array.isArray(rows) ? rows : [];
renderChatConversations();
if (chatOpen) renderChatConversations();
updateChatBadge();
return chatConversations;
}
function renderChatConversations() {
const list = document.getElementById('student-chat-conv-list');
const list = document.getElementById('student-chat-sidebar');
if (!list) return;
if (!chatConversations.length) {
list.innerHTML = '<div class="student-chat-empty">Chưa có tin nhắn</div>';
@@ -385,55 +372,47 @@ function renderChatConversations() {
const unread = Number(c.unread || 0);
const active = sid === activeStaffId ? ' active' : '';
const name = escapeHtml(c.staffName || c.staffEmail || 'Giảng viên');
const preview = escapeHtml(c.lastMessage || '');
return `<button type="button" class="student-chat-conv-btn${active}" data-staff-id="${sid}">
const preview = escapeHtml(c.lastMessage || '');
return `<button type="button" class="student-chat-conv-row${active}" data-staff-id="${sid}">
<span class="student-chat-conv-name">${name}${unread > 0 ? `<em class="student-chat-conv-unread">${unread}</em>` : ''}</span>
<span class="student-chat-conv-preview">${preview}</span>
</button>`;
}).join('');
list.querySelectorAll('.student-chat-conv-btn').forEach((btn) => {
btn.addEventListener('click', () => {
const sid = Number(btn.getAttribute('data-staff-id'));
pickStaffChat(sid);
});
list.querySelectorAll('.student-chat-conv-row').forEach((btn) => {
btn.addEventListener('click', () => selectStaffChat(Number(btn.getAttribute('data-staff-id'))));
});
}
async function pickStaffChat(staffId) {
activeStaffId = staffId;
const head = document.getElementById('student-chat-thread-head');
const conv = chatConversations.find((c) => Number(c.staffId) === staffId);
if (head) head.textContent = conv?.staffName || conv?.staffEmail || 'Giảng viên';
const input = document.getElementById('student-chat-input');
const sendBtn = document.getElementById('student-chat-send');
if (input) input.disabled = !staffId;
if (sendBtn) sendBtn.disabled = !staffId;
renderChatConversations();
if (staffId) await loadChatMessages(staffId);
}
async function loadChatMessages(staffId) {
async function loadChatMessages(staffId, silent = false) {
const msgs = await window.go.main.App.GetChatMessages(staffId);
chatMessages = Array.isArray(msgs) ? msgs : [];
renderChatMessages();
renderChatMessages(silent);
updateChatBadge();
loadChatConversations().catch(console.error);
if (!silent) loadChatConversations().catch(console.error);
}
function renderChatMessages() {
function renderChatMessages(silent = false) {
const box = document.getElementById('student-chat-messages');
if (!box) return;
const wasAtBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 48;
if (!chatMessages.length) {
box.innerHTML = '<div class="student-chat-empty">Chưa có tin nhắn</div>';
lastRenderedMsgCount = 0;
return;
}
if (chatMessages.length === lastRenderedMsgCount && silent) return;
lastRenderedMsgCount = chatMessages.length;
box.innerHTML = chatMessages.map((m) => {
const role = m.senderRole === 'student' ? 'student' : 'staff';
const time = m.createdAt ? new Date(m.createdAt).toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' }) : '';
const label = role === 'staff' ? (m.staffName || 'Giảng viên') : 'Bạn';
return `<div class="student-chat-bubble student-chat-bubble--${role}"><div class="student-chat-label">${label}</div><div class="student-chat-body">${escapeHtml(m.body || '')}</div><div class="student-chat-time">${time}</div></div>`;
return `<div class="student-chat-bubble student-chat-bubble--${role}">
<div class="student-chat-body">${escapeHtml(m.body || '')}</div>
<div class="student-chat-time">${time}</div>
</div>`;
}).join('');
box.scrollTop = box.scrollHeight;
if (!silent || wasAtBottom) {
requestAnimationFrame(() => { box.scrollTop = box.scrollHeight; });
}
}
function escapeHtml(s) {

View File

@@ -22,3 +22,5 @@ export function NavigateToLogin():Promise<void>;
export function SendChatMessage(arg1:string):Promise<void>;
export function SendWebcamFrame(arg1:string):Promise<void>;
export function UnlockChatAudio():Promise<void>;

View File

@@ -45,3 +45,7 @@ export function SendChatMessage(arg1) {
export function SendWebcamFrame(arg1) {
return window['go']['main']['App']['SendWebcamFrame'](arg1);
}
export function UnlockChatAudio() {
return window['go']['main']['App']['UnlockChatAudio']();
}

View File

@@ -0,0 +1,91 @@
//go:build windows
package winapi
import (
"strings"
"syscall"
"time"
"unsafe"
)
var (
user32Window = syscall.NewLazyDLL("user32.dll")
procFindWindowW = user32Window.NewProc("FindWindowW")
procEnumWindows = user32Window.NewProc("EnumWindows")
procGetWindowTextW = user32Window.NewProc("GetWindowTextW")
procIsWindowVisible = user32Window.NewProc("IsWindowVisible")
procShowWindow = user32Window.NewProc("ShowWindow")
procSetForegroundWindow = user32Window.NewProc("SetForegroundWindow")
procFlashWindowEx = user32Window.NewProc("FlashWindowEx")
procMessageBeep = user32Window.NewProc("MessageBeep")
)
const (
swRestore = 9
)
type flashwinfo struct {
cbSize uint32
hwnd uintptr
dwFlags uint32
uCount uint32
dwTimeout uint32
}
// ActivateAppWindow — đưa cửa sổ app lên trước + nhấp nháy taskbar
func ActivateAppWindow(titleHint string) {
hwnd := findWindowByTitleContains(titleHint)
if hwnd == 0 {
return
}
_, _, _ = procShowWindow.Call(hwnd, swRestore)
_, _, _ = procSetForegroundWindow.Call(hwnd)
var fi flashwinfo
fi.cbSize = uint32(unsafe.Sizeof(fi))
fi.hwnd = hwnd
fi.dwFlags = 0x0000000E // FLASHW_ALL | FLASHW_TIMERNOFG
fi.uCount = 4
fi.dwTimeout = 0
_, _, _ = procFlashWindowEx.Call(uintptr(unsafe.Pointer(&fi)))
}
// PlayNotifySound — beep hệ thống Windows (không phụ thuộc autoplay trình duyệt)
func PlayNotifySound() {
_, _, _ = procMessageBeep.Call(0x00000040) // MB_ICONASTERISK
time.Sleep(120 * time.Millisecond)
_, _, _ = procMessageBeep.Call(0xFFFFFFFF) // MB_OK
}
var enumTargetTitle string
var enumFoundHwnd uintptr
var enumWindowsCallback = syscall.NewCallback(func(hwnd uintptr, lParam uintptr) uintptr {
ret, _, _ := procIsWindowVisible.Call(hwnd)
if ret == 0 {
return 1
}
buf := make([]uint16, 256)
_, _, _ = procGetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(&buf[0])), 256)
title := syscall.UTF16ToString(buf)
if title != "" && strings.Contains(strings.ToLower(title), strings.ToLower(enumTargetTitle)) {
enumFoundHwnd = hwnd
return 0
}
return 1
})
func findWindowByTitleContains(hint string) uintptr {
if hint == "" {
return 0
}
titlePtr, _ := syscall.UTF16PtrFromString(hint)
hwnd, _, _ := procFindWindowW.Call(0, uintptr(unsafe.Pointer(titlePtr)))
if hwnd != 0 {
return hwnd
}
enumTargetTitle = hint
enumFoundHwnd = 0
_, _, _ = procEnumWindows.Call(enumWindowsCallback, 0)
return enumFoundHwnd
}