File size: 5,275 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
<script setup lang="ts">
import { mdiArrowLeft, mdiSend, mdiCircle } from '@mdi/js'
import {
  isValidPhoneNumber,
  getCountryCallingCode,
  parsePhoneNumber,
  type CountryCode,
} from 'libphonenumber-js'
import { getApiErrorMessage, toApiError } from '~/utils/api-error'

definePageMeta({
  middleware: ['auth'],
})

useHead({
  title: 'New Message - httpSMS',
})

const router = useRouter()
const { mdAndDown, mdAndUp } = useVDisplay()
const notificationsStore = useNotificationsStore()
const phonesStore = usePhonesStore()
const { useApi } = useApiComposable()
const { formatPhoneNumber } = useFilters()

const sending = ref(false)
const formPhoneNumber = ref('')
const phoneCountry = ref('US')
const formContent = ref('')
const formAttachments = ref('')
const errors = ref(new Map<string, string[]>())

function getRecipientNumber(): string {
  const phone = formPhoneNumber.value
  if (isValidPhoneNumber(phone)) {
    return phone
  }
  // Short code — strip the country dial code prefix
  const dialCode = getCountryCallingCode(
    phoneCountry.value.toUpperCase() as CountryCode,
  )
  const prefix = `+${dialCode}`
  if (phone.startsWith(prefix)) {
    return phone.slice(prefix.length)
  }
  return phone
}

async function sendMessage() {
  errors.value = new Map()
  sending.value = true

  try {
    const api = useApi()
    await api('/v1/messages/send', {
      method: 'POST',
      body: {
        to: getRecipientNumber(),
        from: phonesStore.owner,
        content: formContent.value,
        sim: 'DEFAULT',
        attachments: formAttachments.value
          .trim()
          .split(',')
          .filter((x) => x.trim() !== '')
          .map((x) => x.trim()),
      },
    })
    notificationsStore.addNotification({
      message: 'Message sent successfully!',
      type: 'success',
    })
    await router.push('/threads')
  } catch (err: unknown) {
    const data = toApiError(err).data?.data
    if (data) {
      const newErrors = new Map<string, string[]>()
      if (data.content) newErrors.set('content', data.content)
      if (data.to)
        newErrors.set(
          'to',
          data.to.map((x: string) =>
            x.replace('to field', 'phone number field'),
          ),
        )
      if (data.attachments) newErrors.set('attachments', data.attachments)
      if (data.from) {
        notificationsStore.addNotification({
          message: data.from[0]!,
          type: 'error',
        })
      }
      errors.value = newErrors
    } else {
      notificationsStore.addNotification({
        message: getApiErrorMessage(err, 'Failed to send message'),
        type: 'error',
      })
    }
  } finally {
    sending.value = false
  }
}

onMounted(async () => {
  await phonesStore.loadPhones()
  if (phonesStore.owner) {
    const country = parsePhoneNumber(phonesStore.owner)?.country
    if (country) {
      phoneCountry.value = country
    }
  }
})
</script>

<template>
  <VContainer fluid :class="{ 'fill-height': true }">
    <div class="w-100 h-100">
      <VAppBar>
        <VBtn icon to="/threads">
          <VIcon :icon="mdiArrowLeft" />
        </VBtn>
        <VToolbarTitle>
          New Message
          <template v-if="phonesStore.owner && mdAndUp">
            <VIcon size="12" class="mx-2" color="primary" :icon="mdiCircle" />
            {{ formatPhoneNumber(phonesStore.owner) }}
          </template>
        </VToolbarTitle>
      </VAppBar>
      <VContainer>
        <VRow>
          <VCol cols="12" md="8" offset-md="2" xl="6" offset-xl="3">
            <p class="mb-8 mt-0">
              Enter the recipient's phone number and your message below, and
              we'll deliver a real SMS it through your connected Android phone.
              You can also text a short code like
              <v-code>24273</v-code> without entering a full phone number.
            </p>
            <form>
              <v-phone-input
                v-model="formPhoneNumber"
                v-model:country="phoneCountry"
                :disabled="sending"
                :error="errors.has('to')"
                :error-messages="errors.get('to')"
                variant="outlined"
                color="primary"
                density="compact"
                persistent-placeholder
                placeholder="Recipient phone number e.g 18005550199"
                label="Phone Number"
                country-label="Country"
              />
              <VTextarea
                v-model="formContent"
                :error="errors.has('content')"
                :error-messages="errors.get('content')"
                :disabled="sending"
                variant="outlined"
                density="compact"
                color="primary"
                persistent-placeholder
                placeholder="Enter your message here"
                label="Content"
              />
              <loading-button
                :disabled="sending"
                :block="mdAndDown"
                :loading="sending"
                :icon="mdiSend"
                @click="sendMessage"
              >
                Send Message
              </loading-button>
            </form>
          </VCol>
        </VRow>
      </VContainer>
    </div>
  </VContainer>
</template>