Skip to content

Send and receive SMS messages using your Android phone programmatically via a simple HTTP API

feat(web): create all Pinia stores and route middleware

Acho Arnold292699f4b17c
diff --git a/web/app/middleware/auth.ts b/web/app/middleware/auth.ts
new file mode 100644
index 00000000..94de7eda
--- /dev/null
+++ b/web/app/middleware/auth.ts
@@ -0,0 +1,6 @@
+export default defineNuxtRouteMiddleware((to) => {
+ const authStore = useAuthStore();
+ if (authStore.authUser === null) {
+ return navigateTo({ path: "/login", query: { to: to.path } });
+ }
+});
diff --git a/web/app/middleware/guest.ts b/web/app/middleware/guest.ts
new file mode 100644
index 00000000..969e67db
--- /dev/null
+++ b/web/app/middleware/guest.ts
@@ -0,0 +1,6 @@
+export default defineNuxtRouteMiddleware(() => {
+ const authStore = useAuthStore();
+ if (authStore.authUser !== null) {
+ return navigateTo("/threads");
+ }
+});
diff --git a/web/app/stores/app.ts b/web/app/stores/app.ts
new file mode 100644
index 00000000..0bf383f8
--- /dev/null
+++ b/web/app/stores/app.ts
@@ -0,0 +1,43 @@
+import { defineStore } from "pinia";
+
+export interface AppData {
+ url: string;
+ name: string;
+ env: string;
+ appDownloadUrl: string;
+ documentationUrl: string;
+ githubUrl: string;
+}
+
+export const useAppStore = defineStore("app", () => {
+ const config = useRuntimeConfig();
+ const polling = ref(false);
+
+ const appData = computed<AppData>(() => {
+ let url = (config.public.appUrl as string) || "";
+ if (url.length > 0 && url[url.length - 1] === "/") {
+ url = url.substring(0, url.length - 1);
+ }
+ return {
+ url,
+ env: config.public.appEnv as string,
+ appDownloadUrl: config.public.appDownloadUrl as string,
+ documentationUrl: config.public.appDocumentationUrl as string,
+ githubUrl: config.public.appGithubUrl as string,
+ name: config.public.appName as string,
+ };
+ });
+
+ const isLocal = computed(() => config.public.appEnv === "local");
+
+ function setPolling(value: boolean) {
+ polling.value = value;
+ }
+
+ return {
+ polling,
+ appData,
+ isLocal,
+ setPolling,
+ };
+});
diff --git a/web/app/stores/auth.ts b/web/app/stores/auth.ts
new file mode 100644
index 00000000..805445fc
--- /dev/null
+++ b/web/app/stores/auth.ts
@@ -0,0 +1,119 @@
+import { defineStore } from "pinia";
+import { setAuthHeader, setApiKey } from "~/composables/useApi";
+import type { User } from "~~/shared/types/user";
+
+export interface AuthUser {
+ email: string | null;
+ displayName: string | null;
+ id: string;
+}
+
+export const useAuthStore = defineStore("auth", () => {
+ const authStateChanged = ref(false);
+ const authUser = ref<AuthUser | null>(null);
+ const user = ref<User | null>(null);
+ const { apiFetch } = useApi();
+
+ async function setAuthUserAction(newUser: AuthUser | null | undefined) {
+ const userChanged = newUser?.id !== authUser.value?.id;
+ authUser.value = newUser ?? null;
+ authStateChanged.value = true;
+
+ if (userChanged && newUser !== null) {
+ await Promise.all([loadUser(), loadPhones()]);
+ }
+ }
+
+ async function onAuthStateChanged(firebaseUser: any) {
+ if (firebaseUser == null) {
+ authUser.value = null;
+ user.value = null;
+ authStateChanged.value = true;
+ setApiKey("");
+ return;
+ }
+ setAuthHeader(await firebaseUser.getIdToken());
+ const { uid, email, displayName } = firebaseUser;
+ authUser.value = { id: uid, email, displayName };
+ authStateChanged.value = true;
+ }
+
+ async function onIdTokenChanged(firebaseUser: any) {
+ if (firebaseUser == null) {
+ setApiKey("");
+ return;
+ }
+ setAuthHeader(await firebaseUser.getIdToken());
+ }
+
+ async function loadUser() {
+ const response = await apiFetch<{ data: User }>("/v1/users/me");
+ user.value = response.data;
+ }
+
+ async function updateUser(payload: { owner?: string; timezone?: string }) {
+ const phonesStore = usePhonesStore();
+ if (payload.owner) {
+ phonesStore.setOwner(payload.owner);
+ }
+
+ const activePhone = phonesStore.activePhone;
+ if (!activePhone) return;
+
+ const response = await apiFetch<{ data: User }>("/v1/users/me", {
+ method: "PUT",
+ body: {
+ active_phone_id: activePhone.id,
+ timezone: payload.timezone ?? user.value?.timezone,
+ },
+ });
+
+ setApiKey(response.data.api_key);
+ user.value = response.data;
+ }
+
+ async function deleteUserAccount(): Promise<string> {
+ const response = await apiFetch<{ message: string }>("/v1/users/me", {
+ method: "DELETE",
+ });
+ return response.message;
+ }
+
+ async function rotateApiKey(userId: string): Promise<User> {
+ const response = await apiFetch<{ data: User }>(
+ `/v1/users/${userId}/api-keys`,
+ {
+ method: "DELETE",
+ },
+ );
+ user.value = response.data;
+ setApiKey(response.data.api_key);
+ return response.data;
+ }
+
+ function resetState() {
+ user.value = null;
+ authUser.value = null;
+ authStateChanged.value = true;
+ setApiKey("");
+ }
+
+ function loadPhones() {
+ const phonesStore = usePhonesStore();
+ return phonesStore.loadPhones(false);
+ }
+
+ return {
+ authStateChanged,
+ authUser,
+ user,
+ setAuthUserAction,
+ onAuthStateChanged,
+ onIdTokenChanged,
+ loadUser,
+ updateUser,
+ deleteUserAccount,
+ rotateApiKey,
+ resetState,
+ };
+});
diff --git a/web/app/stores/billing.ts b/web/app/stores/billing.ts
new file mode 100644
index 00000000..e280d2ba
--- /dev/null
+++ b/web/app/stores/billing.ts
@@ -0,0 +1,298 @@
+import { defineStore } from "pinia";
+import type { BillingUsage } from "~~/shared/types/billing";
+import type {
+ EntitiesWebhook,
+ EntitiesDiscord,
+ EntitiesMessageSendSchedule,
+ EntitiesPhoneAPIKey,
+ RequestsWebhookStore,
+ RequestsWebhookUpdate,
+ RequestsDiscordStore,
+ RequestsDiscordUpdate,
+ RequestsMessageSendScheduleStore,
+ RequestsUserNotificationUpdate,
+ RequestsUserPaymentInvoice,
+ ResponsesUserSubscriptionPaymentsResponse,
+} from "~~/shared/types/api";
+
+export const useBillingStore = defineStore("billing", () => {
+ const billingUsage = ref<BillingUsage | null>(null);
+ const billingUsageHistory = ref<BillingUsage[]>([]);
+ const { apiFetch } = useApi();
+ const notificationsStore = useNotificationsStore();
+
+ async function loadBillingUsage() {
+ const response = await apiFetch<{ data: BillingUsage }>(
+ "/v1/billing/usage",
+ );
+ billingUsage.value = response.data;
+ }
+
+ async function loadBillingUsageHistory() {
+ const response = await apiFetch<{ data: BillingUsage[] }>(
+ "/v1/billing/usage-history",
+ );
+ billingUsageHistory.value = response.data;
+ }
+
+ async function getSubscriptionUpdateLink(): Promise<string> {
+ const response = await apiFetch<{ data: string }>(
+ "/v1/users/subscription-update-url",
+ );
+ return response.data;
+ }
+
+ async function cancelSubscription(): Promise<string> {
+ const response = await apiFetch<{ message: string }>(
+ "/v1/users/subscription",
+ {
+ method: "DELETE",
+ },
+ );
+ return response.message;
+ }
+
+ async function indexSubscriptionPayments(): Promise<ResponsesUserSubscriptionPaymentsResponse> {
+ const response = await apiFetch<ResponsesUserSubscriptionPaymentsResponse>(
+ "/v1/users/subscription/payments",
+ { params: { limit: 100 } },
+ );
+ return response;
+ }
+
+ async function generateSubscriptionPaymentInvoice(
+ subscriptionInvoiceId: string,
+ request: RequestsUserPaymentInvoice,
+ ): Promise<void> {
+ const response = await apiFetch(
+ `/v1/users/subscription/invoices/${subscriptionInvoiceId}`,
+ {
+ method: "POST",
+ body: request,
+ responseType: "blob",
+ },
+ );
+
+ const pdfBlob = new Blob([response as any], { type: "application/pdf" });
+ const url = window.URL.createObjectURL(pdfBlob);
+ const tempLink = document.createElement("a");
+ tempLink.href = url;
+ tempLink.setAttribute("download", "Invoice.pdf");
+ document.body.appendChild(tempLink);
+ tempLink.click();
+ document.body.removeChild(tempLink);
+ window.URL.revokeObjectURL(url);
+ }
+
+ // Webhooks
+ async function createWebhook(
+ payload: RequestsWebhookStore,
+ ): Promise<EntitiesWebhook> {
+ const response = await apiFetch<{ data: EntitiesWebhook }>("/v1/webhooks", {
+ method: "POST",
+ body: payload,
+ });
+ return response.data;
+ }
+
+ async function getWebhooks(): Promise<EntitiesWebhook[]> {
+ const response = await apiFetch<{ data: EntitiesWebhook[] }>(
+ "/v1/webhooks",
+ {
+ params: { limit: 100 },
+ },
+ );
+ return response.data;
+ }
+
+ async function updateWebhook(
+ payload: RequestsWebhookUpdate & { id: string },
+ ): Promise<EntitiesWebhook> {
+ const response = await apiFetch<{ data: EntitiesWebhook }>(
+ `/v1/webhooks/${payload.id}`,
+ {
+ method: "PUT",
+ body: payload,
+ },
+ );
+ return response.data;
+ }
+
+ async function deleteWebhook(id: string): Promise<void> {
+ await apiFetch(`/v1/webhooks/${id}`, { method: "DELETE" });
+ }
+
+ // Discord
+ async function createDiscord(
+ payload: RequestsDiscordStore,
+ ): Promise<EntitiesDiscord> {
+ const response = await apiFetch<{ data: EntitiesDiscord }>(
+ "/v1/discord-integrations",
+ {
+ method: "POST",
+ body: payload,
+ },
+ );
+ return response.data;
+ }
+
+ async function getDiscordIntegrations(): Promise<EntitiesDiscord[]> {
+ const response = await apiFetch<{ data: EntitiesDiscord[] }>(
+ "/v1/discord-integrations",
+ {
+ params: { limit: 100 },
+ },
+ );
+ return response.data;
+ }
+
+ async function updateDiscordIntegration(
+ payload: RequestsDiscordUpdate & { id: string },
+ ): Promise<EntitiesDiscord> {
+ const response = await apiFetch<{ data: EntitiesDiscord }>(
+ `/v1/discord-integrations/${payload.id}`,
+ {
+ method: "PUT",
+ body: payload,
+ },
+ );
+ return response.data;
+ }
+
+ async function deleteDiscordIntegration(id: string): Promise<void> {
+ await apiFetch(`/v1/discord-integrations/${id}`, { method: "DELETE" });
+ }
+
+ // Send Schedules
+ async function getSendSchedules(): Promise<EntitiesMessageSendSchedule[]> {
+ const response = await apiFetch<{ data: EntitiesMessageSendSchedule[] }>(
+ "/v1/send-schedules",
+ );
+ return response.data;
+ }
+
+ async function createSendSchedule(
+ payload: RequestsMessageSendScheduleStore,
+ ): Promise<EntitiesMessageSendSchedule> {
+ const response = await apiFetch<{ data: EntitiesMessageSendSchedule }>(
+ "/v1/send-schedules",
+ {
+ method: "POST",
+ body: payload,
+ },
+ );
+ return response.data;
+ }
+
+ async function updateSendSchedule(
+ payload: RequestsMessageSendScheduleStore & { id: string },
+ ): Promise<EntitiesMessageSendSchedule> {
+ const response = await apiFetch<{ data: EntitiesMessageSendSchedule }>(
+ `/v1/send-schedules/${payload.id}`,
+ {
+ method: "PUT",
+ body: payload,
+ },
+ );
+ return response.data;
+ }
+
+ async function deleteSendSchedule(id: string): Promise<void> {
+ await apiFetch(`/v1/send-schedules/${id}`, { method: "DELETE" });
+ }
+
+ // Phone API Keys
+ async function storePhoneApiKey(name: string): Promise<EntitiesPhoneAPIKey> {
+ const response = await apiFetch<{
+ data: EntitiesPhoneAPIKey;
+ message: string;
+ }>("/v1/phone-api-keys", {
+ method: "POST",
+ body: { name },
+ });
+ notificationsStore.addNotification({
+ message: response.message,
+ type: "success",
+ });
+ return response.data;
+ }
+
+ async function indexPhoneApiKeys(): Promise<EntitiesPhoneAPIKey[]> {
+ const response = await apiFetch<{ data: EntitiesPhoneAPIKey[] }>(
+ "/v1/phone-api-keys",
+ {
+ params: { limit: 100 },
+ },
+ );
+ return response.data;
+ }
+
+ async function deletePhoneApiKey(id: string): Promise<void> {
+ const response = await apiFetch<{ message: string }>(
+ `/v1/phone-api-keys/${id}`,
+ { method: "DELETE" },
+ );
+ notificationsStore.addNotification({
+ message: response.message,
+ type: "success",
+ });
+ }
+
+ async function deletePhoneFromPhoneApiKey(
+ phoneApiKeyId: string,
+ phoneId: string,
+ ): Promise<void> {
+ const response = await apiFetch<{ message: string }>(
+ `/v1/phone-api-keys/${phoneApiKeyId}/phones/${phoneId}`,
+ { method: "DELETE" },
+ );
+ notificationsStore.addNotification({
+ message: response.message,
+ type: "success",
+ });
+ }
+
+ // Email notifications
+ async function saveEmailNotifications(
+ userId: string,
+ payload: RequestsUserNotificationUpdate,
+ ): Promise<void> {
+ const authStore = useAuthStore();
+ const response = await apiFetch<{ data: any }>(
+ `/v1/users/${userId}/notifications`,
+ {
+ method: "PUT",
+ body: payload,
+ },
+ );
+ authStore.user = response.data;
+ }
+
+ return {
+ billingUsage,
+ billingUsageHistory,
+ loadBillingUsage,
+ loadBillingUsageHistory,
+ getSubscriptionUpdateLink,
+ cancelSubscription,
+ indexSubscriptionPayments,
+ generateSubscriptionPaymentInvoice,
+ createWebhook,
+ getWebhooks,
+ updateWebhook,
+ deleteWebhook,
+ createDiscord,
+ getDiscordIntegrations,
+ updateDiscordIntegration,
+ deleteDiscordIntegration,
+ getSendSchedules,
+ createSendSchedule,
+ updateSendSchedule,
+ deleteSendSchedule,
+ storePhoneApiKey,
+ indexPhoneApiKeys,
+ deletePhoneApiKey,
+ deletePhoneFromPhoneApiKey,
+ saveEmailNotifications,
+ };
+});
diff --git a/web/app/stores/messages.ts b/web/app/stores/messages.ts
new file mode 100644
index 00000000..86955d62
--- /dev/null
+++ b/web/app/stores/messages.ts
@@ -0,0 +1,92 @@
+import { defineStore } from "pinia";
+import type { EntitiesMessage } from "~~/shared/types/api";
+import type { SearchMessagesRequest } from "~~/shared/types/message";
+
+export type SIM = "SIM1" | "SIM2" | "DEFAULT";
+
+export interface SendMessageRequest {
+ from: string;
+ to: string;
+ content: string;
+ sim: SIM;
+ request_id?: string;
+}
+
+export const useMessagesStore = defineStore("messages", () => {
+ const { apiFetch } = useApi();
+ const notificationsStore = useNotificationsStore();
+
+ async function sendMessage(request: SendMessageRequest) {
+ try {
+ const response = await apiFetch<{ message: string }>(
+ "/v1/messages/send",
+ {
+ method: "POST",
+ body: request,
+ },
+ );
+ notificationsStore.addNotification({
+ message: response.message,
+ type: "success",
+ });
+ } catch (e: any) {
+ notificationsStore.addNotification({
+ message: e?.data?.message ?? "Error while sending message",
+ type: "error",
+ });
+ }
+ const threadsStore = useThreadsStore();
+ await threadsStore.loadThreads();
+ }
+
+ async function deleteMessage(messageId: string) {
+ await apiFetch(`/v1/messages/${messageId}`, { method: "DELETE" });
+ notificationsStore.addNotification({
+ message: "The message has been deleted successfully",
+ type: "success",
+ });
+ }
+
+ async function searchMessages(
+ payload: SearchMessagesRequest,
+ ): Promise<EntitiesMessage[]> {
+ const token = payload.token;
+ const params = { ...payload };
+ delete params.token;
+
+ const response = await apiFetch<{ data: EntitiesMessage[] }>(
+ "/v1/messages/search",
+ {
+ params,
+ headers: token ? { token } : undefined,
+ },
+ );
+ return response.data;
+ }
+
+ async function sendBulkMessages(document: File): Promise<void> {
+ const formData = new FormData();
+ formData.append("document", document);
+ const response = await apiFetch<{ message?: string }>("/v1/bulk-messages", {
+ method: "POST",
+ body: formData,
+ });
+ notificationsStore.addNotification({
+ message: response.message ?? "Bulk messages sent successfully",
+ type: "success",
+ });
+ }
+
+ async function fetchBulkMessageOrders(): Promise<any[]> {
+ const response = await apiFetch<{ data: any[] }>("/v1/bulk-messages");
+ return response.data ?? [];
+ }
+
+ return {
+ sendMessage,
+ deleteMessage,
+ searchMessages,
+ sendBulkMessages,
+ fetchBulkMessageOrders,
+ };
+});
diff --git a/web/app/stores/notifications.ts b/web/app/stores/notifications.ts
new file mode 100644
index 00000000..9ce85e7a
--- /dev/null
+++ b/web/app/stores/notifications.ts
@@ -0,0 +1,45 @@
+import { defineStore } from "pinia";
+
+export type NotificationType = "error" | "success" | "info";
+
+export interface Notification {
+ message: string;
+ timeout: number;
+ active: boolean;
+ type: NotificationType;
+}
+
+export interface NotificationRequest {
+ message: string;
+ type: NotificationType;
+}
+
+const DEFAULT_TIMEOUT = 3000;
+
+export const useNotificationsStore = defineStore("notifications", () => {
+ const notification = ref<Notification>({
+ active: false,
+ message: "",
+ type: "success",
+ timeout: DEFAULT_TIMEOUT,
+ });
+
+ function addNotification(request: NotificationRequest) {
+ notification.value = {
+ active: true,
+ message: request.message,
+ type: request.type,
+ timeout: Math.floor(Math.random() * 100) + DEFAULT_TIMEOUT,
+ };
+ }
+
+ function disableNotification() {
+ notification.value.active = false;
+ }
+
+ return {
+ notification,
+ addNotification,
+ disableNotification,
+ };
+});
diff --git a/web/app/stores/phones.ts b/web/app/stores/phones.ts
new file mode 100644
index 00000000..e6c5bbf0
--- /dev/null
+++ b/web/app/stores/phones.ts
@@ -0,0 +1,108 @@
+import { defineStore } from "pinia";
+import type { EntitiesPhone } from "~~/shared/types/api";
+import type { Heartbeat } from "~~/shared/types/heartbeat";
+
+export const usePhonesStore = defineStore("phones", () => {
+ const phones = ref<EntitiesPhone[]>([]);
+ const owner = ref<string | null>(null);
+ const heartbeat = ref<Heartbeat | null>(null);
+ const { apiFetch } = useApi();
+ const notificationsStore = useNotificationsStore();
+
+ const activePhone = computed<EntitiesPhone | null>(() => {
+ return phones.value.find((x) => x.phone_number === owner.value) ?? null;
+ });
+
+ function setOwner(value: string) {
+ owner.value = value;
+ }
+
+ async function loadPhones(force: boolean = false) {
+ if (phones.value.length > 0 && !force) return;
+
+ const response = await apiFetch<{ data: EntitiesPhone[] }>("/v1/phones", {
+ params: { limit: 100 },
+ });
+ phones.value = response.data;
+
+ const authStore = useAuthStore();
+ if (authStore.user?.active_phone_id) {
+ const phone = response.data.find(
+ (x) => x.id === authStore.user?.active_phone_id,
+ );
+ if (phone) {
+ owner.value = phone.phone_number;
+ }
+ }
+
+ if (!owner.value && phones.value.length > 0) {
+ owner.value = phones.value[0].phone_number;
+ }
+ }
+
+ async function deletePhone(phoneID: string) {
+ await apiFetch(`/v1/phones/${phoneID}`, { method: "DELETE" });
+ await loadPhones(true);
+ }
+
+ async function updatePhone(phone: EntitiesPhone) {
+ try {
+ const response = await apiFetch<{ message: string }>("/v1/phones", {
+ method: "PUT",
+ body: {
+ fcm_token: phone.fcm_token,
+ sim: phone.sim,
+ phone_number: phone.phone_number,
+ message_expiration_seconds: parseInt(
+ phone.message_expiration_seconds.toString(),
+ ),
+ missed_call_auto_reply: phone.missed_call_auto_reply,
+ max_send_attempts: parseInt(phone.max_send_attempts.toString()),
+ messages_per_minute: parseInt(phone.messages_per_minute.toString()),
+ message_send_schedule_id: phone.message_send_schedule_id ?? null,
+ },
+ });
+ notificationsStore.addNotification({
+ message: response.message,
+ type: "success",
+ });
+ await loadPhones(true);
+ } catch (error: any) {
+ notificationsStore.addNotification({
+ message: error?.data?.message ?? "Error while updating phone",
+ type: "error",
+ });
+ }
+ }
+
+ async function getHeartbeat(limit = 1): Promise<Heartbeat[]> {
+ const response = await apiFetch<{ data: Heartbeat[] }>("/v1/heartbeats", {
+ params: { limit, owner: owner.value },
+ });
+ if (response.data.length > 0) {
+ heartbeat.value = response.data[0];
+ } else {
+ heartbeat.value = null;
+ }
+ return response.data;
+ }
+
+ function resetState() {
+ phones.value = [];
+ owner.value = null;
+ heartbeat.value = null;
+ }
+
+ return {
+ phones,
+ owner,
+ heartbeat,
+ activePhone,
+ setOwner,
+ loadPhones,
+ deletePhone,
+ updatePhone,
+ getHeartbeat,
+ resetState,
+ };
+});
diff --git a/web/app/stores/threads.ts b/web/app/stores/threads.ts
new file mode 100644
index 00000000..c30b6d8a
--- /dev/null
+++ b/web/app/stores/threads.ts
@@ -0,0 +1,115 @@
+import { defineStore } from "pinia";
+import type { MessageThread } from "~~/shared/types/message-thread";
+import type { Message } from "~~/shared/types/message";
+
+export const useThreadsStore = defineStore("threads", () => {
+ const threads = ref<MessageThread[]>([]);
+ const threadId = ref<string | null>(null);
+ const loadingThreads = ref(true);
+ const archivedThreads = ref(false);
+ const { apiFetch } = useApi();
+ const notificationsStore = useNotificationsStore();
+
+ const currentThread = computed<MessageThread | null>(() => {
+ return threads.value.find((x) => x.id === threadId.value) ?? null;
+ });
+
+ const hasThread = computed(
+ () => threadId.value != null && !loadingThreads.value,
+ );
+
+ function hasThreadId(id: string): boolean {
+ return threads.value.find((x) => x.id === id) !== undefined;
+ }
+
+ async function loadThreads() {
+ const phonesStore = usePhonesStore();
+ if (phonesStore.owner === null && phonesStore.phones.length === 0) {
+ loadingThreads.value = false;
+ return;
+ }
+
+ const response = await apiFetch<{ data: MessageThread[] }>(
+ "/v1/message-threads",
+ {
+ params: {
+ owner: phonesStore.owner ?? phonesStore.phones[0]?.phone_number,
+ limit: 100,
+ is_archived: archivedThreads.value,
+ },
+ },
+ );
+
+ phonesStore.getHeartbeat().catch(console.error);
+ threads.value = [...response.data];
+ loadingThreads.value = false;
+ }
+
+ async function loadThreadMessages(id: string | null): Promise<Message[]> {
+ threadId.value = id;
+ const thread = currentThread.value;
+ if (!thread) throw new Error(`Cannot find thread with id ${id}`);
+
+ const response = await apiFetch<{ data: Message[] }>("/v1/messages", {
+ params: {
+ contact: thread.contact,
+ owner: thread.owner,
+ limit: 50,
+ },
+ });
+ return response.data;
+ }
+
+ function setThreadId(id: string | null) {
+ threadId.value = id;
+ }
+
+ function toggleArchive() {
+ archivedThreads.value = !archivedThreads.value;
+ }
+
+ async function updateThread(payload: {
+ threadId: string;
+ isArchived: boolean;
+ }) {
+ await apiFetch(`/v1/message-threads/${payload.threadId}`, {
+ method: "PUT",
+ body: { is_archived: payload.isArchived },
+ });
+ archivedThreads.value = payload.isArchived;
+ await loadThreads();
+ }
+
+ async function deleteThread(id: string) {
+ await apiFetch(`/v1/message-threads/${id}`, { method: "DELETE" });
+ threadId.value = null;
+ notificationsStore.addNotification({
+ message: "The message thread has been deleted successfully",
+ type: "success",
+ });
+ }
+
+ function resetState() {
+ threads.value = [];
+ threadId.value = null;
+ archivedThreads.value = false;
+ loadingThreads.value = true;
+ }
+
+ return {
+ threads,
+ threadId,
+ loadingThreads,
+ archivedThreads,
+ currentThread,
+ hasThread,
+ hasThreadId,
+ loadThreads,
+ loadThreadMessages,
+ setThreadId,
+ toggleArchive,
+ updateThread,
+ deleteThread,
+ resetState,
+ };
+});