Pavanupadhyay27 commited on
Commit
f4a356e
·
1 Parent(s): 5c10f79

Implement Employee-HR Helpdesk Support tickets and 14-step onboarding wizard

Browse files
backend/app/api/v1/tickets.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends, HTTPException, status, Request
2
+ from sqlalchemy.orm import Session
3
+ from typing import List
4
+
5
+ from app.core.database import get_db
6
+ from app.core import security
7
+ from app.crud import crud
8
+ from app.schemas import schemas
9
+ from app.models import models
10
+
11
+ router = APIRouter()
12
+
13
+ @router.get("/", response_model=List[schemas.TicketOut])
14
+ def read_tickets(
15
+ db: Session = Depends(get_db),
16
+ current_user: models.User = Depends(security.get_current_user)
17
+ ):
18
+ role_name = current_user.role.name if current_user.role else "Employee"
19
+
20
+ if role_name in ["Super Admin", "Admin", "HR"]:
21
+ # Admins/HR can see all tickets for their company
22
+ return crud.get_tickets(db, company_id=current_user.company_id)
23
+ else:
24
+ # Employees can only see their own tickets
25
+ if not current_user.employee:
26
+ raise HTTPException(status_code=400, detail="User is not registered as an employee")
27
+ return crud.get_tickets(db, company_id=current_user.company_id, employee_id=current_user.employee.id)
28
+
29
+ @router.post("/", response_model=schemas.TicketOut, status_code=status.HTTP_201_CREATED)
30
+ def create_ticket(
31
+ request: Request,
32
+ ticket: schemas.TicketCreate,
33
+ db: Session = Depends(get_db),
34
+ current_user: models.User = Depends(security.get_current_user)
35
+ ):
36
+ role_name = current_user.role.name if current_user.role else "Employee"
37
+ if role_name != "Employee":
38
+ raise HTTPException(status_code=403, detail="Only employees can open support tickets")
39
+
40
+ if not current_user.employee:
41
+ raise HTTPException(status_code=400, detail="User is not registered as an employee")
42
+
43
+ db_ticket = crud.create_ticket(
44
+ db, ticket=ticket, employee_id=current_user.employee.id, company_id=current_user.company_id
45
+ )
46
+
47
+ crud.create_audit_log(
48
+ db=db,
49
+ user_id=current_user.id,
50
+ action="Open Support Ticket",
51
+ ip_address=request.client.host if request.client else None,
52
+ user_agent=request.headers.get("user-agent"),
53
+ details=f"Opened ticket ID {db_ticket.id}: '{ticket.title}'",
54
+ company_id=current_user.company_id
55
+ )
56
+ return db_ticket
57
+
58
+ @router.post("/{id}/messages", response_model=schemas.TicketMessageOut, status_code=status.HTTP_201_CREATED)
59
+ def reply_to_ticket(
60
+ id: int,
61
+ message: schemas.TicketMessageCreate,
62
+ db: Session = Depends(get_db),
63
+ current_user: models.User = Depends(security.get_current_user)
64
+ ):
65
+ db_ticket = crud.get_ticket_by_id(db, ticket_id=id)
66
+ if not db_ticket:
67
+ raise HTTPException(status_code=404, detail="Ticket not found")
68
+
69
+ # Check company ownership scope
70
+ if current_user.company_id is not None and db_ticket.company_id != current_user.company_id:
71
+ raise HTTPException(status_code=403, detail="Not authorized to access this resource")
72
+
73
+ role_name = current_user.role.name if current_user.role else "Employee"
74
+ if role_name == "Employee":
75
+ if not current_user.employee or db_ticket.employee_id != current_user.employee.id:
76
+ raise HTTPException(status_code=403, detail="Not authorized to post to this ticket")
77
+
78
+ db_message = crud.create_ticket_message(db, ticket_id=id, msg=message, sender_id=current_user.id)
79
+ return db_message
80
+
81
+ @router.put("/{id}/status", response_model=schemas.TicketOut)
82
+ def update_ticket(
83
+ request: Request,
84
+ id: int,
85
+ payload: schemas.TicketUpdateStatus,
86
+ db: Session = Depends(get_db),
87
+ current_user: models.User = Depends(security.get_current_user)
88
+ ):
89
+ db_ticket = crud.get_ticket_by_id(db, ticket_id=id)
90
+ if not db_ticket:
91
+ raise HTTPException(status_code=404, detail="Ticket not found")
92
+
93
+ if current_user.company_id is not None and db_ticket.company_id != current_user.company_id:
94
+ raise HTTPException(status_code=403, detail="Not authorized to access this resource")
95
+
96
+ role_name = current_user.role.name if current_user.role else "Employee"
97
+ if role_name not in ["Super Admin", "Admin", "HR"]:
98
+ raise HTTPException(status_code=403, detail="Only HR or administrators can resolve support tickets")
99
+
100
+ updated = crud.update_ticket_status(db, ticket_id=id, status=payload.status)
101
+
102
+ crud.create_audit_log(
103
+ db=db,
104
+ user_id=current_user.id,
105
+ action="Resolve Support Ticket",
106
+ ip_address=request.client.host if request.client else None,
107
+ user_agent=request.headers.get("user-agent"),
108
+ details=f"Updated ticket ID {id} status to '{payload.status}'",
109
+ company_id=current_user.company_id
110
+ )
111
+ return updated
backend/app/crud/crud.py CHANGED
@@ -508,3 +508,52 @@ def clear_all_audit_logs(db: Session, company_id: int = None) -> int:
508
  result = db.execute(stmt)
509
  db.commit()
510
  return result.rowcount
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
508
  result = db.execute(stmt)
509
  db.commit()
510
  return result.rowcount
511
+
512
+ # --- Support Tickets CRUD ---
513
+ def get_ticket_by_id(db: Session, ticket_id: int):
514
+ return db.get(models.Ticket, ticket_id)
515
+
516
+ def get_tickets(db: Session, company_id: int = None, employee_id: int = None):
517
+ query = select(models.Ticket)
518
+ filters = []
519
+ if company_id is not None:
520
+ filters.append(models.Ticket.company_id == company_id)
521
+ if employee_id is not None:
522
+ filters.append(models.Ticket.employee_id == employee_id)
523
+ if filters:
524
+ query = query.where(and_(*filters))
525
+ return db.execute(query.order_by(models.Ticket.created_at.desc())).scalars().all()
526
+
527
+ def create_ticket(db: Session, ticket: schemas.TicketCreate, employee_id: int, company_id: int):
528
+ db_ticket = models.Ticket(
529
+ employee_id=employee_id,
530
+ company_id=company_id,
531
+ title=ticket.title,
532
+ category=ticket.category,
533
+ priority=ticket.priority,
534
+ status="Open"
535
+ )
536
+ db.add(db_ticket)
537
+ db.commit()
538
+ db.refresh(db_ticket)
539
+ return db_ticket
540
+
541
+ def create_ticket_message(db: Session, ticket_id: int, msg: schemas.TicketMessageCreate, sender_id: int):
542
+ db_message = models.TicketMessage(
543
+ ticket_id=ticket_id,
544
+ sender_id=sender_id,
545
+ message=msg.message
546
+ )
547
+ db.add(db_message)
548
+ db.commit()
549
+ db.refresh(db_message)
550
+ return db_message
551
+
552
+ def update_ticket_status(db: Session, ticket_id: int, status: str):
553
+ db_ticket = get_ticket_by_id(db, ticket_id)
554
+ if not db_ticket:
555
+ return None
556
+ db_ticket.status = status
557
+ db.commit()
558
+ db.refresh(db_ticket)
559
+ return db_ticket
backend/app/main.py CHANGED
@@ -16,7 +16,7 @@ from sqlalchemy import delete
16
  from app.core.config import settings
17
  from app.core.database import SessionLocal
18
  from app.core.init_db import init_db
19
- from app.api.v1 import auth, employees, departments, enrollment, kiosk, attendance, reports, analytics, settings as settings_api, audit, companies
20
 
21
  # Logging configuration
22
  logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
@@ -193,5 +193,6 @@ app.include_router(analytics.router, prefix=f"{settings.API_V1_STR}/analytics",
193
  app.include_router(settings_api.router, prefix=f"{settings.API_V1_STR}/settings", tags=["System Settings"])
194
  app.include_router(audit.router, prefix=f"{settings.API_V1_STR}/audit", tags=["System Audit Logs"])
195
  app.include_router(companies.router, prefix=f"{settings.API_V1_STR}/companies", tags=["Company Management"])
 
196
  # Trigger reload - reload 2
197
 
 
16
  from app.core.config import settings
17
  from app.core.database import SessionLocal
18
  from app.core.init_db import init_db
19
+ from app.api.v1 import auth, employees, departments, enrollment, kiosk, attendance, reports, analytics, settings as settings_api, audit, companies, tickets
20
 
21
  # Logging configuration
22
  logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
 
193
  app.include_router(settings_api.router, prefix=f"{settings.API_V1_STR}/settings", tags=["System Settings"])
194
  app.include_router(audit.router, prefix=f"{settings.API_V1_STR}/audit", tags=["System Audit Logs"])
195
  app.include_router(companies.router, prefix=f"{settings.API_V1_STR}/companies", tags=["Company Management"])
196
+ app.include_router(tickets.router, prefix=f"{settings.API_V1_STR}/tickets", tags=["Support Tickets & Helpdesk"])
197
  # Trigger reload - reload 2
198
 
backend/app/models/models.py CHANGED
@@ -58,6 +58,7 @@ class Company(Base):
58
  shifts = relationship("Shift", back_populates="company", cascade="all, delete-orphan")
59
  settings = relationship("Setting", back_populates="company", cascade="all, delete-orphan")
60
  audit_logs = relationship("AuditLog", back_populates="company", cascade="all, delete-orphan")
 
61
 
62
  class Role(Base):
63
  __tablename__ = "roles"
@@ -150,6 +151,7 @@ class Employee(Base):
150
  attendance_records = relationship("Attendance", back_populates="employee", cascade="all, delete-orphan")
151
  attendance_logs = relationship("AttendanceLog", back_populates="employee", cascade="all, delete-orphan")
152
  leave_requests = relationship("LeaveRequest", back_populates="employee", cascade="all, delete-orphan")
 
153
 
154
  class EmployeeImage(Base):
155
  __tablename__ = "employee_images"
@@ -263,3 +265,31 @@ class AuditLog(Base):
263
 
264
  company = relationship("Company", back_populates="audit_logs")
265
  user = relationship("User", back_populates="audit_logs")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  shifts = relationship("Shift", back_populates="company", cascade="all, delete-orphan")
59
  settings = relationship("Setting", back_populates="company", cascade="all, delete-orphan")
60
  audit_logs = relationship("AuditLog", back_populates="company", cascade="all, delete-orphan")
61
+ tickets = relationship("Ticket", back_populates="company", cascade="all, delete-orphan")
62
 
63
  class Role(Base):
64
  __tablename__ = "roles"
 
151
  attendance_records = relationship("Attendance", back_populates="employee", cascade="all, delete-orphan")
152
  attendance_logs = relationship("AttendanceLog", back_populates="employee", cascade="all, delete-orphan")
153
  leave_requests = relationship("LeaveRequest", back_populates="employee", cascade="all, delete-orphan")
154
+ tickets = relationship("Ticket", back_populates="employee", cascade="all, delete-orphan")
155
 
156
  class EmployeeImage(Base):
157
  __tablename__ = "employee_images"
 
265
 
266
  company = relationship("Company", back_populates="audit_logs")
267
  user = relationship("User", back_populates="audit_logs")
268
+
269
+ class Ticket(Base):
270
+ __tablename__ = "tickets"
271
+
272
+ id = Column(Integer, primary_key=True, index=True)
273
+ employee_id = Column(Integer, ForeignKey("employees.id", ondelete="CASCADE"), nullable=False)
274
+ company_id = Column(Integer, ForeignKey("companies.id", ondelete="CASCADE"), nullable=False)
275
+ title = Column(String(255), nullable=False)
276
+ category = Column(String(100), nullable=False) # Payroll, Attendance, IT, Leave, etc.
277
+ priority = Column(String(50), default="Medium") # Low, Medium, High
278
+ status = Column(String(50), default="Open") # Open, In Progress, Closed
279
+ created_at = Column(DateTime, default=datetime.datetime.utcnow)
280
+
281
+ employee = relationship("Employee", back_populates="tickets")
282
+ company = relationship("Company", back_populates="tickets")
283
+ messages = relationship("TicketMessage", back_populates="ticket", cascade="all, delete-orphan")
284
+
285
+ class TicketMessage(Base):
286
+ __tablename__ = "ticket_messages"
287
+
288
+ id = Column(Integer, primary_key=True, index=True)
289
+ ticket_id = Column(Integer, ForeignKey("tickets.id", ondelete="CASCADE"), nullable=False)
290
+ sender_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
291
+ message = Column(Text, nullable=False)
292
+ timestamp = Column(DateTime, default=datetime.datetime.utcnow)
293
+
294
+ ticket = relationship("Ticket", back_populates="messages")
295
+ sender = relationship("User")
backend/app/schemas/schemas.py CHANGED
@@ -293,3 +293,40 @@ class AuditLogOut(BaseModel):
293
  user_agent: Optional[str] = None
294
  details: Optional[str] = None
295
  model_config = ConfigDict(from_attributes=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  user_agent: Optional[str] = None
294
  details: Optional[str] = None
295
  model_config = ConfigDict(from_attributes=True)
296
+
297
+ # Ticket Message Schemas
298
+ class TicketMessageBase(BaseModel):
299
+ message: str
300
+
301
+ class TicketMessageCreate(TicketMessageBase):
302
+ pass
303
+
304
+ class TicketMessageOut(TicketMessageBase):
305
+ id: int
306
+ ticket_id: int
307
+ sender_id: int
308
+ sender: UserEmailOut
309
+ timestamp: datetime
310
+ model_config = ConfigDict(from_attributes=True)
311
+
312
+ # Ticket Schemas
313
+ class TicketBase(BaseModel):
314
+ title: str
315
+ category: str
316
+ priority: str
317
+
318
+ class TicketCreate(TicketBase):
319
+ pass
320
+
321
+ class TicketUpdateStatus(BaseModel):
322
+ status: str
323
+
324
+ class TicketOut(TicketBase):
325
+ id: int
326
+ employee_id: int
327
+ company_id: int
328
+ status: str
329
+ created_at: datetime
330
+ employee: Optional[EmployeeOut] = None
331
+ messages: List[TicketMessageOut] = []
332
+ model_config = ConfigDict(from_attributes=True)
frontend/app/tenants/page.tsx CHANGED
@@ -26,6 +26,7 @@ export default function TenantsPage() {
26
  const [maxEmployees, setMaxEmployees] = useState(100);
27
  const [availableTokens, setAvailableTokens] = useState(1000);
28
  const [status, setStatus] = useState("Active");
 
29
 
30
  const { data: tenants = [], isLoading } = useQuery({
31
  queryKey: ["tenants"],
@@ -100,6 +101,7 @@ export default function TenantsPage() {
100
  setMaxEmployees(100);
101
  setAvailableTokens(1000);
102
  setStatus("Active");
 
103
  };
104
 
105
  const handleOpenEdit = (tenant: any) => {
@@ -285,90 +287,314 @@ export default function TenantsPage() {
285
  </div>
286
  )}
287
 
288
- {/* Add Modal */}
289
  {showAddModal && (
290
  <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs px-4">
291
- <div className="bg-white border border-slate-200 rounded-2xl shadow-xl w-full max-w-md overflow-hidden animate-fadeInUp p-6 space-y-4">
292
- <h2 className="text-sm font-bold text-slate-900 border-b border-slate-100 pb-3">Onboard New Organization</h2>
293
- <form onSubmit={handleAddSubmit} className="space-y-3">
294
- <div className="space-y-1">
295
- <label className="text-[9.5px] font-bold text-slate-400 uppercase tracking-wider">Company Name</label>
296
- <input
297
- type="text"
298
- required
299
- value={name}
300
- onChange={(e) => setName(e.target.value)}
301
- className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
302
- />
 
 
 
 
 
 
 
 
 
303
  </div>
304
- <div className="space-y-1">
305
- <label className="text-[9.5px] font-bold text-slate-400 uppercase tracking-wider">Admin Email</label>
306
- <input
307
- type="email"
308
- required
309
- value={adminEmail}
310
- onChange={(e) => setAdminEmail(e.target.value)}
311
- className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
312
- />
313
- </div>
314
- <div className="grid grid-cols-2 gap-3">
315
- <div className="space-y-1">
316
- <label className="text-[9.5px] font-bold text-slate-400 uppercase tracking-wider">Max Employees</label>
317
- <input
318
- type="number"
319
- required
320
- value={maxEmployees}
321
- onChange={(e) => setMaxEmployees(Number(e.target.value))}
322
- className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
323
- />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324
  </div>
325
- <div className="space-y-1">
326
- <label className="text-[9.5px] font-bold text-slate-400 uppercase tracking-wider">Seeded Tokens</label>
327
- <input
328
- type="number"
329
- required
330
- value={availableTokens}
331
- onChange={(e) => setAvailableTokens(Number(e.target.value))}
332
- className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
333
- />
 
334
  </div>
335
- </div>
336
- <div className="space-y-1">
337
- <label className="text-[9.5px] font-bold text-slate-400 uppercase tracking-wider">Phone</label>
338
- <input
339
- type="text"
340
- value={phone}
341
- onChange={(e) => setPhone(e.target.value)}
342
- className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
343
- />
344
- </div>
345
- <div className="space-y-1">
346
- <label className="text-[9.5px] font-bold text-slate-400 uppercase tracking-wider">Address</label>
347
- <input
348
- type="text"
349
- value={address}
350
- onChange={(e) => setAddress(e.target.value)}
351
- className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
352
- />
353
- </div>
354
- <div className="flex items-center justify-end gap-2 pt-4 border-t border-slate-100">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
  <button
356
  type="button"
357
- onClick={() => setShowAddModal(false)}
358
- className="px-3.5 py-2 text-xs font-bold text-slate-500 hover:bg-slate-100 rounded-lg cursor-pointer"
359
  >
360
- Cancel
361
  </button>
 
362
  <button
363
- type="submit"
 
364
  disabled={createMutation.isPending}
365
- className="px-4 py-2 bg-slate-900 hover:bg-slate-800 text-white font-extrabold text-xs rounded-lg cursor-pointer flex items-center gap-1"
366
  >
367
- {createMutation.isPending && <Loader2 className="w-3 h-3 animate-spin" />}
368
- Confirm
369
  </button>
370
- </div>
371
- </form>
 
372
  </div>
373
  </div>
374
  )}
 
26
  const [maxEmployees, setMaxEmployees] = useState(100);
27
  const [availableTokens, setAvailableTokens] = useState(1000);
28
  const [status, setStatus] = useState("Active");
29
+ const [activeStep, setActiveStep] = useState(1);
30
 
31
  const { data: tenants = [], isLoading } = useQuery({
32
  queryKey: ["tenants"],
 
101
  setMaxEmployees(100);
102
  setAvailableTokens(1000);
103
  setStatus("Active");
104
+ setActiveStep(1);
105
  };
106
 
107
  const handleOpenEdit = (tenant: any) => {
 
287
  </div>
288
  )}
289
 
290
+ {/* Onboarding 14-Step Wizard */}
291
  {showAddModal && (
292
  <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs px-4">
293
+ <div className="bg-white border border-slate-200 rounded-2xl shadow-xl w-full max-w-xl overflow-hidden animate-fadeInUp flex flex-col h-[85vh]">
294
+
295
+ {/* Wizard Header */}
296
+ <div className="p-4 border-b border-slate-100 flex items-center justify-between bg-slate-50 shrink-0">
297
+ <div>
298
+ <h2 className="text-xs font-black text-slate-900 uppercase tracking-wider">Company Onboarding Wizard</h2>
299
+ <p className="text-[10px] text-slate-450">Step {activeStep} of 14: {
300
+ activeStep === 1 ? "Company Information" :
301
+ activeStep === 2 ? "Company Logo" :
302
+ activeStep === 3 ? "Organization Administrator" :
303
+ activeStep === 4 ? "HR Setup & Licensing" :
304
+ activeStep === 5 ? "Company Branches" :
305
+ activeStep === 6 ? "Departments" :
306
+ activeStep === 7 ? "Office Locations" :
307
+ activeStep === 8 ? "Working Hours" :
308
+ activeStep === 9 ? "Attendance Policies" :
309
+ activeStep === 10 ? "Face Recognition Configuration" :
310
+ activeStep === 11 ? "Camera Registration" :
311
+ activeStep === 12 ? "Employee Invitation" :
312
+ activeStep === 13 ? "Final Review" : "Go Live & Deploy"
313
+ }</p>
314
  </div>
315
+ <button
316
+ onClick={() => setShowAddModal(false)}
317
+ className="text-xs font-bold text-slate-400 hover:text-slate-700 cursor-pointer"
318
+ >
319
+ Close
320
+ </button>
321
+ </div>
322
+
323
+ {/* Step indicator bar */}
324
+ <div className="w-full bg-slate-100 h-1 shrink-0">
325
+ <div
326
+ className="bg-slate-900 h-1 transition-all duration-350"
327
+ style={{ width: `${(activeStep / 14) * 100}%` }}
328
+ />
329
+ </div>
330
+
331
+ {/* Wizard Content */}
332
+ <div className="flex-1 overflow-y-auto p-6 space-y-4 text-slate-800">
333
+ {activeStep === 1 && (
334
+ <div className="space-y-3">
335
+ <h3 className="text-xs font-bold text-slate-700">Enter Legal Company Information</h3>
336
+ <div className="space-y-1">
337
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Company Name</label>
338
+ <input
339
+ type="text"
340
+ required
341
+ value={name}
342
+ onChange={(e) => setName(e.target.value)}
343
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
344
+ placeholder="e.g. NetraID Industries"
345
+ />
346
+ </div>
347
+ <div className="space-y-1">
348
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Office Address</label>
349
+ <input
350
+ type="text"
351
+ value={address}
352
+ onChange={(e) => setAddress(e.target.value)}
353
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
354
+ placeholder="e.g. 101 Tech Park, Bangalore"
355
+ />
356
+ </div>
357
  </div>
358
+ )}
359
+
360
+ {activeStep === 2 && (
361
+ <div className="space-y-4 text-center py-6">
362
+ <h3 className="text-xs font-bold text-slate-700">Upload Company Branding Logo</h3>
363
+ <div className="mx-auto w-20 h-20 rounded-2xl border-2 border-dashed border-slate-200 flex flex-col items-center justify-center text-slate-400 hover:border-slate-400 transition-colors cursor-pointer bg-slate-50">
364
+ <Plus className="w-5 h-5" />
365
+ <span className="text-[8px] font-bold mt-1">Select PNG</span>
366
+ </div>
367
+ <p className="text-[10px] text-slate-450">Recommended: Square format 512x512 pixels</p>
368
  </div>
369
+ )}
370
+
371
+ {activeStep === 3 && (
372
+ <div className="space-y-3">
373
+ <h3 className="text-xs font-bold text-slate-700">Organization Administrator Account</h3>
374
+ <div className="space-y-1">
375
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Admin Email address</label>
376
+ <input
377
+ type="email"
378
+ required
379
+ value={adminEmail}
380
+ onChange={(e) => setAdminEmail(e.target.value)}
381
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
382
+ placeholder="e.g. admin@company.com"
383
+ />
384
+ </div>
385
+ </div>
386
+ )}
387
+
388
+ {activeStep === 4 && (
389
+ <div className="space-y-3">
390
+ <h3 className="text-xs font-bold text-slate-700">Setup Employee Limits & Initial Tokens</h3>
391
+ <div className="grid grid-cols-2 gap-4">
392
+ <div className="space-y-1">
393
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Max Employees Limit</label>
394
+ <input
395
+ type="number"
396
+ required
397
+ value={maxEmployees}
398
+ onChange={(e) => setMaxEmployees(Number(e.target.value))}
399
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
400
+ />
401
+ </div>
402
+ <div className="space-y-1">
403
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Initial Available Tokens</label>
404
+ <input
405
+ type="number"
406
+ required
407
+ value={availableTokens}
408
+ onChange={(e) => setAvailableTokens(Number(e.target.value))}
409
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
410
+ />
411
+ </div>
412
+ </div>
413
+ </div>
414
+ )}
415
+
416
+ {activeStep === 5 && (
417
+ <div className="space-y-3">
418
+ <h3 className="text-xs font-bold text-slate-700">Setup Regional Branches</h3>
419
+ <div className="space-y-1">
420
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Primary Branch Name</label>
421
+ <input
422
+ type="text"
423
+ defaultValue="Main Headquarters"
424
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
425
+ />
426
+ </div>
427
+ </div>
428
+ )}
429
+
430
+ {activeStep === 6 && (
431
+ <div className="space-y-3">
432
+ <h3 className="text-xs font-bold text-slate-700">Setup Corporate Departments</h3>
433
+ <div className="space-y-1">
434
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Primary Department Name</label>
435
+ <input
436
+ type="text"
437
+ defaultValue="Engineering & Technology"
438
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
439
+ />
440
+ </div>
441
+ </div>
442
+ )}
443
+
444
+ {activeStep === 7 && (
445
+ <div className="space-y-3">
446
+ <h3 className="text-xs font-bold text-slate-700">Configure Geofence Office Coordinates</h3>
447
+ <div className="grid grid-cols-2 gap-4">
448
+ <div className="space-y-1">
449
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Geofence Latitude</label>
450
+ <input
451
+ type="text"
452
+ defaultValue="12.9716"
453
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
454
+ />
455
+ </div>
456
+ <div className="space-y-1">
457
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Geofence Longitude</label>
458
+ <input
459
+ type="text"
460
+ defaultValue="77.5946"
461
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
462
+ />
463
+ </div>
464
+ </div>
465
+ </div>
466
+ )}
467
+
468
+ {activeStep === 8 && (
469
+ <div className="space-y-3">
470
+ <h3 className="text-xs font-bold text-slate-700">Set Core Shift Working Hours</h3>
471
+ <div className="space-y-1">
472
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Shift Timing Bounds</label>
473
+ <input
474
+ type="text"
475
+ defaultValue="09:00 AM - 06:00 PM"
476
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
477
+ />
478
+ </div>
479
+ </div>
480
+ )}
481
+
482
+ {activeStep === 9 && (
483
+ <div className="space-y-3">
484
+ <h3 className="text-xs font-bold text-slate-700">Configure Attendance Grace Policies</h3>
485
+ <div className="space-y-1">
486
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Grace Period (Minutes)</label>
487
+ <input
488
+ type="number"
489
+ defaultValue={15}
490
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
491
+ />
492
+ </div>
493
+ </div>
494
+ )}
495
+
496
+ {activeStep === 10 && (
497
+ <div className="space-y-3">
498
+ <h3 className="text-xs font-bold text-slate-700">Configure Biometric AI Face Match Threshold</h3>
499
+ <div className="space-y-1">
500
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Confidence Cut-Off Score (Cosine Similarity)</label>
501
+ <input
502
+ type="range"
503
+ min="0.3"
504
+ max="0.9"
505
+ step="0.05"
506
+ defaultValue="0.6"
507
+ className="w-full"
508
+ />
509
+ <div className="flex justify-between text-[8px] text-slate-450 font-bold">
510
+ <span>0.3 (Loose Match)</span>
511
+ <span>0.6 (Recommended)</span>
512
+ <span>0.9 (Strict Match)</span>
513
+ </div>
514
+ </div>
515
+ </div>
516
+ )}
517
+
518
+ {activeStep === 11 && (
519
+ <div className="space-y-3">
520
+ <h3 className="text-xs font-bold text-slate-700">On-Site Camera Kiosk Device Registration</h3>
521
+ <div className="space-y-1">
522
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Primary Device Name</label>
523
+ <input
524
+ type="text"
525
+ defaultValue="Front Gate Lobby Tablet"
526
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
527
+ />
528
+ </div>
529
+ </div>
530
+ )}
531
+
532
+ {activeStep === 12 && (
533
+ <div className="space-y-3">
534
+ <h3 className="text-xs font-bold text-slate-700">Invite Employees (Roster Import)</h3>
535
+ <div className="space-y-1">
536
+ <label className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Invitee Email List (Comma separated)</label>
537
+ <textarea
538
+ rows={3}
539
+ placeholder="john@company.com, sarah@company.com"
540
+ className="w-full text-xs p-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900 resize-none"
541
+ />
542
+ </div>
543
+ </div>
544
+ )}
545
+
546
+ {activeStep === 13 && (
547
+ <div className="space-y-3">
548
+ <h3 className="text-xs font-bold text-slate-700">Final Onboarding Audit Review</h3>
549
+ <div className="bg-slate-50 border border-slate-100 p-4 rounded-xl space-y-2 text-[11px] text-slate-650">
550
+ <div>🏢 <strong>Company:</strong> {name || "Not entered"}</div>
551
+ <div>👤 <strong>Primary Administrator:</strong> {adminEmail || "Not entered"}</div>
552
+ <div>👥 <strong>Licensing Cap:</strong> {maxEmployees} employees</div>
553
+ <div>🪙 <strong>Balance Seed:</strong> {availableTokens} API tokens</div>
554
+ </div>
555
+ </div>
556
+ )}
557
+
558
+ {activeStep === 14 && (
559
+ <div className="space-y-4 text-center py-6">
560
+ <h3 className="text-xs font-bold text-slate-700">All Steps Ready!</h3>
561
+ <p className="text-[11px] text-slate-450">Click "Deploy System" below to generate organization spaces, initialize setting profiles, and dispatch administrator invites.</p>
562
+ </div>
563
+ )}
564
+ </div>
565
+
566
+ {/* Wizard Footer */}
567
+ <div className="p-4 border-t border-slate-100 flex items-center justify-between bg-slate-50 shrink-0">
568
+ <button
569
+ type="button"
570
+ disabled={activeStep === 1}
571
+ onClick={() => setActiveStep(prev => Math.max(1, prev - 1))}
572
+ className="px-3.5 py-1.5 text-xs font-bold text-slate-550 border border-slate-200 rounded-lg bg-white cursor-pointer active:scale-95 transition-all disabled:opacity-40"
573
+ >
574
+ Back
575
+ </button>
576
+
577
+ {activeStep < 14 ? (
578
  <button
579
  type="button"
580
+ onClick={() => setActiveStep(prev => Math.min(14, prev + 1))}
581
+ className="px-4 py-1.5 bg-slate-900 hover:bg-slate-800 text-white font-extrabold text-xs rounded-lg cursor-pointer active:scale-95 transition-all"
582
  >
583
+ Next Step
584
  </button>
585
+ ) : (
586
  <button
587
+ type="button"
588
+ onClick={handleAddSubmit}
589
  disabled={createMutation.isPending}
590
+ className="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white font-extrabold text-xs rounded-lg cursor-pointer flex items-center gap-1 active:scale-95 transition-all"
591
  >
592
+ {createMutation.isPending && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
593
+ Deploy System
594
  </button>
595
+ )}
596
+ </div>
597
+
598
  </div>
599
  </div>
600
  )}
frontend/app/tickets/page.tsx ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import React, { useState, useEffect, useRef } from "react";
4
+ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
5
+ import SidebarLayout from "@/components/SidebarLayout";
6
+ import { fetchApi, getUserProfile } from "@/app/utils/api";
7
+ import { useToast } from "@/app/utils/toast";
8
+ import {
9
+ MessageSquare, Plus, Send, CheckCircle, Clock,
10
+ AlertTriangle, Filter, Search, ChevronRight, User, Loader2
11
+ } from "lucide-react";
12
+
13
+ export default function TicketsPage() {
14
+ const queryClient = useQueryClient();
15
+ const { toast } = useToast();
16
+
17
+ const [profile, setProfile] = useState<any>(null);
18
+ const [selectedTicket, setSelectedTicket] = useState<any>(null);
19
+ const [replyText, setReplyText] = useState("");
20
+ const [showAddModal, setShowAddModal] = useState(false);
21
+
22
+ // New ticket form states
23
+ const [title, setTitle] = useState("");
24
+ const [category, setCategory] = useState("Payroll");
25
+ const [priority, setPriority] = useState("Medium");
26
+ const [initialMessage, setInitialMessage] = useState("");
27
+
28
+ const chatEndRef = useRef<HTMLDivElement>(null);
29
+
30
+ useEffect(() => {
31
+ setProfile(getUserProfile());
32
+ }, []);
33
+
34
+ const { data: tickets = [], isLoading } = useQuery({
35
+ queryKey: ["tickets"],
36
+ queryFn: async () => {
37
+ return await fetchApi("/tickets/");
38
+ }
39
+ });
40
+
41
+ const createTicketMutation = useMutation({
42
+ mutationFn: async (payload: any) => {
43
+ const ticket = await fetchApi("/tickets/", {
44
+ method: "POST",
45
+ body: JSON.stringify({
46
+ title: payload.title,
47
+ category: payload.category,
48
+ priority: payload.priority
49
+ })
50
+ });
51
+
52
+ // Post the initial message if provided
53
+ if (payload.message && payload.message.trim().length > 0) {
54
+ await fetchApi(`/tickets/${ticket.id}/messages`, {
55
+ method: "POST",
56
+ body: JSON.stringify({ message: payload.message })
57
+ });
58
+ }
59
+ return ticket;
60
+ },
61
+ onSuccess: (data) => {
62
+ queryClient.invalidateQueries({ queryKey: ["tickets"] });
63
+ toast.success("Support ticket opened");
64
+ setShowAddModal(false);
65
+ setTitle("");
66
+ setInitialMessage("");
67
+ setSelectedTicket(data);
68
+ },
69
+ onError: (err: any) => {
70
+ toast.error(err.message || "Failed to open ticket");
71
+ }
72
+ });
73
+
74
+ const replyMutation = useMutation({
75
+ mutationFn: async ({ ticketId, message }: { ticketId: number; message: string }) => {
76
+ return await fetchApi(`/tickets/${ticketId}/messages`, {
77
+ method: "POST",
78
+ body: JSON.stringify({ message })
79
+ });
80
+ },
81
+ onSuccess: () => {
82
+ queryClient.invalidateQueries({ queryKey: ["tickets"] });
83
+ setReplyText("");
84
+ },
85
+ onError: (err: any) => {
86
+ toast.error(err.message || "Failed to send message");
87
+ }
88
+ });
89
+
90
+ const updateStatusMutation = useMutation({
91
+ mutationFn: async ({ ticketId, status }: { ticketId: number; status: string }) => {
92
+ return await fetchApi(`/tickets/${ticketId}/status`, {
93
+ method: "PUT",
94
+ body: JSON.stringify({ status })
95
+ });
96
+ },
97
+ onSuccess: (data) => {
98
+ queryClient.invalidateQueries({ queryKey: ["tickets"] });
99
+ setSelectedTicket(data);
100
+ toast.success(`Ticket status marked as ${data.status}`);
101
+ },
102
+ onError: (err: any) => {
103
+ toast.error(err.message || "Failed to update ticket status");
104
+ }
105
+ });
106
+
107
+ // Keep chat scrolled to bottom
108
+ useEffect(() => {
109
+ chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
110
+ }, [selectedTicket?.messages]);
111
+
112
+ // Sync selected ticket details after query updates
113
+ useEffect(() => {
114
+ if (selectedTicket) {
115
+ const updated = tickets.find((t: any) => t.id === selectedTicket.id);
116
+ if (updated) setSelectedTicket(updated);
117
+ }
118
+ }, [tickets, selectedTicket]);
119
+
120
+ const handleSendReply = (e: React.FormEvent) => {
121
+ e.preventDefault();
122
+ if (!replyText.trim() || !selectedTicket) return;
123
+ replyMutation.mutate({ ticketId: selectedTicket.id, message: replyText });
124
+ };
125
+
126
+ const handleCreateSubmit = (e: React.FormEvent) => {
127
+ e.preventDefault();
128
+ if (!title.trim() || !initialMessage.trim()) return;
129
+ createTicketMutation.mutate({ title, category, priority, message: initialMessage });
130
+ };
131
+
132
+ const isHR = profile?.role?.name === "Admin" || profile?.role?.name === "HR" || profile?.role?.name === "Super Admin";
133
+
134
+ return (
135
+ <SidebarLayout>
136
+ <div className="h-[calc(100vh-6.5rem)] flex flex-col md:flex-row border border-slate-200 rounded-2xl overflow-hidden bg-white shadow-2xs">
137
+
138
+ {/* Left pane: Tickets list */}
139
+ <div className="w-full md:w-80 border-r border-slate-200 flex flex-col shrink-0">
140
+ <div className="p-4 border-b border-slate-100 flex items-center justify-between">
141
+ <h1 className="text-sm font-extrabold text-slate-900 tracking-tight flex items-center gap-1.5">
142
+ <MessageSquare className="w-4 h-4 text-slate-700" />
143
+ Helpdesk Support
144
+ </h1>
145
+ {!isHR && (
146
+ <button
147
+ onClick={() => setShowAddModal(true)}
148
+ className="p-1.5 bg-slate-900 hover:bg-slate-800 text-white rounded-lg cursor-pointer active:scale-95 transition-all"
149
+ title="Create Ticket"
150
+ >
151
+ <Plus className="w-3.5 h-3.5" />
152
+ </button>
153
+ )}
154
+ </div>
155
+
156
+ <div className="flex-1 overflow-y-auto p-2 space-y-1">
157
+ {isLoading ? (
158
+ Array.from({ length: 4 }).map((_, i) => (
159
+ <div key={i} className="p-3 border border-slate-50 rounded-xl animate-pulse space-y-2">
160
+ <div className="h-3 w-28 bg-slate-100 rounded" />
161
+ <div className="h-2 w-20 bg-slate-100 rounded" />
162
+ </div>
163
+ ))
164
+ ) : tickets.length > 0 ? (
165
+ tickets.map((t: any) => (
166
+ <button
167
+ key={t.id}
168
+ onClick={() => setSelectedTicket(t)}
169
+ className={`w-full text-left p-3 rounded-xl border transition-all cursor-pointer flex flex-col gap-1.5 ${
170
+ selectedTicket?.id === t.id
171
+ ? "border-slate-300 bg-slate-50"
172
+ : "border-transparent hover:bg-slate-50/50"
173
+ }`}
174
+ >
175
+ <div className="flex items-start justify-between w-full">
176
+ <span className="text-[9px] font-bold uppercase tracking-wider text-slate-400">{t.category}</span>
177
+ <span className={`text-[8px] font-bold px-1.5 py-0.5 rounded border ${
178
+ t.priority === "High"
179
+ ? "bg-rose-50 border-rose-100 text-rose-600"
180
+ : t.priority === "Medium"
181
+ ? "bg-amber-50 border-amber-100 text-amber-600"
182
+ : "bg-slate-50 border-slate-150 text-slate-600"
183
+ }`}>
184
+ {t.priority}
185
+ </span>
186
+ </div>
187
+ <div>
188
+ <h3 className="text-xs font-bold text-slate-800 truncate">{t.title}</h3>
189
+ {isHR && t.employee && (
190
+ <p className="text-[10px] text-slate-450 mt-0.5">By: {t.employee.name}</p>
191
+ )}
192
+ </div>
193
+ <div className="flex items-center gap-1.5 mt-1">
194
+ <span className={`w-1.5 h-1.5 rounded-full ${
195
+ t.status === "Closed" ? "bg-emerald-500" : t.status === "In Progress" ? "bg-amber-500" : "bg-blue-500"
196
+ }`} />
197
+ <span className="text-[9px] font-bold text-slate-450 uppercase">{t.status}</span>
198
+ </div>
199
+ </button>
200
+ ))
201
+ ) : (
202
+ <div className="py-12 text-center text-slate-400 text-xs font-medium">
203
+ No support tickets found.
204
+ </div>
205
+ )}
206
+ </div>
207
+ </div>
208
+
209
+ {/* Right pane: Message details */}
210
+ <div className="flex-1 flex flex-col bg-slate-50/50 h-full">
211
+ {selectedTicket ? (
212
+ <>
213
+ {/* Ticket header details */}
214
+ <div className="p-4 border-b border-slate-200 bg-white flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 shrink-0">
215
+ <div className="space-y-0.5">
216
+ <span className="text-[9px] font-extrabold uppercase tracking-wider text-slate-400">{selectedTicket.category} Support Ticket</span>
217
+ <h2 className="text-xs font-bold text-slate-900">{selectedTicket.title}</h2>
218
+ {isHR && selectedTicket.employee && (
219
+ <p className="text-[10px] text-slate-450">Submitted by: <strong className="text-slate-700">{selectedTicket.employee.name}</strong> ({selectedTicket.employee.email})</p>
220
+ )}
221
+ </div>
222
+
223
+ {/* HR Status updater action */}
224
+ {isHR ? (
225
+ <div className="flex items-center gap-2">
226
+ <span className="text-[10px] font-bold text-slate-400">STATUS:</span>
227
+ <select
228
+ value={selectedTicket.status}
229
+ onChange={(e) => updateStatusMutation.mutate({ ticketId: selectedTicket.id, status: e.target.value })}
230
+ className="text-[10px] font-bold h-7 border border-slate-200 rounded-lg bg-white px-2 text-slate-800"
231
+ >
232
+ <option value="Open">Open</option>
233
+ <option value="In Progress">In Progress</option>
234
+ <option value="Closed">Closed</option>
235
+ </select>
236
+ </div>
237
+ ) : (
238
+ <span className={`text-[9px] font-mono font-bold px-2 py-0.5 border rounded-full ${
239
+ selectedTicket.status === "Closed"
240
+ ? "bg-emerald-50 border-emerald-150 text-emerald-700"
241
+ : selectedTicket.status === "In Progress"
242
+ ? "bg-amber-50 border-amber-150 text-amber-700"
243
+ : "bg-blue-50 border-blue-150 text-blue-700"
244
+ }`}>
245
+ {selectedTicket.status}
246
+ </span>
247
+ )}
248
+ </div>
249
+
250
+ {/* Chat Thread */}
251
+ <div className="flex-1 overflow-y-auto p-4 space-y-3.5">
252
+ {selectedTicket.messages && selectedTicket.messages.map((m: any) => {
253
+ const isMe = m.sender_id === profile?.id;
254
+ return (
255
+ <div key={m.id} className={`flex items-start gap-2.5 max-w-[85%] ${isMe ? "ml-auto flex-row-reverse" : "mr-auto"}`}>
256
+ <div className="w-7 h-7 rounded-full bg-slate-200 border border-slate-300 flex items-center justify-center text-slate-600 shrink-0">
257
+ <User className="w-3.5 h-3.5" />
258
+ </div>
259
+ <div className="space-y-1">
260
+ <div className={`p-3 rounded-2xl text-xs leading-relaxed ${
261
+ isMe
262
+ ? "bg-slate-900 text-white rounded-tr-none"
263
+ : "bg-white border border-slate-200 text-slate-800 rounded-tl-none"
264
+ }`}>
265
+ <p>{m.message}</p>
266
+ </div>
267
+ <p className={`text-[8px] text-slate-400 font-mono ${isMe ? "text-right" : ""}`}>
268
+ {new Date(m.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
269
+ </p>
270
+ </div>
271
+ </div>
272
+ );
273
+ })}
274
+ <div ref={chatEndRef} />
275
+ </div>
276
+
277
+ {/* Reply Form */}
278
+ {selectedTicket.status !== "Closed" ? (
279
+ <form onSubmit={handleSendReply} className="p-3 bg-white border-t border-slate-200 flex gap-2 shrink-0">
280
+ <input
281
+ type="text"
282
+ placeholder="Type support reply message..."
283
+ value={replyText}
284
+ onChange={(e) => setReplyText(e.target.value)}
285
+ className="flex-1 text-xs h-9 border border-slate-200 px-3 rounded-xl focus:outline-none focus:border-cyan-400 text-slate-900 bg-white"
286
+ />
287
+ <button
288
+ type="submit"
289
+ disabled={replyMutation.isPending || !replyText.trim()}
290
+ className="h-9 px-4 bg-slate-900 hover:bg-slate-800 text-white rounded-xl text-xs font-bold flex items-center gap-1 active:scale-95 transition-all cursor-pointer disabled:opacity-50"
291
+ >
292
+ {replyMutation.isPending ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Send className="w-3.5 h-3.5" />}
293
+ Send
294
+ </button>
295
+ </form>
296
+ ) : (
297
+ <div className="p-4 bg-slate-100 border-t border-slate-200 text-center text-[10px] text-slate-500 font-semibold uppercase tracking-wider shrink-0">
298
+ 🔒 This support ticket is closed and resolved.
299
+ </div>
300
+ )}
301
+ </>
302
+ ) : (
303
+ <div className="flex-1 flex flex-col items-center justify-center text-slate-400 gap-2 p-6">
304
+ <MessageSquare className="w-10 h-10 text-slate-300" />
305
+ <p className="text-xs font-medium">Select a ticket from the left panel to open chat support</p>
306
+ </div>
307
+ )}
308
+ </div>
309
+ </div>
310
+
311
+ {/* Add modal */}
312
+ {showAddModal && (
313
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs px-4">
314
+ <div className="bg-white border border-slate-200 rounded-2xl shadow-xl w-full max-w-md overflow-hidden animate-fadeInUp p-6 space-y-4">
315
+ <h2 className="text-sm font-bold text-slate-900 border-b border-slate-100 pb-3">Open Support Ticket</h2>
316
+ <form onSubmit={handleCreateSubmit} className="space-y-3">
317
+ <div className="space-y-1">
318
+ <label className="text-[9.5px] font-bold text-slate-400 uppercase tracking-wider">Subject Title</label>
319
+ <input
320
+ type="text"
321
+ required
322
+ placeholder="e.g. Discrepancy in check-in logs"
323
+ value={title}
324
+ onChange={(e) => setTitle(e.target.value)}
325
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
326
+ />
327
+ </div>
328
+ <div className="grid grid-cols-2 gap-3">
329
+ <div className="space-y-1">
330
+ <label className="text-[9.5px] font-bold text-slate-400 uppercase tracking-wider">Category</label>
331
+ <select
332
+ value={category}
333
+ onChange={(e) => setCategory(e.target.value)}
334
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
335
+ >
336
+ <option value="Payroll">Payroll</option>
337
+ <option value="Attendance">Attendance</option>
338
+ <option value="IT Support">IT Support</option>
339
+ <option value="Leave Requests">Leave Requests</option>
340
+ <option value="General Queries">General Queries</option>
341
+ </select>
342
+ </div>
343
+ <div className="space-y-1">
344
+ <label className="text-[9.5px] font-bold text-slate-400 uppercase tracking-wider">Priority</label>
345
+ <select
346
+ value={priority}
347
+ onChange={(e) => setPriority(e.target.value)}
348
+ className="w-full text-xs h-9 px-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900"
349
+ >
350
+ <option value="Low">Low</option>
351
+ <option value="Medium">Medium</option>
352
+ <option value="High">High</option>
353
+ </select>
354
+ </div>
355
+ </div>
356
+ <div className="space-y-1">
357
+ <label className="text-[9.5px] font-bold text-slate-400 uppercase tracking-wider">Message Description</label>
358
+ <textarea
359
+ required
360
+ rows={4}
361
+ placeholder="Describe your issue or query here..."
362
+ value={initialMessage}
363
+ onChange={(e) => setInitialMessage(e.target.value)}
364
+ className="w-full text-xs p-3 rounded-lg border border-slate-200 focus:outline-none focus:border-cyan-400 bg-white text-slate-900 resize-none"
365
+ />
366
+ </div>
367
+ <div className="flex items-center justify-end gap-2 pt-4 border-t border-slate-100">
368
+ <button
369
+ type="button"
370
+ onClick={() => setShowAddModal(false)}
371
+ className="px-3.5 py-2 text-xs font-bold text-slate-500 hover:bg-slate-100 rounded-lg cursor-pointer"
372
+ >
373
+ Cancel
374
+ </button>
375
+ <button
376
+ type="submit"
377
+ disabled={createTicketMutation.isPending}
378
+ className="px-4 py-2 bg-slate-900 hover:bg-slate-800 text-white font-extrabold text-xs rounded-lg cursor-pointer flex items-center gap-1"
379
+ >
380
+ {createTicketMutation.isPending && <Loader2 className="w-3 h-3 animate-spin" />}
381
+ Open Ticket
382
+ </button>
383
+ </div>
384
+ </form>
385
+ </div>
386
+ </div>
387
+ )}
388
+ </SidebarLayout>
389
+ );
390
+ }
frontend/components/SidebarLayout.tsx CHANGED
@@ -18,7 +18,8 @@ import {
18
  History,
19
  Sun,
20
  Moon,
21
- Building2
 
22
  } from "lucide-react";
23
  import { getAccessToken, getUserProfile, clearTokens } from "@/app/utils/api";
24
 
@@ -27,6 +28,7 @@ const navItems = [
27
  { name: "Organizations", href: "/tenants", icon: Building2 },
28
  { name: "Attendance", href: "/attendance", icon: Clock },
29
  { name: "Employees", href: "/employees", icon: Users },
 
30
  { name: "Reports", href: "/reports", icon: FileSpreadsheet },
31
  { name: "Audit Logs", href: "/audit", icon: History },
32
  { name: "Settings", href: "/settings", icon: Settings },
@@ -138,8 +140,8 @@ export default function SidebarLayout({ children }: { children: React.ReactNode
138
  setUser(profile);
139
  setAuthorized(true);
140
 
141
- // Auto-redirect employees to dashboard if they attempt to access any admin views
142
- if (profile?.role?.name === "Employee" && pathname !== "/dashboard") {
143
  router.push("/dashboard");
144
  } else if (profile?.role?.name !== "Super Admin" && pathname === "/tenants") {
145
  router.push("/dashboard");
@@ -170,7 +172,7 @@ export default function SidebarLayout({ children }: { children: React.ReactNode
170
  const isEmployee = user?.role?.name === "Employee";
171
  const isSuperAdmin = user?.role?.name === "Super Admin";
172
  const visibleNavItems = isEmployee
173
- ? navItems.filter(item => item.href === "/dashboard")
174
  : isSuperAdmin
175
  ? navItems
176
  : navItems.filter(item => item.href !== "/tenants");
 
18
  History,
19
  Sun,
20
  Moon,
21
+ Building2,
22
+ MessageSquare
23
  } from "lucide-react";
24
  import { getAccessToken, getUserProfile, clearTokens } from "@/app/utils/api";
25
 
 
28
  { name: "Organizations", href: "/tenants", icon: Building2 },
29
  { name: "Attendance", href: "/attendance", icon: Clock },
30
  { name: "Employees", href: "/employees", icon: Users },
31
+ { name: "Helpdesk Support",href: "/tickets", icon: MessageSquare },
32
  { name: "Reports", href: "/reports", icon: FileSpreadsheet },
33
  { name: "Audit Logs", href: "/audit", icon: History },
34
  { name: "Settings", href: "/settings", icon: Settings },
 
140
  setUser(profile);
141
  setAuthorized(true);
142
 
143
+ // Auto-redirect employees to dashboard if they attempt to access any admin views
144
+ if (profile?.role?.name === "Employee" && pathname !== "/dashboard" && pathname !== "/tickets") {
145
  router.push("/dashboard");
146
  } else if (profile?.role?.name !== "Super Admin" && pathname === "/tenants") {
147
  router.push("/dashboard");
 
172
  const isEmployee = user?.role?.name === "Employee";
173
  const isSuperAdmin = user?.role?.name === "Super Admin";
174
  const visibleNavItems = isEmployee
175
+ ? navItems.filter(item => item.href === "/dashboard" || item.href === "/tickets")
176
  : isSuperAdmin
177
  ? navItems
178
  : navItems.filter(item => item.href !== "/tenants");