Skip to content

Commit 66477f8

Browse files
committed
feat(database): implement WarningDatabaseService for managing warnings and remove spamtime option
- Add methods for creating, updating, deleting, and retrieving warnings: - `create`: Inserts a new warning into the database. - `update`: Updates an existing warning's reason and timestamp. - `delete`: Deletes a warning by ID. - `getById`: Retrieves a warning by ID. - `getByUserId`: Fetches all warnings associated with a specific user. - `getByGroupId`: Fetches the latest warning associated with a specific group. - `getAll`: Fetches warnings with optional filters for group ID and user ID. - `save`: Saves a new warning if one does not exist for a group. - Ensure proper handling of database queries and parameters. - Use a consistent approach for query structuring and parameter binding. - Leverage `DatabaseService` for query execution and CRUD operations. This implementation provides a robust interface for warning management, ensuring easy integration and scalability for user and group-related operations.
1 parent 4b97907 commit 66477f8

6 files changed

Lines changed: 121 additions & 22 deletions

File tree

src/database/models/Channel.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export class ChannelService {
2+
async create() {}
3+
async update() {}
4+
async delete() {}
5+
async getByChannelId() {}
6+
}

src/database/models/Group.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ export class GroupService {
1616
chat_permissions: JSON.stringify(group.chat_permissions),
1717
approved_users: group.approved_users || [],
1818
warnings: group.warnings || [],
19-
is_spam_time: group.is_spam_time || false,
2019
members: group.members || [],
20+
welcome_message: group.welcome_message,
2121
updated_at: group.updated_at || new Date(),
2222
joined_at: group.joined_at || new Date(),
2323
});
@@ -31,7 +31,7 @@ export class GroupService {
3131
chat_permissions: group.chat_permissions,
3232
approved_users: group.approved_users,
3333
warnings: group.warnings,
34-
is_spam_time: group.is_spam_time,
34+
welcome_message: group.welcome_message,
3535
members: group.members,
3636
updated_at: group.updated_at || new Date(),
3737
};
@@ -47,6 +47,7 @@ export class GroupService {
4747
const [id, title] = [ctx.chat!.id!, ctx.chat!.title];
4848
const perrmission = (await ctx.api.getChat(id)).permissions;
4949
let group = await this.getByGroupId(id);
50+
const default_welcome_message = `Welcome to ${ctx.chat!.title}\n\nWe are so glad to have you here!. If you have any questions, don't hesitate to ask! 💬\n\nEnjoy your time here!`;
5051
if (!group) {
5152
const newGroupData: Omit<Group, 'id'> = {
5253
joined_at: new Date(),
@@ -56,8 +57,8 @@ export class GroupService {
5657
black_list: [],
5758
chat_permissions: perrmission || {},
5859
approved_users: [],
59-
warnings: 0,
60-
is_spam_time: false,
60+
warnings: [],
61+
welcome_message: default_welcome_message,
6162
members: [],
6263
};
6364
group = await this.create(newGroupData);

src/database/models/Warning.ts

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import { PoolClient } from 'pg';
2+
import { Warning } from '../../types/database/TablesTypes';
3+
import { DatabaseService } from '../service/Databas';
4+
export class WarningDatabaseService {
5+
private _db: DatabaseService;
6+
constructor(private _client: PoolClient) {
7+
this._db = new DatabaseService(_client);
8+
}
9+
10+
// Create a new warning
11+
async create(warning: Omit<Warning, 'id'>): Promise<Warning> {
12+
return await this._db.insert<Warning>('Warning', {
13+
user_id: warning.user_id,
14+
group_id: warning.group_id,
15+
reason: warning.reason,
16+
warned_at: warning.warned_at || new Date(),
17+
});
18+
}
19+
20+
// Update an existing warning (reason)
21+
async update(warning: Warning): Promise<Warning | null> {
22+
const updatedWarning = await this._db.update<Warning>(
23+
'Warning',
24+
{
25+
reason: warning.reason,
26+
warned_at: warning.warned_at || new Date(),
27+
},
28+
{ id: warning.id }
29+
);
30+
31+
return updatedWarning ?? null;
32+
}
33+
34+
// Delete a specific warning
35+
async delete(warningId: number): Promise<boolean> {
36+
const deletedWarnings = await this._db.delete<Warning>('Warning', { id: warningId });
37+
return deletedWarnings.length > 0;
38+
}
39+
40+
// Fetch a warning by ID
41+
async getById(warningId: number): Promise<Warning | null> {
42+
const query = `SELECT * FROM "Warning" WHERE id = $1;`;
43+
const result = await this._db.query<Warning>(query, [warningId]);
44+
return result.rows[0] || null;
45+
}
46+
47+
// Fetch all warnings for a specific user
48+
async getByUserId(userId: number): Promise<Warning[]> {
49+
const query = `
50+
SELECT * FROM "Warning"
51+
WHERE user_id = $1
52+
ORDER BY warned_at DESC;
53+
`;
54+
const result = await this._db.query<Warning>(query, [userId]);
55+
return result.rows;
56+
}
57+
58+
// Fetch all warnings for a specific group
59+
async getByGroupId(groupId: number): Promise<Warning> {
60+
const query = `
61+
SELECT * FROM "Warning"
62+
WHERE group_id = $1
63+
ORDER BY warned_at DESC;
64+
`;
65+
const result = await this._db.query<Warning>(query, [groupId]);
66+
return result.rows[0];
67+
}
68+
async getAll(filter: { groupId?: number; userId?: number } = {}): Promise<Warning[]> {
69+
const conditions: string[] = [];
70+
const params: any[] = [];
71+
72+
if (filter.groupId) {
73+
conditions.push(`group_id = $${params.length + 1}`);
74+
params.push(filter.groupId);
75+
}
76+
if (filter.userId) {
77+
conditions.push(`user_id = $${params.length + 1}`);
78+
params.push(filter.userId);
79+
}
80+
81+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
82+
const query = `
83+
SELECT * FROM "Warning"
84+
${whereClause}
85+
ORDER BY warned_at DESC;
86+
`;
87+
88+
const result = await this._db.query<Warning>(query, params);
89+
return result.rows;
90+
}
91+
92+
async save(groupId: number, userId: number, reason: string): Promise<Warning> {
93+
let warn = await this.getByGroupId(groupId);
94+
if (!warn) {
95+
const newGroupData: Omit<Warning, 'id'> = {
96+
group_id: groupId,
97+
reason: reason,
98+
user_id: userId,
99+
warned_at: new Date(),
100+
};
101+
warn = await this.create(newGroupData);
102+
}
103+
return warn!;
104+
}
105+
}

src/database/sql/Tables.sql

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ CREATE TABLE IF NOT EXISTS "Group" (
2222
joined_at TIMESTAMP DEFAULT NOW(),
2323
approved_users BIGINT[], -- Array of approved user IDs
2424
warnings BIGINT[], -- Number of warnings in the group
25-
is_spam_time BOOLEAN DEFAULT FALSE, -- Flag for spam detection
2625
welcome_message TEXT,
2726
members BIGINT[]
2827
);

src/database/sql/seed/SeedDataTables.sql

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ VALUES
66
(777888999, 'user3','fuser3' ,'user', 0, ARRAY[123456789],NOW(),NOW()),
77
(333444555, 'user4', 'fuser4','user', 1, ARRAY[123456789, 987654321],NOW(),NOW());
88
-- Seeding the Group table
9-
INSERT INTO "Group" (group_id, group_name, black_list, chat_permissions, updated_at, joined_at, approved_users, warnings, is_spam_time,welcome_message,members)
9+
INSERT INTO "Group" (group_id, group_name, black_list, chat_permissions, updated_at, joined_at, approved_users, warnings,welcome_message,members)
1010
VALUES
11-
(123456789, 'Test Group 1', ARRAY['BadWord1', 'BadWord2'], '{"can_post": true, "can_message": true}', NOW(), NOW(), ARRAY[1, 2], ARRAY[0], FALSE,'welcome message',ARRAY[0,2]),
12-
(987654321, 'Test Group 2', ARRAY['OffensiveUser1'], '{"can_post": false, "can_message": false}', NOW(), NOW(), ARRAY[3, 4], ARRAY[1], TRUE,'welcome message2',ARRAY[3,4]);
11+
(123456789, 'Test Group 1', ARRAY['BadWord1', 'BadWord2'], '{"can_post": true, "can_message": true}', NOW(), NOW(), ARRAY[1, 2], ARRAY[0],'welcome message',ARRAY[0,2]),
12+
(987654321, 'Test Group 2', ARRAY['OffensiveUser1'], '{"can_post": false, "can_message": false}', NOW(), NOW(), ARRAY[3, 4], ARRAY[1],'welcome message2',ARRAY[3,4]);
1313
-- Seeding the Warning table after Group data has been inserted
1414
INSERT INTO "Warning" (user_id, group_id, warned_at, reason)
1515
VALUES

src/types/database/TablesTypes.ts

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@ export interface Group {
77
black_list: string[];
88
chat_permissions: ChatPermissions;
99
approved_users: number[];
10-
warnings: number;
11-
is_spam_time: boolean;
10+
warnings: number[];
1211
members: number[];
1312
updated_at: Date;
13+
welcome_message: string;
1414
joined_at: Date;
1515
}
1616
export interface User {
@@ -31,12 +31,6 @@ export interface Warning {
3131
reason: string;
3232
warned_at: Date;
3333
}
34-
export interface ApprovedUser {
35-
id: number;
36-
user_id: User['id'];
37-
group_id: Group['id'];
38-
username: string;
39-
}
4034
export interface Channel {
4135
id: number;
4236
name: string;
@@ -50,9 +44,3 @@ export interface GroupRule {
5044
added_by: User['id'];
5145
added_at: Date;
5246
}
53-
export interface GroupMessageSettings {
54-
id: number;
55-
group_id: Group['id'];
56-
is_locked: boolean;
57-
welcome_message: string;
58-
}

0 commit comments

Comments
 (0)