import { pool } from '../../../../lib/postgres/connection.js'; import { camelCase } from '../../../../lib/util/camelCase.js'; import { getValue } from '../../../../lib/util/registry.js'; interface Filter { key: string; operation: string; value: unknown; } export class ContactSubmissionCollection { private baseQuery: any; private totalQuery: any; public currentFilters: Filter[] = []; public currentPage = 1; constructor(baseQuery: any) { this.baseQuery = baseQuery; this.baseQuery.orderBy('contact_submission.created_at', 'DESC'); } async init(filters: Filter[] = []): Promise { const currentFilters: Filter[] = []; const contactSubmissionCollectionFilters = await getValue( 'contactSubmissionCollectionFilters', [] ); contactSubmissionCollectionFilters.forEach((filter: any) => { const check = filters.find( (f) => f.key === filter.key && filter.operation.includes(f.operation) ); if (filter.key === '*' || check) { filter.callback( this.baseQuery, check?.operation, check?.value, currentFilters ); } }); // "Mark as spam" has to mean something. With no explicit status filter the // grid is an inbox, not an archive: spam is hidden unless the operator asks // for it by name. Applied before the count is cloned so the total matches // what is listed. if (!currentFilters.some((f) => f.key === 'status')) { this.baseQuery.andWhere('contact_submission.status', '!=', 'spam'); } const totalQuery = this.baseQuery.clone(); totalQuery.select( 'COUNT(contact_submission.contact_submission_id)', 'total' ); totalQuery.removeOrderBy(); totalQuery.removeLimit(); this.currentFilters = currentFilters; const pageFilter = currentFilters.find((f) => f.key === 'page'); this.currentPage = pageFilter ? parseInt(String(pageFilter.value), 10) || 1 : 1; this.totalQuery = totalQuery; } async items(): Promise>> { const items = await this.baseQuery.execute(pool); return items.map((row: Record) => camelCase(row)); } async total(): Promise { const total = await this.totalQuery.execute(pool); return total[0].total; } }