boxy/app/lib/rewards.ts
2025-06-25 01:10:53 +05:30

206 lines
5.6 KiB
TypeScript

// Types for rewards
export interface Reward {
id: string;
name: string;
price: string;
image: string;
}
// Types for inventory items
export interface InventoryItem {
id: string;
user_id: string;
reward_id: string;
unlocked_on: string;
}
// Function to fetch a random reward from the API
export async function fetchRandomReward(): Promise<Reward | null> {
try {
console.log('Fetching random reward from API...');
const response = await fetch('/api/get-random-reward', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const reward = await response.json();
console.log('Random reward fetched successfully:', reward);
// Validate the reward data
if (!reward.id || !reward.name || !reward.price) {
throw new Error('Invalid reward data received');
}
return reward;
} catch (error) {
console.error('Error fetching random reward:', error);
throw error;
}
}
// Function to get receipt ID from Stripe session
export async function getReceiptId(sessionId: string): Promise<string | null> {
try {
console.log('Getting receipt ID for session:', sessionId);
const response = await fetch(`/api/get-receipt-id?sessionId=${sessionId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
if (response.status === 404) {
console.log('Receipt ID not found for session:', sessionId);
return null;
}
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Receipt ID retrieved successfully:', data.receiptId);
return data.receiptId;
} catch (error) {
console.error('Error getting receipt ID:', error);
throw error;
}
}
// Function to add an item to inventory
export async function addInventoryItem(receiptId: string, userId: string, rewardId: string): Promise<boolean> {
try {
console.log('Adding inventory item:', { receiptId, userId, rewardId });
const response = await fetch('/api/add-inventory-item', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
receiptId,
userId,
rewardId,
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log('Inventory item added successfully:', result);
return result.success === true;
} catch (error) {
console.error('Error adding inventory item:', error);
throw error;
}
}
// Function to fetch inventory items for a user
export async function fetchInventoryItems(userId: string): Promise<InventoryItem[]> {
try {
console.log('Fetching inventory items for user:', userId);
const response = await fetch(`/api/get-inventory-items?userId=${userId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const inventoryItems = await response.json();
console.log('Inventory items fetched successfully:', inventoryItems);
return inventoryItems;
} catch (error) {
console.error('Error fetching inventory items:', error);
throw error;
}
}
// Function to get reward details by ID
export async function getRewardById(rewardId: string): Promise<Reward | null> {
try {
console.log('Getting reward details for ID:', rewardId);
const response = await fetch(`/api/get-reward-by-id?id=${rewardId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
if (response.status === 404) {
console.log('Reward not found for ID:', rewardId);
return null;
}
throw new Error(`HTTP error! status: ${response.status}`);
}
const reward = await response.json();
console.log('Reward details fetched successfully:', reward);
// Validate the reward data
if (!reward.id || !reward.name || !reward.price) {
throw new Error('Invalid reward data received');
}
return reward;
} catch (error) {
console.error('Error getting reward by ID:', error);
throw error;
}
}
// Function to clean image URL (remove escaped backslashes)
export function cleanImageUrl(url: string): string {
return url.replace(/\\/g, '');
}
// Function to get rarity color based on price
export function getRarityColor(price: string): string {
const numPrice = parseFloat(price);
if (numPrice >= 1000) return 'bg-yellow-500/20 text-yellow-300'; // Legendary
if (numPrice >= 500) return 'bg-purple-500/20 text-purple-300'; // Epic
if (numPrice >= 100) return 'bg-blue-500/20 text-blue-300'; // Rare
return 'bg-gray-500/20 text-gray-300'; // Common
}
// Function to get rarity label based on price
export function getRarityLabel(price: string): string {
const numPrice = parseFloat(price);
if (numPrice >= 1000) return 'LEGENDARY';
if (numPrice >= 500) return 'EPIC';
if (numPrice >= 100) return 'RARE';
return 'COMMON';
}
// Function to format date
export function formatDate(dateString: string): string {
const date = new Date(dateString);
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
}