File size: 7,239 Bytes
83a59ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { EntitiesContact } from '~~/shared/types/api'
import { getApiErrorMessage } from '~/utils/api-error'

export interface ContactInput {
  name: string
  emails: string[]
  phone_numbers: string[]
  properties?: Record<string, string>
}

export interface LoadContactsOptions {
  force?: boolean
  skip?: number
  limit?: number
  sortBy?: 'name' | 'updated_at'
  sortDescending?: boolean
}

export interface ContactMutationOptions {
  refresh?: boolean
}

// DEFAULT_LIMIT mirrors the contacts page's initial items-per-page. It is only
// used when a caller (e.g. a mutation refresh) does not specify its own limit.
const DEFAULT_LIMIT = 10

export const useContactsStore = defineStore('contacts', () => {
  const contacts = ref<EntitiesContact[]>([])
  const total = ref(0)
  const loading = ref(false)
  const search = ref('')
  const { apiFetch } = useApi()
  const notificationsStore = useNotificationsStore()
  let loadContactsGeneration = 0

  // The pagination window last requested by the page. Mutation-triggered
  // refreshes reuse it so the user stays on the page they were viewing.
  let currentSkip = 0
  let currentLimit = DEFAULT_LIMIT
  let currentSortBy: 'name' | 'updated_at' = 'updated_at'
  let currentSortDescending = true

  function normalizeOptions(
    options: LoadContactsOptions | boolean,
  ): LoadContactsOptions {
    if (typeof options === 'boolean') {
      return { force: options }
    }
    return options
  }

  async function loadContacts(
    options: LoadContactsOptions | boolean = {},
  ): Promise<void> {
    const {
      force = false,
      skip,
      limit,
      sortBy,
      sortDescending,
    } = normalizeOptions(options)

    if (skip !== undefined) {
      currentSkip = skip
    }
    if (limit !== undefined) {
      currentLimit = limit
    }
    if (sortBy !== undefined) {
      currentSortBy = sortBy
    }
    if (sortDescending !== undefined) {
      currentSortDescending = sortDescending
    }

    if (contacts.value.length > 0 && !force) return

    const generation = ++loadContactsGeneration
    loading.value = true
    try {
      const term = search.value.trim()
      const params: Record<string, string | number | boolean> = {
        skip: currentSkip,
        limit: currentLimit,
        sort_by: currentSortBy,
        sort_descending: currentSortDescending,
      }
      if (term) {
        params.query = term
      }
      const response = await apiFetch<{
        data: EntitiesContact[]
        total?: number
      }>('/v1/contacts', { params })
      if (generation === loadContactsGeneration) {
        contacts.value = response.data ?? []
        total.value = response.total ?? contacts.value.length
      }
    } catch (error: unknown) {
      if (generation !== loadContactsGeneration) {
        return
      }
      notificationsStore.addNotification({
        message: getApiErrorMessage(error, 'Error while loading contacts'),
        type: 'error',
      })
      throw error
    } finally {
      if (generation === loadContactsGeneration) {
        loading.value = false
      }
    }
  }

  async function saveContacts(
    items: ContactInput | ContactInput[],
    options: ContactMutationOptions = {},
  ): Promise<EntitiesContact[]> {
    const contactsToSave = Array.isArray(items) ? items : [items]
    const { refresh = true } = options

    loading.value = true
    try {
      let response: { data: EntitiesContact[] }
      try {
        response = await apiFetch<{ data: EntitiesContact[] }>('/v1/contacts', {
          method: 'POST',
          body: contactsToSave,
        })
      } catch (error: unknown) {
        notificationsStore.addNotification({
          message: getApiErrorMessage(error, 'Error while saving contacts'),
          type: 'error',
        })
        throw error
      }

      notificationsStore.addNotification({
        message:
          contactsToSave.length > 1
            ? 'Contacts created successfully'
            : 'Contact created successfully',
        type: 'success',
      })
      if (refresh) {
        await loadContacts(true)
      }
      return response.data
    } finally {
      loading.value = false
    }
  }

  async function updateContact(
    id: string,
    payload: ContactInput,
    options: ContactMutationOptions = {},
  ): Promise<EntitiesContact> {
    const { refresh = true } = options
    loading.value = true
    try {
      let response: { data: EntitiesContact }
      try {
        response = await apiFetch<{ data: EntitiesContact }>(
          `/v1/contacts/${id}`,
          {
            method: 'PUT',
            body: payload,
          },
        )
      } catch (error: unknown) {
        notificationsStore.addNotification({
          message: getApiErrorMessage(error, 'Error while updating contact'),
          type: 'error',
        })
        throw error
      }

      notificationsStore.addNotification({
        message: 'Contact updated',
        type: 'success',
      })
      if (refresh) {
        await loadContacts(true)
      }
      return response.data
    } finally {
      loading.value = false
    }
  }

  async function deleteContact(id: string): Promise<void> {
    loading.value = true
    try {
      await apiFetch(`/v1/contacts/${id}`, { method: 'DELETE' })
      // Invalidate any in-flight load so a stale response cannot resurrect the
      // just-deleted contact. Bumping the generation makes loadContacts skip
      // its assignment (and its finally toggling loading) for the older request.
      loadContactsGeneration++
      contacts.value = contacts.value.filter((contact) => contact.id !== id)
      total.value = Math.max(0, total.value - 1)
      notificationsStore.addNotification({
        message: 'Contact deleted successfully',
        type: 'success',
      })
    } catch (error: unknown) {
      notificationsStore.addNotification({
        message: getApiErrorMessage(error, 'Error while deleting contact'),
        type: 'error',
      })
      throw error
    } finally {
      loading.value = false
    }
  }

  async function uploadCsv(file: File): Promise<void> {
    loading.value = true
    try {
      try {
        const formData = new FormData()
        formData.append('document', file)

        await apiFetch('/v1/contacts/upload', {
          method: 'POST',
          body: formData,
        })
      } catch (error: unknown) {
        notificationsStore.addNotification({
          message: getApiErrorMessage(error, 'Error while importing contacts'),
          type: 'error',
        })
        throw error
      }

      notificationsStore.addNotification({
        message: 'Contacts imported successfully',
        type: 'success',
      })
      await loadContacts(true)
    } finally {
      loading.value = false
    }
  }

  function resetState() {
    loadContactsGeneration++
    contacts.value = []
    total.value = 0
    loading.value = false
    search.value = ''
    currentSkip = 0
    currentLimit = DEFAULT_LIMIT
  }

  return {
    contacts,
    total,
    loading,
    search,
    loadContacts,
    saveContacts,
    updateContact,
    deleteContact,
    uploadCsv,
    resetState,
  }
})