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 397 398 399 400 401 402 403 404 | "use client"; import { useState, useEffect, useCallback } from "react"; import { Icon } from "@/components/ui/icons"; import { clientLogger } from '@/lib/logging/clientLogger'; interface PointAdjustment { id: number; userId: number; user: { id: number; email: string; name: string; }; points: number; description: string | null; createdAt: string; } interface UserSearchResult { id: number; email: string; firstName: string | null; lastName: string | null; } export default function LoyaltyPoints() { const [adjustments, setAdjustments] = useState<PointAdjustment[]>([]); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null); // Form state const [userSearch, setUserSearch] = useState(""); const [searchResults, setSearchResults] = useState<UserSearchResult[]>([]); const [selectedUser, setSelectedUser] = useState<UserSearchResult | null>(null); const [points, setPoints] = useState(""); const [adjustType, setAdjustType] = useState<"award" | "deduct">("award"); const [reason, setReason] = useState(""); const [customReason, setCustomReason] = useState(""); const [submitting, setSubmitting] = useState(false); const [successMessage, setSuccessMessage] = useState(""); useEffect(() => { fetchAdjustments(); }, []); const searchUsers = useCallback(async () => { try { const res = await fetch(`/api/admin/users?search=${encodeURIComponent(userSearch)}&limit=5`); const data = await res.json(); if (data.success !== false) { setSearchResults(data.data || data || []); } } catch (err) { clientLogger.error('Error searching users', err instanceof Error ? err : new Error(String(err)), { userSearch }); } }, [userSearch]); useEffect(() => { if (userSearch.length >= 2) { searchUsers(); } else { setSearchResults([]); } }, [userSearch, searchUsers]); const fetchAdjustments = async () => { setLoading(true); setError(null); try { const res = await fetch("/api/admin/loyalty/points?limit=10"); const data = await res.json(); if (!res.ok || data.success === false) { throw new Error(data.error || "Failed to fetch adjustments"); } setAdjustments(data.data || []); } catch (err) { setError(err instanceof Error ? err.message : "Failed to fetch adjustments"); } finally { setLoading(false); } }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!selectedUser || !points) return; const finalReason = reason === "Other" ? customReason : reason; if (!finalReason) { alert("Please provide a reason"); return; } setSubmitting(true); setSuccessMessage(""); try { const res = await fetch("/api/admin/loyalty/points", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userId: selectedUser.id, points: parseInt(points), reason: finalReason, type: adjustType})}); const data = await res.json(); if (!res.ok || data.success === false) { throw new Error(data.error || "Failed to adjust points"); } setSuccessMessage( `Successfully ${adjustType === "award" ? "awarded" : "deducted"} ${points} points ${adjustType === "award" ? "to" : "from"} ${selectedUser.email}` ); // Reset form setSelectedUser(null); setUserSearch(""); setPoints(""); setReason(""); setCustomReason(""); // Refresh adjustments list fetchAdjustments(); } catch (err) { alert(err instanceof Error ? err.message : "Failed to adjust points"); } finally { setSubmitting(false); } }; const formatDate = (dateString: string) => { return new Date(dateString).toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit"}); }; return ( <div className="space-y-6"> {/* Header */} <div> <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100"> Points Management </h1> <p className="text-gray-600 dark:text-gray-400 mt-1"> Manually award or deduct loyalty points </p> </div> {/* Success Message */} {successMessage && ( <div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4 text-green-700 dark:text-green-400"> {successMessage} </div> )} {/* Points Adjustment Form */} <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6"> <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4"> Adjust Points </h2> <form onSubmit={handleSubmit} className="space-y-4"> {/* User Search */} <div> <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"> User </label> {selectedUser ? ( <div className="flex items-center justify-between p-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700"> <div> <p className="font-medium text-gray-900 dark:text-gray-100"> {selectedUser.firstName} {selectedUser.lastName} </p> <p className="text-sm text-gray-600 dark:text-gray-400"> {selectedUser.email} </p> </div> <button type="button" onClick={() => { setSelectedUser(null); setUserSearch(""); }} className="text-gray-400 hover:text-gray-600" > <Icon name="close" className="w-5 h-5" /> </button> </div> ) : ( <div className="relative"> <input type="text" value={userSearch} onChange={(e) => setUserSearch(e.target.value)} placeholder="Search by email or name..." className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100" /> {searchResults.length > 0 && ( <div className="absolute z-10 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg"> {searchResults.map((user) => ( <button key={user.id} type="button" onClick={() => { setSelectedUser(user); setSearchResults([]); }} className="w-full px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-700 first:rounded-t-lg last:rounded-b-lg" > <p className="font-medium text-gray-900 dark:text-gray-100"> {user.firstName} {user.lastName} </p> <p className="text-sm text-gray-600 dark:text-gray-400"> {user.email} </p> </button> ))} </div> )} </div> )} </div> {/* Type */} <div> <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"> Type </label> <div className="flex gap-4"> <label className="flex items-center"> <input type="radio" name="type" value="award" checked={adjustType === "award"} onChange={() => setAdjustType("award")} className="mr-2" /> <span className="text-gray-900 dark:text-gray-100">Award Points</span> </label> <label className="flex items-center"> <input type="radio" name="type" value="deduct" checked={adjustType === "deduct"} onChange={() => setAdjustType("deduct")} className="mr-2" /> <span className="text-gray-900 dark:text-gray-100">Deduct Points</span> </label> </div> </div> {/* Points Amount */} <div> <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"> Points Amount </label> <input type="number" min="1" value={points} onChange={(e) => setPoints(e.target.value)} placeholder="Enter points" className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100" /> </div> {/* Reason */} <div> <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"> Reason </label> <select value={reason} onChange={(e) => setReason(e.target.value)} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100" > <option value="">Select a reason</option> <option value="Customer service adjustment">Customer service adjustment</option> <option value="Promotional bonus">Promotional bonus</option> <option value="Error correction">Error correction</option> <option value="Birthday bonus">Birthday bonus</option> <option value="Review reward">Review reward</option> <option value="Referral reward">Referral reward</option> <option value="Other">Other</option> </select> </div> {/* Custom Reason */} {reason === "Other" && ( <div> <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"> Custom Reason </label> <input type="text" value={customReason} onChange={(e) => setCustomReason(e.target.value)} placeholder="Enter custom reason" className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100" /> </div> )} {/* Submit */} <button type="submit" disabled={!selectedUser || !points || !reason || submitting} className="w-full px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed" > {submitting ? "Processing..." : `${adjustType === "award" ? "Award" : "Deduct"} Points`} </button> </form> </div> {/* Recent Adjustments */} <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700"> <div className="p-4 border-b border-gray-200 dark:border-gray-700"> <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100"> Recent Adjustments </h2> </div> {error && ( <div className="p-4 text-red-600 dark:text-red-400">{error}</div> )} <div className="overflow-x-auto"> <table className="w-full"> <thead className="bg-gray-50 dark:bg-gray-900"> <tr> <th className="px-4 py-3 text-left text-sm font-medium text-gray-600 dark:text-gray-400"> Date </th> <th className="px-4 py-3 text-left text-sm font-medium text-gray-600 dark:text-gray-400"> User </th> <th className="px-4 py-3 text-right text-sm font-medium text-gray-600 dark:text-gray-400"> Points </th> <th className="px-4 py-3 text-left text-sm font-medium text-gray-600 dark:text-gray-400"> Reason </th> </tr> </thead> <tbody className="divide-y divide-gray-200 dark:divide-gray-700"> {loading ? ( <tr> <td colSpan={4} className="px-4 py-8 text-center text-gray-500"> Loading... </td> </tr> ) : adjustments.length === 0 ? ( <tr> <td colSpan={4} className="px-4 py-8 text-center text-gray-500"> No adjustments yet </td> </tr> ) : ( adjustments.map((adj) => ( <tr key={adj.id} className="hover:bg-gray-50 dark:hover:bg-gray-700"> <td className="px-4 py-3 text-gray-600 dark:text-gray-400"> {formatDate(adj.createdAt)} </td> <td className="px-4 py-3"> <p className="font-medium text-gray-900 dark:text-gray-100"> {adj.user.name} </p> <p className="text-sm text-gray-500">{adj.user.email}</p> </td> <td className="px-4 py-3 text-right"> <span className={`font-medium ${ adj.points > 0 ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400" }`} > {adj.points > 0 ? "+" : ""} {adj.points.toLocaleString()} </span> </td> <td className="px-4 py-3 text-gray-600 dark:text-gray-400"> {adj.description} </td> </tr> )) )} </tbody> </table> </div> </div> </div> ); } |