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 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 | "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 PricingRuleBuilder from "@/components/features/admin/pricing/PricingRuleBuilder"; // Types interface PricingCondition { field: string; operator: string; value: string | number | string[] | number[]; } type PricingRuleType = | "VOLUME_DISCOUNT" | "TIME_BASED" | "INVENTORY_BASED" | "SEGMENT_BASED" | "CLEARANCE" | "FIRST_TIME_BUYER" | "BUNDLE_DISCOUNT" | "COMPETITIVE" | "SEASONAL" | "DEMAND_BASED"; type PricingTargetType = | "ALL_PRODUCTS" | "SPECIFIC_PRODUCTS" | "SPECIFIC_CATEGORIES" | "CART_TOTAL"; interface PricingRule { id: number; name: string; description: string | null; type: PricingRuleType; discountType: "PERCENTAGE" | "FIXED_AMOUNT"; discountValue: number; conditions: PricingCondition[]; priority: number; stackable: boolean; minimumQuantity: number | null; minimumPurchase: number | null; maximumDiscount: number | null; startDate: string | null; endDate: string | null; isActive: boolean; targetType: PricingTargetType; targetProductIds: number[]; targetCategoryIds: number[]; targetSegmentIds: number[]; abTestEnabled: boolean; abTestVariant: string | null; abTestPercent: number | null; applicationCount: number; totalDiscounted: number; createdAt: string; updatedAt: string; } interface Analytics { overview: { totalRules: number; activeRules: number; totalApplications: number; totalDiscounted: number; period: string; }; rulesByType: { type: string; count: number }[]; topRules: { id: number; name: string; type: string; applicationCount: number; totalDiscounted: number; }[]; } const RULE_TYPE_LABELS: Record<PricingRuleType, string> = { VOLUME_DISCOUNT: "Volume Discount", TIME_BASED: "Time-Based", INVENTORY_BASED: "Inventory-Based", SEGMENT_BASED: "Segment-Based", CLEARANCE: "Clearance", FIRST_TIME_BUYER: "First-Time Buyer", BUNDLE_DISCOUNT: "Bundle Discount", COMPETITIVE: "Competitive", SEASONAL: "Seasonal", DEMAND_BASED: "Demand-Based"}; const RULE_TYPE_COLORS: Record<PricingRuleType, string> = { VOLUME_DISCOUNT: "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200", TIME_BASED: "bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200", INVENTORY_BASED: "bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200", SEGMENT_BASED: "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200", CLEARANCE: "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200", FIRST_TIME_BUYER: "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200", BUNDLE_DISCOUNT: "bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200", COMPETITIVE: "bg-pink-100 text-pink-800 dark:bg-pink-900 dark:text-pink-200", SEASONAL: "bg-teal-100 text-teal-800 dark:bg-teal-900 dark:text-teal-200", DEMAND_BASED: "bg-cyan-100 text-cyan-800 dark:bg-cyan-900 dark:text-cyan-200"}; export default function AdminPricingPage() { const [rules, setRules] = useState<PricingRule[]>([]); const [analytics, setAnalytics] = useState<Analytics | null>(null); const [loading, setLoading] = useState(true); const [showBuilder, setShowBuilder] = useState(false); const [editingRule, setEditingRule] = useState<PricingRule | null>(null); const [deleteRuleId, setDeleteRuleId] = useState<number | null>(null); const [deleting, setDeleting] = useState(false); const [filterType, setFilterType] = useState<string>(""); const [filterActive, setFilterActive] = useState<string>(""); const fetchRules = useCallback(async () => { try { setLoading(true); const params = new URLSearchParams(); if (filterType) params.set("type", filterType); if (filterActive) params.set("isActive", filterActive); const res = await fetch(`/api/admin/pricing?${params.toString()}`); const result = await res.json(); if (result.success) { setRules(result.data); } else { toast.error("Failed to load pricing rules"); } } catch { toast.error("Failed to load pricing rules"); } finally { setLoading(false); } }, [filterType, filterActive]); const fetchAnalytics = useCallback(async () => { try { const res = await fetch("/api/admin/pricing/analytics?period=30d"); const result = await res.json(); if (result.success) { setAnalytics(result.data); } } catch { // Silently fail analytics } }, []); useEffect(() => { fetchRules(); fetchAnalytics(); }, [fetchRules, fetchAnalytics]); const handleCreate = () => { setEditingRule(null); setShowBuilder(true); }; const handleEdit = (rule: PricingRule) => { setEditingRule(rule); setShowBuilder(true); }; const handleSave = async (data: Omit<PricingRule, "id" | "applicationCount" | "totalDiscounted" | "createdAt" | "updatedAt">) => { try { const url = editingRule ? `/api/admin/pricing/${editingRule.id}` : "/api/admin/pricing"; const method = editingRule ? "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(editingRule ? "Rule updated" : "Rule created"); setShowBuilder(false); setEditingRule(null); fetchRules(); fetchAnalytics(); } else { toast.error(result.error || "Failed to save rule"); } } catch { toast.error("Failed to save rule"); } }; const handleDelete = async () => { if (!deleteRuleId) return; setDeleting(true); try { const res = await fetch(`/api/admin/pricing/${deleteRuleId}`, { method: "DELETE"}); const result = await res.json(); if (result.success) { toast.success("Rule deleted"); setDeleteRuleId(null); fetchRules(); fetchAnalytics(); } else { toast.error(result.error || "Failed to delete rule"); } } catch { toast.error("Failed to delete rule"); } finally { setDeleting(false); } }; const handleToggleActive = async (rule: PricingRule) => { try { const res = await fetch(`/api/admin/pricing/${rule.id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ isActive: !rule.isActive })}); const result = await res.json(); if (result.success) { toast.success(`Rule ${rule.isActive ? "deactivated" : "activated"}`); fetchRules(); } else { toast.error(result.error || "Failed to update rule"); } } catch { toast.error("Failed to update rule"); } }; const formatDiscount = (rule: PricingRule): string => { if (rule.discountType === "PERCENTAGE") { return `${rule.discountValue}%`; } return `$${rule.discountValue.toFixed(2)}`; }; const isRuleActive = (rule: PricingRule): boolean => { if (!rule.isActive) return false; const now = new Date(); if (rule.startDate && new Date(rule.startDate) > now) return false; if (rule.endDate && new Date(rule.endDate) < now) return false; return true; }; 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); setEditingRule(null); }} leftIcon={<Icon name="chevron-left" size={16} />} > Back to Pricing Rules </Button> </div> <PricingRuleBuilder rule={editingRule} onSave={handleSave} onCancel={() => { setShowBuilder(false); setEditingRule(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"> Dynamic Pricing </h1> <p className="text-gray-600 dark:text-gray-400 mt-1"> Create and manage dynamic pricing rules </p> </div> <Button variant="primary" onClick={handleCreate}> <Icon name="plus" size={16} className="mr-2" /> Create Rule </Button> </div> {/* Analytics Overview */} {analytics && ( <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8"> <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4"> <div className="flex items-center gap-3"> <div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg"> <Icon name="tag" size={20} className="text-blue-600 dark:text-blue-400" /> </div> <div> <p className="text-sm text-gray-600 dark:text-gray-400">Total Rules</p> <p className="text-xl font-semibold text-gray-900 dark:text-white"> {analytics.overview.totalRules} </p> </div> </div> </div> <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4"> <div className="flex items-center gap-3"> <div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg"> <Icon name="check-circle" size={20} className="text-green-600 dark:text-green-400" /> </div> <div> <p className="text-sm text-gray-600 dark:text-gray-400">Active Rules</p> <p className="text-xl font-semibold text-gray-900 dark:text-white"> {analytics.overview.activeRules} </p> </div> </div> </div> <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4"> <div className="flex items-center gap-3"> <div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg"> <Icon name="bolt" size={20} className="text-purple-600 dark:text-purple-400" /> </div> <div> <p className="text-sm text-gray-600 dark:text-gray-400"> Applications (30d) </p> <p className="text-xl font-semibold text-gray-900 dark:text-white"> {analytics.overview.totalApplications.toLocaleString()} </p> </div> </div> </div> <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4"> <div className="flex items-center gap-3"> <div className="p-2 bg-yellow-100 dark:bg-yellow-900 rounded-lg"> <Icon name="credit-card" size={20} className="text-yellow-600 dark:text-yellow-400" /> </div> <div> <p className="text-sm text-gray-600 dark:text-gray-400"> Total Discounted (30d) </p> <p className="text-xl font-semibold text-gray-900 dark:text-white"> ${analytics.overview.totalDiscounted.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2})} </p> </div> </div> </div> </div> )} {/* Filters */} <div className="bg-white dark:bg-gray-800 rounded-lg shadow mb-6 p-4"> <div className="flex flex-wrap gap-4 items-center"> <div> <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"> Rule Type </label> <select value={filterType} onChange={(e) => setFilterType(e.target.value)} className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100" > <option value="">All Types</option> {Object.entries(RULE_TYPE_LABELS).map(([value, label]) => ( <option key={value} value={value}> {label} </option> ))} </select> </div> <div> <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"> Status </label> <select value={filterActive} onChange={(e) => setFilterActive(e.target.value)} className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100" > <option value="">All Statuses</option> <option value="true">Active</option> <option value="false">Inactive</option> </select> </div> </div> </div> {/* Rules List */} {loading ? ( <div className="flex items-center justify-center py-12"> <Icon name="reload" size={32} className="animate-spin text-primary" /> </div> ) : rules.length === 0 ? ( <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-12 text-center"> <Icon name="tag" 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 Pricing Rules Yet </h3> <p className="text-gray-600 dark:text-gray-400 mb-6"> Create your first pricing rule to start offering dynamic discounts. </p> <Button variant="primary" onClick={handleCreate}> Create Your First Rule </Button> </div> ) : ( <div className="grid gap-4"> {rules.map((rule) => { const active = isRuleActive(rule); return ( <div key={rule.id} className={`bg-white dark:bg-gray-800 rounded-lg shadow border-l-4 ${ active ? "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"> {rule.name} </h3> <span className={`px-2 py-0.5 text-xs rounded-full ${ RULE_TYPE_COLORS[rule.type] }`} > {RULE_TYPE_LABELS[rule.type]} </span> {!active && ( <span className="px-2 py-0.5 text-xs bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded"> {!rule.isActive ? "Inactive" : "Scheduled"} </span> )} </div> {rule.description && ( <p className="text-gray-600 dark:text-gray-400 text-sm mb-4"> {rule.description} </p> )} {/* Rule Details */} <div className="flex flex-wrap gap-4 text-sm mb-4"> <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400"> <Icon name="tag" size={16} /> <span className="font-medium text-green-600 dark:text-green-400"> {formatDiscount(rule)} off </span> </div> {rule.minimumQuantity && ( <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400"> <Icon name="package" size={16} /> <span>Min qty: {rule.minimumQuantity}</span> </div> )} {rule.minimumPurchase && ( <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400"> <Icon name="shopping-cart" size={16} /> <span>Min: ${rule.minimumPurchase.toFixed(2)}</span> </div> )} <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400"> <Icon name="bolt" size={16} /> <span>Priority: {rule.priority}</span> </div> {rule.stackable && ( <span className="px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded"> Stackable </span> )} {rule.abTestEnabled && ( <span className="px-2 py-0.5 text-xs bg-purple-100 dark:bg-purple-900 text-purple-800 dark:text-purple-200 rounded"> A/B Test ({rule.abTestPercent}%) </span> )} </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="bolt" size={16} /> <span> {rule.applicationCount.toLocaleString()} applications </span> </div> <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400"> <Icon name="credit-card" size={16} /> <span> ${rule.totalDiscounted.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2})}{" "} discounted </span> </div> {(rule.startDate || rule.endDate) && ( <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400"> <Icon name="calendar" size={16} /> <span> {rule.startDate ? new Date(rule.startDate).toLocaleDateString() : "Now"} {" - "} {rule.endDate ? new Date(rule.endDate).toLocaleDateString() : "No end"} </span> </div> )} </div> </div> {/* Actions */} <div className="flex items-center gap-2 ml-4"> <button onClick={() => handleToggleActive(rule)} className={`p-2 rounded hover:bg-gray-100 dark:hover:bg-gray-700 ${ rule.isActive ? "text-green-600" : "text-gray-400" }`} title={rule.isActive ? "Deactivate" : "Activate"} > <Icon name={rule.isActive ? "check-circle" : "x-circle"} size={20} /> </button> <button onClick={() => handleEdit(rule)} 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={() => setDeleteRuleId(rule.id)} className="p-2 rounded hover:bg-gray-100 dark:hover:bg-gray-700 text-red-600" title="Delete" > <Icon name="trash" size={20} /> </button> </div> </div> </div> </div> ); })} </div> )} {/* Delete Confirmation */} <ConfirmDialog isOpen={deleteRuleId !== null} onCancel={() => setDeleteRuleId(null)} onConfirm={handleDelete} title="Delete Pricing Rule" message="Are you sure you want to delete this pricing rule? This action cannot be undone." confirmText={deleting ? "Deleting..." : "Delete"} variant="danger" /> </div> ); } |