diff --git a/backend/__tests__/aiTrendHelper.test.js b/backend/__tests__/aiTrendHelper.test.js index 6296bcd4..d77ad9f3 100644 --- a/backend/__tests__/aiTrendHelper.test.js +++ b/backend/__tests__/aiTrendHelper.test.js @@ -19,7 +19,7 @@ describe('generateAIInsight', () => { }) // Mock user scan .mockReturnValueOnce({ - promise: () => Promise.resolve({ Items: [{ name: 'Alice', reputationScore: 5 }] }) + promise: () => Promise.resolve({ Items: [{ username: 'Alice', reputationScore: 5 }] }) }) // Mock transaction scan .mockReturnValueOnce({ @@ -34,4 +34,69 @@ describe('generateAIInsight', () => { insights ).toContain('⚠️ Varias transacciones están experimentando retrasos. Incentiva a los productores a responder a los PINGs rápidamente.'); }); + + describe('producer data in insight text', () => { + const producer = (fields) => ({ + role: 'producer', + password: '$2a$10$secrethashsecrethash', + email: `${fields.id}@example.test`, + phone: `+1555010${fields.id.slice(-1)}`, + verified: true, + location: 'RegionX', + locationPrivacy: false, + ...fields + }); + + const mockScans = (users) => { + mockScan + .mockReturnValueOnce({ promise: () => Promise.resolve({ Items: [] }) }) + .mockReturnValueOnce({ promise: () => Promise.resolve({ Items: users }) }) + .mockReturnValueOnce({ promise: () => Promise.resolve({ Items: [] }) }); + }; + + const expectNoPrivateFields = (insights, users) => { + const text = insights.join('\n'); + for (const user of users) { + expect(text).not.toContain(user.password); + expect(text).not.toContain(user.email); + expect(text).not.toContain(user.phone); + } + }; + + it('names producers by username, never by email, hash or phone', async () => { + const users = [ + producer({ id: 'u1', username: 'alice', reputationScore: 5 }), + producer({ id: 'u2', reputationScore: 4 }) + ]; + mockScans(users); + + const insights = await generateAIInsight(undefined, 'en'); + + expect(insights).toContain('🏆 Top rated producers this week: alice'); + expectNoPrivateFields(insights, users); + }); + + it('omits the producer insight when no producer has a public name', async () => { + const users = [producer({ id: 'u3', reputationScore: 5 })]; + mockScans(users); + + const insights = await generateAIInsight(undefined, 'en'); + + expect(insights.some(i => i.startsWith('🏆'))).toBe(false); + expectNoPrivateFields(insights, users); + }); + + it('leaves location-private producers out of region insights', async () => { + const users = [ + producer({ id: 'u4', username: 'hidden', reputationScore: 9, locationPrivacy: true }), + producer({ id: 'u5', username: 'shown', reputationScore: 1 }) + ]; + mockScans(users); + + const insights = await generateAIInsight('RegionX', 'en'); + + expect(insights).toContain('🏆 Top rated producers this week: shown'); + expect(insights.join('\n')).not.toContain('hidden'); + }); + }); }); diff --git a/backend/__tests__/trendsRoutes.test.js b/backend/__tests__/trendsRoutes.test.js new file mode 100644 index 00000000..63faf649 --- /dev/null +++ b/backend/__tests__/trendsRoutes.test.js @@ -0,0 +1,144 @@ +const request = require('supertest'); +const express = require('express'); + +const mockScan = jest.fn(); + +jest.mock('../lib/dynamodbClient', () => ({ + scan: mockScan +})); + +const trendsRoutes = require('../trends/trendsRoutes'); +const { USER_TABLE_NAME } = require('../models/user'); +const { LISTING_TABLE_NAME } = require('../models/listing'); +const { TRANSACTION_TABLE_NAME } = require('../models/transaction'); + +const PUBLIC_FIELDS = ['id', 'username', 'locationType', 'reputationScore', 'reputationWeight']; + +const producers = [ + { + id: 'u1', + username: 'alice', + email: 'alice@example.test', + phone: '+15550101', + password: '$2a$10$alicehashalicehash', + role: 'producer', + verified: true, + verificationCode: '111111', + location: 'RegionX', + coordinates: { lat: 1, long: 2 }, + locationType: 'farm', + locationPrivacy: false, + reputationScore: 3, + reputationWeight: 2 + }, + { + id: 'u2', + username: 'bea', + email: 'bea@example.test', + phone: '+15550102', + password: '$2a$10$beahashbeahashbea', + role: 'producer', + verified: false, + location: 'RegionX', + locationPrivacy: true, + reputationScore: 5, + reputationWeight: 1 + }, + { + id: 'u3', + email: 'nousername@example.test', + phone: '+15550103', + password: '$2a$10$thirdhashthirdhash', + role: 'producer', + location: 'RegionX', + reputationScore: 4 + } +]; + +const tables = { + [USER_TABLE_NAME]: producers, + [LISTING_TABLE_NAME]: [{ id: 'l1', userId: 'u1', location: 'RegionX', createdAt: '2026-11-01T00:00:00Z' }], + [TRANSACTION_TABLE_NAME]: [{ id: 't1', sellerId: 'u1', lastPing: '2026-11-01T00:00:00Z', pingCount: 1 }] +}; + +const getRoutes = trendsRoutes.stack + .filter(layer => layer.route && layer.route.methods.get) + .map(layer => layer.route.path); + +describe('trendsRoutes', () => { + let app; + beforeEach(() => { + mockScan.mockReset(); + mockScan.mockImplementation(params => ({ + promise: () => Promise.resolve({ Items: (tables[params.TableName] || []).map(item => ({ ...item })) }) + })); + app = express(); + app.use('/trends', trendsRoutes); + }); + + it('covers every GET route', () => { + expect(getRoutes).toEqual(expect.arrayContaining(['/top-rated', '/ai/insight'])); + }); + + describe.each(getRoutes)('GET /trends%s', (path) => { + it.each([ + ['without region', ''], + ['with region', '?region=RegionX'] + ])('sends no password hash, email or phone %s', async (_label, query) => { + const res = await request(app).get(`/trends${path}${query}`); + + expect(res.status).toBe(200); + const body = JSON.stringify(res.body); + for (const user of producers) { + expect(body).not.toContain(user.password); + expect(body).not.toContain(user.email); + expect(body).not.toContain(user.phone); + } + }); + }); + + describe('GET /trends/top-rated', () => { + it('returns only public producer fields', async () => { + const res = await request(app).get('/trends/top-rated'); + + expect(res.status).toBe(200); + expect(res.body.map(p => p.id)).toEqual(['u2', 'u3', 'u1']); + for (const item of res.body) { + for (const key of Object.keys(item)) { + expect(PUBLIC_FIELDS).toContain(key); + } + } + expect(res.body[2]).toEqual({ + id: 'u1', + username: 'alice', + locationType: 'farm', + reputationScore: 3, + reputationWeight: 2 + }); + }); + + it('leaves location-private producers out of region results', async () => { + const res = await request(app).get('/trends/top-rated?region=RegionX'); + + expect(res.status).toBe(200); + expect(res.body.map(p => p.id)).toEqual(['u3', 'u1']); + }); + + it('treats a non-boolean locationPrivacy as private', async () => { + mockScan.mockImplementationOnce(() => ({ + promise: () => Promise.resolve({ + Items: [ + { id: 'u4', username: 'dee', role: 'producer', location: 'RegionX', locationPrivacy: 'true', reputationScore: 3 }, + { id: 'u5', username: 'eve', role: 'producer', location: 'RegionX', locationPrivacy: 1, reputationScore: 2 }, + { id: 'u6', username: 'fay', role: 'producer', location: 'RegionX', reputationScore: 1 } + ] + }) + })); + + const res = await request(app).get('/trends/top-rated?region=RegionX'); + + expect(res.status).toBe(200); + expect(res.body.map(p => p.id)).toEqual(['u6']); + }); + }); +}); diff --git a/backend/trends/trendsRoutes.js b/backend/trends/trendsRoutes.js index 0670d26c..de7e1811 100644 --- a/backend/trends/trendsRoutes.js +++ b/backend/trends/trendsRoutes.js @@ -4,7 +4,7 @@ const docClient = require('../lib/dynamodbClient'); const { USER_TABLE_NAME } = require('../models/user'); const { LISTING_TABLE_NAME } = require('../models/listing'); const { TRANSACTION_TABLE_NAME } = require('../models/transaction'); -const { generateAIInsight } = require('../utils/aiTrendHelper'); +const { generateAIInsight, publicProducers } = require('../utils/aiTrendHelper'); // 1. Top Rated Producers router.get('/top-rated', async (req, res) => { @@ -22,7 +22,9 @@ router.get('/top-rated', async (req, res) => { params.ExpressionAttributeValues[':r'] = region; } const data = await docClient.scan(params).promise(); - const sorted = data.Items.sort((a, b) => b.reputationScore - a.reputationScore).slice(0, parseInt(limit)); + const sorted = publicProducers(data.Items, region) + .sort((a, b) => b.reputationScore - a.reputationScore) + .slice(0, parseInt(limit)); res.json(sorted); } catch (err) { res.status(500).json({ error: 'Aggregation failed' }); diff --git a/backend/utils/aiTrendHelper.js b/backend/utils/aiTrendHelper.js index c46a6cb6..bbd51f7d 100644 --- a/backend/utils/aiTrendHelper.js +++ b/backend/utils/aiTrendHelper.js @@ -4,6 +4,28 @@ const { LISTING_TABLE_NAME } = require('../models/listing'); const { TRANSACTION_TABLE_NAME } = require('../models/transaction'); const { translateMessage, translateTerm } = require('./translation'); +// Producer fields that may leave /trends, as an allowlist: credentials, contact +// details, role, verification state and location are never returned. +const PUBLIC_PRODUCER_FIELDS = ['id', 'username', 'locationType', 'reputationScore', 'reputationWeight']; + +function toPublicProducer(user = {}) { + const safe = {}; + for (const field of PUBLIC_PRODUCER_FIELDS) { + if (user[field] !== undefined) safe[field] = user[field]; + } + return safe; +} + +// Region filters still match on location, so under one, producers with +// locationPrivacy set are left out. Any truthy value counts as private, as +// setLocation's `privacy` flag implies; getPublicLocations reads it the other +// way, so that meaning is to be confirmed. +function publicProducers(items = [], region) { + return items + .filter(u => !(region && u.locationPrivacy)) + .map(toPublicProducer); +} + /** * Generate localized AI insights for marketplace trends. * @param {string} region - Region or locale identifier used for data filtering. @@ -51,9 +73,11 @@ async function generateAIInsight(region, locale = 'en') { userParams.ExpressionAttributeValues[':r'] = region; } const usersRes = await docClient.scan(userParams).promise(); - const topUsers = usersRes.Items.sort((a, b) => b.reputationScore - a.reputationScore).slice(0, 3); - if (topUsers.length > 0) { - const names = topUsers.map(u => u.name || u.email).join(', '); + const topUsers = publicProducers(usersRes.Items, region) + .sort((a, b) => b.reputationScore - a.reputationScore) + .slice(0, 3); + const names = topUsers.map(u => u.username).filter(Boolean).join(', '); + if (names) { insights.push( translateMessage('top_rated_producers', locale, { names, @@ -90,4 +114,4 @@ async function generateAIInsight(region, locale = 'en') { return insights; } -module.exports = { generateAIInsight }; +module.exports = { generateAIInsight, publicProducers };