import { ref } from 'vue' import { defineStore } from 'pinia' import { useLabels } from '@/composables/useLabels' import IvyMessage from '@/views/_components/message/ivyMessage.ts' import { useApiClient } from '@/composables/useApiClient' import { getErrorMessage } from '@/utils/errorHandling' import type { Confirmation } from '@/types/confirmations' /** * Multi-confirmation table operations (search, reorder). REST routes are Pro Essentials; * store lives in Lite and is only used when multiple_confirmations is licensed. */ export const useConfirmationMultiSetting = defineStore('confirmationMultiSetting', () => { const tableData = ref([]) const paginationMeta = ref({ page: 1, perPage: 10, total: 0, }) const { getLabel } = useLabels() const { request } = useApiClient() const searchConfirmations = async ({ page = 1, perPage = 10, search = '', sortBy = 'position', sortOrder = 'asc', filters = {}, formId: filterFormId = null, }: { page?: number perPage?: number search?: string sortBy?: string sortOrder?: string filters?: Record formId?: number | null } = {}) => { try { const mergedFilters = { ...filters } if (filterFormId !== null && filterFormId !== undefined) { mergedFilters.formId = filterFormId } const { data, error } = await request('confirmations/search', { method: 'GET', params: { page, perPage, search, orderBy: sortBy, order: sortOrder, filters: mergedFilters, }, }) if (error) { IvyMessage({ message: `${getLabel('error_fetching_confirmations')} ${getErrorMessage(error)}`, type: 'error', }) return } const response = data?.data?.data tableData.value = (response?.data || []) as Confirmation[] paginationMeta.value = response?.meta || { page: 1, perPage: 10, total: 0 } } catch (error) { IvyMessage({ message: `${getLabel('error_fetching_confirmations')} ${getErrorMessage(error)}`, type: 'error', }) } } const reorderConfirmations = async (formIdValue: number, orderedIds: number[]) => { try { const { error } = await request('/confirmations/reorder', { method: 'POST', data: { formId: formIdValue, orderedIds }, }) if (error) { const apiMessage = typeof error === 'object' && error !== null && 'message' in error && typeof (error as { message?: string }).message === 'string' ? (error as { message: string }).message : getErrorMessage(error) IvyMessage({ message: `${getLabel('error_to_update_confirmation')} ${apiMessage}`, type: 'error', }) return false } return true } catch (error) { IvyMessage({ message: `${getLabel('error_to_update_confirmation')} ${getErrorMessage(error)}`, type: 'error', }) return false } } const loadAllConfirmationsForForm = async (filterFormId: number): Promise => { try { const { data, error, status } = await request(`/confirmations/${filterFormId}`, { method: 'GET', }) if (error || status !== 200) { return [] } return (data?.data?.data || []) as Confirmation[] } catch { return [] } } return { tableData, paginationMeta, searchConfirmations, reorderConfirmations, loadAllConfirmationsForForm, } })