Spaces:
Paused
Paused
File size: 10,545 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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 | <script setup lang="ts">
import {
mdiAccount,
mdiAlertCircleOutline,
mdiClose,
mdiContentSaveCheck,
mdiEmailOutline,
mdiPlus,
} from '@mdi/js'
import { parsePhoneNumberFromString } from 'libphonenumber-js'
import type { EntitiesContact } from '~~/shared/types/api'
import { useContactsStore, type ContactInput } from '~/stores/contacts'
import { toApiError } from '~/utils/api-error'
import { ErrorMessages } from '~/utils/errors'
interface PropertyRow {
key: string
value: string
}
interface PhoneNumberRow {
value: string
country: string
}
interface ContactForm {
name: string
phoneNumbers: PhoneNumberRow[]
emails: string[]
properties: PropertyRow[]
}
const props = withDefaults(
defineProps<{
modelValue: boolean
contact?: EntitiesContact | null
initialPhoneNumber?: string
refreshContacts?: boolean
}>(),
{
contact: null,
initialPhoneNumber: '',
refreshContacts: true,
},
)
const emit = defineEmits<{
saved: [contacts: EntitiesContact[]]
'update:modelValue': [value: boolean]
}>()
const contactsStore = useContactsStore()
const saving = ref(false)
const form = ref<ContactForm>(emptyForm())
const formErrors = ref(new ErrorMessages())
const dialogTitle = computed(() =>
props.contact ? 'Edit Contact' : 'Add Contact',
)
function phoneNumberRow(value = ''): PhoneNumberRow {
return {
value,
country: parsePhoneNumberFromString(value)?.country ?? 'US',
}
}
function emptyForm(): ContactForm {
return {
name: '',
phoneNumbers: [phoneNumberRow(props?.initialPhoneNumber)],
emails: [''],
properties: [{ key: '', value: '' }],
}
}
function resetForm() {
const contact = props.contact
if (!contact) {
form.value = emptyForm()
} else {
const propertyEntries = Object.entries(contact.properties ?? {}).map(
([key, value]) => ({ key, value }),
)
form.value = {
name: contact.name ?? '',
phoneNumbers: contact.phone_numbers?.length
? contact.phone_numbers.map((value) => phoneNumberRow(value))
: [phoneNumberRow()],
emails: contact.emails?.length ? [...contact.emails] : [''],
properties: propertyEntries.length
? propertyEntries
: [{ key: '', value: '' }],
}
}
formErrors.value = new ErrorMessages()
}
function closeDialog() {
emit('update:modelValue', false)
}
function addPhoneNumber() {
form.value.phoneNumbers.push(phoneNumberRow())
}
function removePhoneNumber(index: number) {
form.value.phoneNumbers.splice(index, 1)
if (form.value.phoneNumbers.length === 0) {
form.value.phoneNumbers.push(phoneNumberRow())
}
}
function addEmail() {
form.value.emails.push('')
}
function removeEmail(index: number) {
form.value.emails.splice(index, 1)
if (form.value.emails.length === 0) {
form.value.emails.push('')
}
}
function addProperty() {
form.value.properties.push({ key: '', value: '' })
}
function removeProperty(index: number) {
form.value.properties.splice(index, 1)
if (form.value.properties.length === 0) {
form.value.properties.push({ key: '', value: '' })
}
}
function buildPayload(): ContactInput {
const properties: Record<string, string> = {}
form.value.properties.forEach((row) => {
const key = row.key.trim()
if (key) {
properties[key] = row.value
}
})
return {
name: form.value.name.trim(),
phone_numbers: form.value.phoneNumbers
.map(({ value }) => value.trim())
.filter((value) => value.length > 0),
emails: form.value.emails
.map((value) => value.trim())
.filter((value) => value.length > 0),
properties,
}
}
function validateForm(): boolean {
const bag = new ErrorMessages()
if (form.value.name.trim() === '') {
bag.add('name', 'The name is required.')
}
const hasPhone = form.value.phoneNumbers.some(
({ value }) => value.trim().length > 0,
)
if (!hasPhone) {
bag.add('phone_numbers', 'At least one phone number is required.')
}
formErrors.value = bag
return bag.size() === 0
}
function fieldErrorsFromApi(error: unknown): string[] {
const data = toApiError(error).data?.data
if (!data || typeof data !== 'object') {
return []
}
return Object.values(data).flat()
}
async function submitForm() {
if (!validateForm()) {
return
}
const payload = buildPayload()
saving.value = true
try {
const savedContacts = props.contact
? [
await contactsStore.updateContact(props.contact.id, payload, {
refresh: props.refreshContacts,
}),
]
: await contactsStore.saveContacts([payload], {
refresh: props.refreshContacts,
})
closeDialog()
emit('saved', savedContacts)
} catch (error: unknown) {
const bag = new ErrorMessages()
const messages = fieldErrorsFromApi(error)
if (messages.length > 0) {
bag.addMany('contacts', messages)
}
formErrors.value = bag
} finally {
saving.value = false
}
}
watch(
() => props.modelValue,
(isOpen) => {
if (isOpen) {
resetForm()
}
},
{ immediate: true },
)
</script>
<template>
<VDialog
:model-value="modelValue"
max-width="640"
opacity="0.9"
@update:model-value="emit('update:modelValue', $event)"
>
<VCard>
<VCardTitle class="d-flex align-center">
<span>{{ dialogTitle }}</span>
<VSpacer />
<VBtn
:icon="mdiClose"
variant="text"
color="warning"
size="small"
aria-label="Close dialog"
@click="closeDialog"
/>
</VCardTitle>
<VCardText>
<VAlert
v-if="formErrors.get('contacts').length"
type="error"
variant="tonal"
density="comfortable"
class="mb-4"
:icon="mdiAlertCircleOutline"
>
<ul class="pl-4 mb-0">
<li v-for="message in formErrors.get('contacts')" :key="message">
{{ message }}
</li>
</ul>
</VAlert>
<VTextField
v-model="form.name"
label="Name"
variant="outlined"
density="comfortable"
persistent-placeholder
placeholder="e.g John Doe"
:prepend-inner-icon="mdiAccount"
:error="formErrors.has('name')"
:error-messages="formErrors.get('name')"
class="mb-2"
/>
<div class="d-flex align-center mt-2 mb-1">
<span class="text-subtitle-2">Phone Numbers</span>
<VSpacer />
<VBtn
variant="text"
color="primary"
size="small"
:prepend-icon="mdiPlus"
@click="addPhoneNumber"
>
Add
</VBtn>
</div>
<div
v-for="(phone, index) in form.phoneNumbers"
:key="`phone-${index}`"
class="d-flex align-start ga-2"
>
<div class="mt-2" style="flex: 0 0 92%">
<v-phone-input
v-model="phone.value"
v-model:country="phone.country"
:label="`Phone number ${index + 1}`"
country-label="Country"
placeholder="Phone number e.g 18005550199"
variant="outlined"
density="comfortable"
color="primary"
persistent-placeholder
:error="index === 0 && formErrors.has('phone_numbers')"
:error-messages="
index === 0 ? formErrors.get('phone_numbers') : []
"
/>
</div>
<div style="flex: 0 0 8%">
<VBtn
:icon="mdiClose"
variant="text"
size="small"
class="mt-1"
aria-label="Remove phone number"
@click="removePhoneNumber(index)"
/>
</div>
</div>
<div class="d-flex align-center mt-2 mb-1">
<span class="text-subtitle-2">Email Addresses</span>
<VSpacer />
<VBtn
variant="text"
color="primary"
size="small"
:prepend-icon="mdiPlus"
@click="addEmail"
>
Add
</VBtn>
</div>
<div
v-for="(email, index) in form.emails"
:key="`email-${email}-${index}`"
class="d-flex align-start ga-2"
>
<VTextField
v-model="form.emails[index]"
:label="`Email ${index + 1}`"
placeholder="e.g alice@example.com"
variant="outlined"
autocomplete="email"
type="email"
persistent-placeholder
density="comfortable"
:prepend-inner-icon="mdiEmailOutline"
/>
<VBtn
:icon="mdiClose"
variant="text"
size="small"
class="mt-1"
aria-label="Remove email"
@click="removeEmail(index)"
/>
</div>
<div class="d-flex align-center mt-2 mb-1">
<span class="text-subtitle-2">Properties</span>
<VSpacer />
<VBtn
variant="text"
color="primary"
size="small"
:prepend-icon="mdiPlus"
@click="addProperty"
>
Add
</VBtn>
</div>
<div
v-for="(property, index) in form.properties"
:key="`property-${index}`"
class="d-flex align-start ga-2"
>
<VTextField
v-model="property.key"
label="Key"
variant="outlined"
density="comfortable"
/>
<VTextField
v-model="property.value"
label="Value"
variant="outlined"
density="comfortable"
/>
<VBtn
:icon="mdiClose"
variant="text"
size="small"
class="mt-1"
aria-label="Remove property"
@click="removeProperty(index)"
/>
</div>
</VCardText>
<VCardActions class="pb-4">
<VBtn
color="primary"
variant="flat"
:loading="saving"
:disabled="saving"
:prepend-icon="mdiContentSaveCheck"
@click="submitForm"
>
Save Contact
</VBtn>
<VSpacer />
<VBtn color="warning" variant="text" @click="closeDialog">Close</VBtn>
</VCardActions>
</VCard>
</VDialog>
</template>
|