diff --git a/src/database/migrations/002-ticket-and-poll-details.sql b/src/database/migrations/002-ticket-and-poll-details.sql new file mode 100644 index 0000000..cca7473 --- /dev/null +++ b/src/database/migrations/002-ticket-and-poll-details.sql @@ -0,0 +1,7 @@ +-- Claim and close details of a ticket (M6-T05 / M6-T06) +ALTER TABLE tickets ADD COLUMN claimed_at TEXT; +ALTER TABLE tickets ADD COLUMN close_reason TEXT; + +-- Faster lookups for the poll scheduler and the result rendering (M10) +CREATE INDEX IF NOT EXISTS idx_polls_due ON polls (status, ends_at); +CREATE INDEX IF NOT EXISTS idx_poll_votes_choice ON poll_votes (poll_id, choice_index); diff --git a/src/database/repositories/moderation-repository.js b/src/database/repositories/moderation-repository.js new file mode 100644 index 0000000..a003e95 --- /dev/null +++ b/src/database/repositories/moderation-repository.js @@ -0,0 +1,50 @@ +import { getDatabase } from '../index.js'; + +export function recordAction({ + guildId, + action, + moderatorId, + targetId = null, + reason = null, + durationMs = null, +}) { + getDatabase() + .prepare( + `INSERT INTO moderation_actions (guild_id, action, target_id, moderator_id, reason, duration_ms) + VALUES (?, ?, ?, ?, ?, ?)`, + ) + .run(guildId, action, targetId, moderatorId, reason, durationMs); +} + +export function listActions({ guildId, targetId = null, action = null, limit = 20 }) { + const clauses = ['guild_id = ?']; + const params = [guildId]; + if (targetId) { + clauses.push('target_id = ?'); + params.push(targetId); + } + if (action) { + clauses.push('action = ?'); + params.push(action); + } + params.push(limit); + + return getDatabase() + .prepare(`SELECT * FROM moderation_actions WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) + .all(...params); +} + +export function countActions({ guildId, targetId, action }) { + const row = getDatabase() + .prepare( + 'SELECT COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? AND target_id = ? AND action = ?', + ) + .get(guildId, targetId, action); + return row.count; +} + +export function countByAction(guildId) { + return getDatabase() + .prepare('SELECT action, COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? GROUP BY action') + .all(guildId); +} diff --git a/src/database/repositories/notification-repository.js b/src/database/repositories/notification-repository.js new file mode 100644 index 0000000..62e0f17 --- /dev/null +++ b/src/database/repositories/notification-repository.js @@ -0,0 +1,34 @@ +import { getDatabase } from '../index.js'; + +/** Per-guild override of a notification channel (M9-T01). */ +export function setNotificationChannel({ guildId, type, channelId, detailLevel = 'normal' }) { + getDatabase() + .prepare( + `INSERT INTO notification_channels (guild_id, type, channel_id, detail_level) + VALUES (?, ?, ?, ?) + ON CONFLICT (guild_id, type) DO UPDATE SET + channel_id = excluded.channel_id, + detail_level = excluded.detail_level`, + ) + .run(guildId, type, channelId, detailLevel); +} + +export function getNotificationChannel(guildId, type) { + return ( + getDatabase() + .prepare('SELECT * FROM notification_channels WHERE guild_id = ? AND type = ?') + .get(guildId, type) ?? null + ); +} + +export function listNotificationChannels(guildId) { + return getDatabase() + .prepare('SELECT * FROM notification_channels WHERE guild_id = ? ORDER BY type') + .all(guildId); +} + +export function removeNotificationChannel(guildId, type) { + return getDatabase() + .prepare('DELETE FROM notification_channels WHERE guild_id = ? AND type = ?') + .run(guildId, type).changes; +} diff --git a/src/database/repositories/poll-repository.js b/src/database/repositories/poll-repository.js new file mode 100644 index 0000000..bc8d811 --- /dev/null +++ b/src/database/repositories/poll-repository.js @@ -0,0 +1,97 @@ +import { getDatabase } from '../index.js'; + +export function createPoll({ guildId, channelId, creatorId, question, choices, endsAt = null }) { + const { lastInsertRowid } = getDatabase() + .prepare( + `INSERT INTO polls (guild_id, channel_id, creator_id, question, choices, ends_at) + VALUES (?, ?, ?, ?, ?, ?)`, + ) + .run(guildId, channelId, creatorId, question, JSON.stringify(choices), endsAt); + return Number(lastInsertRowid); +} + +export function attachPollMessage(id, messageId) { + getDatabase().prepare('UPDATE polls SET message_id = ? WHERE id = ?').run(messageId, id); +} + +export function getPoll(id) { + return getDatabase().prepare('SELECT * FROM polls WHERE id = ?').get(id) ?? null; +} + +export function getPollByMessage(messageId) { + return getDatabase().prepare('SELECT * FROM polls WHERE message_id = ?').get(messageId) ?? null; +} + +export function listPolls({ guildId, status = null, limit = 10 }) { + const clauses = ['guild_id = ?']; + const params = [guildId]; + if (status) { + clauses.push('status = ?'); + params.push(status); + } + params.push(limit); + + return getDatabase() + .prepare(`SELECT * FROM polls WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) + .all(...params); +} + +/** Polls whose end date is reached and that are still open (M10-T05). */ +export function listDuePolls(limit = 10) { + return getDatabase() + .prepare( + `SELECT * FROM polls + WHERE status = 'open' AND ends_at IS NOT NULL AND ends_at <= datetime('now') + ORDER BY ends_at ASC LIMIT ?`, + ) + .all(limit); +} + +export function listOpenPolls(limit = 25) { + return getDatabase() + .prepare("SELECT * FROM polls WHERE status = 'open' ORDER BY id ASC LIMIT ?") + .all(limit); +} + +export function listVotes(pollId) { + return getDatabase().prepare('SELECT user_id, choice_index FROM poll_votes WHERE poll_id = ?').all(pollId); +} + +/** Counts votes per choice index: `[{ choice_index, count }]`. */ +export function countVotes(pollId) { + return getDatabase() + .prepare('SELECT choice_index, COUNT(*) AS count FROM poll_votes WHERE poll_id = ? GROUP BY choice_index') + .all(pollId); +} + +/** + * Creates or updates a vote. Returns 'created', 'changed' or 'unchanged' (M10-T04). + */ +export function castVote(pollId, userId, choiceIndex) { + const database = getDatabase(); + const previous = database + .prepare('SELECT choice_index FROM poll_votes WHERE poll_id = ? AND user_id = ?') + .get(pollId, userId); + + if (previous && previous.choice_index === choiceIndex) return 'unchanged'; + + database + .prepare( + `INSERT INTO poll_votes (poll_id, user_id, choice_index) VALUES (?, ?, ?) + ON CONFLICT (poll_id, user_id) DO UPDATE SET choice_index = excluded.choice_index, + voted_at = datetime('now')`, + ) + .run(pollId, userId, choiceIndex); + + return previous ? 'changed' : 'created'; +} + +export function closePoll(id) { + return getDatabase().prepare("UPDATE polls SET status = 'closed' WHERE id = ? AND status = 'open'").run(id) + .changes; +} + +export function countPolls(guildId) { + const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM polls WHERE guild_id = ?').get(guildId); + return row.count; +} diff --git a/src/database/repositories/settings-repository.js b/src/database/repositories/settings-repository.js index 1734002..2ba7e8e 100644 --- a/src/database/repositories/settings-repository.js +++ b/src/database/repositories/settings-repository.js @@ -7,6 +7,18 @@ export function getSetting(guildId, key, fallback = null) { return row ? JSON.parse(row.value) : fallback; } +/** + * Reads a setting without throwing when the database is not ready (tests, early startup). + * Never use it when a missing database should be an error. + */ +export function resolveSetting(guildId, key, fallback = null) { + try { + return getSetting(guildId, key, fallback); + } catch { + return fallback; + } +} + export function setSetting(guildId, key, value, updatedBy = null) { getDatabase() .prepare( diff --git a/src/database/repositories/ticket-repository.js b/src/database/repositories/ticket-repository.js new file mode 100644 index 0000000..9f97d46 --- /dev/null +++ b/src/database/repositories/ticket-repository.js @@ -0,0 +1,71 @@ +import { getDatabase } from '../index.js'; + +export function createTicket({ guildId, channelId, categoryId, authorId }) { + const { lastInsertRowid } = getDatabase() + .prepare('INSERT INTO tickets (guild_id, channel_id, category_id, author_id) VALUES (?, ?, ?, ?)') + .run(guildId, channelId, categoryId, authorId); + return Number(lastInsertRowid); +} + +export function getTicket(id) { + return getDatabase().prepare('SELECT * FROM tickets WHERE id = ?').get(id) ?? null; +} + +export function getTicketByChannel(channelId) { + return getDatabase().prepare('SELECT * FROM tickets WHERE channel_id = ?').get(channelId) ?? null; +} + +/** Returns the open ticket of an author for a category, if any (M6-T08). */ +export function getOpenTicket({ guildId, authorId, categoryId }) { + return ( + getDatabase() + .prepare( + `SELECT * FROM tickets + WHERE guild_id = ? AND author_id = ? AND category_id = ? AND status = 'open'`, + ) + .get(guildId, authorId, categoryId) ?? null + ); +} + +export function listTickets({ guildId, status = null, authorId = null, limit = 20 }) { + const clauses = ['guild_id = ?']; + const params = [guildId]; + if (status) { + clauses.push('status = ?'); + params.push(status); + } + if (authorId) { + clauses.push('author_id = ?'); + params.push(authorId); + } + params.push(limit); + + return getDatabase() + .prepare(`SELECT * FROM tickets WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`) + .all(...params); +} + +export function claimTicket(id, userId) { + return getDatabase() + .prepare( + "UPDATE tickets SET claimed_by = ?, claimed_at = datetime('now') WHERE id = ? AND status = 'open'", + ) + .run(userId, id).changes; +} + +export function closeTicket(id, { closedBy, reason = null }) { + return getDatabase() + .prepare( + `UPDATE tickets + SET status = 'closed', closed_at = datetime('now'), closed_by = ?, close_reason = ? + WHERE id = ? AND status = 'open'`, + ) + .run(closedBy, reason, id).changes; +} + +export function countOpenTickets(guildId) { + const row = getDatabase() + .prepare("SELECT COUNT(*) AS count FROM tickets WHERE guild_id = ? AND status = 'open'") + .get(guildId); + return row.count; +} diff --git a/tests/repositories.test.js b/tests/repositories.test.js new file mode 100644 index 0000000..1accca9 --- /dev/null +++ b/tests/repositories.test.js @@ -0,0 +1,189 @@ +import assert from 'node:assert/strict'; +import { after, before, beforeEach, describe, it } from 'node:test'; +import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { + countActions, + listActions, + recordAction, +} from '../src/database/repositories/moderation-repository.js'; +import { + getNotificationChannel, + removeNotificationChannel, + setNotificationChannel, +} from '../src/database/repositories/notification-repository.js'; +import { + castVote, + closePoll, + countVotes, + createPoll, + listDuePolls, +} from '../src/database/repositories/poll-repository.js'; +import { + claimTicket, + closeTicket, + countOpenTickets, + createTicket, + getOpenTicket, + getTicketByChannel, +} from '../src/database/repositories/ticket-repository.js'; + +const reset = () => + getDatabase().exec( + 'DELETE FROM tickets; DELETE FROM moderation_actions; DELETE FROM polls; DELETE FROM poll_votes; DELETE FROM notification_channels;', + ); + +describe('ticket repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(reset); + + const openTicket = () => createTicket({ guildId: 'g', channelId: 'c1', categoryId: 'bug', authorId: 'u1' }); + + it('creates a ticket and finds it by channel', () => { + const id = openTicket(); + const ticket = getTicketByChannel('c1'); + assert.equal(ticket.id, id); + assert.equal(ticket.status, 'open'); + assert.equal(ticket.claimed_by, null); + }); + + it('refuses a second open ticket for the same author and category', () => { + openTicket(); + assert.throws( + () => createTicket({ guildId: 'g', channelId: 'c2', categoryId: 'bug', authorId: 'u1' }), + /UNIQUE/, + ); + assert.equal(getOpenTicket({ guildId: 'g', authorId: 'u1', categoryId: 'bug' }).channel_id, 'c1'); + }); + + it('allows a new ticket once the previous one is closed', () => { + const id = openTicket(); + closeTicket(id, { closedBy: 'staff', reason: 'résolu' }); + const newId = createTicket({ guildId: 'g', channelId: 'c3', categoryId: 'bug', authorId: 'u1' }); + assert.notEqual(newId, id); + assert.equal(countOpenTickets('g'), 1); + }); + + it('records who claimed and closed a ticket', () => { + const id = openTicket(); + assert.equal(claimTicket(id, 'staff'), 1); + assert.equal(getTicketByChannel('c1').claimed_by, 'staff'); + + assert.equal(closeTicket(id, { closedBy: 'staff', reason: 'ok' }), 1); + const closed = getTicketByChannel('c1'); + assert.equal(closed.status, 'closed'); + assert.equal(closed.close_reason, 'ok'); + assert.ok(closed.closed_at); + }); + + it('cannot close a ticket twice', () => { + const id = openTicket(); + closeTicket(id, { closedBy: 'staff' }); + assert.equal(closeTicket(id, { closedBy: 'staff' }), 0); + }); +}); + +describe('moderation repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(reset); + + it('records and lists actions of a target', () => { + recordAction({ guildId: 'g', action: 'warn', moderatorId: 'm1', targetId: 'u1', reason: 'spam' }); + recordAction({ guildId: 'g', action: 'warn', moderatorId: 'm1', targetId: 'u1', reason: 'again' }); + recordAction({ guildId: 'g', action: 'kick', moderatorId: 'm2', targetId: 'u2' }); + + assert.equal(countActions({ guildId: 'g', targetId: 'u1', action: 'warn' }), 2); + const history = listActions({ guildId: 'g', targetId: 'u1' }); + assert.equal(history.length, 2); + assert.equal(history[0].reason, 'again'); + + assert.equal(listActions({ guildId: 'g', action: 'kick' }).length, 1); + }); + + it('keeps the duration of a mute', () => { + recordAction({ + guildId: 'g', + action: 'mute', + moderatorId: 'm1', + targetId: 'u1', + durationMs: 60_000, + }); + assert.equal(listActions({ guildId: 'g', targetId: 'u1' })[0].duration_ms, 60_000); + }); +}); + +describe('poll repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(reset); + + const poll = () => + createPoll({ + guildId: 'g', + channelId: 'c', + creatorId: 'u1', + question: 'Question ?', + choices: ['a', 'b'], + endsAt: null, + }); + + it('counts one vote per user and allows a change of mind', () => { + const id = poll(); + assert.equal(castVote(id, 'u1', 0), 'created'); + assert.equal(castVote(id, 'u1', 0), 'unchanged'); + assert.equal(castVote(id, 'u1', 1), 'changed'); + assert.equal(castVote(id, 'u2', 1), 'created'); + + const counts = countVotes(id); + assert.equal(counts.length, 1); + assert.deepEqual({ ...counts[0] }, { choice_index: 1, count: 2 }); + }); + + it('lists only the polls whose end date has passed', () => { + const due = createPoll({ + guildId: 'g', + channelId: 'c', + creatorId: 'u1', + question: 'Bientôt fini', + choices: ['a', 'b'], + endsAt: '2000-01-01 00:00:00', + }); + createPoll({ + guildId: 'g', + channelId: 'c', + creatorId: 'u1', + question: 'En cours', + choices: ['a', 'b'], + endsAt: '2999-01-01 00:00:00', + }); + + const ids = listDuePolls().map((row) => row.id); + assert.deepEqual(ids, [due]); + }); + + it('closes a poll only once', () => { + const id = poll(); + assert.equal(closePoll(id), 1); + assert.equal(closePoll(id), 0); + }); +}); + +describe('notification repository', () => { + before(() => initDatabase(':memory:')); + after(() => closeDatabase()); + beforeEach(reset); + + it('stores one channel per type and replaces it', () => { + setNotificationChannel({ guildId: 'g', type: 'issues', channelId: 'c1' }); + setNotificationChannel({ guildId: 'g', type: 'issues', channelId: 'c2' }); + assert.equal(getNotificationChannel('g', 'issues').channel_id, 'c2'); + assert.equal(getNotificationChannel('other', 'issues'), null); + }); + + it('removes an override and reports it', () => { + setNotificationChannel({ guildId: 'g', type: 'release', channelId: 'c1' }); + assert.equal(removeNotificationChannel('g', 'release'), 1); + assert.equal(removeNotificationChannel('g', 'release'), 0); + }); +});