Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions backend/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -951,16 +951,29 @@ export async function createApp(options = {}) {
status = 'published';
}

// Handle urgency sorting separately since it requires application-level logic
const isUrgencySort = sort === 'urgency';
const dbSort = isUrgencySort ? undefined : sort;
const dbOrder = isUrgencySort ? undefined : order;

const items = campaignRepository.list({
active: activeFilter,
q,
sort,
order,
sort: dbSort,
order: dbOrder,
category,
tags,
status,
});
const payload = paginateItems(items, req.query);

// Apply urgency sorting if requested
let sortedItems = items;
if (isUrgencySort) {
const { sortByUrgency } = await import('./utils/urgency.js');
sortedItems = sortByUrgency(items);
}

const payload = paginateItems(sortedItems, req.query);
shortCache.set(cacheKey, {
expiresAt: Date.now() + shortCacheTtlMs,
payload,
Expand Down
113 changes: 113 additions & 0 deletions backend/src/utils/urgency.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/**
* Urgency calculation utilities for backend campaign sorting.
* Matches the frontend urgency logic for consistent behavior.
*/

/**
* Check if campaign is ending soon (< 24 hours)
* @param {string | null} endDate
* @param {Date} [now]
* @returns {boolean}
*/
function isEndingSoon(endDate, now = new Date()) {
if (!endDate) return false;
const end = new Date(endDate);
if (Number.isNaN(end.getTime())) return false;

const remaining = end.getTime() - now.getTime();
const TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;
return remaining > 0 && remaining < TWENTY_FOUR_HOURS_MS;
}

/**
* Check if campaign is filling fast (> 85% capacity)
* @param {number} participantCount
* @param {number} maxParticipants
* @returns {boolean}
*/
function isFillingFast(participantCount, maxParticipants) {
if (!maxParticipants || maxParticipants === 0) return false;
if (participantCount === undefined || participantCount === null) return false;

const fillPercentage = participantCount / maxParticipants;
return fillPercentage > 0.85;
}

/**
* Check if campaign just launched (< 48 hours since start)
* @param {string | null} startDate
* @param {Date} [now]
* @returns {boolean}
*/
function isJustLaunched(startDate, now = new Date()) {
if (!startDate) return false;
const start = new Date(startDate);
if (Number.isNaN(start.getTime())) return false;

const elapsed = now.getTime() - start.getTime();
if (elapsed < 0) return false; // Not started yet

const FORTY_EIGHT_HOURS_MS = 48 * 60 * 60 * 1000;
return elapsed < FORTY_EIGHT_HOURS_MS;
}

/**
* Calculate urgency score for sorting.
* Higher score = more urgent.
* @param {object} campaign
* @param {string | null} campaign.endDate
* @param {string | null} campaign.startDate
* @param {number} [campaign.participantCount]
* @param {number} [campaign.maxParticipants]
* @param {Date} [now]
* @returns {number}
*/
export function calculateUrgencyScore(campaign, now = new Date()) {
if (!campaign) return 0;

const { endDate, startDate, participantCount = 0, maxParticipants = 0 } = campaign;

// Priority 1: Ending soon - highest score based on time remaining
if (isEndingSoon(endDate, now)) {
const end = new Date(endDate);
const remainingMs = end.getTime() - now.getTime();
// Score: 1,000,000 - seconds remaining (sooner = higher score)
return 1_000_000 - Math.floor(remainingMs / 1000);
}

// Priority 2: Filling fast - medium score based on fill percentage
if (isFillingFast(participantCount, maxParticipants)) {
const percentage = Math.min(Math.round((participantCount / maxParticipants) * 100), 100);
// Score: 500,000 + percentage * 100 (fuller = higher score)
return 500_000 + percentage * 100;
}

// Priority 3: Just launched - lower scores are just slightly elevated
if (isJustLaunched(startDate, now)) {
return 1000;
}

return 0;
}

/**
* Sort campaigns by urgency (descending - most urgent first)
* @param {Array<object>} campaigns
* @param {Date} [now]
* @returns {Array<object>}
*/
export function sortByUrgency(campaigns, now = new Date()) {
return campaigns.slice().sort((a, b) => {
const scoreA = calculateUrgencyScore(a, now);
const scoreB = calculateUrgencyScore(b, now);

// Higher urgency score first
if (scoreB !== scoreA) return scoreB - scoreA;

// Fallback: featured campaigns first
if (a.featured !== b.featured) return a.featured ? -1 : 1;

// Final fallback: ID ascending
return Number(a.id) - Number(b.id);
});
}
2 changes: 1 addition & 1 deletion frontend/src/Explore.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import './Explore.css';
const CAMPAIGNS_PER_PAGE = 9;
const RAIL_LIMIT = 6;

const VALID_SORT_KEYS = new Set(['newest', 'oldest', 'name_asc', 'name_desc', 'reward_desc']);
const VALID_SORT_KEYS = new Set(['newest', 'oldest', 'name_asc', 'name_desc', 'reward_desc', 'urgency']);

function normalizeSortKey(raw) {
return VALID_SORT_KEYS.has(raw) ? raw : 'newest';
Expand Down
8 changes: 8 additions & 0 deletions frontend/src/Landing.css
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,14 @@
gap: 1rem;
}

.campaign-card-badges {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 0.5rem;
flex-shrink: 0;
}

.campaign-card-eyebrow {
margin: 0 0 0.3rem;
color: var(--text-muted);
Expand Down
6 changes: 5 additions & 1 deletion frontend/src/components/CampaignCard.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useId } from 'react';
import { Link } from 'react-router-dom';
import StatusBadge from './StatusBadge';
import UrgencyBadge from './UrgencyBadge';

function formatDate(value) {
if (!value) return '';
Expand Down Expand Up @@ -33,7 +34,10 @@ export default function CampaignCard({ campaign }) {
</h3>
</div>

<StatusBadge status={status} />
<div className="campaign-card-badges">
<UrgencyBadge campaign={campaign} />
<StatusBadge status={status} />
</div>
</div>

<p className="campaign-card-description">{description}</p>
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/components/CampaignFilters.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ export default function CampaignFilters({
<option value="name_asc">Name A–Z</option>
<option value="name_desc">Name Z–A</option>
<option value="reward_desc">Reward (high to low)</option>
<option value="urgency">Urgency</option>
</select>
</label>
</div>
Expand All @@ -118,6 +119,8 @@ export function sortKeyToApiParams(key) {
return { sort: 'name', order: 'desc' };
case 'reward_desc':
return { sort: 'reward_per_action', order: 'desc' };
case 'urgency':
return { sort: 'urgency', order: 'desc' };
case 'newest':
default:
return { sort: 'created_at', order: 'desc' };
Expand Down
76 changes: 76 additions & 0 deletions frontend/src/components/UrgencyBadge.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
.urgency-badge {
display: inline-flex;
align-items: center;
gap: 0.25rem;
padding: 0.25rem 0.625rem;
border-radius: 0.375rem;
font-size: 0.75rem;
font-weight: 600;
line-height: 1.25;
white-space: nowrap;
transition: transform 0.2s ease;
}

.urgency-badge:hover {
transform: scale(1.05);
}

.urgency-badge-icon {
font-size: 0.875rem;
}

/* Ending Soon - Red theme */
.urgency-badge--ending-soon {
background-color: #fee;
color: #c00;
border: 1px solid #fcc;
}

@media (prefers-color-scheme: dark) {
.urgency-badge--ending-soon {
background-color: rgba(239, 68, 68, 0.15);
color: #fca5a5;
border-color: rgba(239, 68, 68, 0.3);
}
}

/* Filling Fast - Orange theme */
.urgency-badge--filling-fast {
background-color: #fff4e6;
color: #c2410c;
border: 1px solid #fed7aa;
}

@media (prefers-color-scheme: dark) {
.urgency-badge--filling-fast {
background-color: rgba(249, 115, 22, 0.15);
color: #fdba74;
border-color: rgba(249, 115, 22, 0.3);
}
}

/* Just Launched - Green theme */
.urgency-badge--just-launched {
background-color: #f0fdf4;
color: #15803d;
border: 1px solid #bbf7d0;
}

@media (prefers-color-scheme: dark) {
.urgency-badge--just-launched {
background-color: rgba(34, 197, 94, 0.15);
color: #86efac;
border-color: rgba(34, 197, 94, 0.3);
}
}

/* Accessibility: Respect reduced motion preference */
@media (prefers-reduced-motion: reduce) {
.urgency-badge {
transition: none;
}

.urgency-badge:hover {
transform: none;
}
}
62 changes: 62 additions & 0 deletions frontend/src/components/UrgencyBadge.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { useEffect, useState } from 'react';
import { getUrgencyBadge, BADGE_TYPES, getTimeRemaining, formatCountdown } from '../utils/urgencyUtils';
import './UrgencyBadge.css';

/**
* UrgencyBadge component displays time-sensitive signals for campaigns
* @param {object} props
* @param {object} props.campaign - Campaign data
*/
export default function UrgencyBadge({ campaign }) {
const [badge, setBadge] = useState(() => getUrgencyBadge(campaign));

useEffect(() => {
// Update badge immediately
const updateBadge = () => {
setBadge(getUrgencyBadge(campaign));
};

updateBadge();

// For "Ending Soon" badges, update every minute
const initialBadge = getUrgencyBadge(campaign);
if (initialBadge?.type === BADGE_TYPES.ENDING_SOON) {
const intervalId = setInterval(updateBadge, 60_000); // 60 seconds
return () => clearInterval(intervalId);
}

return undefined;
}, [campaign]);

if (!badge) return null;

// Render badge based on type
switch (badge.type) {
case BADGE_TYPES.ENDING_SOON:
return (
<span className="urgency-badge urgency-badge--ending-soon" role="status" aria-live="polite">
<span className="urgency-badge-icon" aria-hidden="true">⏱</span>
{badge.data.label}
</span>
);

case BADGE_TYPES.FILLING_FAST:
return (
<span className="urgency-badge urgency-badge--filling-fast" role="status">
<span className="urgency-badge-icon" aria-hidden="true">🔥</span>
{badge.data.label}
</span>
);

case BADGE_TYPES.JUST_LAUNCHED:
return (
<span className="urgency-badge urgency-badge--just-launched" role="status">
<span className="urgency-badge-icon" aria-hidden="true">✨</span>
{badge.data.label}
</span>
);

default:
return null;
}
}
2 changes: 1 addition & 1 deletion frontend/src/lib/apiClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ async function request(url, options = {}) {
* q?: string,
* page?: number,
* limit?: number,
* sort?: 'name' | 'created_at' | 'updated_at' | 'reward_per_action' | 'id',
* sort?: 'name' | 'created_at' | 'updated_at' | 'reward_per_action' | 'id' | 'urgency',
* order?: 'asc' | 'desc'
* }} [params]
*/
Expand Down
Loading
Loading