From d24dd80bc29a60f47aa99570bd46c5c67be69063 Mon Sep 17 00:00:00 2001 From: Reyhaan S Date: Thu, 22 Oct 2026 03:41:07 +0530 Subject: [PATCH] fix: don't record joins for complaints that don't exist Complaint.join inserted the complaint_joins row first and only then found out, via the UPDATE, that there was no such complaint. The caller got a 404, but the row stayed. complaint_joins has no foreign key, so when a complaint with that id was created later, the same user or session was told "You have already joined this complaint" and saw it in their joined list, while supporter_count was never incremented. Check that the complaint exists before inserting. --- backend/src/models/Complaint.js | 7 +++++++ backend/tests/complaintJoin.test.js | 25 +++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 backend/tests/complaintJoin.test.js diff --git a/backend/src/models/Complaint.js b/backend/src/models/Complaint.js index 2b8dd1c..0209348 100644 --- a/backend/src/models/Complaint.js +++ b/backend/src/models/Complaint.js @@ -216,6 +216,13 @@ class Complaint { * @returns {Object} Updated complaint */ static async join(id, userId = null, sessionId = null) { + // Check first: recording a join for an id that doesn't exist yet leaves + // a row that later makes the real complaint report "already joined". + const existing = await pool.query('SELECT 1 FROM complaints WHERE id = $1', [id]); + if (existing.rows.length === 0) { + return null; + } + const insertResult = await pool.query( `INSERT OR IGNORE INTO complaint_joins (complaint_id, user_id, session_id) VALUES ($1, $2, $3)`, [id, userId, sessionId] diff --git a/backend/tests/complaintJoin.test.js b/backend/tests/complaintJoin.test.js new file mode 100644 index 0000000..d746bef --- /dev/null +++ b/backend/tests/complaintJoin.test.js @@ -0,0 +1,25 @@ +process.env.JWT_SECRET = process.env.JWT_SECRET || 'x'.repeat(48); +const { test, before } = require('node:test'); +const assert = require('node:assert'); +const initDatabase = require('../src/config/initDatabase'); +const Complaint = require('../src/models/Complaint'); +const pool = require('../src/config/database'); + +before(async () => { + await initDatabase(); +}); + +test('joining a complaint that does not exist records nothing', async () => { + const { rows } = await pool.query('SELECT COALESCE(MAX(id), 0) AS max_id FROM complaints'); + const missingId = Number(rows[0].max_id) + 100000; + const sessionId = `join-test-${Date.now()}`; + + const result = await Complaint.join(missingId, null, sessionId); + + assert.strictEqual(result, null); + const joins = await pool.query( + 'SELECT COUNT(*) AS n FROM complaint_joins WHERE complaint_id = $1', + [missingId] + ); + assert.strictEqual(Number(joins.rows[0].n), 0); +});