91 lines
2.5 KiB
TypeScript
91 lines
2.5 KiB
TypeScript
// modules/helpdesk/helpdesk.conversation.service.ts
|
|
import { FastifyInstance } from 'fastify'
|
|
import { getOrCreateContact } from './helpdesk.contact.service.js'
|
|
import {useNextNumberRangeNumber} from "../../utils/functions";
|
|
|
|
export async function createConversation(
|
|
server: FastifyInstance,
|
|
{
|
|
tenant_id,
|
|
contact,
|
|
channel_instance_id,
|
|
subject,
|
|
customer_id = null,
|
|
contact_person_id = null
|
|
}: {
|
|
tenant_id: number
|
|
contact: { email?: string; phone?: string; display_name?: string }
|
|
channel_instance_id: string
|
|
subject?: string,
|
|
customer_id?: number,
|
|
contact_person_id?: number
|
|
}
|
|
) {
|
|
const contactRecord = await getOrCreateContact(server, tenant_id, contact)
|
|
|
|
const {usedNumber } = await useNextNumberRangeNumber(server, tenant_id, "tickets")
|
|
|
|
const { data, error } = await server.supabase
|
|
.from('helpdesk_conversations')
|
|
.insert({
|
|
tenant_id,
|
|
contact_id: contactRecord.id,
|
|
channel_instance_id,
|
|
subject: subject || null,
|
|
status: 'open',
|
|
created_at: new Date().toISOString(),
|
|
customer_id,
|
|
contact_person_id,
|
|
ticket_number: usedNumber
|
|
})
|
|
.select()
|
|
.single()
|
|
|
|
if (error) throw error
|
|
return data
|
|
}
|
|
|
|
export async function getConversations(
|
|
server: FastifyInstance,
|
|
tenant_id: number,
|
|
opts?: { status?: string; limit?: number }
|
|
) {
|
|
const { status, limit = 50 } = opts || {}
|
|
|
|
let query = server.supabase.from('helpdesk_conversations').select('*, customer_id(*)').eq('tenant_id', tenant_id)
|
|
|
|
if (status) query = query.eq('status', status)
|
|
query = query.order('last_message_at', { ascending: false }).limit(limit)
|
|
|
|
const { data, error } = await query
|
|
if (error) throw error
|
|
|
|
const mappedData = data.map(entry => {
|
|
return {
|
|
...entry,
|
|
customer: entry.customer_id
|
|
}
|
|
})
|
|
|
|
return mappedData
|
|
}
|
|
|
|
export async function updateConversationStatus(
|
|
server: FastifyInstance,
|
|
conversation_id: string,
|
|
status: string
|
|
) {
|
|
const valid = ['open', 'in_progress', 'waiting_for_customer', 'answered', 'closed']
|
|
if (!valid.includes(status)) throw new Error('Invalid status')
|
|
|
|
const { data, error } = await server.supabase
|
|
.from('helpdesk_conversations')
|
|
.update({ status })
|
|
.eq('id', conversation_id)
|
|
.select()
|
|
.single()
|
|
|
|
if (error) throw error
|
|
return data
|
|
}
|