feat: add admin messaging interface
- Add admin messages API endpoints (/api/v1/admin/messages) - Add admin messages page route (/admin/messages) - Add messages.html template with split-panel conversation view - Add messages.js Alpine component for messaging UI - Add Messages link to admin sidebar under Platform Administration - Add message icon with unread badge to admin header - Update init-alpine.js with headerMessages component 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -31,11 +31,13 @@ from . import (
|
|||||||
code_quality,
|
code_quality,
|
||||||
companies,
|
companies,
|
||||||
content_pages,
|
content_pages,
|
||||||
|
customers,
|
||||||
dashboard,
|
dashboard,
|
||||||
inventory,
|
inventory,
|
||||||
letzshop,
|
letzshop,
|
||||||
logs,
|
logs,
|
||||||
marketplace,
|
marketplace,
|
||||||
|
messages,
|
||||||
monitoring,
|
monitoring,
|
||||||
notifications,
|
notifications,
|
||||||
order_item_exceptions,
|
order_item_exceptions,
|
||||||
@@ -91,6 +93,9 @@ router.include_router(
|
|||||||
# Include user management endpoints
|
# Include user management endpoints
|
||||||
router.include_router(users.router, tags=["admin-users"])
|
router.include_router(users.router, tags=["admin-users"])
|
||||||
|
|
||||||
|
# Include customer management endpoints
|
||||||
|
router.include_router(customers.router, tags=["admin-customers"])
|
||||||
|
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# Dashboard & Statistics
|
# Dashboard & Statistics
|
||||||
@@ -151,6 +156,9 @@ router.include_router(settings.router, tags=["admin-settings"])
|
|||||||
# Include notifications and alerts endpoints
|
# Include notifications and alerts endpoints
|
||||||
router.include_router(notifications.router, tags=["admin-notifications"])
|
router.include_router(notifications.router, tags=["admin-notifications"])
|
||||||
|
|
||||||
|
# Include messaging endpoints
|
||||||
|
router.include_router(messages.router, tags=["admin-messages"])
|
||||||
|
|
||||||
# Include log management endpoints
|
# Include log management endpoints
|
||||||
router.include_router(logs.router, tags=["admin-logs"])
|
router.include_router(logs.router, tags=["admin-logs"])
|
||||||
|
|
||||||
|
|||||||
647
app/api/v1/admin/messages.py
Normal file
647
app/api/v1/admin/messages.py
Normal file
@@ -0,0 +1,647 @@
|
|||||||
|
# app/api/v1/admin/messages.py
|
||||||
|
"""
|
||||||
|
Admin messaging endpoints.
|
||||||
|
|
||||||
|
Provides endpoints for:
|
||||||
|
- Viewing conversations (admin_vendor and admin_customer channels)
|
||||||
|
- Sending and receiving messages
|
||||||
|
- Managing conversation status
|
||||||
|
- File attachments
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFile
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.api.deps import get_current_admin_api
|
||||||
|
from app.core.database import get_db
|
||||||
|
from app.services.message_attachment_service import message_attachment_service
|
||||||
|
from app.services.messaging_service import messaging_service
|
||||||
|
from models.database.message import ConversationType, ParticipantType
|
||||||
|
from models.database.user import User
|
||||||
|
from models.schema.message import (
|
||||||
|
AdminConversationListResponse,
|
||||||
|
AdminConversationSummary,
|
||||||
|
CloseConversationResponse,
|
||||||
|
ConversationCreate,
|
||||||
|
ConversationDetailResponse,
|
||||||
|
MarkReadResponse,
|
||||||
|
MessageCreate,
|
||||||
|
MessageResponse,
|
||||||
|
NotificationPreferencesUpdate,
|
||||||
|
ParticipantInfo,
|
||||||
|
ParticipantResponse,
|
||||||
|
RecipientListResponse,
|
||||||
|
RecipientOption,
|
||||||
|
ReopenConversationResponse,
|
||||||
|
UnreadCountResponse,
|
||||||
|
)
|
||||||
|
from models.schema.message import AttachmentResponse
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/messages")
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# HELPER FUNCTIONS
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
def _enrich_message(
|
||||||
|
db: Session, message: Any, include_attachments: bool = True
|
||||||
|
) -> MessageResponse:
|
||||||
|
"""Enrich message with sender info and attachments."""
|
||||||
|
sender_info = messaging_service.get_participant_info(
|
||||||
|
db, message.sender_type, message.sender_id
|
||||||
|
)
|
||||||
|
|
||||||
|
attachments = []
|
||||||
|
if include_attachments and message.attachments:
|
||||||
|
for att in message.attachments:
|
||||||
|
attachments.append(
|
||||||
|
AttachmentResponse(
|
||||||
|
id=att.id,
|
||||||
|
filename=att.filename,
|
||||||
|
original_filename=att.original_filename,
|
||||||
|
file_size=att.file_size,
|
||||||
|
mime_type=att.mime_type,
|
||||||
|
is_image=att.is_image,
|
||||||
|
image_width=att.image_width,
|
||||||
|
image_height=att.image_height,
|
||||||
|
download_url=message_attachment_service.get_download_url(
|
||||||
|
att.file_path
|
||||||
|
),
|
||||||
|
thumbnail_url=(
|
||||||
|
message_attachment_service.get_download_url(att.thumbnail_path)
|
||||||
|
if att.thumbnail_path
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return MessageResponse(
|
||||||
|
id=message.id,
|
||||||
|
conversation_id=message.conversation_id,
|
||||||
|
sender_type=message.sender_type,
|
||||||
|
sender_id=message.sender_id,
|
||||||
|
content=message.content,
|
||||||
|
is_system_message=message.is_system_message,
|
||||||
|
is_deleted=message.is_deleted,
|
||||||
|
created_at=message.created_at,
|
||||||
|
sender_name=sender_info["name"] if sender_info else None,
|
||||||
|
sender_email=sender_info["email"] if sender_info else None,
|
||||||
|
attachments=attachments,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _enrich_conversation_summary(
|
||||||
|
db: Session, conversation: Any, current_user_id: int
|
||||||
|
) -> AdminConversationSummary:
|
||||||
|
"""Enrich conversation with other participant info and unread count."""
|
||||||
|
# Get current user's participant record
|
||||||
|
my_participant = next(
|
||||||
|
(
|
||||||
|
p
|
||||||
|
for p in conversation.participants
|
||||||
|
if p.participant_type == ParticipantType.ADMIN
|
||||||
|
and p.participant_id == current_user_id
|
||||||
|
),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
unread_count = my_participant.unread_count if my_participant else 0
|
||||||
|
|
||||||
|
# Get other participant info
|
||||||
|
other = messaging_service.get_other_participant(
|
||||||
|
conversation, ParticipantType.ADMIN, current_user_id
|
||||||
|
)
|
||||||
|
other_info = None
|
||||||
|
if other:
|
||||||
|
info = messaging_service.get_participant_info(
|
||||||
|
db, other.participant_type, other.participant_id
|
||||||
|
)
|
||||||
|
if info:
|
||||||
|
other_info = ParticipantInfo(
|
||||||
|
id=info["id"],
|
||||||
|
type=info["type"],
|
||||||
|
name=info["name"],
|
||||||
|
email=info.get("email"),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Get last message preview
|
||||||
|
last_message_preview = None
|
||||||
|
if conversation.messages:
|
||||||
|
last_msg = conversation.messages[-1] if conversation.messages else None
|
||||||
|
if last_msg:
|
||||||
|
preview = last_msg.content[:100]
|
||||||
|
if len(last_msg.content) > 100:
|
||||||
|
preview += "..."
|
||||||
|
last_message_preview = preview
|
||||||
|
|
||||||
|
# Get vendor info if applicable
|
||||||
|
vendor_name = None
|
||||||
|
vendor_code = None
|
||||||
|
if conversation.vendor:
|
||||||
|
vendor_name = conversation.vendor.name
|
||||||
|
vendor_code = conversation.vendor.vendor_code
|
||||||
|
|
||||||
|
return AdminConversationSummary(
|
||||||
|
id=conversation.id,
|
||||||
|
conversation_type=conversation.conversation_type,
|
||||||
|
subject=conversation.subject,
|
||||||
|
vendor_id=conversation.vendor_id,
|
||||||
|
is_closed=conversation.is_closed,
|
||||||
|
closed_at=conversation.closed_at,
|
||||||
|
last_message_at=conversation.last_message_at,
|
||||||
|
message_count=conversation.message_count,
|
||||||
|
created_at=conversation.created_at,
|
||||||
|
unread_count=unread_count,
|
||||||
|
other_participant=other_info,
|
||||||
|
last_message_preview=last_message_preview,
|
||||||
|
vendor_name=vendor_name,
|
||||||
|
vendor_code=vendor_code,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# CONVERSATION LIST
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=AdminConversationListResponse)
|
||||||
|
def list_conversations(
|
||||||
|
conversation_type: ConversationType | None = Query(None, description="Filter by type"),
|
||||||
|
is_closed: bool | None = Query(None, description="Filter by status"),
|
||||||
|
skip: int = Query(0, ge=0),
|
||||||
|
limit: int = Query(20, ge=1, le=100),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_admin: User = Depends(get_current_admin_api),
|
||||||
|
) -> AdminConversationListResponse:
|
||||||
|
"""List conversations for admin (admin_vendor and admin_customer channels)."""
|
||||||
|
conversations, total, total_unread = messaging_service.list_conversations(
|
||||||
|
db=db,
|
||||||
|
participant_type=ParticipantType.ADMIN,
|
||||||
|
participant_id=current_admin.id,
|
||||||
|
conversation_type=conversation_type,
|
||||||
|
is_closed=is_closed,
|
||||||
|
skip=skip,
|
||||||
|
limit=limit,
|
||||||
|
)
|
||||||
|
|
||||||
|
return AdminConversationListResponse(
|
||||||
|
conversations=[
|
||||||
|
_enrich_conversation_summary(db, c, current_admin.id) for c in conversations
|
||||||
|
],
|
||||||
|
total=total,
|
||||||
|
total_unread=total_unread,
|
||||||
|
skip=skip,
|
||||||
|
limit=limit,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/unread-count", response_model=UnreadCountResponse)
|
||||||
|
def get_unread_count(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_admin: User = Depends(get_current_admin_api),
|
||||||
|
) -> UnreadCountResponse:
|
||||||
|
"""Get total unread message count for header badge."""
|
||||||
|
count = messaging_service.get_unread_count(
|
||||||
|
db=db,
|
||||||
|
participant_type=ParticipantType.ADMIN,
|
||||||
|
participant_id=current_admin.id,
|
||||||
|
)
|
||||||
|
return UnreadCountResponse(total_unread=count)
|
||||||
|
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# RECIPIENTS
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/recipients", response_model=RecipientListResponse)
|
||||||
|
def get_recipients(
|
||||||
|
recipient_type: ParticipantType = Query(..., description="Type of recipients to list"),
|
||||||
|
search: str | None = Query(None, description="Search by name/email"),
|
||||||
|
vendor_id: int | None = Query(None, description="Filter by vendor"),
|
||||||
|
skip: int = Query(0, ge=0),
|
||||||
|
limit: int = Query(50, ge=1, le=100),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_admin: User = Depends(get_current_admin_api),
|
||||||
|
) -> RecipientListResponse:
|
||||||
|
"""Get list of available recipients for compose modal."""
|
||||||
|
from models.database.customer import Customer
|
||||||
|
from models.database.vendor import VendorUser
|
||||||
|
|
||||||
|
recipients = []
|
||||||
|
|
||||||
|
if recipient_type == ParticipantType.VENDOR:
|
||||||
|
# List vendor users (for admin_vendor conversations)
|
||||||
|
query = (
|
||||||
|
db.query(User, VendorUser)
|
||||||
|
.join(VendorUser, User.id == VendorUser.user_id)
|
||||||
|
.filter(User.is_active == True) # noqa: E712
|
||||||
|
)
|
||||||
|
if vendor_id:
|
||||||
|
query = query.filter(VendorUser.vendor_id == vendor_id)
|
||||||
|
if search:
|
||||||
|
search_pattern = f"%{search}%"
|
||||||
|
query = query.filter(
|
||||||
|
(User.username.ilike(search_pattern))
|
||||||
|
| (User.email.ilike(search_pattern))
|
||||||
|
| (User.first_name.ilike(search_pattern))
|
||||||
|
| (User.last_name.ilike(search_pattern))
|
||||||
|
)
|
||||||
|
|
||||||
|
total = query.count()
|
||||||
|
results = query.offset(skip).limit(limit).all()
|
||||||
|
|
||||||
|
for user, vendor_user in results:
|
||||||
|
name = f"{user.first_name or ''} {user.last_name or ''}".strip() or user.username
|
||||||
|
recipients.append(
|
||||||
|
RecipientOption(
|
||||||
|
id=user.id,
|
||||||
|
type=ParticipantType.VENDOR,
|
||||||
|
name=name,
|
||||||
|
email=user.email,
|
||||||
|
vendor_id=vendor_user.vendor_id,
|
||||||
|
vendor_name=vendor_user.vendor.name if vendor_user.vendor else None,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
elif recipient_type == ParticipantType.CUSTOMER:
|
||||||
|
# List customers (for admin_customer conversations)
|
||||||
|
query = db.query(Customer).filter(Customer.is_active == True) # noqa: E712
|
||||||
|
if vendor_id:
|
||||||
|
query = query.filter(Customer.vendor_id == vendor_id)
|
||||||
|
if search:
|
||||||
|
search_pattern = f"%{search}%"
|
||||||
|
query = query.filter(
|
||||||
|
(Customer.email.ilike(search_pattern))
|
||||||
|
| (Customer.first_name.ilike(search_pattern))
|
||||||
|
| (Customer.last_name.ilike(search_pattern))
|
||||||
|
)
|
||||||
|
|
||||||
|
total = query.count()
|
||||||
|
results = query.offset(skip).limit(limit).all()
|
||||||
|
|
||||||
|
for customer in results:
|
||||||
|
name = f"{customer.first_name or ''} {customer.last_name or ''}".strip()
|
||||||
|
recipients.append(
|
||||||
|
RecipientOption(
|
||||||
|
id=customer.id,
|
||||||
|
type=ParticipantType.CUSTOMER,
|
||||||
|
name=name or customer.email,
|
||||||
|
email=customer.email,
|
||||||
|
vendor_id=customer.vendor_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
total = 0
|
||||||
|
|
||||||
|
return RecipientListResponse(recipients=recipients, total=total)
|
||||||
|
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# CREATE CONVERSATION
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ConversationDetailResponse)
|
||||||
|
def create_conversation(
|
||||||
|
data: ConversationCreate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_admin: User = Depends(get_current_admin_api),
|
||||||
|
) -> ConversationDetailResponse:
|
||||||
|
"""Create a new conversation."""
|
||||||
|
# Validate conversation type for admin
|
||||||
|
if data.conversation_type not in [
|
||||||
|
ConversationType.ADMIN_VENDOR,
|
||||||
|
ConversationType.ADMIN_CUSTOMER,
|
||||||
|
]:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Admin can only create admin_vendor or admin_customer conversations",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Validate recipient type matches conversation type
|
||||||
|
if (
|
||||||
|
data.conversation_type == ConversationType.ADMIN_VENDOR
|
||||||
|
and data.recipient_type != ParticipantType.VENDOR
|
||||||
|
):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="admin_vendor conversations require a vendor recipient",
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
data.conversation_type == ConversationType.ADMIN_CUSTOMER
|
||||||
|
and data.recipient_type != ParticipantType.CUSTOMER
|
||||||
|
):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="admin_customer conversations require a customer recipient",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create conversation
|
||||||
|
conversation = messaging_service.create_conversation(
|
||||||
|
db=db,
|
||||||
|
conversation_type=data.conversation_type,
|
||||||
|
subject=data.subject,
|
||||||
|
initiator_type=ParticipantType.ADMIN,
|
||||||
|
initiator_id=current_admin.id,
|
||||||
|
recipient_type=data.recipient_type,
|
||||||
|
recipient_id=data.recipient_id,
|
||||||
|
vendor_id=data.vendor_id,
|
||||||
|
initial_message=data.initial_message,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(conversation)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Admin {current_admin.username} created conversation {conversation.id} "
|
||||||
|
f"with {data.recipient_type.value}:{data.recipient_id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Return full detail response
|
||||||
|
return _build_conversation_detail(db, conversation, current_admin.id)
|
||||||
|
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# CONVERSATION DETAIL
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
def _build_conversation_detail(
|
||||||
|
db: Session, conversation: Any, current_user_id: int
|
||||||
|
) -> ConversationDetailResponse:
|
||||||
|
"""Build full conversation detail response."""
|
||||||
|
# Get my participant for unread count
|
||||||
|
my_participant = next(
|
||||||
|
(
|
||||||
|
p
|
||||||
|
for p in conversation.participants
|
||||||
|
if p.participant_type == ParticipantType.ADMIN
|
||||||
|
and p.participant_id == current_user_id
|
||||||
|
),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
unread_count = my_participant.unread_count if my_participant else 0
|
||||||
|
|
||||||
|
# Build participant responses
|
||||||
|
participants = []
|
||||||
|
for p in conversation.participants:
|
||||||
|
info = messaging_service.get_participant_info(
|
||||||
|
db, p.participant_type, p.participant_id
|
||||||
|
)
|
||||||
|
participants.append(
|
||||||
|
ParticipantResponse(
|
||||||
|
id=p.id,
|
||||||
|
participant_type=p.participant_type,
|
||||||
|
participant_id=p.participant_id,
|
||||||
|
unread_count=p.unread_count,
|
||||||
|
last_read_at=p.last_read_at,
|
||||||
|
email_notifications=p.email_notifications,
|
||||||
|
muted=p.muted,
|
||||||
|
participant_info=(
|
||||||
|
ParticipantInfo(
|
||||||
|
id=info["id"],
|
||||||
|
type=info["type"],
|
||||||
|
name=info["name"],
|
||||||
|
email=info.get("email"),
|
||||||
|
)
|
||||||
|
if info
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Build message responses
|
||||||
|
messages = [_enrich_message(db, m) for m in conversation.messages]
|
||||||
|
|
||||||
|
# Get vendor name if applicable
|
||||||
|
vendor_name = None
|
||||||
|
if conversation.vendor:
|
||||||
|
vendor_name = conversation.vendor.name
|
||||||
|
|
||||||
|
return ConversationDetailResponse(
|
||||||
|
id=conversation.id,
|
||||||
|
conversation_type=conversation.conversation_type,
|
||||||
|
subject=conversation.subject,
|
||||||
|
vendor_id=conversation.vendor_id,
|
||||||
|
is_closed=conversation.is_closed,
|
||||||
|
closed_at=conversation.closed_at,
|
||||||
|
closed_by_type=conversation.closed_by_type,
|
||||||
|
closed_by_id=conversation.closed_by_id,
|
||||||
|
last_message_at=conversation.last_message_at,
|
||||||
|
message_count=conversation.message_count,
|
||||||
|
created_at=conversation.created_at,
|
||||||
|
updated_at=conversation.updated_at,
|
||||||
|
participants=participants,
|
||||||
|
messages=messages,
|
||||||
|
unread_count=unread_count,
|
||||||
|
vendor_name=vendor_name,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{conversation_id}", response_model=ConversationDetailResponse)
|
||||||
|
def get_conversation(
|
||||||
|
conversation_id: int,
|
||||||
|
mark_read: bool = Query(True, description="Automatically mark as read"),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_admin: User = Depends(get_current_admin_api),
|
||||||
|
) -> ConversationDetailResponse:
|
||||||
|
"""Get conversation detail with messages."""
|
||||||
|
conversation = messaging_service.get_conversation(
|
||||||
|
db=db,
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
participant_type=ParticipantType.ADMIN,
|
||||||
|
participant_id=current_admin.id,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not conversation:
|
||||||
|
raise HTTPException(status_code=404, detail="Conversation not found")
|
||||||
|
|
||||||
|
# Mark as read if requested
|
||||||
|
if mark_read:
|
||||||
|
messaging_service.mark_conversation_read(
|
||||||
|
db=db,
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
reader_type=ParticipantType.ADMIN,
|
||||||
|
reader_id=current_admin.id,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
return _build_conversation_detail(db, conversation, current_admin.id)
|
||||||
|
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# SEND MESSAGE
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{conversation_id}/messages", response_model=MessageResponse)
|
||||||
|
async def send_message(
|
||||||
|
conversation_id: int,
|
||||||
|
content: str = Form(...),
|
||||||
|
files: list[UploadFile] = File(default=[]),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_admin: User = Depends(get_current_admin_api),
|
||||||
|
) -> MessageResponse:
|
||||||
|
"""Send a message in a conversation, optionally with attachments."""
|
||||||
|
# Verify access
|
||||||
|
conversation = messaging_service.get_conversation(
|
||||||
|
db=db,
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
participant_type=ParticipantType.ADMIN,
|
||||||
|
participant_id=current_admin.id,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not conversation:
|
||||||
|
raise HTTPException(status_code=404, detail="Conversation not found")
|
||||||
|
|
||||||
|
if conversation.is_closed:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400, detail="Cannot send messages to a closed conversation"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Process attachments
|
||||||
|
attachments = []
|
||||||
|
for file in files:
|
||||||
|
try:
|
||||||
|
att_data = await message_attachment_service.validate_and_store(
|
||||||
|
db=db, file=file, conversation_id=conversation_id
|
||||||
|
)
|
||||||
|
attachments.append(att_data)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
# Send message
|
||||||
|
message = messaging_service.send_message(
|
||||||
|
db=db,
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
sender_type=ParticipantType.ADMIN,
|
||||||
|
sender_id=current_admin.id,
|
||||||
|
content=content,
|
||||||
|
attachments=attachments if attachments else None,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(message)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Admin {current_admin.username} sent message {message.id} "
|
||||||
|
f"in conversation {conversation_id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return _enrich_message(db, message)
|
||||||
|
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# CONVERSATION ACTIONS
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{conversation_id}/close", response_model=CloseConversationResponse)
|
||||||
|
def close_conversation(
|
||||||
|
conversation_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_admin: User = Depends(get_current_admin_api),
|
||||||
|
) -> CloseConversationResponse:
|
||||||
|
"""Close a conversation."""
|
||||||
|
conversation = messaging_service.close_conversation(
|
||||||
|
db=db,
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
closer_type=ParticipantType.ADMIN,
|
||||||
|
closer_id=current_admin.id,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not conversation:
|
||||||
|
raise HTTPException(status_code=404, detail="Conversation not found")
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
logger.info(
|
||||||
|
f"Admin {current_admin.username} closed conversation {conversation_id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return CloseConversationResponse(
|
||||||
|
success=True,
|
||||||
|
message="Conversation closed",
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{conversation_id}/reopen", response_model=ReopenConversationResponse)
|
||||||
|
def reopen_conversation(
|
||||||
|
conversation_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_admin: User = Depends(get_current_admin_api),
|
||||||
|
) -> ReopenConversationResponse:
|
||||||
|
"""Reopen a closed conversation."""
|
||||||
|
conversation = messaging_service.reopen_conversation(
|
||||||
|
db=db,
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
opener_type=ParticipantType.ADMIN,
|
||||||
|
opener_id=current_admin.id,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not conversation:
|
||||||
|
raise HTTPException(status_code=404, detail="Conversation not found")
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
logger.info(
|
||||||
|
f"Admin {current_admin.username} reopened conversation {conversation_id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return ReopenConversationResponse(
|
||||||
|
success=True,
|
||||||
|
message="Conversation reopened",
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{conversation_id}/read", response_model=MarkReadResponse)
|
||||||
|
def mark_read(
|
||||||
|
conversation_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_admin: User = Depends(get_current_admin_api),
|
||||||
|
) -> MarkReadResponse:
|
||||||
|
"""Mark conversation as read."""
|
||||||
|
success = messaging_service.mark_conversation_read(
|
||||||
|
db=db,
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
reader_type=ParticipantType.ADMIN,
|
||||||
|
reader_id=current_admin.id,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
return MarkReadResponse(
|
||||||
|
success=success,
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
unread_count=0,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class PreferencesUpdateResponse(BaseModel):
|
||||||
|
"""Response for preferences update."""
|
||||||
|
success: bool
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{conversation_id}/preferences", response_model=PreferencesUpdateResponse)
|
||||||
|
def update_preferences(
|
||||||
|
conversation_id: int,
|
||||||
|
preferences: NotificationPreferencesUpdate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_admin: User = Depends(get_current_admin_api),
|
||||||
|
) -> PreferencesUpdateResponse:
|
||||||
|
"""Update notification preferences for a conversation."""
|
||||||
|
success = messaging_service.update_notification_preferences(
|
||||||
|
db=db,
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
participant_type=ParticipantType.ADMIN,
|
||||||
|
participant_id=current_admin.id,
|
||||||
|
email_notifications=preferences.email_notifications,
|
||||||
|
muted=preferences.muted,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
return PreferencesUpdateResponse(success=success)
|
||||||
@@ -476,6 +476,79 @@ async def admin_customers_page(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# NOTIFICATIONS ROUTES
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/notifications", response_class=HTMLResponse, include_in_schema=False)
|
||||||
|
async def admin_notifications_page(
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(get_current_admin_from_cookie_or_header),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Render notifications management page.
|
||||||
|
Shows all admin notifications and platform alerts.
|
||||||
|
"""
|
||||||
|
return templates.TemplateResponse(
|
||||||
|
"admin/notifications.html",
|
||||||
|
{
|
||||||
|
"request": request,
|
||||||
|
"user": current_user,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# MESSAGING ROUTES
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/messages", response_class=HTMLResponse, include_in_schema=False)
|
||||||
|
async def admin_messages_page(
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(get_current_admin_from_cookie_or_header),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Render messaging page.
|
||||||
|
Shows all conversations (admin_vendor and admin_customer channels).
|
||||||
|
"""
|
||||||
|
return templates.TemplateResponse(
|
||||||
|
"admin/messages.html",
|
||||||
|
{
|
||||||
|
"request": request,
|
||||||
|
"user": current_user,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/messages/{conversation_id}",
|
||||||
|
response_class=HTMLResponse,
|
||||||
|
include_in_schema=False,
|
||||||
|
)
|
||||||
|
async def admin_conversation_detail_page(
|
||||||
|
request: Request,
|
||||||
|
conversation_id: int = Path(..., description="Conversation ID"),
|
||||||
|
current_user: User = Depends(get_current_admin_from_cookie_or_header),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Render conversation detail page.
|
||||||
|
Shows the full conversation thread with messages.
|
||||||
|
"""
|
||||||
|
return templates.TemplateResponse(
|
||||||
|
"admin/messages.html",
|
||||||
|
{
|
||||||
|
"request": request,
|
||||||
|
"user": current_user,
|
||||||
|
"conversation_id": conversation_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# INVENTORY MANAGEMENT ROUTES
|
# INVENTORY MANAGEMENT ROUTES
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
|
|||||||
358
app/templates/admin/messages.html
Normal file
358
app/templates/admin/messages.html
Normal file
@@ -0,0 +1,358 @@
|
|||||||
|
{# app/templates/admin/messages.html #}
|
||||||
|
{% extends "admin/base.html" %}
|
||||||
|
{% from 'shared/macros/headers.html' import page_header %}
|
||||||
|
{% from 'shared/macros/alerts.html' import loading_state, error_state %}
|
||||||
|
|
||||||
|
{% block title %}Messages{% endblock %}
|
||||||
|
|
||||||
|
{% block alpine_data %}adminMessages({{ conversation_id or 'null' }}){% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{{ page_header('Messages', buttons=[
|
||||||
|
{'text': 'New Conversation', 'icon': 'plus', 'click': 'showComposeModal = true', 'primary': True}
|
||||||
|
]) }}
|
||||||
|
|
||||||
|
{{ loading_state('Loading conversations...') }}
|
||||||
|
|
||||||
|
{{ error_state('Error loading conversations') }}
|
||||||
|
|
||||||
|
<!-- Main Messages Layout -->
|
||||||
|
<div x-show="!loading" class="flex gap-6 h-[calc(100vh-220px)]">
|
||||||
|
<!-- Conversations List (Left Panel) -->
|
||||||
|
<div class="w-96 flex-shrink-0 flex flex-col bg-white rounded-lg shadow-md dark:bg-gray-800 overflow-hidden">
|
||||||
|
<!-- Filters -->
|
||||||
|
<div class="p-4 border-b border-gray-200 dark:border-gray-700">
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<select
|
||||||
|
x-model="filters.conversation_type"
|
||||||
|
@change="page = 1; loadConversations()"
|
||||||
|
class="flex-1 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
|
||||||
|
>
|
||||||
|
<option value="">All Types</option>
|
||||||
|
<option value="admin_vendor">Vendors</option>
|
||||||
|
<option value="admin_customer">Customers</option>
|
||||||
|
</select>
|
||||||
|
<select
|
||||||
|
x-model="filters.is_closed"
|
||||||
|
@change="page = 1; loadConversations()"
|
||||||
|
class="flex-1 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
|
||||||
|
>
|
||||||
|
<option value="">All Status</option>
|
||||||
|
<option value="false">Open</option>
|
||||||
|
<option value="true">Closed</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Conversation List -->
|
||||||
|
<div class="flex-1 overflow-y-auto">
|
||||||
|
<template x-if="loadingConversations && conversations.length === 0">
|
||||||
|
<div class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
|
||||||
|
<span x-html="$icon('spinner', 'w-6 h-6 mx-auto mb-2 animate-spin')"></span>
|
||||||
|
<p>Loading...</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template x-if="!loadingConversations && conversations.length === 0">
|
||||||
|
<div class="px-4 py-12 text-center text-gray-500 dark:text-gray-400">
|
||||||
|
<span x-html="$icon('chat-bubble-left-right', 'w-12 h-12 mx-auto mb-3 text-gray-300')"></span>
|
||||||
|
<p class="font-medium">No conversations</p>
|
||||||
|
<p class="text-sm mt-1">Start a new conversation</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<ul class="divide-y divide-gray-200 dark:divide-gray-700">
|
||||||
|
<template x-for="conv in conversations" :key="conv.id">
|
||||||
|
<li
|
||||||
|
@click="selectConversation(conv.id)"
|
||||||
|
class="px-4 py-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
|
||||||
|
:class="{
|
||||||
|
'bg-purple-50 dark:bg-purple-900/20': selectedConversationId === conv.id,
|
||||||
|
'border-l-4 border-purple-500': selectedConversationId === conv.id
|
||||||
|
}"
|
||||||
|
>
|
||||||
|
<div class="flex items-start justify-between">
|
||||||
|
<div class="flex-1 min-w-0">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate" x-text="conv.subject"></span>
|
||||||
|
<span x-show="conv.unread_count > 0"
|
||||||
|
class="px-2 py-0.5 text-xs bg-red-100 text-red-600 rounded-full dark:bg-red-600 dark:text-white"
|
||||||
|
x-text="conv.unread_count"></span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2 mt-1">
|
||||||
|
<span class="inline-flex items-center px-1.5 py-0.5 text-xs rounded"
|
||||||
|
:class="conv.conversation_type === 'admin_vendor' ? 'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300' : 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300'"
|
||||||
|
x-text="conv.conversation_type === 'admin_vendor' ? 'Vendor' : 'Customer'"></span>
|
||||||
|
<span class="text-xs text-gray-500 dark:text-gray-400 truncate" x-text="conv.other_participant?.name || 'Unknown'"></span>
|
||||||
|
</div>
|
||||||
|
<p x-show="conv.last_message_preview"
|
||||||
|
class="text-xs text-gray-500 dark:text-gray-400 mt-1 truncate"
|
||||||
|
x-text="conv.last_message_preview"></p>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col items-end ml-2">
|
||||||
|
<span class="text-xs text-gray-400" x-text="formatRelativeTime(conv.last_message_at || conv.created_at)"></span>
|
||||||
|
<span x-show="conv.is_closed"
|
||||||
|
class="mt-1 px-1.5 py-0.5 text-xs bg-gray-100 text-gray-500 rounded dark:bg-gray-700">
|
||||||
|
Closed
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
</template>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Pagination -->
|
||||||
|
<div x-show="totalConversations > limit" class="p-3 border-t border-gray-200 dark:border-gray-700">
|
||||||
|
<div class="flex items-center justify-between text-sm">
|
||||||
|
<span class="text-gray-500 dark:text-gray-400" x-text="`${skip + 1}-${Math.min(skip + limit, totalConversations)} of ${totalConversations}`"></span>
|
||||||
|
<div class="flex gap-1">
|
||||||
|
<button @click="page--; loadConversations()" :disabled="page <= 1"
|
||||||
|
class="px-2 py-1 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded disabled:opacity-50">
|
||||||
|
<span x-html="$icon('chevron-left', 'w-4 h-4')"></span>
|
||||||
|
</button>
|
||||||
|
<button @click="page++; loadConversations()" :disabled="page * limit >= totalConversations"
|
||||||
|
class="px-2 py-1 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded disabled:opacity-50">
|
||||||
|
<span x-html="$icon('chevron-right', 'w-4 h-4')"></span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Conversation Detail (Right Panel) -->
|
||||||
|
<div class="flex-1 flex flex-col bg-white rounded-lg shadow-md dark:bg-gray-800 overflow-hidden">
|
||||||
|
<!-- No conversation selected -->
|
||||||
|
<template x-if="!selectedConversationId">
|
||||||
|
<div class="flex-1 flex items-center justify-center text-gray-500 dark:text-gray-400">
|
||||||
|
<div class="text-center">
|
||||||
|
<span x-html="$icon('chat-bubble-left-right', 'w-16 h-16 mx-auto mb-4 text-gray-300')"></span>
|
||||||
|
<p class="font-medium">Select a conversation</p>
|
||||||
|
<p class="text-sm mt-1">Or start a new one</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Conversation loaded -->
|
||||||
|
<template x-if="selectedConversationId && selectedConversation">
|
||||||
|
<div class="flex flex-col h-full">
|
||||||
|
<!-- Header -->
|
||||||
|
<div class="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700">
|
||||||
|
<div>
|
||||||
|
<h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100" x-text="selectedConversation.subject"></h3>
|
||||||
|
<div class="flex items-center gap-2 mt-1">
|
||||||
|
<span class="text-sm text-gray-500 dark:text-gray-400">
|
||||||
|
with <span class="font-medium" x-text="getOtherParticipantName()"></span>
|
||||||
|
</span>
|
||||||
|
<span x-show="selectedConversation.vendor_name"
|
||||||
|
class="text-xs text-gray-400">
|
||||||
|
(<span x-text="selectedConversation.vendor_name"></span>)
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<template x-if="!selectedConversation.is_closed">
|
||||||
|
<button @click="closeConversation()"
|
||||||
|
class="px-3 py-1.5 text-sm font-medium text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600">
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
<template x-if="selectedConversation.is_closed">
|
||||||
|
<button @click="reopenConversation()"
|
||||||
|
class="px-3 py-1.5 text-sm font-medium text-purple-600 bg-purple-100 rounded-lg hover:bg-purple-200 dark:bg-purple-900 dark:text-purple-300">
|
||||||
|
Reopen
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Messages -->
|
||||||
|
<div class="flex-1 overflow-y-auto p-4 space-y-4" x-ref="messagesContainer">
|
||||||
|
<template x-if="loadingMessages">
|
||||||
|
<div class="flex items-center justify-center py-8">
|
||||||
|
<span x-html="$icon('spinner', 'w-6 h-6 animate-spin text-purple-500')"></span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template x-for="msg in selectedConversation.messages" :key="msg.id">
|
||||||
|
<div class="flex"
|
||||||
|
:class="msg.sender_type === 'admin' ? 'justify-end' : 'justify-start'">
|
||||||
|
<!-- System message -->
|
||||||
|
<template x-if="msg.is_system_message">
|
||||||
|
<div class="text-center w-full py-2">
|
||||||
|
<span class="px-3 py-1 text-xs text-gray-500 bg-gray-100 rounded-full dark:bg-gray-700 dark:text-gray-400"
|
||||||
|
x-text="msg.content"></span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Regular message -->
|
||||||
|
<template x-if="!msg.is_system_message">
|
||||||
|
<div class="max-w-[70%]">
|
||||||
|
<div class="rounded-lg px-4 py-2"
|
||||||
|
:class="msg.sender_type === 'admin'
|
||||||
|
? 'bg-purple-600 text-white'
|
||||||
|
: 'bg-gray-100 text-gray-900 dark:bg-gray-700 dark:text-gray-100'">
|
||||||
|
<p class="text-sm whitespace-pre-wrap" x-text="msg.content"></p>
|
||||||
|
|
||||||
|
<!-- Attachments -->
|
||||||
|
<template x-if="msg.attachments && msg.attachments.length > 0">
|
||||||
|
<div class="mt-2 space-y-1">
|
||||||
|
<template x-for="att in msg.attachments" :key="att.id">
|
||||||
|
<a :href="att.download_url"
|
||||||
|
target="_blank"
|
||||||
|
class="flex items-center gap-2 text-xs underline"
|
||||||
|
:class="msg.sender_type === 'admin' ? 'text-purple-200 hover:text-white' : 'text-purple-600 hover:text-purple-800 dark:text-purple-400'">
|
||||||
|
<span x-html="att.is_image ? $icon('photo', 'w-4 h-4') : $icon('paper-clip', 'w-4 h-4')"></span>
|
||||||
|
<span x-text="att.original_filename"></span>
|
||||||
|
</a>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2 mt-1 px-1"
|
||||||
|
:class="msg.sender_type === 'admin' ? 'justify-end' : 'justify-start'">
|
||||||
|
<span class="text-xs text-gray-400" x-text="msg.sender_name || 'Unknown'"></span>
|
||||||
|
<span class="text-xs text-gray-400" x-text="formatTime(msg.created_at)"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Reply Form -->
|
||||||
|
<template x-if="!selectedConversation.is_closed">
|
||||||
|
<div class="border-t border-gray-200 dark:border-gray-700 p-4">
|
||||||
|
<form @submit.prevent="sendMessage()" class="flex gap-3">
|
||||||
|
<div class="flex-1">
|
||||||
|
<textarea
|
||||||
|
x-model="replyContent"
|
||||||
|
@keydown.enter.meta="sendMessage()"
|
||||||
|
@keydown.enter.ctrl="sendMessage()"
|
||||||
|
rows="2"
|
||||||
|
placeholder="Type your message... (Cmd/Ctrl+Enter to send)"
|
||||||
|
class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300 resize-none"
|
||||||
|
></textarea>
|
||||||
|
<div class="flex items-center justify-between mt-2">
|
||||||
|
<label class="flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400 cursor-pointer hover:text-gray-700 dark:hover:text-gray-300">
|
||||||
|
<input type="file" multiple @change="handleFileSelect" class="hidden" x-ref="fileInput">
|
||||||
|
<span x-html="$icon('paper-clip', 'w-5 h-5')"></span>
|
||||||
|
<span>Attach files</span>
|
||||||
|
</label>
|
||||||
|
<template x-if="attachedFiles.length > 0">
|
||||||
|
<div class="flex items-center gap-2 text-sm text-gray-500">
|
||||||
|
<span x-text="attachedFiles.length + ' file(s)'"></span>
|
||||||
|
<button type="button" @click="attachedFiles = []" class="text-red-500 hover:text-red-700">
|
||||||
|
<span x-html="$icon('x-mark', 'w-4 h-4')"></span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button type="submit"
|
||||||
|
:disabled="!replyContent.trim() && attachedFiles.length === 0 || sendingMessage"
|
||||||
|
class="px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed self-end">
|
||||||
|
<span x-show="!sendingMessage" x-html="$icon('paper-airplane', 'w-5 h-5')"></span>
|
||||||
|
<span x-show="sendingMessage" x-html="$icon('spinner', 'w-5 h-5 animate-spin')"></span>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Closed message -->
|
||||||
|
<template x-if="selectedConversation.is_closed">
|
||||||
|
<div class="border-t border-gray-200 dark:border-gray-700 p-4 text-center text-gray-500 dark:text-gray-400">
|
||||||
|
<p class="text-sm">This conversation is closed. Reopen it to send messages.</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Compose Modal -->
|
||||||
|
<div x-show="showComposeModal"
|
||||||
|
x-cloak
|
||||||
|
class="fixed inset-0 z-50 flex items-center justify-center"
|
||||||
|
@keydown.escape.window="showComposeModal = false">
|
||||||
|
<div class="absolute inset-0 bg-black bg-opacity-50" @click="showComposeModal = false"></div>
|
||||||
|
<div class="relative bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-lg mx-4">
|
||||||
|
<div class="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
|
||||||
|
<h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">New Conversation</h3>
|
||||||
|
<button @click="showComposeModal = false" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
|
||||||
|
<span x-html="$icon('x-mark', 'w-5 h-5')"></span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form @submit.prevent="createConversation()" class="p-6 space-y-4">
|
||||||
|
<!-- Recipient Type -->
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Send to</label>
|
||||||
|
<select
|
||||||
|
x-model="compose.recipientType"
|
||||||
|
@change="compose.recipientId = null; loadRecipients()"
|
||||||
|
class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
|
||||||
|
>
|
||||||
|
<option value="">Select type...</option>
|
||||||
|
<option value="vendor">Vendor</option>
|
||||||
|
<option value="customer">Customer</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Recipient -->
|
||||||
|
<div x-show="compose.recipientType">
|
||||||
|
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Recipient</label>
|
||||||
|
<select
|
||||||
|
x-model="compose.recipientId"
|
||||||
|
class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
|
||||||
|
>
|
||||||
|
<option value="">Select recipient...</option>
|
||||||
|
<template x-for="r in recipients" :key="r.id">
|
||||||
|
<option :value="r.id" x-text="r.name + (r.vendor_name ? ' (' + r.vendor_name + ')' : '') + ' - ' + (r.email || '')"></option>
|
||||||
|
</template>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Subject -->
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Subject</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
x-model="compose.subject"
|
||||||
|
placeholder="What is this about?"
|
||||||
|
class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Message -->
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Message</label>
|
||||||
|
<textarea
|
||||||
|
x-model="compose.message"
|
||||||
|
rows="4"
|
||||||
|
placeholder="Type your message..."
|
||||||
|
class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300 resize-none"
|
||||||
|
></textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Actions -->
|
||||||
|
<div class="flex justify-end gap-3 pt-4">
|
||||||
|
<button type="button" @click="showComposeModal = false"
|
||||||
|
class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button type="submit"
|
||||||
|
:disabled="!compose.recipientId || !compose.subject.trim() || creatingConversation"
|
||||||
|
class="px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 disabled:opacity-50">
|
||||||
|
<span x-show="!creatingConversation">Start Conversation</span>
|
||||||
|
<span x-show="creatingConversation">Creating...</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block page_scripts %}
|
||||||
|
<script src="{{ url_for('static', path='admin/js/messages.js') }}"></script>
|
||||||
|
{% endblock %}
|
||||||
@@ -29,57 +29,121 @@
|
|||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
|
|
||||||
|
<!-- Messages link with badge -->
|
||||||
|
<li class="relative" x-data="headerMessages()">
|
||||||
|
<a href="/admin/messages"
|
||||||
|
class="relative align-middle rounded-md focus:outline-none focus:shadow-outline-purple"
|
||||||
|
aria-label="Messages">
|
||||||
|
<span x-html="$icon('chat-bubble-left-right', 'w-5 h-5')"></span>
|
||||||
|
<!-- Unread badge -->
|
||||||
|
<span x-show="unreadCount > 0"
|
||||||
|
aria-hidden="true"
|
||||||
|
class="absolute top-0 right-0 inline-flex items-center justify-center w-4 h-4 text-xs font-bold text-white transform translate-x-1 -translate-y-1 bg-green-600 border-2 border-white rounded-full dark:border-gray-800"
|
||||||
|
x-text="unreadCount > 9 ? '9+' : unreadCount"></span>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
|
||||||
<!-- Notifications menu -->
|
<!-- Notifications menu -->
|
||||||
<li class="relative" x-data="{ notifOpen: false }">
|
<li class="relative" x-data="headerNotifications()">
|
||||||
<button class="relative align-middle rounded-md focus:outline-none focus:shadow-outline-purple"
|
<button class="relative align-middle rounded-md focus:outline-none focus:shadow-outline-purple"
|
||||||
@click="notifOpen = !notifOpen"
|
@click="toggleDropdown()"
|
||||||
@keydown.escape="notifOpen = false"
|
@keydown.escape="notifOpen = false"
|
||||||
aria-label="Notifications" aria-haspopup="true">
|
aria-label="Notifications" aria-haspopup="true">
|
||||||
<span x-html="$icon('bell', 'w-5 h-5')"></span>
|
<span x-html="$icon('bell', 'w-5 h-5')"></span>
|
||||||
<span aria-hidden="true" class="absolute top-0 right-0 inline-block w-3 h-3 transform translate-x-1 -translate-y-1 bg-red-600 border-2 border-white rounded-full dark:border-gray-800"></span>
|
<!-- Notification badge -->
|
||||||
|
<span x-show="unreadCount > 0"
|
||||||
|
aria-hidden="true"
|
||||||
|
class="absolute top-0 right-0 inline-flex items-center justify-center w-4 h-4 text-xs font-bold text-white transform translate-x-1 -translate-y-1 bg-red-600 border-2 border-white rounded-full dark:border-gray-800"
|
||||||
|
x-text="unreadCount > 9 ? '9+' : unreadCount"></span>
|
||||||
|
<span x-show="unreadCount === 0"
|
||||||
|
aria-hidden="true"
|
||||||
|
class="absolute top-0 right-0 inline-block w-2 h-2 transform translate-x-1 -translate-y-1 bg-gray-400 rounded-full dark:border-gray-800"></span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<ul x-show="notifOpen"
|
<div x-show="notifOpen"
|
||||||
x-cloak
|
x-cloak
|
||||||
x-transition:leave="transition ease-in duration-150"
|
x-transition:leave="transition ease-in duration-150"
|
||||||
x-transition:leave-start="opacity-100"
|
x-transition:leave-start="opacity-100"
|
||||||
x-transition:leave-end="opacity-0"
|
x-transition:leave-end="opacity-0"
|
||||||
@click.away="notifOpen = false"
|
@click.away="notifOpen = false"
|
||||||
@keydown.escape="notifOpen = false"
|
@keydown.escape="notifOpen = false"
|
||||||
class="absolute right-0 w-56 p-2 mt-2 space-y-2 text-gray-600 bg-white border border-gray-100 rounded-md shadow-md dark:text-gray-300 dark:border-gray-700 dark:bg-gray-700">
|
class="absolute right-0 w-80 mt-2 text-gray-600 bg-white border border-gray-100 rounded-md shadow-lg dark:text-gray-300 dark:border-gray-700 dark:bg-gray-700 z-50">
|
||||||
<li class="flex">
|
|
||||||
<a class="inline-flex items-center justify-between w-full px-2 py-1 text-sm font-semibold transition-colors duration-150 rounded-md hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200" href="#">
|
<!-- Header -->
|
||||||
<span>Messages</span>
|
<div class="flex items-center justify-between px-4 py-2 border-b dark:border-gray-600">
|
||||||
<span class="inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-red-600 bg-red-100 rounded-full dark:text-red-100 dark:bg-red-600">13</span>
|
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">Notifications</h3>
|
||||||
|
<template x-if="unreadCount > 0">
|
||||||
|
<button @click="markAllRead()"
|
||||||
|
class="text-xs text-purple-600 hover:text-purple-800 dark:text-purple-400">
|
||||||
|
Mark all read
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Notifications list -->
|
||||||
|
<ul class="max-h-64 overflow-y-auto">
|
||||||
|
<!-- Loading state -->
|
||||||
|
<template x-if="loading">
|
||||||
|
<li class="px-4 py-3 text-center text-sm text-gray-500">
|
||||||
|
<span x-html="$icon('spinner', 'w-4 h-4 inline mr-2')"></span>
|
||||||
|
Loading...
|
||||||
|
</li>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Empty state -->
|
||||||
|
<template x-if="!loading && notifications.length === 0">
|
||||||
|
<li class="px-4 py-6 text-center">
|
||||||
|
<span x-html="$icon('bell', 'w-8 h-8 mx-auto mb-2 text-gray-300')"></span>
|
||||||
|
<p class="text-sm text-gray-500">No notifications</p>
|
||||||
|
</li>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Notification items -->
|
||||||
|
<template x-for="notif in notifications" :key="notif.id">
|
||||||
|
<li class="border-b dark:border-gray-600 last:border-0">
|
||||||
|
<a :href="notif.action_url || '/admin/notifications'"
|
||||||
|
@click="markAsRead(notif.id)"
|
||||||
|
class="flex items-start px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors">
|
||||||
|
<!-- Priority indicator -->
|
||||||
|
<span class="flex-shrink-0 w-2 h-2 mt-2 mr-3 rounded-full"
|
||||||
|
:class="{
|
||||||
|
'bg-red-500': notif.priority === 'critical',
|
||||||
|
'bg-orange-500': notif.priority === 'high',
|
||||||
|
'bg-blue-500': notif.priority === 'normal',
|
||||||
|
'bg-gray-400': notif.priority === 'low'
|
||||||
|
}"></span>
|
||||||
|
<div class="flex-1 min-w-0">
|
||||||
|
<p class="text-sm font-medium text-gray-800 dark:text-gray-200 truncate" x-text="notif.title"></p>
|
||||||
|
<p class="text-xs text-gray-500 dark:text-gray-400 line-clamp-2" x-text="notif.message"></p>
|
||||||
|
<p class="text-xs text-gray-400 mt-1" x-text="formatTimeAgo(notif.created_at)"></p>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
</template>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<!-- Footer -->
|
||||||
|
<div class="px-4 py-2 border-t dark:border-gray-600">
|
||||||
|
<a href="/admin/notifications"
|
||||||
|
class="block text-center text-sm text-purple-600 hover:text-purple-800 dark:text-purple-400">
|
||||||
|
View all notifications
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</div>
|
||||||
<li class="flex">
|
</div>
|
||||||
<a class="inline-flex items-center justify-between w-full px-2 py-1 text-sm font-semibold transition-colors duration-150 rounded-md hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200" href="#">
|
|
||||||
<span>Sales</span>
|
|
||||||
<span class="inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-red-600 bg-red-100 rounded-full dark:text-red-100 dark:bg-red-600">2</span>
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
<li class="flex">
|
|
||||||
<a class="inline-flex items-center justify-between w-full px-2 py-1 text-sm font-semibold transition-colors duration-150 rounded-md hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200" href="#">
|
|
||||||
<span>Alerts</span>
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</li>
|
</li>
|
||||||
|
|
||||||
<!-- Profile menu - ✅ FIXED with self-contained Alpine data -->
|
<!-- Profile menu -->
|
||||||
<li class="relative" x-data="{ profileOpen: false }">
|
<li class="relative" x-data="{ profileOpen: false }">
|
||||||
<button class="align-middle rounded-full focus:shadow-outline-purple focus:outline-none"
|
<button class="align-middle rounded-full focus:shadow-outline-purple focus:outline-none"
|
||||||
@click="profileOpen = !profileOpen"
|
@click="profileOpen = !profileOpen"
|
||||||
@keydown.escape="profileOpen = false"
|
@keydown.escape="profileOpen = false"
|
||||||
aria-label="Account"
|
aria-label="Account"
|
||||||
aria-haspopup="true">
|
aria-haspopup="true">
|
||||||
<img class="object-cover w-8 h-8 rounded-full"
|
<img class="object-cover w-8 h-8 rounded-full"
|
||||||
src="https://images.unsplash.com/photo-1502378735452-bc7d86632805?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&s=aa3a807e1bbdfd4364d1f449eaa96d82"
|
src="https://images.unsplash.com/photo-1502378735452-bc7d86632805?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&s=aa3a807e1bbdfd4364d1f449eaa96d82"
|
||||||
alt="" aria-hidden="true"/>
|
alt="" aria-hidden="true"/>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<!-- Use x-show instead of x-if for reliability -->
|
|
||||||
<ul x-show="profileOpen"
|
<ul x-show="profileOpen"
|
||||||
x-cloak
|
x-cloak
|
||||||
x-transition:leave="transition ease-in duration-150"
|
x-transition:leave="transition ease-in duration-150"
|
||||||
@@ -97,13 +161,13 @@
|
|||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
<li class="flex">
|
<li class="flex">
|
||||||
<a class="inline-flex items-center w-full px-2 py-1 text-sm font-semibold transition-colors duration-150 rounded-md hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200" href="#">
|
<a class="inline-flex items-center w-full px-2 py-1 text-sm font-semibold transition-colors duration-150 rounded-md hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200" href="/admin/settings">
|
||||||
<span x-html="$icon('cog', 'w-4 h-4 mr-3')"></span>
|
<span x-html="$icon('cog', 'w-4 h-4 mr-3')"></span>
|
||||||
<span>Settings</span>
|
<span>Settings</span>
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
<li class="flex">
|
<li class="flex">
|
||||||
<button
|
<button
|
||||||
@click="handleLogout()"
|
@click="handleLogout()"
|
||||||
class="inline-flex items-center w-full px-2 py-1 text-sm font-semibold transition-colors duration-150 rounded-md hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200 text-left">
|
class="inline-flex items-center w-full px-2 py-1 text-sm font-semibold transition-colors duration-150 rounded-md hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200 text-left">
|
||||||
<span x-html="$icon('logout', 'w-4 h-4 mr-3')"></span>
|
<span x-html="$icon('logout', 'w-4 h-4 mr-3')"></span>
|
||||||
@@ -116,8 +180,85 @@
|
|||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<!-- Logout handler script -->
|
<!-- Header notifications and logout handler script -->
|
||||||
<script>
|
<script>
|
||||||
|
// Header notifications component
|
||||||
|
function headerNotifications() {
|
||||||
|
return {
|
||||||
|
notifOpen: false,
|
||||||
|
loading: false,
|
||||||
|
notifications: [],
|
||||||
|
unreadCount: 0,
|
||||||
|
pollInterval: null,
|
||||||
|
|
||||||
|
init() {
|
||||||
|
this.loadNotifications();
|
||||||
|
// Poll for new notifications every 60 seconds
|
||||||
|
this.pollInterval = setInterval(() => this.loadNotifications(), 60000);
|
||||||
|
},
|
||||||
|
|
||||||
|
destroy() {
|
||||||
|
if (this.pollInterval) {
|
||||||
|
clearInterval(this.pollInterval);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async toggleDropdown() {
|
||||||
|
this.notifOpen = !this.notifOpen;
|
||||||
|
if (this.notifOpen) {
|
||||||
|
await this.loadNotifications();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async loadNotifications() {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get('/admin/notifications/recent?limit=5');
|
||||||
|
this.notifications = response.notifications || [];
|
||||||
|
this.unreadCount = response.unread_count || 0;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to load notifications:', error);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async markAsRead(notificationId) {
|
||||||
|
try {
|
||||||
|
await apiClient.put(`/admin/notifications/${notificationId}/read`);
|
||||||
|
// Update local state
|
||||||
|
const notif = this.notifications.find(n => n.id === notificationId);
|
||||||
|
if (notif) {
|
||||||
|
this.notifications = this.notifications.filter(n => n.id !== notificationId);
|
||||||
|
this.unreadCount = Math.max(0, this.unreadCount - 1);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to mark notification as read:', error);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async markAllRead() {
|
||||||
|
try {
|
||||||
|
await apiClient.put('/admin/notifications/mark-all-read');
|
||||||
|
this.notifications = [];
|
||||||
|
this.unreadCount = 0;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to mark all as read:', error);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
formatTimeAgo(dateString) {
|
||||||
|
if (!dateString) return '';
|
||||||
|
const date = new Date(dateString);
|
||||||
|
const now = new Date();
|
||||||
|
const diff = Math.floor((now - date) / 1000);
|
||||||
|
|
||||||
|
if (diff < 60) return 'Just now';
|
||||||
|
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
|
||||||
|
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
|
||||||
|
if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`;
|
||||||
|
return date.toLocaleDateString();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Add handleLogout function to Alpine data
|
// Add handleLogout function to Alpine data
|
||||||
document.addEventListener('alpine:init', () => {
|
document.addEventListener('alpine:init', () => {
|
||||||
// Extend the data() function to include logout
|
// Extend the data() function to include logout
|
||||||
@@ -127,8 +268,8 @@ document.addEventListener('alpine:init', () => {
|
|||||||
return {
|
return {
|
||||||
...baseData,
|
...baseData,
|
||||||
handleLogout() {
|
handleLogout() {
|
||||||
console.log('🚪 Logging out...');
|
console.log('Logging out...');
|
||||||
|
|
||||||
// Call logout API
|
// Call logout API
|
||||||
fetch('/api/v1/admin/auth/logout', {
|
fetch('/api/v1/admin/auth/logout', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -137,17 +278,14 @@ document.addEventListener('alpine:init', () => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
console.log('✅ Logout API called successfully');
|
console.log('Logout API called successfully');
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.error('âš ï¸ Logout API error (continuing anyway):', error);
|
console.error('Logout API error (continuing anyway):', error);
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
// Clear all tokens
|
// Clear all tokens
|
||||||
console.log('🧹 Clearing tokens...');
|
|
||||||
localStorage.clear();
|
localStorage.clear();
|
||||||
|
|
||||||
console.log('🔄 Redirecting to login...');
|
|
||||||
window.location.href = '/admin/login';
|
window.location.href = '/admin/login';
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,6 +72,7 @@
|
|||||||
{{ menu_item('companies', '/admin/companies', 'office-building', 'Companies') }}
|
{{ menu_item('companies', '/admin/companies', 'office-building', 'Companies') }}
|
||||||
{{ menu_item('vendors', '/admin/vendors', 'shopping-bag', 'Vendors') }}
|
{{ menu_item('vendors', '/admin/vendors', 'shopping-bag', 'Vendors') }}
|
||||||
{{ menu_item('users', '/admin/users', 'users', 'Users') }}
|
{{ menu_item('users', '/admin/users', 'users', 'Users') }}
|
||||||
|
{{ menu_item('messages', '/admin/messages', 'chat-bubble-left-right', 'Messages') }}
|
||||||
{% endcall %}
|
{% endcall %}
|
||||||
|
|
||||||
<!-- Vendor Operations Section -->
|
<!-- Vendor Operations Section -->
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ function data() {
|
|||||||
companies: 'platformAdmin',
|
companies: 'platformAdmin',
|
||||||
vendors: 'platformAdmin',
|
vendors: 'platformAdmin',
|
||||||
users: 'platformAdmin',
|
users: 'platformAdmin',
|
||||||
|
messages: 'platformAdmin',
|
||||||
// Vendor Operations (Products, Customers, Inventory, Orders, Shipping)
|
// Vendor Operations (Products, Customers, Inventory, Orders, Shipping)
|
||||||
'marketplace-products': 'vendorOps',
|
'marketplace-products': 'vendorOps',
|
||||||
'vendor-products': 'vendorOps',
|
'vendor-products': 'vendorOps',
|
||||||
@@ -221,4 +222,39 @@ function languageSelector(currentLang, enabledLanguages) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Export to window for use in templates
|
// Export to window for use in templates
|
||||||
window.languageSelector = languageSelector;
|
window.languageSelector = languageSelector;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Header messages badge component
|
||||||
|
* Shows unread message count in header
|
||||||
|
*/
|
||||||
|
function headerMessages() {
|
||||||
|
return {
|
||||||
|
unreadCount: 0,
|
||||||
|
pollInterval: null,
|
||||||
|
|
||||||
|
async init() {
|
||||||
|
await this.fetchUnreadCount();
|
||||||
|
// Poll every 30 seconds
|
||||||
|
this.pollInterval = setInterval(() => this.fetchUnreadCount(), 30000);
|
||||||
|
},
|
||||||
|
|
||||||
|
destroy() {
|
||||||
|
if (this.pollInterval) {
|
||||||
|
clearInterval(this.pollInterval);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async fetchUnreadCount() {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get('/admin/messages/unread-count');
|
||||||
|
this.unreadCount = response.total_unread || 0;
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail - don't spam console for auth issues on login page
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Export to window
|
||||||
|
window.headerMessages = headerMessages;
|
||||||
489
static/admin/js/messages.js
Normal file
489
static/admin/js/messages.js
Normal file
@@ -0,0 +1,489 @@
|
|||||||
|
/**
|
||||||
|
* Admin Messages Page
|
||||||
|
*
|
||||||
|
* Handles the messaging interface including:
|
||||||
|
* - Conversation list with filtering and pagination
|
||||||
|
* - Message thread display
|
||||||
|
* - Sending messages with attachments
|
||||||
|
* - Creating new conversations
|
||||||
|
*/
|
||||||
|
|
||||||
|
const messagesLog = window.LogConfig?.createLogger('MESSAGES') || console;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Admin Messages Component
|
||||||
|
*/
|
||||||
|
function adminMessages(initialConversationId = null) {
|
||||||
|
return {
|
||||||
|
// Loading states
|
||||||
|
loading: true,
|
||||||
|
loadingConversations: false,
|
||||||
|
loadingMessages: false,
|
||||||
|
sendingMessage: false,
|
||||||
|
creatingConversation: false,
|
||||||
|
|
||||||
|
// Conversations state
|
||||||
|
conversations: [],
|
||||||
|
page: 1,
|
||||||
|
skip: 0,
|
||||||
|
limit: 20,
|
||||||
|
totalConversations: 0,
|
||||||
|
totalUnread: 0,
|
||||||
|
|
||||||
|
// Filters
|
||||||
|
filters: {
|
||||||
|
conversation_type: '',
|
||||||
|
is_closed: ''
|
||||||
|
},
|
||||||
|
|
||||||
|
// Selected conversation
|
||||||
|
selectedConversationId: initialConversationId,
|
||||||
|
selectedConversation: null,
|
||||||
|
|
||||||
|
// Reply form
|
||||||
|
replyContent: '',
|
||||||
|
attachedFiles: [],
|
||||||
|
|
||||||
|
// Compose modal
|
||||||
|
showComposeModal: false,
|
||||||
|
compose: {
|
||||||
|
recipientType: '',
|
||||||
|
recipientId: null,
|
||||||
|
subject: '',
|
||||||
|
message: ''
|
||||||
|
},
|
||||||
|
recipients: [],
|
||||||
|
loadingRecipients: false,
|
||||||
|
|
||||||
|
// Polling
|
||||||
|
pollInterval: null,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize component
|
||||||
|
*/
|
||||||
|
async init() {
|
||||||
|
messagesLog.debug('Initializing messages page');
|
||||||
|
await this.loadConversations();
|
||||||
|
|
||||||
|
if (this.selectedConversationId) {
|
||||||
|
await this.loadConversation(this.selectedConversationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.loading = false;
|
||||||
|
|
||||||
|
// Start polling for new messages
|
||||||
|
this.startPolling();
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start polling for updates
|
||||||
|
*/
|
||||||
|
startPolling() {
|
||||||
|
this.pollInterval = setInterval(async () => {
|
||||||
|
// Only poll if we have a selected conversation
|
||||||
|
if (this.selectedConversationId && !document.hidden) {
|
||||||
|
await this.refreshCurrentConversation();
|
||||||
|
}
|
||||||
|
// Update unread count
|
||||||
|
await this.updateUnreadCount();
|
||||||
|
}, 30000); // 30 seconds
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop polling
|
||||||
|
*/
|
||||||
|
destroy() {
|
||||||
|
if (this.pollInterval) {
|
||||||
|
clearInterval(this.pollInterval);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// CONVERSATIONS LIST
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load conversations with current filters
|
||||||
|
*/
|
||||||
|
async loadConversations() {
|
||||||
|
this.loadingConversations = true;
|
||||||
|
try {
|
||||||
|
this.skip = (this.page - 1) * this.limit;
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
params.append('skip', this.skip);
|
||||||
|
params.append('limit', this.limit);
|
||||||
|
|
||||||
|
if (this.filters.conversation_type) {
|
||||||
|
params.append('conversation_type', this.filters.conversation_type);
|
||||||
|
}
|
||||||
|
if (this.filters.is_closed !== '') {
|
||||||
|
params.append('is_closed', this.filters.is_closed);
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await apiClient.get(`/admin/messages?${params}`);
|
||||||
|
this.conversations = response.conversations || [];
|
||||||
|
this.totalConversations = response.total || 0;
|
||||||
|
this.totalUnread = response.total_unread || 0;
|
||||||
|
|
||||||
|
messagesLog.debug(`Loaded ${this.conversations.length} conversations`);
|
||||||
|
} catch (error) {
|
||||||
|
messagesLog.error('Failed to load conversations:', error);
|
||||||
|
window.showToast?.('Failed to load conversations', 'error');
|
||||||
|
} finally {
|
||||||
|
this.loadingConversations = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update unread count
|
||||||
|
*/
|
||||||
|
async updateUnreadCount() {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get('/admin/messages/unread-count');
|
||||||
|
this.totalUnread = response.total_unread || 0;
|
||||||
|
} catch (error) {
|
||||||
|
messagesLog.error('Failed to update unread count:', error);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Select a conversation
|
||||||
|
*/
|
||||||
|
async selectConversation(conversationId) {
|
||||||
|
if (this.selectedConversationId === conversationId) return;
|
||||||
|
|
||||||
|
this.selectedConversationId = conversationId;
|
||||||
|
await this.loadConversation(conversationId);
|
||||||
|
|
||||||
|
// Update URL without reload
|
||||||
|
const url = new URL(window.location);
|
||||||
|
url.pathname = `/admin/messages/${conversationId}`;
|
||||||
|
window.history.pushState({}, '', url);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load conversation detail
|
||||||
|
*/
|
||||||
|
async loadConversation(conversationId) {
|
||||||
|
this.loadingMessages = true;
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get(`/admin/messages/${conversationId}?mark_read=true`);
|
||||||
|
this.selectedConversation = response;
|
||||||
|
|
||||||
|
// Update unread count in list
|
||||||
|
const conv = this.conversations.find(c => c.id === conversationId);
|
||||||
|
if (conv) {
|
||||||
|
this.totalUnread = Math.max(0, this.totalUnread - conv.unread_count);
|
||||||
|
conv.unread_count = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
messagesLog.debug(`Loaded conversation ${conversationId} with ${response.messages?.length || 0} messages`);
|
||||||
|
|
||||||
|
// Scroll to bottom
|
||||||
|
await this.$nextTick();
|
||||||
|
this.scrollToBottom();
|
||||||
|
} catch (error) {
|
||||||
|
messagesLog.error('Failed to load conversation:', error);
|
||||||
|
window.showToast?.('Failed to load conversation', 'error');
|
||||||
|
} finally {
|
||||||
|
this.loadingMessages = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Refresh current conversation
|
||||||
|
*/
|
||||||
|
async refreshCurrentConversation() {
|
||||||
|
if (!this.selectedConversationId) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get(`/admin/messages/${this.selectedConversationId}?mark_read=true`);
|
||||||
|
const oldCount = this.selectedConversation?.messages?.length || 0;
|
||||||
|
const newCount = response.messages?.length || 0;
|
||||||
|
|
||||||
|
this.selectedConversation = response;
|
||||||
|
|
||||||
|
// If new messages, scroll to bottom
|
||||||
|
if (newCount > oldCount) {
|
||||||
|
await this.$nextTick();
|
||||||
|
this.scrollToBottom();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
messagesLog.error('Failed to refresh conversation:', error);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scroll messages to bottom
|
||||||
|
*/
|
||||||
|
scrollToBottom() {
|
||||||
|
const container = this.$refs.messagesContainer;
|
||||||
|
if (container) {
|
||||||
|
container.scrollTop = container.scrollHeight;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// SENDING MESSAGES
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle file selection
|
||||||
|
*/
|
||||||
|
handleFileSelect(event) {
|
||||||
|
const files = Array.from(event.target.files);
|
||||||
|
this.attachedFiles = files;
|
||||||
|
messagesLog.debug(`Selected ${files.length} files`);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a message
|
||||||
|
*/
|
||||||
|
async sendMessage() {
|
||||||
|
if (!this.replyContent.trim() && this.attachedFiles.length === 0) return;
|
||||||
|
if (!this.selectedConversationId) return;
|
||||||
|
|
||||||
|
this.sendingMessage = true;
|
||||||
|
try {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('content', this.replyContent);
|
||||||
|
|
||||||
|
for (const file of this.attachedFiles) {
|
||||||
|
formData.append('files', file);
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(`/api/v1/admin/messages/${this.selectedConversationId}/messages`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData,
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${window.getAuthToken?.() || ''}`
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json();
|
||||||
|
throw new Error(error.detail || 'Failed to send message');
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = await response.json();
|
||||||
|
|
||||||
|
// Add to messages
|
||||||
|
if (this.selectedConversation) {
|
||||||
|
this.selectedConversation.messages.push(message);
|
||||||
|
this.selectedConversation.message_count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear form
|
||||||
|
this.replyContent = '';
|
||||||
|
this.attachedFiles = [];
|
||||||
|
if (this.$refs.fileInput) {
|
||||||
|
this.$refs.fileInput.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scroll to bottom
|
||||||
|
await this.$nextTick();
|
||||||
|
this.scrollToBottom();
|
||||||
|
|
||||||
|
messagesLog.debug(`Sent message ${message.id}`);
|
||||||
|
} catch (error) {
|
||||||
|
messagesLog.error('Failed to send message:', error);
|
||||||
|
window.showToast?.(error.message || 'Failed to send message', 'error');
|
||||||
|
} finally {
|
||||||
|
this.sendingMessage = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// CONVERSATION ACTIONS
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Close conversation
|
||||||
|
*/
|
||||||
|
async closeConversation() {
|
||||||
|
if (!confirm('Are you sure you want to close this conversation?')) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await apiClient.post(`/admin/messages/${this.selectedConversationId}/close`);
|
||||||
|
|
||||||
|
if (this.selectedConversation) {
|
||||||
|
this.selectedConversation.is_closed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update in list
|
||||||
|
const conv = this.conversations.find(c => c.id === this.selectedConversationId);
|
||||||
|
if (conv) {
|
||||||
|
conv.is_closed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.showToast?.('Conversation closed', 'success');
|
||||||
|
} catch (error) {
|
||||||
|
messagesLog.error('Failed to close conversation:', error);
|
||||||
|
window.showToast?.('Failed to close conversation', 'error');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reopen conversation
|
||||||
|
*/
|
||||||
|
async reopenConversation() {
|
||||||
|
try {
|
||||||
|
await apiClient.post(`/admin/messages/${this.selectedConversationId}/reopen`);
|
||||||
|
|
||||||
|
if (this.selectedConversation) {
|
||||||
|
this.selectedConversation.is_closed = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update in list
|
||||||
|
const conv = this.conversations.find(c => c.id === this.selectedConversationId);
|
||||||
|
if (conv) {
|
||||||
|
conv.is_closed = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.showToast?.('Conversation reopened', 'success');
|
||||||
|
} catch (error) {
|
||||||
|
messagesLog.error('Failed to reopen conversation:', error);
|
||||||
|
window.showToast?.('Failed to reopen conversation', 'error');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// CREATE CONVERSATION
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load recipients for compose modal
|
||||||
|
*/
|
||||||
|
async loadRecipients() {
|
||||||
|
if (!this.compose.recipientType) {
|
||||||
|
this.recipients = [];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.loadingRecipients = true;
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get(`/admin/messages/recipients?recipient_type=${this.compose.recipientType}&limit=100`);
|
||||||
|
this.recipients = response.recipients || [];
|
||||||
|
messagesLog.debug(`Loaded ${this.recipients.length} recipients`);
|
||||||
|
} catch (error) {
|
||||||
|
messagesLog.error('Failed to load recipients:', error);
|
||||||
|
window.showToast?.('Failed to load recipients', 'error');
|
||||||
|
} finally {
|
||||||
|
this.loadingRecipients = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create new conversation
|
||||||
|
*/
|
||||||
|
async createConversation() {
|
||||||
|
if (!this.compose.recipientId || !this.compose.subject.trim()) return;
|
||||||
|
|
||||||
|
this.creatingConversation = true;
|
||||||
|
try {
|
||||||
|
// Determine conversation type
|
||||||
|
const conversationType = this.compose.recipientType === 'vendor'
|
||||||
|
? 'admin_vendor'
|
||||||
|
: 'admin_customer';
|
||||||
|
|
||||||
|
// Get vendor_id if customer
|
||||||
|
let vendorId = null;
|
||||||
|
if (this.compose.recipientType === 'customer') {
|
||||||
|
const recipient = this.recipients.find(r => r.id === parseInt(this.compose.recipientId));
|
||||||
|
vendorId = recipient?.vendor_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await apiClient.post('/admin/messages', {
|
||||||
|
conversation_type: conversationType,
|
||||||
|
subject: this.compose.subject,
|
||||||
|
recipient_type: this.compose.recipientType,
|
||||||
|
recipient_id: parseInt(this.compose.recipientId),
|
||||||
|
vendor_id: vendorId,
|
||||||
|
initial_message: this.compose.message || null
|
||||||
|
});
|
||||||
|
|
||||||
|
// Close modal and reset
|
||||||
|
this.showComposeModal = false;
|
||||||
|
this.compose = {
|
||||||
|
recipientType: '',
|
||||||
|
recipientId: null,
|
||||||
|
subject: '',
|
||||||
|
message: ''
|
||||||
|
};
|
||||||
|
this.recipients = [];
|
||||||
|
|
||||||
|
// Reload conversations and select new one
|
||||||
|
await this.loadConversations();
|
||||||
|
await this.selectConversation(response.id);
|
||||||
|
|
||||||
|
window.showToast?.('Conversation created', 'success');
|
||||||
|
} catch (error) {
|
||||||
|
messagesLog.error('Failed to create conversation:', error);
|
||||||
|
window.showToast?.(error.message || 'Failed to create conversation', 'error');
|
||||||
|
} finally {
|
||||||
|
this.creatingConversation = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// HELPERS
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get other participant name
|
||||||
|
*/
|
||||||
|
getOtherParticipantName() {
|
||||||
|
if (!this.selectedConversation?.participants) return 'Unknown';
|
||||||
|
|
||||||
|
const other = this.selectedConversation.participants.find(
|
||||||
|
p => p.participant_type !== 'admin'
|
||||||
|
);
|
||||||
|
|
||||||
|
return other?.participant_info?.name || 'Unknown';
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format relative time
|
||||||
|
*/
|
||||||
|
formatRelativeTime(dateString) {
|
||||||
|
if (!dateString) return '';
|
||||||
|
|
||||||
|
const date = new Date(dateString);
|
||||||
|
const now = new Date();
|
||||||
|
const diff = Math.floor((now - date) / 1000);
|
||||||
|
|
||||||
|
if (diff < 60) return 'Now';
|
||||||
|
if (diff < 3600) return `${Math.floor(diff / 60)}m`;
|
||||||
|
if (diff < 86400) return `${Math.floor(diff / 3600)}h`;
|
||||||
|
if (diff < 172800) return 'Yesterday';
|
||||||
|
if (diff < 604800) return `${Math.floor(diff / 86400)}d`;
|
||||||
|
|
||||||
|
return date.toLocaleDateString();
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format time for messages
|
||||||
|
*/
|
||||||
|
formatTime(dateString) {
|
||||||
|
if (!dateString) return '';
|
||||||
|
|
||||||
|
const date = new Date(dateString);
|
||||||
|
const now = new Date();
|
||||||
|
const isToday = date.toDateString() === now.toDateString();
|
||||||
|
|
||||||
|
if (isToday) {
|
||||||
|
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||||
|
}
|
||||||
|
|
||||||
|
return date.toLocaleString([], {
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make available globally
|
||||||
|
window.adminMessages = adminMessages;
|
||||||
Reference in New Issue
Block a user