Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr SMS Gateway8 * File : backend/src/messages/query.ts9 * Module : messages10 * Repository : https://git.spboucher.ai/maclustr-sms11 * Project Website : https://sms.spboucher.ai12 * Created : 2026-11-3013 * Last Modified : 2026-11-3014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { sql } from "../db.ts"43import { bad, clampLimit, decodeCursor, encodeCursor, iso } from "../util.ts"44import { publicMessage } from "./service.ts"4546export interface MessageFilters { direction?: string; status?: string; to?: string; from?: string; peer?: string; device_id?: string; sim_id?: string; application_id?: string; conversation_id?: string; created_after?: string; created_before?: string; limit?: unknown; cursor?: string }47/** Portée d'une application : ses propres envois, et les SMS reçus sur les SIM qui lui sont permises. */48export interface Scope { appId: string; allowedSimIds: string[] | null; inbound: boolean; outbound: boolean }4950const date = (v: string | undefined, name: string) => { if (v === undefined) return null; const t = Date.parse(v); if (!Number.isFinite(t)) throw bad("invalid_request", `${name} : date ISO 8601 attendue`); return new Date(t) }5152export async function listMessages(f: MessageFilters, scope: Scope | null, withText = true) {53 const limit = clampLimit(f.limit), cur = decodeCursor(f.cursor)54 const statuses = f.status ? f.status.split(",").map(s => s.trim().toUpperCase()).filter(Boolean) : null55 const after = date(f.created_after, "created_after"), before = date(f.created_before, "created_before")56 const visible = scope ? sql`and (57 ${scope.outbound ? sql`(m.direction = 'outbound' and m.application_id = ${scope.appId})` : sql`false`}58 or ${scope.inbound ? (scope.allowedSimIds ? sql`(m.direction = 'inbound' and m.sim_id = any(${scope.allowedSimIds}))` : sql`m.direction = 'inbound'`) : sql`false`})` : sql``59 const rows = await sql`60 select m.* from messages m where true ${visible}61 ${f.direction ? sql`and m.direction = ${f.direction}` : sql``}62 ${statuses ? sql`and m.status = any(${statuses})` : sql``}63 ${f.to ? sql`and m.to_number = ${f.to}` : sql``}64 ${f.from ? sql`and m.from_number = ${f.from}` : sql``}65 ${f.peer ? sql`and (m.to_number = ${f.peer} or m.from_number = ${f.peer})` : sql``}66 ${f.device_id ? sql`and m.device_id = ${f.device_id}` : sql``}67 ${f.sim_id ? sql`and m.sim_id = ${f.sim_id}` : sql``}68 ${f.application_id ? sql`and m.application_id = ${f.application_id}` : sql``}69 ${f.conversation_id ? sql`and m.conversation_id = ${f.conversation_id}` : sql``}70 ${after ? sql`and m.created_at >= ${after}` : sql``}71 ${before ? sql`and m.created_at < ${before}` : sql``}72 ${cur ? sql`and (m.created_at, m.id) < (${cur[0]}::timestamptz, ${cur[1]})` : sql``}73 order by m.created_at desc, m.id desc limit ${limit + 1}`74 const page = rows.slice(0, limit)75 const last = page[page.length - 1]76 return { data: page.map(m => publicMessage(m, withText)), has_more: rows.length > limit, next_cursor: rows.length > limit && last ? encodeCursor(new Date(last.created_at), last.id) : null }77}7879export async function messageEvents(id: string) {80 const ev = await sql`select type, from_status, to_status, source, detail, created_at from message_events where message_id = ${id} order by id`81 return ev.map(e => ({ type: e.type, from: e.from_status?.toLowerCase() ?? null, to: e.to_status?.toLowerCase() ?? null, source: e.source, detail: e.detail, at: iso(e.created_at) }))82}8384export async function listConversations(f: { sim_id?: string; limit?: unknown; cursor?: string }, allowedSimIds: string[] | null) {85 const limit = clampLimit(f.limit), cur = decodeCursor(f.cursor)86 const rows = await sql`87 select c.*, coalesce(s.manual_number, s.reported_number) as number, s.device_id from conversations c join sim_profiles s on s.id = c.sim_id where true88 ${allowedSimIds ? sql`and c.sim_id = any(${allowedSimIds})` : sql``} ${f.sim_id ? sql`and c.sim_id = ${f.sim_id}` : sql``}89 ${cur ? sql`and (c.last_message_at, c.id) < (${cur[0]}::timestamptz, ${cur[1]})` : sql``}90 order by c.last_message_at desc, c.id desc limit ${limit + 1}`91 const page = rows.slice(0, limit), last = page[page.length - 1]92 return {93 data: page.map(c => ({ id: c.id, sim_id: c.sim_id, device_id: c.device_id, number: c.number, peer: c.peer, last_message_at: iso(c.last_message_at), last_direction: c.last_direction,94 inbound_count: c.inbound_count, outbound_count: c.outbound_count, unread: c.unread })),95 has_more: rows.length > limit, next_cursor: rows.length > limit && last ? encodeCursor(new Date(last.last_message_at), last.id) : null,96 }97}98