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 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | "use client";
import { useState, useEffect, useCallback } from "react";
import { Icon } from "@/components/ui/icons/Icon";
import { clientLogger } from '@/lib/logging/clientLogger';
// Types
interface Affiliate {
id: number;
code: string;
referralUrl: string;
commissionType: string;
commissionRate: number;
tier: string;
status: string;
totalClicks: number;
totalConversions: number;
totalSales: number;
totalEarnings: number;
pendingEarnings: number;
paidEarnings: number;
conversionRate: number;
payoutMethod: string | null;
minimumPayout: number;
website: string | null;
bio: string | null;
approvedAt: string | null;
clickCount: number;
saleCount: number;
payoutCount: number;
createdAt: string;
}
interface DashboardData {
recentClicks: {
id: number;
visitorId: string;
referrer: string | null;
landingPage: string | null;
converted: boolean;
clickedAt: string;
}[];
recentSales: {
id: number;
orderId: number;
orderTotal: number;
commissionAmount: number;
status: string;
createdAt: string;
}[];
pendingPayouts: {
id: number;
amount: number;
status: string;
requestedAt: string;
}[];
stats: {
clicksToday: number;
clicksThisWeek: number;
clicksThisMonth: number;
salesThisMonth: number;
earningsThisMonth: number;
};
}
interface Sale {
id: number;
orderId: number;
orderTotal: number;
commissionType: string;
commissionRate: number;
commissionAmount: number;
status: string;
approvedAt: string | null;
rejectedAt: string | null;
rejectionReason: string | null;
paidAt: string | null;
createdAt: string;
}
interface Payout {
id: number;
amount: number;
method: string;
status: string;
transactionId: string | null;
transactionFee: number | null;
notes: string | null;
requestedAt: string;
processedAt: string | null;
saleIds: number[];
}
interface Pagination {
page: number;
limit: number;
total: number;
totalPages: number;
}
type Tab = "dashboard" | "sales" | "payouts" | "settings";
interface AffiliateDashboardProps {
className?: string;
}
const TIER_COLORS: Record<string, string> = {
BRONZE: "bg-amber-600",
SILVER: "bg-gray-400",
GOLD: "bg-yellow-500",
PLATINUM: "bg-purple-500"};
const STATUS_COLORS: Record<string, string> = {
PENDING: "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200",
ACTIVE: "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",
APPROVED: "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",
REJECTED: "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200",
PAID: "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",
PROCESSING: "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200",
COMPLETED: "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",
CANCELLED: "bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200"};
export function AffiliateDashboard({ className = "" }: AffiliateDashboardProps) {
const [activeTab, setActiveTab] = useState<Tab>("dashboard");
const [affiliate, setAffiliate] = useState<Affiliate | null>(null);
const [dashboard, setDashboard] = useState<DashboardData | null>(null);
const [sales, setSales] = useState<Sale[]>([]);
const [payouts, setPayouts] = useState<Payout[]>([]);
const [pagination, setPagination] = useState<Pagination>({
page: 1,
limit: 20,
total: 0,
totalPages: 0});
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
// Registration form
const [showRegisterForm, setShowRegisterForm] = useState(false);
const [registerData, setRegisterData] = useState({
website: "",
bio: "",
payoutMethod: ""});
// Settings form
const [settingsData, setSettingsData] = useState({
website: "",
bio: "",
payoutMethod: ""});
const [savingSettings, setSavingSettings] = useState(false);
// Copy state
const [copied, setCopied] = useState(false);
const fetchAffiliateData = useCallback(async () => {
setLoading(true);
try {
const response = await fetch("/api/user/affiliate");
const data = await response.json();
if (data.success) {
if (data.data) {
setAffiliate(data.data.affiliate);
setDashboard(data.data.dashboard);
setSettingsData({
website: data.data.affiliate.website || "",
bio: data.data.affiliate.bio || "",
payoutMethod: data.data.affiliate.payoutMethod || ""});
}
} else {
setError(data.error);
}
} catch (err) {
setError("Failed to fetch affiliate data");
clientLogger.error('Failed to fetch affiliate data', err instanceof Error ? err : new Error(String(err)));
} finally {
setLoading(false);
}
}, []);
const fetchSales = useCallback(async () => {
try {
const params = new URLSearchParams({
page: pagination.page.toString(),
limit: pagination.limit.toString()});
const response = await fetch(`/api/user/affiliate/sales?${params}`);
const data = await response.json();
if (data.success) {
setSales(data.data);
setPagination(data.pagination);
} else {
setError(data.error);
}
} catch (err) {
setError("Failed to fetch sales");
clientLogger.error('Failed to fetch sales', err instanceof Error ? err : new Error(String(err)));
}
}, [pagination.page, pagination.limit]);
const fetchPayouts = useCallback(async () => {
try {
const params = new URLSearchParams({
page: pagination.page.toString(),
limit: pagination.limit.toString()});
const response = await fetch(`/api/user/affiliate/payouts?${params}`);
const data = await response.json();
if (data.success) {
setPayouts(data.data);
setPagination(data.pagination);
} else {
setError(data.error);
}
} catch (err) {
setError("Failed to fetch payouts");
clientLogger.error('Failed to fetch payouts', err instanceof Error ? err : new Error(String(err)));
}
}, [pagination.page, pagination.limit]);
useEffect(() => {
fetchAffiliateData();
}, [fetchAffiliateData]);
useEffect(() => {
if (affiliate) {
if (activeTab === "sales") {
fetchSales();
} else if (activeTab === "payouts") {
fetchPayouts();
}
}
}, [activeTab, affiliate, fetchSales, fetchPayouts]);
const handleRegister = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
try {
const response = await fetch("/api/user/affiliate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(registerData)});
const data = await response.json();
if (data.success) {
setSuccessMessage("Registration submitted successfully! Your application is pending review.");
setShowRegisterForm(false);
fetchAffiliateData();
} else {
setError(data.error);
}
} catch (err) {
setError("Failed to register as affiliate");
clientLogger.error('Failed to register as affiliate', err instanceof Error ? err : new Error(String(err)));
} finally {
setLoading(false);
}
};
const handleSaveSettings = async (e: React.FormEvent) => {
e.preventDefault();
setSavingSettings(true);
try {
const response = await fetch("/api/user/affiliate", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(settingsData)});
const data = await response.json();
if (data.success) {
setSuccessMessage("Settings saved successfully!");
fetchAffiliateData();
} else {
setError(data.error);
}
} catch (err) {
setError("Failed to save settings");
clientLogger.error('Failed to save settings', err instanceof Error ? err : new Error(String(err)));
} finally {
setSavingSettings(false);
}
};
const handleRequestPayout = async () => {
try {
const response = await fetch("/api/user/affiliate/payouts", {
method: "POST"});
const data = await response.json();
if (data.success) {
setSuccessMessage("Payout request submitted successfully!");
fetchAffiliateData();
fetchPayouts();
} else {
setError(data.error);
}
} catch (err) {
setError("Failed to request payout");
clientLogger.error('Failed to request payout', err instanceof Error ? err : new Error(String(err)));
}
};
const copyToClipboard = async (text: string) => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (err) {
clientLogger.error('Failed to copy to clipboard', err instanceof Error ? err : new Error(String(err)));
}
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD"}).format(amount);
};
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString("en-US", {
year: "numeric",
month: "short",
day: "numeric"});
};
// Not registered state
if (!loading && !affiliate) {
return (
<div className={`space-y-6 ${className}`}>
<div className="text-center py-12">
<Icon
name="users"
className="w-16 h-16 mx-auto text-gray-400 dark:text-gray-600 mb-4"
/>
<h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
Join Our Affiliate Program
</h2>
<p className="text-gray-500 dark:text-gray-400 mb-6 max-w-md mx-auto">
Earn commissions by referring customers to our platform. Share your unique
link and earn money for every sale!
</p>
{showRegisterForm ? (
<div className="max-w-md mx-auto bg-white dark:bg-gray-800 rounded-lg shadow p-6">
<form onSubmit={handleRegister} className="space-y-4 text-left">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Website (optional)
</label>
<input
type="url"
value={registerData.website}
onChange={(e) =>
setRegisterData({ ...registerData, website: e.target.value })
}
className="w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-3 py-2 text-sm"
placeholder="https://yourwebsite.com"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Bio (optional)
</label>
<textarea
value={registerData.bio}
onChange={(e) =>
setRegisterData({ ...registerData, bio: e.target.value })
}
rows={3}
className="w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-3 py-2 text-sm"
placeholder="Tell us about yourself..."
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Preferred Payout Method
</label>
<select
value={registerData.payoutMethod}
onChange={(e) =>
setRegisterData({ ...registerData, payoutMethod: e.target.value })
}
className="w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-3 py-2 text-sm"
>
<option value="">Select...</option>
<option value="paypal">PayPal</option>
<option value="bank_transfer">Bank Transfer</option>
<option value="crypto">Cryptocurrency</option>
</select>
</div>
<div className="flex gap-2">
<button
type="button"
onClick={() => setShowRegisterForm(false)}
className="flex-1 px-4 py-2 rounded border border-gray-300 dark:border-gray-600 text-sm hover:bg-gray-100 dark:hover:bg-gray-700"
>
Cancel
</button>
<button
type="submit"
disabled={loading}
className="flex-1 px-4 py-2 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 disabled:opacity-50"
>
{loading ? "Submitting..." : "Apply Now"}
</button>
</div>
</form>
</div>
) : (
<button
onClick={() => setShowRegisterForm(true)}
className="px-6 py-3 bg-blue-600 text-white rounded-lg text-lg hover:bg-blue-700"
>
Become an Affiliate
</button>
)}
</div>
</div>
);
}
// Pending approval state
if (affiliate?.status === "PENDING") {
return (
<div className={`space-y-6 ${className}`}>
<div className="text-center py-12">
<Icon
name="clock"
className="w-16 h-16 mx-auto text-yellow-500 dark:text-yellow-400 mb-4"
/>
<h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
Application Pending
</h2>
<p className="text-gray-500 dark:text-gray-400 mb-6 max-w-md mx-auto">
Your affiliate application is being reviewed. We'll notify you once it's
approved.
</p>
<div className="text-sm text-gray-400">
Applied on {formatDate(affiliate.createdAt)}
</div>
</div>
</div>
);
}
// Suspended or rejected state
if (affiliate?.status === "SUSPENDED" || affiliate?.status === "REJECTED") {
return (
<div className={`space-y-6 ${className}`}>
<div className="text-center py-12">
<Icon
name="alert-circle"
className="w-16 h-16 mx-auto text-red-500 dark:text-red-400 mb-4"
/>
<h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
Account {affiliate.status === "SUSPENDED" ? "Suspended" : "Rejected"}
</h2>
<p className="text-gray-500 dark:text-gray-400 mb-6 max-w-md mx-auto">
{affiliate.status === "SUSPENDED"
? "Your affiliate account has been suspended. Please contact support for more information."
: "Your affiliate application was not approved. Please contact support if you have questions."}
</p>
</div>
</div>
);
}
const renderDashboard = () => {
if (!affiliate || !dashboard) return null;
return (
<div className="space-y-6">
{/* Referral Link */}
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
Your Referral Link
</h3>
<div className="flex gap-2">
<input
type="text"
readOnly
value={affiliate.referralUrl}
className="flex-1 rounded-md border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 px-3 py-2 text-sm"
/>
<button
onClick={() => copyToClipboard(affiliate.referralUrl)}
className="px-4 py-2 bg-blue-600 text-white rounded text-sm hover:bg-blue-700"
>
{copied ? (
<Icon name="check" className="w-4 h-4" />
) : (
<Icon name="copy" className="w-4 h-4" />
)}
</button>
</div>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
Share this link to earn {affiliate.commissionRate}% commission on referred sales
</p>
</div>
{/* Stats Overview */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
<div className="flex items-center justify-between">
<div className="text-sm text-gray-500 dark:text-gray-400">Total Earnings</div>
<span
className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium text-white ${TIER_COLORS[affiliate.tier]}`}
>
{affiliate.tier}
</span>
</div>
<div className="text-2xl font-bold text-gray-900 dark:text-white">
{formatCurrency(affiliate.totalEarnings)}
</div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
<div className="text-sm text-gray-500 dark:text-gray-400">Pending Earnings</div>
<div className="text-2xl font-bold text-yellow-600 dark:text-yellow-400">
{formatCurrency(affiliate.pendingEarnings)}
</div>
{affiliate.pendingEarnings >= affiliate.minimumPayout && (
<button
onClick={handleRequestPayout}
className="mt-2 px-3 py-1 bg-green-600 text-white rounded text-xs hover:bg-green-700"
>
Request Payout
</button>
)}
</div>
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
<div className="text-sm text-gray-500 dark:text-gray-400">Total Clicks</div>
<div className="text-2xl font-bold text-gray-900 dark:text-white">
{affiliate.totalClicks.toLocaleString()}
</div>
<div className="text-xs text-green-600 dark:text-green-400">
+{dashboard.stats.clicksToday} today
</div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
<div className="text-sm text-gray-500 dark:text-gray-400">Conversion Rate</div>
<div className="text-2xl font-bold text-gray-900 dark:text-white">
{affiliate.conversionRate.toFixed(2)}%
</div>
<div className="text-xs text-gray-500 dark:text-gray-400">
{affiliate.totalConversions} conversions
</div>
</div>
</div>
{/* Recent Activity */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Recent Clicks */}
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">
Recent Clicks
</h3>
{dashboard.recentClicks.length === 0 ? (
<p className="text-sm text-gray-500 dark:text-gray-400">No clicks yet</p>
) : (
<div className="space-y-2">
{dashboard.recentClicks.slice(0, 5).map((click) => (
<div
key={click.id}
className="flex items-center justify-between text-sm"
>
<div className="flex items-center gap-2">
{click.converted ? (
<Icon name="check-circle" className="w-4 h-4 text-green-500" />
) : (
<span className="w-4 h-4 rounded-full border-2 border-gray-400 inline-block" />
)}
<span className="text-gray-700 dark:text-gray-300 truncate max-w-[150px]">
{click.landingPage || "/"}
</span>
</div>
<span className="text-gray-500 dark:text-gray-400 text-xs">
{formatDate(click.clickedAt)}
</span>
</div>
))}
</div>
)}
</div>
{/* Recent Sales */}
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">
Recent Sales
</h3>
{dashboard.recentSales.length === 0 ? (
<p className="text-sm text-gray-500 dark:text-gray-400">No sales yet</p>
) : (
<div className="space-y-2">
{dashboard.recentSales.slice(0, 5).map((sale) => (
<div
key={sale.id}
className="flex items-center justify-between text-sm"
>
<div className="flex items-center gap-2">
<span className={`px-2 py-0.5 rounded text-xs ${STATUS_COLORS[sale.status]}`}>
{sale.status}
</span>
<span className="text-gray-700 dark:text-gray-300">
Order #{sale.orderId}
</span>
</div>
<span className="text-green-600 dark:text-green-400 font-medium">
+{formatCurrency(sale.commissionAmount)}
</span>
</div>
))}
</div>
)}
</div>
</div>
</div>
);
};
const renderSales = () => {
return (
<div className="space-y-4">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead className="bg-gray-50 dark:bg-gray-700">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
Order
</th>
<th className="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
Order Total
</th>
<th className="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
Commission
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
Status
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
Date
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200 dark:divide-gray-700">
{sales.length === 0 ? (
<tr>
<td colSpan={5} className="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
No sales yet
</td>
</tr>
) : (
sales.map((sale) => (
<tr key={sale.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
#{sale.orderId}
</td>
<td className="px-4 py-3 whitespace-nowrap text-right text-sm text-gray-700 dark:text-gray-300">
{formatCurrency(sale.orderTotal)}
</td>
<td className="px-4 py-3 whitespace-nowrap text-right text-sm text-green-600 dark:text-green-400 font-medium">
+{formatCurrency(sale.commissionAmount)}
</td>
<td className="px-4 py-3 whitespace-nowrap">
<span className={`px-2 py-0.5 rounded text-xs ${STATUS_COLORS[sale.status]}`}>
{sale.status}
</span>
{sale.rejectionReason && (
<div className="text-xs text-red-500 mt-1">{sale.rejectionReason}</div>
)}
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
{formatDate(sale.createdAt)}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
);
};
const renderPayouts = () => {
return (
<div className="space-y-4">
{/* Request payout button */}
{affiliate && affiliate.pendingEarnings >= affiliate.minimumPayout && (
<div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4 flex items-center justify-between">
<div>
<div className="font-medium text-green-800 dark:text-green-200">
You have {formatCurrency(affiliate.pendingEarnings)} available for payout
</div>
<div className="text-sm text-green-600 dark:text-green-400">
Minimum payout: {formatCurrency(affiliate.minimumPayout)}
</div>
</div>
<button
onClick={handleRequestPayout}
className="px-4 py-2 bg-green-600 text-white rounded text-sm hover:bg-green-700"
>
Request Payout
</button>
</div>
)}
<div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead className="bg-gray-50 dark:bg-gray-700">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
ID
</th>
<th className="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
Amount
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
Method
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
Status
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
Requested
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
Processed
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200 dark:divide-gray-700">
{payouts.length === 0 ? (
<tr>
<td colSpan={6} className="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
No payouts yet
</td>
</tr>
) : (
payouts.map((payout) => (
<tr key={payout.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
#{payout.id}
</td>
<td className="px-4 py-3 whitespace-nowrap text-right text-sm font-medium text-gray-900 dark:text-white">
{formatCurrency(payout.amount)}
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
{payout.method || "N/A"}
</td>
<td className="px-4 py-3 whitespace-nowrap">
<span className={`px-2 py-0.5 rounded text-xs ${STATUS_COLORS[payout.status]}`}>
{payout.status}
</span>
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
{formatDate(payout.requestedAt)}
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
{payout.processedAt ? formatDate(payout.processedAt) : "-"}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
);
};
const renderSettings = () => {
return (
<div className="max-w-lg">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">
Profile Settings
</h3>
<form onSubmit={handleSaveSettings} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Affiliate Code
</label>
<input
type="text"
value={affiliate?.code || ""}
readOnly
className="w-full rounded-md border border-gray-300 dark:border-gray-600 bg-gray-100 dark:bg-gray-700 px-3 py-2 text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Website
</label>
<input
type="url"
value={settingsData.website}
onChange={(e) =>
setSettingsData({ ...settingsData, website: e.target.value })
}
className="w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-3 py-2 text-sm"
placeholder="https://yourwebsite.com"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Bio
</label>
<textarea
value={settingsData.bio}
onChange={(e) =>
setSettingsData({ ...settingsData, bio: e.target.value })
}
rows={3}
className="w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-3 py-2 text-sm"
placeholder="Tell us about yourself..."
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Payout Method
</label>
<select
value={settingsData.payoutMethod}
onChange={(e) =>
setSettingsData({ ...settingsData, payoutMethod: e.target.value })
}
className="w-full rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-3 py-2 text-sm"
>
<option value="">Select...</option>
<option value="paypal">PayPal</option>
<option value="bank_transfer">Bank Transfer</option>
<option value="crypto">Cryptocurrency</option>
</select>
</div>
<button
type="submit"
disabled={savingSettings}
className="w-full px-4 py-2 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 disabled:opacity-50"
>
{savingSettings ? "Saving..." : "Save Settings"}
</button>
</form>
</div>
</div>
);
};
if (loading && !affiliate) {
return (
<div className="flex justify-center items-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
</div>
);
}
return (
<div className={`space-y-6 ${className}`}>
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">
Affiliate Dashboard
</h1>
<p className="text-sm text-gray-500 dark:text-gray-400">
Track your referrals, earnings, and payouts
</p>
</div>
{affiliate && (
<span
className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium text-white ${TIER_COLORS[affiliate.tier]}`}
>
{affiliate.tier} Affiliate
</span>
)}
</div>
{/* Messages */}
{error && (
<div className="bg-red-100 dark:bg-red-900 border border-red-400 dark:border-red-700 text-red-700 dark:text-red-200 px-4 py-3 rounded">
{error}
<button onClick={() => setError(null)} className="float-right font-bold">
×
</button>
</div>
)}
{successMessage && (
<div className="bg-green-100 dark:bg-green-900 border border-green-400 dark:border-green-700 text-green-700 dark:text-green-200 px-4 py-3 rounded">
{successMessage}
<button onClick={() => setSuccessMessage(null)} className="float-right font-bold">
×
</button>
</div>
)}
{/* Tabs */}
<div className="border-b border-gray-200 dark:border-gray-700">
<nav className="flex -mb-px gap-4">
{(["dashboard", "sales", "payouts", "settings"] as Tab[]).map((tab) => (
<button
key={tab}
onClick={() => {
setActiveTab(tab);
setPagination((p) => ({ ...p, page: 1 }));
}}
className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
activeTab === tab
? "border-blue-600 text-blue-600 dark:border-blue-400 dark:text-blue-400"
: "border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
}`}
>
{tab.charAt(0).toUpperCase() + tab.slice(1)}
</button>
))}
</nav>
</div>
{/* Content */}
{activeTab === "dashboard" && renderDashboard()}
{activeTab === "sales" && renderSales()}
{activeTab === "payouts" && renderPayouts()}
{activeTab === "settings" && renderSettings()}
</div>
);
}
export default AffiliateDashboard;
|