import { HttpError } from './service.js' import { searchQuery } from './search.js' export function pagination(options = {}, defaultSize = 25) { const integer = (value, fallback, max, label) => { if (value === undefined) return fallback if ( !['string', 'number'].includes(typeof value) || !/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value)) || Number(value) < 1 || Number(value) > max ) throw new HttpError(400, `${label} ist ungültig.`) return Number(value) } return { requestedPage: integer(options.page, 1, Number.MAX_SAFE_INTEGER, 'Seite'), pageSize: integer(options.pageSize, defaultSize, 100, 'Seitengröße (1–100)'), } } export function pageBounds(total, { requestedPage, pageSize }) { const totalPages = Math.ceil(total / pageSize), page = Math.min(requestedPage, Math.max(1, totalPages)) return { total, page, pageSize, totalPages, offset: (page - 1) * pageSize } } export function visibleQueues(s, user) { const permissions = s.permissions(user), global = permissions['*']?.includes('view') return s .all('SELECT id FROM queues WHERE deleted_at IS NULL') .filter((q) => global || permissions[q.id]?.includes('view')) .map((q) => q.id) } const emptyCounts = () => ({ total: 0, open: 0, new: 0, waiting: 0, closed: 0, mine: 0 }) export function ticketCounts(s, user, allowed = visibleQueues(s, user)) { const counts = { ...emptyCounts(), queues: {} } if (!allowed.length) return counts for (const row of s.all( `SELECT t.queue_id,s.behavior,count(*) n,sum(CASE WHEN t.assignee=? THEN 1 ELSE 0 END) mine FROM tickets t JOIN statuses s ON s.id=t.status_id WHERE t.queue_id IN (${allowed.map(() => '?')}) GROUP BY t.queue_id,s.behavior`, user.id, ...allowed, )) { const queue = (counts.queues[row.queue_id] ||= emptyCounts()) for (const target of [counts, queue]) { target.total += row.n if (row.behavior === 'closed') target.closed += row.n else { target.open += row.n target.mine += row.mine } if (row.behavior === 'new') target.new += row.n if (row.behavior.startsWith('wait_')) target.waiting += row.n } } return counts } export function ticketPage(s, user, filters = {}) { const paging = pagination(filters) for (const [key, max] of Object.entries({ q: 300, queue: 100, status: 100, assignee: 100, tag: 100, sort: 20, view: 20, })) { if ( filters[key] !== undefined && (typeof filters[key] !== 'string' || filters[key].length > max) ) throw new HttpError(400, `Ungültiger Filter: ${key}.`) } const view = filters.view || 'all', sort = filters.sort || 'id' if ( !['all', 'inbox', 'mine', 'waiting', 'closed'].includes(view) || !['id', 'newest', 'oldest', 'subject'].includes(sort) ) throw new HttpError(400, 'Ansicht oder Sortierung ist ungültig.') return s.tx(() => { const allowed = visibleQueues(s, user), counts = ticketCounts(s, user, allowed) if (!allowed.length) { const { offset, ...meta } = pageBounds(0, paging) return { ...meta, items: [], counts } } const clauses = [`t.queue_id IN (${allowed.map(() => '?')})`], params = [...allowed] if (view === 'closed') clauses.push("s.behavior='closed'") else if (view !== 'all') { clauses.push("s.behavior!='closed'") if (view === 'mine') { clauses.push('t.assignee=?') params.push(user.id) } if (view === 'waiting') clauses.push("s.behavior IN ('wait_customer','wait_date','wait_goods')") } if (filters.queue) { clauses.push('t.queue_id=?') params.push(filters.queue) } if (filters.status) { clauses.push('(s.behavior=? OR t.status_id=?)') params.push(filters.status, filters.status) } if (filters.assignee === 'unassigned') clauses.push('t.assignee IS NULL') else if (filters.assignee) { clauses.push('t.assignee=?') params.push(filters.assignee) } if (filters.tag === 'none') clauses.push( 'NOT EXISTS (SELECT 1 FROM ticket_tags a JOIN queue_tags q ON q.id=a.tag_id WHERE a.ticket_id=t.id AND q.queue_id=t.queue_id)', ) else if (filters.tag) { const tag = s.get('SELECT queue_id FROM queue_tags WHERE id=?', filters.tag) if (!tag || !allowed.includes(tag.queue_id)) clauses.push('0') else { clauses.push('t.queue_id=?', 't.id IN (SELECT ticket_id FROM ticket_tags WHERE tag_id=?)') params.push(tag.queue_id, filters.tag) } } if (filters.q?.trim()) { const query = searchQuery(filters.q) if (!query) clauses.push('0') else { clauses.push('t.id IN (SELECT rowid FROM ticket_search WHERE ticket_search MATCH ?)') params.push(query) } } const from = 'FROM tickets t JOIN statuses s ON s.id=t.status_id', where = clauses.join(' AND ') const total = s.get(`SELECT count(*) n ${from} WHERE ${where}`, ...params).n const { offset, ...meta } = pageBounds(total, paging) const order = { id: 't.id DESC', newest: 't.updated_at DESC,t.id DESC', oldest: 't.updated_at ASC,t.id ASC', subject: 't.subject COLLATE NOCASE ASC,t.id DESC', }[sort] // Select the page's IDs first: body previews and tag data are never materialized for skipped rows. const ids = s .all( `SELECT t.id ${from} WHERE ${where} ORDER BY ${order} LIMIT ? OFFSET ?`, ...params, meta.pageSize, offset, ) .map((t) => t.id) if (!ids.length) return { ...meta, items: [], counts } const placeholders = ids.map(() => '?').join(',') const items = s .all( `SELECT t.*,s.name status_name,s.color status_color,s.behavior,q.name queue_name,q.color queue_color,u.name assignee_name, (SELECT substr(body,1,240) FROM messages WHERE ticket_id=t.id ORDER BY created_at DESC,rowid DESC LIMIT 1) preview FROM tickets t JOIN statuses s ON s.id=t.status_id JOIN queues q ON q.id=t.queue_id LEFT JOIN users u ON u.id=t.assignee WHERE t.id IN (${placeholders}) ORDER BY ${order}`, ...ids, ) .map((t) => ({ ...t, tags: [] })) const byId = new Map(items.map((t) => [t.id, t])) for (const row of s.all( `SELECT a.ticket_id,q.id,q.name,q.color,a.sender,a.created_at FROM ticket_tags a JOIN queue_tags q ON q.id=a.tag_id JOIN tickets t ON t.id=a.ticket_id WHERE a.ticket_id IN (${placeholders}) AND q.queue_id=t.queue_id ORDER BY q.position,q.id`, ...ids, )) { const { ticket_id, ...tag } = row byId.get(ticket_id).tags.push(tag) } return { ...meta, items, counts } }) }