-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-auto-generation.js
More file actions
225 lines (196 loc) · 7.95 KB
/
test-auto-generation.js
File metadata and controls
225 lines (196 loc) · 7.95 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
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
// Test script for auto-generation logic
// Run with: node test-auto-generation.js
const mysql = require('mysql2/promise');
require('dotenv').config();
async function testAutoGeneration() {
const pool = mysql.createPool({
host: process.env.DB_HOST || 'localhost',
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_NAME || 'reading_planner',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
try {
console.log('Testing auto-generation logic...\n');
// Create test user
const [userResult] = await pool.execute(
'INSERT INTO users (username, password_hash, email, reading_speed) VALUES (?, ?, ?, ?)',
['testuser', '$2b$10$dummyhash', 'test@example.com', 50]
);
const userId = userResult.insertId;
console.log(`Created test user with ID: ${userId}`);
// Create test series
const [series1] = await pool.execute('INSERT INTO series (name) VALUES (?)', ['Harry Potter']);
const [series2] = await pool.execute('INSERT INTO series (name) VALUES (?)', ['Lord of the Rings']);
const series1Id = series1.insertId;
const series2Id = series2.insertId;
console.log(`Created series: Harry Potter (${series1Id}), Lord of the Rings (${series2Id})`);
// Create test books (5 series books + 3 non-series)
const books = [
{ title: 'Harry Potter 1', author: 'J.K. Rowling', page_count: 300, series_id: series1Id },
{ title: 'Harry Potter 2', author: 'J.K. Rowling', page_count: 350, series_id: series1Id },
{ title: 'Harry Potter 3', author: 'J.K. Rowling', page_count: 400, series_id: series1Id },
{ title: 'LOTR 1', author: 'J.R.R. Tolkien', page_count: 400, series_id: series2Id },
{ title: 'LOTR 2', author: 'J.R.R. Tolkien', page_count: 350, series_id: series2Id },
{ title: 'Standalone Book 1', author: 'Author A', page_count: 250, series_id: null },
{ title: 'Standalone Book 2', author: 'Author B', page_count: 300, series_id: null },
{ title: 'Standalone Book 3', author: 'Author C', page_count: 200, series_id: null }
];
const bookIds = [];
for (const book of books) {
const [result] = await pool.execute(
'INSERT INTO books (title, author, page_count, series_id, is_reference) VALUES (?, ?, ?, ?, FALSE)',
[book.title, book.author, book.page_count, book.series_id]
);
bookIds.push(result.insertId);
}
console.log(`Created ${bookIds.length} test books`);
// Test auto-generation with different rules
console.log('\n=== Testing Auto-Generation Rules ===');
// Rule 1: Simple concatenation (no interspersing)
console.log('\n1. Simple concatenation (no interspersing):');
const plan1Id = await createTestPlan(pool, userId, 'Simple Concatenation', {
bookIds: [],
seriesIds: [series1Id, series2Id],
rules: {
intersperseSeries: false,
seriesInterval: 2,
alternateGenres: false,
prioritizeSeries: true,
maxBooks: 50
}
});
const items1 = await getPlanItems(pool, plan1Id);
console.log('Queue:', items1.map(item => item.title));
// Rule 2: Series interspersing every 2 books
console.log('\n2. Series interspersing (every 2 series books):');
const plan2Id = await createTestPlan(pool, userId, 'Interspersed Every 2', {
bookIds: [],
seriesIds: [series1Id, series2Id],
rules: {
intersperseSeries: true,
seriesInterval: 2,
alternateGenres: false,
prioritizeSeries: true,
maxBooks: 50
}
});
const items2 = await getPlanItems(pool, plan2Id);
console.log('Queue:', items2.map(item => item.title));
// Rule 3: With specific book selection
console.log('\n3. Specific books with interspersing:');
const plan3Id = await createTestPlan(pool, userId, 'Specific Books', {
bookIds: bookIds.slice(0, 6), // First 6 books
seriesIds: [],
rules: {
intersperseSeries: true,
seriesInterval: 1,
alternateGenres: false,
prioritizeSeries: true,
maxBooks: 50
}
});
const items3 = await getPlanItems(pool, plan3Id);
console.log('Queue:', items3.map(item => item.title));
// Calculate estimates for last plan
const totalPages = items3.reduce((sum, item) => sum + item.page_count, 0);
const estimatedHours = Math.ceil(totalPages / 50); // 50 pages/hour
console.log(`\nEstimates for Plan 3:`);
console.log(`- Total books: ${items3.length}`);
console.log(`- Total pages: ${totalPages}`);
console.log(`- Estimated hours: ${estimatedHours}`);
console.log(`- Estimated days (8h/day): ${Math.ceil(estimatedHours / 8)}`);
console.log('\n=== Test completed successfully! ===');
} catch (error) {
console.error('Test failed:', error);
} finally {
await pool.end();
}
}
async function createTestPlan(pool, userId, name, config) {
// Simulate the generateAdvancedPlan logic
const [planResult] = await pool.execute(
'INSERT INTO plans (user_id, name, description) VALUES (?, ?, ?)',
[userId, name, 'Test auto-generated plan']
);
const planId = planResult.insertId;
// Get unread books (all books for test)
const [books] = await pool.execute(`
SELECT b.id, b.title, b.page_count, b.series_id, s.name as series_name
FROM books b
LEFT JOIN series s ON b.series_id = s.id
WHERE b.is_reference = FALSE
${config.bookIds.length > 0 ? `AND b.id IN (${config.bookIds.map(() => '?').join(',')})` : ''}
${config.seriesIds.length > 0 ? `AND (b.series_id IN (${config.seriesIds.map(() => '?').join(',')}) OR b.series_id IS NULL)` : ''}
ORDER BY b.series_id, b.title
`, [...config.bookIds, ...config.seriesIds]);
// Group books
const seriesBooks = {};
const nonSeriesBooks = [];
books.forEach(book => {
if (book.series_id) {
if (!seriesBooks[book.series_id]) {
seriesBooks[book.series_id] = { seriesName: book.series_name, books: [] };
}
seriesBooks[book.series_id].books.push(book);
} else {
nonSeriesBooks.push(book);
}
});
// Generate queue
const queue = generateQueue(Object.values(seriesBooks), nonSeriesBooks, config.rules);
// Add to plan
let position = 1;
for (const bookId of queue) {
await pool.execute(
'INSERT INTO plan_items (plan_id, book_id, order_position, auto_generated) VALUES (?, ?, ?, TRUE)',
[planId, bookId, position++]
);
}
return planId;
}
function generateQueue(seriesList, nonSeriesBooks, rules) {
const queue = [];
if (!rules.intersperseSeries) {
// Simple concatenation
seriesList.forEach(series => {
series.books.forEach(book => queue.push(book.id));
});
nonSeriesBooks.forEach(book => queue.push(book.id));
} else {
// Interspersing logic
const seriesQueues = seriesList.map(series => [...series.books]);
let seriesIndex = 0;
let nonSeriesIndex = 0;
let seriesBookCount = 0;
while (queue.length < rules.maxBooks && (seriesQueues.some(q => q.length > 0) || nonSeriesIndex < nonSeriesBooks.length)) {
if (seriesBookCount < rules.seriesInterval && seriesQueues[seriesIndex % seriesQueues.length].length > 0) {
const book = seriesQueues[seriesIndex % seriesQueues.length].shift();
queue.push(book.id);
seriesBookCount++;
seriesIndex++;
} else {
const booksToAdd = rules.alternateGenres ? 1 : Math.min(2, nonSeriesBooks.length - nonSeriesIndex);
for (let i = 0; i < booksToAdd && nonSeriesIndex < nonSeriesBooks.length; i++) {
queue.push(nonSeriesBooks[nonSeriesIndex++].id);
}
seriesBookCount = 0;
}
}
}
return queue.slice(0, rules.maxBooks);
}
async function getPlanItems(pool, planId) {
const [items] = await pool.execute(`
SELECT pi.*, b.title, b.page_count
FROM plan_items pi
JOIN books b ON pi.book_id = b.id
WHERE pi.plan_id = ?
ORDER BY pi.order_position
`, [planId]);
return items;
}
// Run the test
testAutoGeneration().catch(console.error);