ifixkart-backend/app/services/CalendarInviteService.py

673 lines
25 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import urllib.parse
from datetime import datetime, timedelta, timezone
from typing import Optional, List, Dict, Any
from sqlalchemy.orm import Session
from sqlalchemy import select, or_, func
import ulid
import app.models.db_base # Ensure all SQLAlchemy relations are loaded
from app.models.ServiceModel import (
ServiceJob,
ServiceAppointment,
ServiceJobAssignment,
ServiceJobEvent,
)
from app.models.CrmModel import CrmTask, CrmCalendarEvent
from app.models.CustomerDeviceModel import CustomerDevice
from app.models.EcomCustomerModel import EcomCustomer
from app.models.TechnicianModel import TechnicianProfile
from app.models.UserModel import User, Role
from app.core.config.Config import settings
class CalendarInviteService:
DEFAULT_STORE_NAME = "iFixKart Service Hub"
DEFAULT_STORE_ADDRESS = "Chennai Central Service Branch, Tamil Nadu, India"
DEFAULT_MAPS_URL = "https://maps.google.com/?q=iFixKart+Chennai"
@classmethod
def _to_utc_compact(cls, dt: datetime) -> str:
"""Convert datetime to iCalendar UTC compact format: YYYYMMDDTHHMMSSZ."""
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
else:
dt = dt.astimezone(timezone.utc)
return dt.strftime("%Y%m%dT%H%M%SZ")
@classmethod
def generate_ics_content(
cls,
job_no: str,
appointment_id: str,
start_time: datetime,
end_time: datetime,
device_name: str,
customer_name: str,
store_address: Optional[str] = None,
problem_summary: Optional[str] = None,
) -> str:
"""
Generate RFC 5545 compliant .ics VCALENDAR content.
"""
now_compact = cls._to_utc_compact(datetime.now(timezone.utc))
start_compact = cls._to_utc_compact(start_time)
end_compact = cls._to_utc_compact(end_time)
uid = f"srv-{job_no}-{appointment_id}@ifixkart.com"
location = store_address or cls.DEFAULT_STORE_ADDRESS
summary = f"iFixKart Repair: {device_name} (#{job_no})"
desc_lines = [
f"Dear {customer_name},",
f"Your walk-in repair appointment for {device_name} is confirmed.",
f"Job Reference: {job_no}",
f"Service Center: {location}",
"",
"Pre-Visit Checklist:",
"β€’ Please backup your personal device data if possible.",
"β€’ Bring your device along with any relevant accessories/chargers.",
"β€’ Keep your screen lock passcode handy for post-repair testing.",
"",
"Contact Support: support@ifixkart.com | +91 90803 23589",
"Thank you for choosing iFixKart!",
]
if problem_summary:
desc_lines.insert(4, f"Reported Issue: {problem_summary}")
description = "\\n".join(desc_lines)
ics_lines = [
"BEGIN:VCALENDAR",
"VERSION:2.0",
"PRODID:-//iFixKart//Service Appointments//EN",
"CALSCALE:GREGORIAN",
"METHOD:REQUEST",
"BEGIN:VEVENT",
f"UID:{uid}",
f"DTSTAMP:{now_compact}",
f"DTSTART:{start_compact}",
f"DTEND:{end_compact}",
f"SUMMARY:{summary}",
f"DESCRIPTION:{description}",
f"LOCATION:{location}",
"STATUS:CONFIRMED",
"SEQUENCE:0",
'ORGANIZER;CN="iFixKart Support":mailto:support@ifixkart.com',
"BEGIN:VALARM",
"TRIGGER:-PT2H",
"ACTION:DISPLAY",
"DESCRIPTION:Reminder: Your iFixKart appointment is in 2 hours",
"END:VALARM",
"END:VEVENT",
"END:VCALENDAR",
]
return "\r\n".join(ics_lines) + "\r\n"
@classmethod
def generate_ics_bytes(
cls,
job_no: str,
appointment_id: str,
start_time: datetime,
end_time: datetime,
device_name: str,
customer_name: str,
store_address: Optional[str] = None,
problem_summary: Optional[str] = None,
) -> bytes:
content = cls.generate_ics_content(
job_no=job_no,
appointment_id=appointment_id,
start_time=start_time,
end_time=end_time,
device_name=device_name,
customer_name=customer_name,
store_address=store_address,
problem_summary=problem_summary,
)
return content.encode("utf-8")
@classmethod
def generate_google_calendar_url(
cls,
job_no: str,
start_time: datetime,
end_time: datetime,
device_name: str,
customer_name: str,
store_address: Optional[str] = None,
problem_summary: Optional[str] = None,
) -> str:
"""
Generate 1-tap Google Calendar web addition link.
"""
start_compact = cls._to_utc_compact(start_time)
end_compact = cls._to_utc_compact(end_time)
dates_param = f"{start_compact}/{end_compact}"
title = f"iFixKart Repair: {device_name} (#{job_no})"
location = store_address or cls.DEFAULT_STORE_ADDRESS
details = (
f"Hi {customer_name}! Your walk-in service is scheduled at iFixKart.\n"
f"Job #{job_no}\n"
f"Device: {device_name}\n"
f"Store: {location}\n"
f"Helpline: +91 90803 23589"
)
if problem_summary:
details += f"\nIssue: {problem_summary}"
params = {
"action": "TEMPLATE",
"text": title,
"dates": dates_param,
"details": details,
"location": location,
}
return f"https://calendar.google.com/calendar/render?{urllib.parse.urlencode(params)}"
@classmethod
def sync_walkin_to_crm(cls, db: Session, job_id: str) -> Dict[str, Any]:
"""
Automatically creates CrmTask and CrmCalendarEvent for confirmed walk-in jobs.
Idempotent: will not duplicate if already synced.
"""
job = db.get(ServiceJob, job_id)
if not job:
return {"status": "SKIPPED", "reason": "Job not found"}
appt = (
db.query(ServiceAppointment)
.filter(
ServiceAppointment.service_job_id == job_id,
ServiceAppointment.status.in_(["CONFIRMED", "HELD", "COMPLETED"]),
)
.order_by(ServiceAppointment.created_at.desc())
.first()
)
customer = (
db.query(EcomCustomer)
.filter(EcomCustomer.customer_id == job.customer_id)
.first()
)
customer_name = (
f"{customer.first_name or ''} {customer.last_name or ''}".strip()
if customer
else "Walk-In Customer"
)
customer_phone = customer.phone if customer else (job.alt_phone or "")
device = (
db.query(CustomerDevice)
.filter(CustomerDevice.device_id == job.device_id)
.first()
)
device_name = (
f"{device.brand or ''} {device.model or ''}".strip()
if device
else (job.service_name_snapshot or "Device Repair")
)
issue_summary = job.custom_service_name or job.service_name_snapshot or "Hardware Diagnosis"
slot_str = ""
if appt:
start_fmt = appt.scheduled_start.strftime("%d %b %Y, %I:%M %p")
end_fmt = appt.scheduled_end.strftime("%I:%M %p")
slot_str = f"{start_fmt} - {end_fmt}"
# 1. Idempotent CrmTask Creation
task = (
db.query(CrmTask)
.filter(
CrmTask.entity_type == "REPAIR_TICKET",
CrmTask.entity_id == job.job_id,
)
.first()
)
if not task:
task = CrmTask(
tenant_id="tenant_default",
title=f"Walk-in Repair: {job.job_no} - {device_name}",
description=f"Customer: {customer_name} ({customer_phone})\nSlot: {slot_str}\nIssue: {issue_summary}",
entity_type="REPAIR_TICKET",
entity_id=job.job_id,
priority=job.priority or "MEDIUM",
status="PENDING",
due_at=appt.scheduled_end if appt else None,
assignee_id=None,
)
db.add(task)
db.flush()
# 2. Idempotent CrmCalendarEvent Creation
event = (
db.query(CrmCalendarEvent)
.filter(
CrmCalendarEvent.source_type == "REPAIR_TICKET",
CrmCalendarEvent.source_id == job.job_id,
)
.first()
)
if not event and appt:
event = CrmCalendarEvent(
tenant_id="tenant_default",
task_id=task.task_id if task else None,
title=f"Walk-in: {device_name} ({job.job_no})",
description=f"Customer: {customer_name} ({customer_phone})\nIssue: {issue_summary}\nLocation: {cls.DEFAULT_STORE_NAME}",
source_type="REPAIR_TICKET",
source_id=job.job_id,
start_time=appt.scheduled_start,
end_time=appt.scheduled_end,
is_all_day=False,
status="SCHEDULED",
)
db.add(event)
db.flush()
db.commit()
return {
"status": "SYNCED",
"job_id": job.job_id,
"task_id": task.task_id if task else None,
"event_id": event.event_id if event else None,
}
@classmethod
def get_active_technicians(cls, db: Session) -> List[Dict[str, Any]]:
"""
Returns all active technicians configured in the system.
"""
# Query technician profiles joined with users
profiles = (
db.query(TechnicianProfile)
.filter(TechnicianProfile.active == True)
.all()
)
tech_list = []
user_ids_seen = set()
for prof in profiles:
user = db.query(User).filter(User.user_id == prof.user_id).first()
if user and user.is_active:
user_ids_seen.add(user.user_id)
tech_list.append({
"technician_id": prof.technician_id,
"user_id": user.user_id,
"name": user.display_name or f"{user.first_name or ''} {user.last_name or ''}".strip(),
"email": user.email,
"phone": user.phone or "",
"role": user.role.role_name if user.role else "Technician",
})
# Fallback: also include any staff user with Technician or Manager role if not already in profile
staff_users = (
db.query(User)
.join(Role, User.role_id == Role.role_id)
.filter(
User.is_active == True,
Role.role_name.in_(["Technician", "Store Manager", "Super Admin"]),
)
.all()
)
for u in staff_users:
if u.user_id not in user_ids_seen:
tech_list.append({
"technician_id": u.user_id,
"user_id": u.user_id,
"name": u.display_name or f"{u.first_name or ''} {u.last_name or ''}".strip(),
"email": u.email,
"phone": u.phone or "",
"role": u.role.role_name if u.role else "Staff",
})
return tech_list
@classmethod
def assign_technician_to_service_job(
cls,
db: Session,
job_id: str,
technician_id: str,
assigned_by: str,
reason: Optional[str] = None,
) -> Dict[str, Any]:
"""
Assigns a technician to a service job:
1. Logs into service_job_assignments
2. Updates CrmTask.assignee_id
3. Updates CrmCalendarEvent description
4. Dispatches timeline event
5. Sends WhatsApp alert to assigned technician
"""
job = db.get(ServiceJob, job_id)
if not job:
raise ValueError(f"Service job '{job_id}' not found.")
# Resolve technician profile/user
tech_prof = (
db.query(TechnicianProfile)
.filter(
or_(
TechnicianProfile.technician_id == technician_id,
TechnicianProfile.user_id == technician_id,
)
)
.first()
)
user_id = tech_prof.user_id if tech_prof else technician_id
tech_user = db.query(User).filter(User.user_id == user_id).first()
tech_name = (
tech_user.display_name
or f"{tech_user.first_name or ''} {tech_user.last_name or ''}".strip()
if tech_user
else "Technician"
)
tech_phone = tech_user.phone if tech_user else ""
# Locate appointment
appt = (
db.query(ServiceAppointment)
.filter(ServiceAppointment.service_job_id == job_id)
.order_by(ServiceAppointment.created_at.desc())
.first()
)
appointment_id = appt.appointment_id if appt else str(ulid.ULID())
# 1. Create ServiceJobAssignment entry
assignment = ServiceJobAssignment(
assignment_id=str(ulid.ULID()),
service_job_id=job.job_id,
appointment_id=appointment_id,
technician_id=technician_id,
assigned_by=assigned_by,
reason=reason or "Assigned via Service Management",
)
db.add(assignment)
# 2. Update CrmTask assignee
task = (
db.query(CrmTask)
.filter(
CrmTask.entity_type == "REPAIR_TICKET",
CrmTask.entity_id == job.job_id,
)
.first()
)
if task:
task.assignee_id = technician_id
db.add(task)
# 3. Update CrmCalendarEvent note
event = (
db.query(CrmCalendarEvent)
.filter(
CrmCalendarEvent.source_type == "REPAIR_TICKET",
CrmCalendarEvent.source_id == job.job_id,
)
.first()
)
if event:
event.description = f"{event.description or ''}\nAssigned Tech: {tech_name}"
db.add(event)
# 4. Timeline Event
timeline_event = ServiceJobEvent(
event_id=str(ulid.ULID()),
job_id=job.job_id,
event_type="TECHNICIAN_ASSIGNED",
performed_by=assigned_by,
notes=f"Assigned to {tech_name} ({technician_id}). Reason: {reason or 'N/A'}",
)
db.add(timeline_event)
db.commit()
# 5. WhatsApp notification to technician
if tech_phone:
try:
from app.services.NotificationGatewayService import NotificationGatewayService
from app.schemas.NotificationGateway import NotificationDispatchCreate
admin_base = getattr(settings, "ADMIN_BASE_URL", "https://admin.ifixkart.com")
job_url = f"{admin_base}/technician?job_id={job.job_id}"
slot_info = (
f"{appt.scheduled_start.strftime('%d %b, %I:%M %p')}"
if appt
else "Walk-In Queue"
)
wa_text = (
f"πŸ”§ *[iFixKart Workshop Assignment]*\n"
f"Hi {tech_name}, you have been assigned to Service Job *#{job.job_no}*.\n"
f"*Device:* {job.service_name_snapshot or 'Customer Hardware'}\n"
f"*Slot:* {slot_info}\n"
f"*Priority:* {job.priority or 'NORMAL'}\n\n"
f"πŸ‘‰ *Open Workshop Ticket:* {job_url}"
)
NotificationGatewayService.dispatch_notification(
db=db,
tenant_id="tenant_default",
payload=NotificationDispatchCreate(
channel="WHATSAPP",
recipient_phone=tech_phone,
body=wa_text,
title=f"New Job Assigned #{job.job_no}",
idempotency_key=f"TECH_ASSIGN:{job.job_id}:{technician_id}",
),
)
except Exception as e:
print(f"[CalendarInviteService] Failed to notify technician on WhatsApp: {e}")
return {
"status": "ASSIGNED",
"job_id": job.job_id,
"technician_id": technician_id,
"technician_name": tech_name,
"assignment_id": assignment.assignment_id,
}
@classmethod
def complete_walkin_crm_task(cls, db: Session, job_id: str) -> None:
"""
Auto-completes corresponding CrmTask and CrmCalendarEvent when repair finishes.
"""
now = datetime.now(timezone.utc)
tasks = (
db.query(CrmTask)
.filter(
CrmTask.entity_type == "REPAIR_TICKET",
CrmTask.entity_id == job_id,
)
.all()
)
for t in tasks:
t.status = "COMPLETED"
t.completed_at = now
db.add(t)
events = (
db.query(CrmCalendarEvent)
.filter(
CrmCalendarEvent.source_type == "REPAIR_TICKET",
CrmCalendarEvent.source_id == job_id,
)
.all()
)
for ev in events:
ev.status = "COMPLETED"
db.add(ev)
db.commit()
@classmethod
def send_appointment_reminders(cls, db: Session) -> Dict[str, Any]:
"""
Checks for confirmed walk-in appointments starting in ~2 hours (between 1h 45m and 2h 15m),
and sends reminders to both customer and assigned technician.
"""
now = datetime.utcnow()
window_start = now + timedelta(hours=1, minutes=45)
window_end = now + timedelta(hours=2, minutes=15)
remind_stmt = (
select(ServiceAppointment)
.join(ServiceJob, ServiceAppointment.service_job_id == ServiceJob.job_id)
.where(
ServiceAppointment.status == "CONFIRMED",
ServiceAppointment.scheduled_start >= window_start,
ServiceAppointment.scheduled_start <= window_end,
ServiceAppointment.reminder_sent == False,
)
)
appointments = db.execute(remind_stmt).scalars().all()
reminders_sent = 0
from app.services.NotificationGatewayService import NotificationGatewayService
from app.schemas.NotificationGateway import NotificationDispatchCreate
for appt in appointments:
job = db.get(ServiceJob, appt.service_job_id)
if not job:
continue
customer = db.query(EcomCustomer).filter(EcomCustomer.customer_id == job.customer_id).first()
customer_name = (
f"{customer.first_name or ''} {customer.last_name or ''}".strip()
if customer
else "Valued Customer"
)
customer_phone = (customer.phone if customer and customer.phone else (job.alt_phone or ""))
if customer and not customer.phone and job.alt_phone:
try:
customer.phone = job.alt_phone.strip()
db.commit()
except Exception:
pass
device = db.query(CustomerDevice).filter(CustomerDevice.device_id == job.device_id).first()
device_str = f"{device.brand or ''} {device.model or ''}".strip() if device else (job.service_name_snapshot or "Device")
slot_start_fmt = appt.scheduled_start.strftime("%I:%M %p")
slot_end_fmt = appt.scheduled_end.strftime("%I:%M %p")
# 1. Customer WhatsApp Reminder
if customer_phone:
cust_msg = (
f"πŸ‘‹ *Hello {customer_name}! Friendly Appointment Reminder*\n\n"
f"Your walk-in service appointment for *{device_str}* is scheduled today in *2 hours*:\n"
f"⏰ *Time Slot:* {slot_start_fmt} - {slot_end_fmt}\n"
f"πŸ“ *Store:* {cls.DEFAULT_STORE_NAME}\n"
f"πŸ—ΊοΈ *Directions:* {cls.DEFAULT_MAPS_URL}\n\n"
f"Please remember to bring your device passcode. See you soon!\n"
f"– Team iFixKart"
)
try:
NotificationGatewayService.dispatch_notification(
db=db,
tenant_id="tenant_default",
payload=NotificationDispatchCreate(
channel="WHATSAPP",
recipient_phone=customer_phone,
body=cust_msg,
title=f"Walk-in Reminder #{job.job_no}",
idempotency_key=f"REMINDER_CUST:{appt.appointment_id}",
),
)
except Exception as ex:
print(f"Error sending customer reminder: {ex}")
# 2. Technician WhatsApp Reminder
assignment = (
db.query(ServiceJobAssignment)
.filter(ServiceJobAssignment.service_job_id == job.job_id)
.order_by(ServiceJobAssignment.assigned_at.desc())
.first()
)
if assignment:
tech_user = db.query(User).filter(User.user_id == assignment.technician_id).first()
if tech_user and tech_user.phone:
tech_msg = (
f"⏰ *[Upcoming Walk-In in 2 Hours]*\n"
f"Customer *{customer_name}* is scheduled to arrive at *{slot_start_fmt}* for Job *#{job.job_no}* ({device_str}).\n"
f"Please ensure workspace readiness."
)
try:
NotificationGatewayService.dispatch_notification(
db=db,
tenant_id="tenant_default",
payload=NotificationDispatchCreate(
channel="WHATSAPP",
recipient_phone=tech_user.phone,
body=tech_msg,
title=f"Technician Slot Reminder #{job.job_no}",
idempotency_key=f"REMINDER_TECH:{appt.appointment_id}",
),
)
except Exception as ex:
print(f"Error sending technician reminder: {ex}")
appt.reminder_sent = True
appt.reminder_sent_at = datetime.utcnow()
reminders_sent += 1
db.commit()
return {"status": "SUCCESS", "reminders_sent": reminders_sent}
@classmethod
def audit_pending_walkin_tasks_eod(cls, db: Session) -> Dict[str, Any]:
"""
Queries all walk-in tasks for today that remain PENDING and triggers Admin internal WhatsApp summary.
"""
today = datetime.utcnow().date()
start_of_day = datetime(today.year, today.month, today.day)
end_of_day = start_of_day + timedelta(days=1)
pending_tasks = (
db.query(CrmTask)
.filter(
CrmTask.entity_type == "REPAIR_TICKET",
CrmTask.status == "PENDING",
CrmTask.due_at >= start_of_day,
CrmTask.due_at < end_of_day,
)
.all()
)
admin_base = getattr(settings, "ADMIN_BASE_URL", "https://admin.ifixkart.com")
summary_lines = []
for idx, t in enumerate(pending_tasks, start=1):
tech_name = "⚠️ UNASSIGNED"
if t.assignee_id:
tech_user = db.query(User).filter(User.user_id == t.assignee_id).first()
if tech_user:
tech_name = tech_user.display_name or f"{tech_user.first_name} {tech_user.last_name}"
summary_lines.append(f"{idx}. {t.title} (Tech: {tech_name})")
from app.core.events.notification_events import dispatch_internal_notification
message = (
f"⚠️ *[iFixKart EOD Alert] {len(pending_tasks)} Walk-In Repair Tasks Pending Today ({today.strftime('%d %b %Y')}):*\n\n"
+ ("\n".join(summary_lines) if summary_lines else "All clear! Zero pending tasks.")
+ f"\n\nπŸ‘‰ *Review CRM Todos:* {admin_base}/crm-todos"
)
dispatch_internal_notification(
event_type="PENDING_WALKIN_TASKS_EOD",
message=message,
context={
"pending_count": len(pending_tasks),
"date": today.strftime("%Y-%m-%d"),
},
)
return {
"status": "AUDIT_COMPLETE",
"date": today.strftime("%Y-%m-%d"),
"pending_count": len(pending_tasks),
}