forked from Xeio/IdleCodeRedeemer
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodes.ts
More file actions
170 lines (147 loc) · 5.65 KB
/
codes.ts
File metadata and controls
170 lines (147 loc) · 5.65 KB
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
import {
SlashCommandBuilder,
ChatInputCommandInteraction,
EmbedBuilder,
MessageFlags,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
} from 'discord.js';
import { codeManager, CHEST_TYPE_NAMES, type LootSummary } from '../database/codeManager';
import { auditManager } from '../database/auditManager';
export const PAGE_SIZE = 5;
export const data = new SlashCommandBuilder()
.setName('codes')
.setDescription('Show your redeemed codes history');
const DISCORD_FIELD_MAX = 1024;
export async function buildCodesPage(
discordId: string,
page: number
): Promise<{ embeds: EmbedBuilder[]; components: ActionRowBuilder<ButtonBuilder>[] }> {
const total = await codeManager.getRedeemedCodeCount(discordId);
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
const safePage = Math.max(0, Math.min(page, totalPages - 1));
const offset = safePage * PAGE_SIZE;
if (total === 0) {
const embed = new EmbedBuilder()
.setColor(0xffaa00)
.setTitle('📝 Redeemed Codes History')
.setDescription("You haven't redeemed any codes yet.");
return { embeds: [embed], components: [] };
}
// Fetch page data; aggregate loot only on page 0 to avoid repeated O(N) full-table scans during pagination
const [redeemedCodes, lootSummary] = await Promise.all([
codeManager.getRedeemedCodeDetails(discordId, PAGE_SIZE, offset),
safePage === 0 ? codeManager.getAggregateLoot(discordId) : Promise.resolve<LootSummary>({ chests: {}, items: {} }),
]);
const embed = new EmbedBuilder()
.setColor(0x0099ff)
.setTitle('📝 Your Redeemed Codes')
.setFooter({ text: `Page ${safePage + 1} of ${totalPages} · ${total} total` });
redeemedCodes.forEach((codeRow, index) => {
const statusLower = (codeRow.status || 'unknown').toLowerCase();
const statusEmoji =
{
success: '✅',
'code expired': '❌',
error: '⚠️',
}[statusLower] || '❓';
const dateStr = codeRow.redeemedAt
? new Date(codeRow.redeemedAt).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
: 'Unknown';
const publicBadge = codeRow.isPublic ? ' 🌐' : '';
let fieldValue = `**Status:** ${statusEmoji} ${statusLower}\n`;
fieldValue += `**Redeemed:** ${dateStr}\n`;
if (codeRow.lootDetail) {
try {
const loot = JSON.parse(codeRow.lootDetail);
if (Array.isArray(loot) && loot.length > 0) {
const lootParts = loot
.map((item: any) => {
const countVal = Number(item.count);
if (!Number.isFinite(countVal) || countVal <= 0) return null;
if (item.chest_type_id !== undefined) {
const name = CHEST_TYPE_NAMES[item.chest_type_id as number] ?? `Chest ${item.chest_type_id}`;
return `${name}: +${countVal}`;
} else if (item.loot_item) {
return `${(item.loot_item as string).replace(/_/g, ' ')}: x${countVal}`;
}
return null;
})
.filter(Boolean);
if (lootParts.length > 0) {
const rewardsStr = `**Rewards:** ${lootParts.join(', ')}`;
const remaining = DISCORD_FIELD_MAX - fieldValue.length - 1;
fieldValue += remaining > 0 ? rewardsStr.substring(0, remaining) + '\n' : '';
}
}
} catch {
// Skip if loot detail is not valid JSON
}
}
embed.addFields({
name: `${offset + index + 1}. ${codeRow.code}${publicBadge}`,
value: fieldValue,
inline: false,
});
});
if (safePage === 0) {
const lootParts: string[] = [];
for (const [name, count] of Object.entries(lootSummary.chests)) {
if (count > 0) lootParts.push(`${name}: ${count.toLocaleString()}`);
}
for (const [name, count] of Object.entries(lootSummary.items)) {
if (count > 0) lootParts.push(`${name}: ${count.toLocaleString()}`);
}
if (lootParts.length > 0) {
let value = lootParts.join(' · ');
if (value.length > DISCORD_FIELD_MAX) {
let truncated = '';
for (const part of lootParts) {
const next = truncated ? `${truncated} · ${part}` : part;
if (next.length > DISCORD_FIELD_MAX - 4) break;
truncated = next;
}
value = `${truncated} …`;
}
embed.addFields({
name: '📦 Total Loot Earned (All Codes)',
value,
inline: false,
});
}
}
const prevButton = new ButtonBuilder()
.setCustomId(`codes:${discordId}:${safePage - 1}`)
.setLabel('◀ Prev')
.setStyle(ButtonStyle.Secondary)
.setDisabled(safePage === 0);
const nextButton = new ButtonBuilder()
.setCustomId(`codes:${discordId}:${safePage + 1}`)
.setLabel('Next ▶')
.setStyle(ButtonStyle.Secondary)
.setDisabled(safePage >= totalPages - 1);
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(prevButton, nextButton);
return { embeds: [embed], components: [row] };
}
export async function execute(interaction: ChatInputCommandInteraction) {
try {
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await auditManager.logAction(interaction.user.id, 'VIEWED_CODES', {});
const { embeds, components } = await buildCodesPage(interaction.user.id, 0);
await interaction.editReply({ embeds, components });
} catch (error) {
console.error('[CODES] Error:', error);
const embed = new EmbedBuilder()
.setColor(0xff0000)
.setTitle('❌ Error')
.setDescription('Failed to retrieve redeemed codes.');
await interaction.editReply({ embeds: [embed] });
}
}