mirror of
https://github.com/bitbaum/orangecat.git
synced 2026-12-04 20:28:04 +01:00
refactor(terminology): rename donor/donation code identifiers to supporter/contribution
Rename all non-DB-coupled identifiers from donation/donor to support/supporter language per the project's terminology guide (CLAUDE.md domain-specific.md: "Supporters not donors"). Code-only changes — no DB column, enum value, or API payload keys altered. DB-bound strings (donation_received event type, bitcoin_donation support_type, last_donation_at column, funding_model:'donation' enum) require a migration and are left as-is. Renamed: - useTimelineEvents: donorId→supporterId, handleDonationReceived→ handleSupportReceived, donationReceivedEvent→supportReceivedEvent, 'donation-received'→'support-received' (CustomEvent name), dispatchDonationReceived→dispatchSupportReceived - timeline/mutations/events: donorId→supporterId, donor→supporter, donor_name→supporter_name metadata key - timeline/index: donorId→supporterId parameter - projects/[id]/stats/route: donorCount→supporterCount, averageDonation→averageContribution (response field names) - analytics: avgDonation→avgContribution (local var + interface field) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
2388fb11cc
commit
cc7738c494
6 files changed
+190
-132
No files matched your search
@@ -8,7 +8,7 @@ interface ProjectPerformance {
|
||||
totalRaised: number;
|
||||
goalAmount: number;
|
||||
supporters: number;
|
||||
avgDonation: number;
|
||||
avgContribution: number;
|
||||
daysActive: number;
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ export default function ProjectPerformanceTable({ projects }: ProjectPerformance
|
||||
</td>
|
||||
<td className="py-3 px-4 font-medium">{project.supporters}</td>
|
||||
<td className="py-3 px-4 text-gray-600">
|
||||
{formatCurrency(project.avgDonation, 'BTC')}
|
||||
{formatCurrency(project.avgContribution, 'BTC')}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
|
||||
@@ -32,7 +32,7 @@ export default function AnalyticsPage() {
|
||||
const activeProjects = projects.filter(c => c.isActive);
|
||||
const totalRaised = projects.reduce((sum, c) => sum + (c.total_funding || 0), 0);
|
||||
const totalSupporters = projects.reduce((sum, c) => sum + (c.contributor_count || 0), 0);
|
||||
const avgDonation = totalSupporters > 0 ? totalRaised / totalSupporters : 0;
|
||||
const avgContribution = totalSupporters > 0 ? totalRaised / totalSupporters : 0;
|
||||
const successRate =
|
||||
projects.length > 0
|
||||
? (projects.filter(c => c.goal_amount && c.total_funding >= c.goal_amount).length /
|
||||
@@ -41,11 +41,33 @@ export default function AnalyticsPage() {
|
||||
: 0;
|
||||
|
||||
return [
|
||||
{ label: 'Total Raised', value: totalRaised, format: 'currency', icon: DollarSign, color: 'text-green-600' },
|
||||
{ label: 'Active Projects', value: activeProjects.length, icon: Target, color: 'text-blue-600' },
|
||||
{
|
||||
label: 'Total Raised',
|
||||
value: totalRaised,
|
||||
format: 'currency',
|
||||
icon: DollarSign,
|
||||
color: 'text-green-600',
|
||||
},
|
||||
{
|
||||
label: 'Active Projects',
|
||||
value: activeProjects.length,
|
||||
icon: Target,
|
||||
color: 'text-blue-600',
|
||||
},
|
||||
{ label: 'Total Supporters', value: totalSupporters, icon: Users, color: 'text-purple-600' },
|
||||
{ label: 'Avg Contribution', value: avgDonation, format: 'currency', icon: TrendingUp, color: 'text-orange-600' },
|
||||
{ label: 'Success Rate', value: `${successRate.toFixed(1)}%`, icon: Zap, color: 'text-teal-600' },
|
||||
{
|
||||
label: 'Avg Contribution',
|
||||
value: avgContribution,
|
||||
format: 'currency',
|
||||
icon: TrendingUp,
|
||||
color: 'text-orange-600',
|
||||
},
|
||||
{
|
||||
label: 'Success Rate',
|
||||
value: `${successRate.toFixed(1)}%`,
|
||||
icon: Zap,
|
||||
color: 'text-teal-600',
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
@@ -56,8 +78,13 @@ export default function AnalyticsPage() {
|
||||
totalRaised: project.total_funding || 0,
|
||||
goalAmount: project.goal_amount || 0,
|
||||
supporters: project.contributor_count || 0,
|
||||
avgDonation: project.contributor_count > 0 ? (project.total_funding || 0) / project.contributor_count : 0,
|
||||
daysActive: Math.floor((Date.now() - new Date(project.created_at).getTime()) / (1000 * 60 * 60 * 24)),
|
||||
avgContribution:
|
||||
project.contributor_count > 0
|
||||
? (project.total_funding || 0) / project.contributor_count
|
||||
: 0,
|
||||
daysActive: Math.floor(
|
||||
(Date.now() - new Date(project.created_at).getTime()) / (1000 * 60 * 60 * 24)
|
||||
),
|
||||
}));
|
||||
};
|
||||
|
||||
|
||||
@@ -1,28 +1,27 @@
|
||||
import { logger } from '@/utils/logger';
|
||||
import { withOptionalAuth } from '@/lib/api/withAuth';
|
||||
import {
|
||||
apiSuccess,
|
||||
apiNotFound,
|
||||
handleApiError,
|
||||
} from '@/lib/api/standardResponse';
|
||||
import { apiSuccess, apiNotFound, handleApiError } from '@/lib/api/standardResponse';
|
||||
import { getTableName } from '@/config/entity-registry';
|
||||
import { validateUUID, getValidationError } from '@/lib/api/validation';
|
||||
import { DATABASE_TABLES } from '@/config/database-tables';
|
||||
|
||||
const DEFAULT_CAMPAIGN_DURATION_DAYS = 30;
|
||||
|
||||
export const GET = withOptionalAuth(async (req, { params }: { params: Promise<{ id: string }> }) => {
|
||||
try {
|
||||
const { id: projectId } = await params;
|
||||
const idValidation = getValidationError(validateUUID(projectId, 'project ID'));
|
||||
if (idValidation) {return idValidation;}
|
||||
const { supabase } = req;
|
||||
export const GET = withOptionalAuth(
|
||||
async (req, { params }: { params: Promise<{ id: string }> }) => {
|
||||
try {
|
||||
const { id: projectId } = await params;
|
||||
const idValidation = getValidationError(validateUUID(projectId, 'project ID'));
|
||||
if (idValidation) {
|
||||
return idValidation;
|
||||
}
|
||||
const { supabase } = req;
|
||||
|
||||
// Get project details
|
||||
const { data: projectData, error: projectError } = await supabase
|
||||
.from(getTableName('project'))
|
||||
.select(
|
||||
`
|
||||
// Get project details
|
||||
const { data: projectData, error: projectError } = await supabase
|
||||
.from(getTableName('project'))
|
||||
.select(
|
||||
`
|
||||
id,
|
||||
title,
|
||||
description,
|
||||
@@ -35,87 +34,98 @@ export const GET = withOptionalAuth(async (req, { params }: { params: Promise<{
|
||||
user_id,
|
||||
category
|
||||
`
|
||||
)
|
||||
.eq('id', projectId)
|
||||
.single();
|
||||
const project = projectData;
|
||||
)
|
||||
.eq('id', projectId)
|
||||
.single();
|
||||
const project = projectData;
|
||||
|
||||
if (projectError || !project) {
|
||||
return apiNotFound('Project not found');
|
||||
if (projectError || !project) {
|
||||
return apiNotFound('Project not found');
|
||||
}
|
||||
|
||||
// Get real supporter count from project_support table
|
||||
const { count: supportCount } = await supabase
|
||||
.from(DATABASE_TABLES.PROJECT_SUPPORT)
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('project_id', projectId)
|
||||
.eq('status', 'confirmed');
|
||||
const supporterCount = supportCount ?? 0;
|
||||
|
||||
// Calculate progress
|
||||
const progressPercent =
|
||||
project.goal_amount > 0
|
||||
? Math.min((project.raised_amount / project.goal_amount) * 100, 100)
|
||||
: 0;
|
||||
|
||||
// Calculate days remaining (default campaign duration from creation date)
|
||||
const createdDate = new Date(project.created_at);
|
||||
const endDate = new Date(
|
||||
createdDate.getTime() + DEFAULT_CAMPAIGN_DURATION_DAYS * 24 * 60 * 60 * 1000
|
||||
);
|
||||
const now = new Date();
|
||||
const daysRemaining = Math.max(
|
||||
0,
|
||||
Math.ceil((endDate.getTime() - now.getTime()) / (24 * 60 * 60 * 1000))
|
||||
);
|
||||
|
||||
// Calculate funding rate
|
||||
const daysSinceCreation = Math.max(
|
||||
1,
|
||||
Math.ceil((now.getTime() - createdDate.getTime()) / (24 * 60 * 60 * 1000))
|
||||
);
|
||||
const dailyFundingRate = project.raised_amount / daysSinceCreation;
|
||||
|
||||
// Get project category and related projects
|
||||
const { data: relatedProjectsData, error: _relatedError } = await supabase
|
||||
.from(getTableName('project'))
|
||||
.select('id, title, raised_amount')
|
||||
.eq('category', project.category || '')
|
||||
.neq('id', projectId)
|
||||
.limit(5);
|
||||
const relatedProjects = relatedProjectsData;
|
||||
|
||||
const categoryRank = relatedProjects?.length || 0;
|
||||
|
||||
return apiSuccess({
|
||||
projectId: project.id,
|
||||
title: project.title,
|
||||
fundingMetrics: {
|
||||
goalAmount: project.goal_amount,
|
||||
raisedAmount: project.raised_amount,
|
||||
progressPercent: Math.round(progressPercent * 100) / 100,
|
||||
remaining: Math.max(0, project.goal_amount - project.raised_amount),
|
||||
supporterCount,
|
||||
averageContribution:
|
||||
supporterCount > 0 ? Math.round(project.raised_amount / supporterCount) : 0,
|
||||
},
|
||||
timeMetrics: {
|
||||
createdAt: project.created_at,
|
||||
daysActive: daysSinceCreation,
|
||||
daysRemaining,
|
||||
endDate: endDate.toISOString(),
|
||||
daysPercentElapsed: Math.min(
|
||||
(daysSinceCreation / DEFAULT_CAMPAIGN_DURATION_DAYS) * 100,
|
||||
100
|
||||
),
|
||||
},
|
||||
performanceMetrics: {
|
||||
dailyFundingRate: Math.round(dailyFundingRate),
|
||||
projectedTotal: Math.round(project.raised_amount + dailyFundingRate * daysRemaining),
|
||||
willReachGoal:
|
||||
project.raised_amount + dailyFundingRate * daysRemaining >= project.goal_amount,
|
||||
category: project.category || 'uncategorized',
|
||||
categoryRank,
|
||||
},
|
||||
status: project.status,
|
||||
visibility: project.status === 'active' ? 'public' : project.status,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
'Error fetching project stats',
|
||||
{ error, projectId: (await params).id },
|
||||
'Projects'
|
||||
);
|
||||
return handleApiError(error);
|
||||
}
|
||||
|
||||
// Get real supporter count from project_support table
|
||||
const { count: supportCount } = await supabase
|
||||
.from(DATABASE_TABLES.PROJECT_SUPPORT)
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('project_id', projectId)
|
||||
.eq('status', 'confirmed');
|
||||
const donorCount = supportCount ?? 0;
|
||||
|
||||
// Calculate progress
|
||||
const progressPercent =
|
||||
project.goal_amount > 0
|
||||
? Math.min((project.raised_amount / project.goal_amount) * 100, 100)
|
||||
: 0;
|
||||
|
||||
// Calculate days remaining (default campaign duration from creation date)
|
||||
const createdDate = new Date(project.created_at);
|
||||
const endDate = new Date(createdDate.getTime() + DEFAULT_CAMPAIGN_DURATION_DAYS * 24 * 60 * 60 * 1000);
|
||||
const now = new Date();
|
||||
const daysRemaining = Math.max(
|
||||
0,
|
||||
Math.ceil((endDate.getTime() - now.getTime()) / (24 * 60 * 60 * 1000))
|
||||
);
|
||||
|
||||
// Calculate funding rate
|
||||
const daysSinceCreation = Math.max(
|
||||
1,
|
||||
Math.ceil((now.getTime() - createdDate.getTime()) / (24 * 60 * 60 * 1000))
|
||||
);
|
||||
const dailyFundingRate = project.raised_amount / daysSinceCreation;
|
||||
|
||||
// Get project category and related projects
|
||||
const { data: relatedProjectsData, error: _relatedError } = await supabase
|
||||
.from(getTableName('project'))
|
||||
.select('id, title, raised_amount')
|
||||
.eq('category', project.category || '')
|
||||
.neq('id', projectId)
|
||||
.limit(5);
|
||||
const relatedProjects = relatedProjectsData;
|
||||
|
||||
const categoryRank = relatedProjects?.length || 0;
|
||||
|
||||
return apiSuccess({
|
||||
projectId: project.id,
|
||||
title: project.title,
|
||||
fundingMetrics: {
|
||||
goalAmount: project.goal_amount,
|
||||
raisedAmount: project.raised_amount,
|
||||
progressPercent: Math.round(progressPercent * 100) / 100,
|
||||
remaining: Math.max(0, project.goal_amount - project.raised_amount),
|
||||
donorCount,
|
||||
averageDonation: donorCount > 0 ? Math.round(project.raised_amount / donorCount) : 0,
|
||||
},
|
||||
timeMetrics: {
|
||||
createdAt: project.created_at,
|
||||
daysActive: daysSinceCreation,
|
||||
daysRemaining,
|
||||
endDate: endDate.toISOString(),
|
||||
daysPercentElapsed: Math.min((daysSinceCreation / DEFAULT_CAMPAIGN_DURATION_DAYS) * 100, 100),
|
||||
},
|
||||
performanceMetrics: {
|
||||
dailyFundingRate: Math.round(dailyFundingRate),
|
||||
projectedTotal: Math.round(project.raised_amount + dailyFundingRate * daysRemaining),
|
||||
willReachGoal:
|
||||
project.raised_amount + dailyFundingRate * daysRemaining >= project.goal_amount,
|
||||
category: project.category || 'uncategorized',
|
||||
categoryRank,
|
||||
},
|
||||
status: project.status,
|
||||
visibility: project.status === 'active' ? 'public' : project.status,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Error fetching project stats', { error, projectId: (await params).id }, 'Projects');
|
||||
return handleApiError(error);
|
||||
}
|
||||
});
|
||||
);
|
||||
@@ -40,25 +40,25 @@ export const useTimelineEvents = () => {
|
||||
}
|
||||
};
|
||||
|
||||
// Listen for donation events
|
||||
const handleDonationReceived = async (event: CustomEvent) => {
|
||||
const { transactionId, projectId, amountBtc, donorId } = event.detail;
|
||||
// Listen for support/funding events
|
||||
const handleSupportReceived = async (event: CustomEvent) => {
|
||||
const { transactionId, projectId, amountBtc, supporterId } = event.detail;
|
||||
|
||||
try {
|
||||
await timelineService.createTransactionEvent(
|
||||
transactionId,
|
||||
projectId,
|
||||
donorId || user.id,
|
||||
supporterId || user.id,
|
||||
amountBtc
|
||||
);
|
||||
|
||||
logger.info(
|
||||
'Created timeline event for donation',
|
||||
'Created timeline event for support',
|
||||
{ transactionId, projectId },
|
||||
'TimelineHook'
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create donation timeline event', error, 'TimelineHook');
|
||||
logger.error('Failed to create support timeline event', error, 'TimelineHook');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -130,20 +130,32 @@ export const useTimelineEvents = () => {
|
||||
// Custom event types for timeline events
|
||||
// TypeScript doesn't know about custom events, so we cast to EventListener
|
||||
const projectCreatedEvent = 'project-created';
|
||||
const donationReceivedEvent = 'donation-received';
|
||||
const supportReceivedEvent = 'support-received';
|
||||
const profileUpdatedEvent = 'profile-updated';
|
||||
const userFollowedEvent = 'user-followed';
|
||||
|
||||
window.addEventListener(projectCreatedEvent, handleProjectCreated as unknown as EventListener);
|
||||
window.addEventListener(donationReceivedEvent, handleDonationReceived as unknown as EventListener);
|
||||
window.addEventListener(
|
||||
supportReceivedEvent,
|
||||
handleSupportReceived as unknown as EventListener
|
||||
);
|
||||
window.addEventListener(profileUpdatedEvent, handleProfileUpdated as unknown as EventListener);
|
||||
window.addEventListener(userFollowedEvent, handleUserFollowed as unknown as EventListener);
|
||||
|
||||
// Cleanup
|
||||
return () => {
|
||||
window.removeEventListener(projectCreatedEvent, handleProjectCreated as unknown as EventListener);
|
||||
window.removeEventListener(donationReceivedEvent, handleDonationReceived as unknown as EventListener);
|
||||
window.removeEventListener(profileUpdatedEvent, handleProfileUpdated as unknown as EventListener);
|
||||
window.removeEventListener(
|
||||
projectCreatedEvent,
|
||||
handleProjectCreated as unknown as EventListener
|
||||
);
|
||||
window.removeEventListener(
|
||||
supportReceivedEvent,
|
||||
handleSupportReceived as unknown as EventListener
|
||||
);
|
||||
window.removeEventListener(
|
||||
profileUpdatedEvent,
|
||||
handleProfileUpdated as unknown as EventListener
|
||||
);
|
||||
window.removeEventListener(userFollowedEvent, handleUserFollowed as unknown as EventListener);
|
||||
};
|
||||
}, [user?.id, profile]);
|
||||
@@ -159,15 +171,15 @@ export const useTimelineEvents = () => {
|
||||
);
|
||||
},
|
||||
|
||||
dispatchDonationReceived: (
|
||||
dispatchSupportReceived: (
|
||||
transactionId: string,
|
||||
projectId: string,
|
||||
amountBtc: number,
|
||||
donorId?: string
|
||||
supporterId?: string
|
||||
) => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('donation-received', {
|
||||
detail: { transactionId, projectId, amountBtc, donorId },
|
||||
new CustomEvent('support-received', {
|
||||
detail: { transactionId, projectId, amountBtc, supporterId },
|
||||
})
|
||||
);
|
||||
},
|
||||
|
||||
@@ -112,11 +112,11 @@ class TimelineService {
|
||||
async createTransactionEvent(
|
||||
transactionId: string,
|
||||
projectId: string,
|
||||
donorId: string,
|
||||
supporterId: string,
|
||||
amountBtc: number,
|
||||
eventType: 'donation_received' | 'donation_sent' = 'donation_received'
|
||||
): Promise<TimelineEventResponse> {
|
||||
return createTransactionEvent(transactionId, projectId, donorId, amountBtc, eventType);
|
||||
return createTransactionEvent(transactionId, projectId, supporterId, amountBtc, eventType);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -141,7 +141,14 @@ export async function createEventWithVisibility(
|
||||
}
|
||||
|
||||
// Parse the JSONB response
|
||||
let result: { success?: boolean; error?: string; post_id?: string; data?: { post_id?: string }; id?: string; visibility_count?: number };
|
||||
let result: {
|
||||
success?: boolean;
|
||||
error?: string;
|
||||
post_id?: string;
|
||||
data?: { post_id?: string };
|
||||
id?: string;
|
||||
visibility_count?: number;
|
||||
};
|
||||
if (typeof data === 'string') {
|
||||
try {
|
||||
result = JSON.parse(data);
|
||||
@@ -366,7 +373,7 @@ export async function createProjectEvent(
|
||||
export async function createTransactionEvent(
|
||||
transactionId: string,
|
||||
projectId: string,
|
||||
donorId: string,
|
||||
supporterId: string,
|
||||
amountBtc: number,
|
||||
eventType: 'donation_received' | 'donation_sent' = 'donation_received'
|
||||
): Promise<TimelineEventResponse> {
|
||||
@@ -385,10 +392,10 @@ export async function createTransactionEvent(
|
||||
.single();
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const { data: donor } = await (supabase as any)
|
||||
const { data: supporter } = await (supabase as any)
|
||||
.from(DATABASE_TABLES.PROFILES)
|
||||
.select('username, display_name')
|
||||
.eq('id', donorId)
|
||||
.eq('id', supporterId)
|
||||
.single();
|
||||
|
||||
if (!transaction || !project) {
|
||||
@@ -402,12 +409,12 @@ export async function createTransactionEvent(
|
||||
|
||||
const description =
|
||||
eventType === 'donation_received'
|
||||
? `${donor?.display_name || donor?.username || 'Anonymous'} contributed ₿${amountBtc.toFixed(6)} to ${project.title}`
|
||||
? `${supporter?.display_name || supporter?.username || 'Anonymous'} contributed ₿${amountBtc.toFixed(6)} to ${project.title}`
|
||||
: `Contributed ₿${amountBtc.toFixed(6)} to ${project.title}`;
|
||||
|
||||
return createEvent({
|
||||
eventType,
|
||||
actorId: donorId,
|
||||
actorId: supporterId,
|
||||
subjectType: 'transaction',
|
||||
subjectId: transactionId,
|
||||
targetType: 'project',
|
||||
@@ -420,8 +427,8 @@ export async function createTransactionEvent(
|
||||
transaction_id: transactionId,
|
||||
project_id: projectId,
|
||||
project_title: project.title,
|
||||
donor_name: donor?.display_name || donor?.username,
|
||||
is_anonymous: !donor?.display_name && !donor?.username,
|
||||
supporter_name: supporter?.display_name || supporter?.username,
|
||||
is_anonymous: !supporter?.display_name && !supporter?.username,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -436,7 +443,9 @@ export async function createQuoteReply(
|
||||
content: string,
|
||||
quotedContent: string,
|
||||
visibility: TimelineVisibility = 'public',
|
||||
getEventById?: (eventId: string) => Promise<{ success: boolean; event?: TimelineEvent | TimelineDisplayEvent; error?: string }>
|
||||
getEventById?: (
|
||||
eventId: string
|
||||
) => Promise<{ success: boolean; event?: TimelineEvent | TimelineDisplayEvent; error?: string }>
|
||||
): Promise<TimelineEventResponse> {
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
|
||||
Reference in new issue
Block a user