Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | "use client"; import { useState, useEffect, useCallback } from "react"; import { Button } from "@/components/ui"; import { Icon } from "@/components/ui/icons"; import ConfirmDialog from "@/components/ui/ConfirmDialog"; import toast from "react-hot-toast"; import SegmentBuilder from "@/components/features/admin/segments/SegmentBuilder"; interface Segment { id: number; name: string; description: string | null; rules: SegmentRuleGroup[]; isActive: boolean; promotionCount: number; memberCount: number | null; createdAt: string; updatedAt: string; } interface SegmentRule { field: string; operator: string; value: string | number | string[] | number[]; } interface SegmentRuleGroup { conditions: SegmentRule[]; logic: "AND" | "OR"; } export default function AdminSegmentsPage() { const [segments, setSegments] = useState<Segment[]>([]); const [loading, setLoading] = useState(true); const [showBuilder, setShowBuilder] = useState(false); const [editingSegment, setEditingSegment] = useState<Segment | null>(null); const [deleteSegmentId, setDeleteSegmentId] = useState<number | null>(null); const [deleting, setDeleting] = useState(false); const fetchSegments = useCallback(async () => { try { setLoading(true); const res = await fetch("/api/admin/segments?includeCount=true"); const result = await res.json(); if (result.success) { setSegments(result.data); } else { toast.error("Failed to load segments"); } } catch { toast.error("Failed to load segments"); } finally { setLoading(false); } }, []); useEffect(() => { fetchSegments(); }, [fetchSegments]); const handleCreate = () => { setEditingSegment(null); setShowBuilder(true); }; const handleEdit = (segment: Segment) => { setEditingSegment(segment); setShowBuilder(true); }; const handleSave = async (data: { name: string; description: string; rules: SegmentRuleGroup[]; isActive: boolean; }) => { try { const url = editingSegment ? `/api/admin/segments/${editingSegment.id}` : "/api/admin/segments"; const method = editingSegment ? "PUT" : "POST"; const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(data)}); const result = await res.json(); if (result.success) { toast.success( editingSegment ? "Segment updated" : "Segment created" ); setShowBuilder(false); setEditingSegment(null); fetchSegments(); } else { toast.error(result.error || "Failed to save segment"); } } catch { toast.error("Failed to save segment"); } }; const handleDelete = async () => { if (!deleteSegmentId) return; setDeleting(true); try { const res = await fetch(`/api/admin/segments/${deleteSegmentId}`, { method: "DELETE"}); const result = await res.json(); if (result.success) { toast.success("Segment deleted"); setDeleteSegmentId(null); fetchSegments(); } else { toast.error(result.error || "Failed to delete segment"); } } catch { toast.error("Failed to delete segment"); } finally { setDeleting(false); } }; const handleToggleActive = async (segment: Segment) => { try { const res = await fetch(`/api/admin/segments/${segment.id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ isActive: !segment.isActive })}); const result = await res.json(); if (result.success) { toast.success( `Segment ${segment.isActive ? "deactivated" : "activated"}` ); fetchSegments(); } else { toast.error(result.error || "Failed to update segment"); } } catch { toast.error("Failed to update segment"); } }; const getFieldLabel = (field: string): string => { const labels: Record<string, string> = { total_spent: "Total Spent", orders_count: "Order Count", lifetime_points: "Lifetime Points", current_tier: "Loyalty Tier", created_at: "Account Created", email_domain: "Email Domain", has_reviewed: "Has Reviewed"}; return labels[field] || field; }; const getOperatorLabel = (operator: string): string => { const labels: Record<string, string> = { equals: "=", not_equals: "!=", greater_than: ">", less_than: "<", greater_than_or_equal: ">=", less_than_or_equal: "<=", contains: "contains", not_contains: "does not contain", in: "in", not_in: "not in", is_empty: "is empty", is_not_empty: "is not empty"}; return labels[operator] || operator; }; if (showBuilder) { return ( <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8"> <div className="mb-6"> <Button variant="ghost" onClick={() => { setShowBuilder(false); setEditingSegment(null); }} leftIcon={<Icon name="chevron-left" size={16} />} > Back to Segments </Button> </div> <SegmentBuilder segment={editingSegment} onSave={handleSave} onCancel={() => { setShowBuilder(false); setEditingSegment(null); }} /> </div> ); } return ( <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8"> {/* Header */} <div className="flex justify-between items-center mb-8"> <div> <h1 className="text-2xl font-bold text-gray-900 dark:text-white"> Customer Segments </h1> <p className="text-gray-600 dark:text-gray-400 mt-1"> Create and manage customer segments for targeted promotions </p> </div> <Button variant="primary" onClick={handleCreate}> <Icon name="plus" size={16} className="mr-2" /> Create Segment </Button> </div> {/* Segments List */} {loading ? ( <div className="flex items-center justify-center py-12"> <Icon name="reload" size={32} className="animate-spin text-primary" /> </div> ) : segments.length === 0 ? ( <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-12 text-center"> <Icon name="users" size={48} className="mx-auto mb-4 text-gray-400 dark:text-gray-600" /> <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2"> No Segments Yet </h3> <p className="text-gray-600 dark:text-gray-400 mb-6"> Create your first customer segment to start targeting specific groups of customers. </p> <Button variant="primary" onClick={handleCreate}> Create Your First Segment </Button> </div> ) : ( <div className="grid gap-4"> {segments.map((segment) => ( <div key={segment.id} className={`bg-white dark:bg-gray-800 rounded-lg shadow border-l-4 ${ segment.isActive ? "border-green-500" : "border-gray-300 dark:border-gray-600" }`} > <div className="p-6"> <div className="flex items-start justify-between"> <div className="flex-1"> <div className="flex items-center gap-3 mb-2"> <h3 className="text-lg font-semibold text-gray-900 dark:text-white"> {segment.name} </h3> {!segment.isActive && ( <span className="px-2 py-0.5 text-xs bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded"> Inactive </span> )} </div> {segment.description && ( <p className="text-gray-600 dark:text-gray-400 text-sm mb-4"> {segment.description} </p> )} {/* Rules Preview */} <div className="mb-4"> <div className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase mb-2"> Rules </div> <div className="flex flex-wrap gap-2"> {segment.rules.map((group, groupIndex) => ( <div key={groupIndex} className="flex items-center gap-1" > {groupIndex > 0 && ( <span className="text-xs text-gray-500 dark:text-gray-400 mx-1"> OR </span> )} <div className="flex items-center gap-1 bg-gray-100 dark:bg-gray-700 rounded px-2 py-1"> {group.conditions.map((cond, condIndex) => ( <span key={condIndex} className="text-xs text-gray-700 dark:text-gray-300" > {condIndex > 0 && ( <span className="text-gray-400 mx-1"> {group.logic} </span> )} {getFieldLabel(cond.field)}{" "} {getOperatorLabel(cond.operator)}{" "} {Array.isArray(cond.value) ? cond.value.join(", ") : cond.value} </span> ))} </div> </div> ))} {segment.rules.length === 0 && ( <span className="text-xs text-gray-500 dark:text-gray-400 italic"> No rules defined (matches all users) </span> )} </div> </div> {/* Stats */} <div className="flex items-center gap-6 text-sm"> <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400"> <Icon name="users" size={16} /> <span> {segment.memberCount !== null ? `${segment.memberCount.toLocaleString()} members` : "Calculating..."} </span> </div> <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400"> <Icon name="tag" size={16} /> <span> {segment.promotionCount} promotion {segment.promotionCount !== 1 ? "s" : ""} </span> </div> </div> </div> {/* Actions */} <div className="flex items-center gap-2 ml-4"> <button onClick={() => handleToggleActive(segment)} className={`p-2 rounded hover:bg-gray-100 dark:hover:bg-gray-700 ${ segment.isActive ? "text-green-600" : "text-gray-400" }`} title={segment.isActive ? "Deactivate" : "Activate"} > <Icon name={segment.isActive ? "check-circle" : "x-circle"} size={20} /> </button> <button onClick={() => handleEdit(segment)} className="p-2 rounded hover:bg-gray-100 dark:hover:bg-gray-700 text-blue-600" title="Edit" > <Icon name="edit" size={20} /> </button> <button onClick={() => setDeleteSegmentId(segment.id)} className="p-2 rounded hover:bg-gray-100 dark:hover:bg-gray-700 text-red-600" title="Delete" disabled={segment.promotionCount > 0} > <Icon name="trash" size={20} /> </button> </div> </div> </div> </div> ))} </div> )} {/* Delete Confirmation */} <ConfirmDialog isOpen={deleteSegmentId !== null} onCancel={() => setDeleteSegmentId(null)} onConfirm={handleDelete} title="Delete Segment" message="Are you sure you want to delete this segment? This action cannot be undone." confirmText={deleting ? "Deleting..." : "Delete"} variant="danger" /> </div> ); } |