Skip to content

Commit a01e4d6

Browse files
committed
fix: wishlist filtering
1 parent 344b9da commit a01e4d6

1 file changed

Lines changed: 52 additions & 45 deletions

File tree

platforms/dreamsync-api/src/services/MatchingService.ts

Lines changed: 52 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -48,44 +48,53 @@ export class MatchingService {
4848
* Analyze all wishlists at once and find matches in a single AI request
4949
*/
5050
async findMatches(wishlists: WishlistData[], existingGroups?: GroupData[]): Promise<MatchResult[]> {
51-
console.log(`🤖 Starting AI matching process for ${wishlists.length} wishlists...`);
52-
console.log(`📊 Analyzing all wishlists in a single AI request (much more efficient!)`);
51+
console.log(`Starting AI matching process for ${wishlists.length} wishlists...`);
52+
console.log(`Analyzing all wishlists in a single AI request (much more efficient!)`);
53+
54+
// Filter out wishlists without valid summaries before processing
55+
const validWishlists = wishlists.filter((wishlist) => {
56+
return wishlist.summaryWants && wishlist.summaryWants.length > 0 &&
57+
wishlist.summaryOffers && wishlist.summaryOffers.length > 0;
58+
});
59+
60+
if (validWishlists.length === 0) {
61+
console.log("No wishlists with valid summaries to match, returning empty array");
62+
return [];
63+
}
64+
65+
if (validWishlists.length < wishlists.length) {
66+
console.log(`Filtered out ${wishlists.length - validWishlists.length} wishlists without valid summaries`);
67+
}
5368

5469
if (existingGroups && existingGroups.length > 0) {
55-
console.log(`🏠 Found ${existingGroups.length} existing groups to consider`);
70+
console.log(`Found ${existingGroups.length} existing groups to consider`);
5671
}
5772

5873
try {
59-
const matchResults = await this.analyzeAllMatches(wishlists, existingGroups);
60-
console.log(`🎉 AI matching process completed! Found ${matchResults.length} matches`);
74+
const matchResults = await this.analyzeAllMatches(validWishlists, existingGroups);
75+
console.log(`AI matching process completed! Found ${matchResults.length} matches`);
6176
return matchResults;
6277
} catch (error) {
63-
console.error("Error in AI matching process:", error);
78+
console.error("Error in AI matching process:", error);
6479
return [];
6580
}
6681
}
6782

6883
private buildAllMatchesPrompt(wishlists: WishlistData[], existingGroups?: GroupData[]): string {
6984
const delimiter = "<|>";
7085
const wishlistHeader = `userId${delimiter}userEname${delimiter}userName${delimiter}wants${delimiter}offers`;
71-
const wishlistRows = wishlists
72-
.filter((wishlist) => {
73-
// Only include wishlists with valid summary arrays
74-
return wishlist.summaryWants && wishlist.summaryWants.length > 0 &&
75-
wishlist.summaryOffers && wishlist.summaryOffers.length > 0;
76-
})
77-
.map((wishlist) => {
78-
// Join array items with semicolons for CSV format
79-
const wants = (wishlist.summaryWants || []).join('; ');
80-
const offers = (wishlist.summaryOffers || []).join('; ');
81-
return [
82-
this.sanitizeField(wishlist.userId),
83-
this.sanitizeField(wishlist.user.ename),
84-
this.sanitizeField(wishlist.user.name || wishlist.user.ename),
85-
this.sanitizeField(wants),
86-
this.sanitizeField(offers),
87-
].join(delimiter);
88-
}).join("\n");
86+
const wishlistRows = wishlists.map((wishlist) => {
87+
// Join array items with semicolons for CSV format
88+
const wants = (wishlist.summaryWants || []).join('; ');
89+
const offers = (wishlist.summaryOffers || []).join('; ');
90+
return [
91+
this.sanitizeField(wishlist.userId),
92+
this.sanitizeField(wishlist.user.ename),
93+
this.sanitizeField(wishlist.user.name || wishlist.user.ename),
94+
this.sanitizeField(wants),
95+
this.sanitizeField(offers),
96+
].join(delimiter);
97+
}).join("\n");
8998

9099
let existingGroupsText = '';
91100
if (existingGroups && existingGroups.length > 0) {
@@ -136,10 +145,8 @@ IMPORTANT RULES:
136145
6. Classify activities properly:
137146
- PRIVATE: Personal services (tutoring, coaching, 1-on-1 lessons, personal projects)
138147
- GROUP: Group activities (sports teams, clubs, workshops, group projects, tournaments)
139-
7. CRITICAL: If wishlists are blank, templated with minimal content, or contain insufficient information to make meaningful matches, return an empty array []
140-
- Blank/templated wishlists have the template structure (## What I Want / ## What I Can Do) but with very few items (2 or fewer) or very short/meaningless content
141-
- Do NOT generate matches based on generic or placeholder content
142-
- Only return matches when there is substantial, meaningful content in the wishlists
148+
149+
NOTE: All wishlists provided have been pre-filtered to ensure they contain valid summary data. You should analyze all provided wishlists and find meaningful matches between them. Only return an empty array [] if you genuinely cannot find any meaningful connections between ANY of the provided users.
143150
144151
Return a JSON array of matches with this structure:
145152
[
@@ -191,12 +198,12 @@ Be thorough and find ALL potential matches!
191198
const prompt = this.buildAllMatchesPrompt(wishlists, existingGroups);
192199

193200
console.log("\n" + "=".repeat(100));
194-
console.log("🤖 AI REQUEST DEBUG - FULL PROMPT SENT TO AI:");
201+
console.log("AI REQUEST DEBUG - FULL PROMPT SENT TO AI:");
195202
console.log("=".repeat(100));
196203
console.log(prompt);
197204
console.log("=".repeat(100));
198-
console.log(`📊 Prompt length: ${prompt.length} characters`);
199-
console.log(`📊 Number of wishlists: ${wishlists.length}`);
205+
console.log(`Prompt length: ${prompt.length} characters`);
206+
console.log(`Number of wishlists: ${wishlists.length}`);
200207
console.log("=".repeat(100) + "\n");
201208

202209
const response = await this.openai.chat.completions.create({
@@ -218,12 +225,12 @@ Be thorough and find ALL potential matches!
218225
const content = response.choices[0]?.message?.content;
219226

220227
console.log("\n" + "=".repeat(100));
221-
console.log("🤖 AI RESPONSE DEBUG - FULL RESPONSE FROM AI:");
228+
console.log("AI RESPONSE DEBUG - FULL RESPONSE FROM AI:");
222229
console.log("=".repeat(100));
223230
console.log(content);
224231
console.log("=".repeat(100));
225-
console.log(`📊 Response length: ${content?.length || 0} characters`);
226-
console.log(`📊 Usage: ${JSON.stringify(response.usage, null, 2)}`);
232+
console.log(`Response length: ${content?.length || 0} characters`);
233+
console.log(`Usage: ${JSON.stringify(response.usage, null, 2)}`);
227234
console.log("=".repeat(100) + "\n");
228235

229236
if (!content) {
@@ -234,25 +241,25 @@ Be thorough and find ALL potential matches!
234241
// Try to extract JSON array from the response
235242
const jsonMatch = content.match(/\[[\s\S]*\]/);
236243
if (!jsonMatch) {
237-
console.log("DEBUG: No JSON array pattern found in response");
238-
console.log("DEBUG: Looking for pattern: /\\[[\\s\\S]*\\]/");
244+
console.log("DEBUG: No JSON array pattern found in response");
245+
console.log("DEBUG: Looking for pattern: /\\[[\\s\\S]*\\]/");
239246
throw new Error("No JSON array found in response");
240247
}
241248

242249
console.log("\n" + "=".repeat(100));
243-
console.log("🔍 JSON EXTRACTION DEBUG:");
250+
console.log("JSON EXTRACTION DEBUG:");
244251
console.log("=".repeat(100));
245-
console.log("📝 Extracted JSON string:");
252+
console.log("Extracted JSON string:");
246253
console.log(jsonMatch[0]);
247254
console.log("=".repeat(100) + "\n");
248255

249256
const matches = JSON.parse(jsonMatch[0]);
250257

251258
console.log("\n" + "=".repeat(100));
252-
console.log("🔍 PARSED MATCHES DEBUG:");
259+
console.log("PARSED MATCHES DEBUG:");
253260
console.log("=".repeat(100));
254-
console.log(`📊 Total matches from AI: ${matches.length}`);
255-
console.log("📝 Raw matches array:");
261+
console.log(`Total matches from AI: ${matches.length}`);
262+
console.log("Raw matches array:");
256263
console.log(JSON.stringify(matches, null, 2));
257264
console.log("=".repeat(100) + "\n");
258265

@@ -264,7 +271,7 @@ Be thorough and find ALL potential matches!
264271
const validMatches: MatchResult[] = [];
265272
for (let i = 0; i < matches.length; i++) {
266273
const match = matches[i];
267-
console.log(`🔍 Validating match ${i + 1}:`, JSON.stringify(match, null, 2));
274+
console.log(`Validating match ${i + 1}:`, JSON.stringify(match, null, 2));
268275

269276
// Check if this is a JOIN_EXISTING_GROUP match (can have 1 user)
270277
const isJoinExistingGroup = match.suggestedActivities?.some((activity: any) =>
@@ -280,7 +287,7 @@ Be thorough and find ALL potential matches!
280287
match.userIds.length >= minUsers &&
281288
match.activityCategory) {
282289

283-
console.log(`Match ${i + 1} is VALID`);
290+
console.log(`Match ${i + 1} is VALID`);
284291
validMatches.push({
285292
confidence: match.confidence,
286293
matchType: match.matchType,
@@ -293,7 +300,7 @@ Be thorough and find ALL potential matches!
293300
activityCategory: match.activityCategory
294301
});
295302
} else {
296-
console.log(`Match ${i + 1} is INVALID:`);
303+
console.log(`Match ${i + 1} is INVALID:`);
297304
console.log(` - confidence: ${match.confidence} (type: ${typeof match.confidence})`);
298305
console.log(` - matchType: ${match.matchType} (valid: ${['private', 'group'].includes(match.matchType)})`);
299306
console.log(` - userIds: ${JSON.stringify(match.userIds)} (isArray: ${Array.isArray(match.userIds)}, length: ${match.userIds?.length}, min required: ${minUsers})`);
@@ -302,7 +309,7 @@ Be thorough and find ALL potential matches!
302309
}
303310
}
304311

305-
console.log(`AI found ${validMatches.length} valid matches from ${matches.length} total suggestions`);
312+
console.log(`AI found ${validMatches.length} valid matches from ${matches.length} total suggestions`);
306313
return validMatches;
307314
} catch (error) {
308315
console.error("Failed to parse OpenAI response:", content);

0 commit comments

Comments
 (0)