@dev.smartpricing/message-composer-layer 4.3.2-fix.1 → 4.5.1-automation.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +357 -46
  2. package/app/api/automations.ts +74 -0
  3. package/app/api/brands.ts +20 -13
  4. package/app/api/client.ts +15 -6
  5. package/app/api/compilation.ts +13 -3
  6. package/app/api/dynamicValues.ts +6 -2
  7. package/app/api/index.ts +1 -0
  8. package/app/api/media.ts +6 -3
  9. package/app/api/messageGroups.ts +34 -15
  10. package/app/api/meta.ts +62 -4
  11. package/app/api/organization.ts +10 -1
  12. package/app/api/tracking.ts +2 -2
  13. package/app/app.config.ts +10 -0
  14. package/app/components/Automations/ActionCard.vue +174 -0
  15. package/app/components/Automations/ActionEditor.vue +398 -0
  16. package/app/components/Automations/Actions.vue +158 -0
  17. package/app/components/Automations/CloneModal.vue +78 -0
  18. package/app/components/Automations/Conditions.vue +155 -0
  19. package/app/components/Automations/Create.vue +114 -0
  20. package/app/components/Automations/Data.vue +46 -0
  21. package/app/components/Automations/DeleteModal.vue +80 -0
  22. package/app/components/Automations/Edit.vue +145 -0
  23. package/app/components/Automations/Form.vue +282 -0
  24. package/app/components/Automations/List.vue +370 -0
  25. package/app/components/Automations/PageGate.vue +50 -0
  26. package/app/components/Automations/SaveProblems.vue +54 -0
  27. package/app/components/Automations/Unavailable.vue +71 -0
  28. package/app/components/Automations/UnavailableBadge.vue +35 -0
  29. package/app/components/Common/AppContextErrors.vue +30 -0
  30. package/app/components/Common/HtmlPreviewIframe.vue +17 -3
  31. package/app/components/Common/MessageGroupSelect.vue +193 -26
  32. package/app/components/Common/MessagePreviewSlideover.vue +3 -0
  33. package/app/components/Common/OrganizationGate.vue +51 -0
  34. package/app/components/Common/OrganizationSelect.vue +27 -0
  35. package/app/components/Common/WhatsappNotConfigured.vue +20 -0
  36. package/app/components/Composer/EmailComposer.vue +9 -1
  37. package/app/components/Composer/MessageLibrary.vue +25 -7
  38. package/app/components/Composer/WabaSelectModal.vue +73 -0
  39. package/app/components/Composer/WhatsappComposer.vue +83 -4
  40. package/app/components/Editor/RichTextEditor.vue +14 -2
  41. package/app/components/Filters/DateInput.vue +57 -0
  42. package/app/components/Filters/Editor.vue +163 -0
  43. package/app/components/Filters/Row.vue +119 -0
  44. package/app/components/Filters/Summary.vue +215 -0
  45. package/app/components/Filters/UnavailableRow.vue +74 -0
  46. package/app/components/Filters/ValueInput.vue +215 -0
  47. package/app/components/Layout/BasePage.vue +2 -0
  48. package/app/components/MessageSendFlow/EmailPreview.vue +81 -0
  49. package/app/components/MessageSendFlow/LanguageSelect.vue +39 -0
  50. package/app/components/MessageSendFlow/MessageSendFlow.vue +265 -0
  51. package/app/components/MessageSendFlow/ParametersForm.vue +51 -0
  52. package/app/components/MetaImport/Button.vue +50 -0
  53. package/app/components/MetaImport/Dialog.vue +261 -0
  54. package/app/components/MetaImport/Outcome.vue +136 -0
  55. package/app/components/MetaImport/ProposalList.vue +192 -0
  56. package/app/components/TemplateList/BaseTable.vue +177 -108
  57. package/app/components/Whatsapp/Preview.vue +17 -16
  58. package/app/components/Whatsapp/PreviewPanel.vue +7 -1
  59. package/app/components/Whatsapp/Translator/Header.vue +4 -19
  60. package/app/composables/apiErrorMessages.ts +1 -0
  61. package/app/composables/automationsContext.ts +42 -0
  62. package/app/composables/composerContext.ts +9 -7
  63. package/app/composables/useAutomationClone.ts +33 -0
  64. package/app/composables/useAutomationEditorTrip.ts +77 -0
  65. package/app/composables/useAutomationSaveProblems.ts +82 -0
  66. package/app/composables/useAutomationUnavailable.ts +98 -0
  67. package/app/composables/useAutomationsGate.ts +68 -0
  68. package/app/composables/useBuiltInOptionLists.ts +44 -0
  69. package/app/composables/useEditorTripBack.ts +15 -0
  70. package/app/composables/useEffectiveOrganization.ts +34 -0
  71. package/app/composables/useMessageGroupList.ts +186 -0
  72. package/app/composables/useMessageGroupWaba.ts +76 -0
  73. package/app/composables/useMessageSendFlow.ts +284 -0
  74. package/app/composables/usePagedMessageGroups.ts +78 -0
  75. package/app/composables/useTemplateOperations.ts +31 -7
  76. package/app/composables/useTracking.ts +14 -5
  77. package/app/composables/useWhatsappConfiguration.ts +32 -0
  78. package/app/layouts/default.vue +5 -1
  79. package/app/middleware/automations-enabled.ts +12 -0
  80. package/app/pages/automations/[id].vue +87 -0
  81. package/app/pages/automations/index.vue +28 -0
  82. package/app/pages/automations/new.vue +53 -0
  83. package/app/pages/brands.vue +1 -0
  84. package/app/pages/images.vue +4 -0
  85. package/app/pages/index.vue +6 -1
  86. package/app/pages/preview/[id].vue +2 -0
  87. package/app/pages/template/email/[id].vue +5 -0
  88. package/app/pages/template/email/create.vue +5 -0
  89. package/app/pages/template/whatsapp/[id].vue +6 -0
  90. package/app/pages/template/whatsapp/create.vue +5 -0
  91. package/app/queries/automations.ts +206 -0
  92. package/app/queries/brands.ts +27 -7
  93. package/app/queries/compilation.ts +16 -3
  94. package/app/queries/dynamicValues.ts +19 -2
  95. package/app/queries/index.ts +1 -0
  96. package/app/queries/media.ts +8 -3
  97. package/app/queries/messageGroups.ts +84 -36
  98. package/app/queries/meta.ts +100 -5
  99. package/app/stores/appContext.ts +18 -48
  100. package/app/stores/editorTrip.ts +67 -0
  101. package/app/stores/effectiveOrganization.ts +128 -0
  102. package/app/stores/emailEditor.ts +5 -1
  103. package/app/stores/metaSubmission.ts +7 -17
  104. package/app/types/app-config.d.ts +3 -0
  105. package/app/types/tracking.ts +50 -0
  106. package/app/utils/automations/form.ts +389 -0
  107. package/app/utils/automations/metadata.ts +71 -0
  108. package/app/utils/automations/unavailable.ts +90 -0
  109. package/app/utils/filters/data/countries.json +998 -0
  110. package/app/utils/filters/data/languages.json +754 -0
  111. package/app/utils/filters/rows.ts +367 -0
  112. package/app/utils/testIds.const.ts +137 -0
  113. package/i18n/locales/de.ts +419 -2
  114. package/i18n/locales/en.ts +398 -2
  115. package/i18n/locales/es.ts +403 -2
  116. package/i18n/locales/fr.ts +410 -2
  117. package/i18n/locales/it.ts +409 -2
  118. package/package.json +4 -4
  119. package/app.config.ts +0 -5
@@ -0,0 +1,265 @@
1
+ <script setup lang="ts">
2
+ import type {
3
+ PostEntity,
4
+ RenderType,
5
+ WhatsappMessage,
6
+ } from '@dev.smartpricing/message-composer-utils/types'
7
+ import type { StepperStep } from 'nuxt-ui-layer/types'
8
+ import { computed, ref, watchEffect } from 'vue'
9
+ import MessageGroupSelect from '~/components/Common/MessageGroupSelect.vue'
10
+ import WhatsappPreview from '~/components/Whatsapp/Preview.vue'
11
+ import EmailPreview from './EmailPreview.vue'
12
+ import LanguageSelect from './LanguageSelect.vue'
13
+ import ParametersForm from './ParametersForm.vue'
14
+ import { useMessageSendFlow, type MessageSendFlowEmits } from '~/composables/useMessageSendFlow'
15
+ import type { MessageSendFlowStep } from '~/types/tracking'
16
+ import { messageSendFlowTestIds } from '~/utils/testIds.const'
17
+
18
+ defineOptions({ name: 'MessageSendFlow' })
19
+
20
+ /**
21
+ * Message Send Flow (spec #67): Message → Parameters (with the preview beside
22
+ * both), then one `/compile` on Confirm whose Sendable Message is emitted as
23
+ * `compiled`.
24
+ * The host owns the container and the send; the component keeps its state
25
+ * after `compiled` and never resets itself.
26
+ *
27
+ * Anatomy follows the design system's multi-step form: a vertical `SStepper`
28
+ * in a body sidebar, the step content beside it, the channel preview in a
29
+ * right panel on every step, Cancel/Back left and Next/Confirm right in the
30
+ * container's footer (`actionsTo`).
31
+ */
32
+ const props = withDefaults(
33
+ defineProps<{
34
+ renderType?: RenderType
35
+ /** Preferred language: preselected when approved, else the first approved. */
36
+ language?: string
37
+ /** Editable prefill; keys the Message does not need are ignored. */
38
+ parameters?: Record<string, string>
39
+ /** Brand override passed to `/compile`. */
40
+ brandId?: string
41
+ /**
42
+ * The Organization the flow works on (ADR 0014), e.g. the conversation's.
43
+ * Unset, the one the layer resolved. The flow never shows a selector.
44
+ */
45
+ organizationId?: string
46
+ /**
47
+ * The WABA the Host sends from: only WhatsApp groups on it are offered
48
+ * (ADR 0015). Unset, the groups of every WABA of the Organization.
49
+ */
50
+ wabaId?: string
51
+ /**
52
+ * Where to render the action bar (Cancel, Back, Next, Confirm): a selector
53
+ * or element in the host's container, e.g. a `UModal` footer. Unset, the
54
+ * bar renders under the steps.
55
+ */
56
+ actionsTo?: string | HTMLElement
57
+ }>(),
58
+ { renderType: 'whatsapp_v1' },
59
+ )
60
+
61
+ const groupId = defineModel<string>('messageGroupId')
62
+ const emit = defineEmits<MessageSendFlowEmits>()
63
+
64
+ const { t } = useI18n()
65
+
66
+ const {
67
+ group,
68
+ groupLoading,
69
+ languages,
70
+ sendable,
71
+ selectedLanguage,
72
+ selectedMessage,
73
+ parameterKeys,
74
+ parametersLoading,
75
+ placeholders,
76
+ parameterValues,
77
+ flowError,
78
+ compiling,
79
+ canConfirm,
80
+ confirm,
81
+ trackEvent,
82
+ } = useMessageSendFlow({
83
+ groupId,
84
+ renderType: () => props.renderType,
85
+ preferredLanguage: () => props.language,
86
+ prefill: () => props.parameters,
87
+ brandId: () => props.brandId,
88
+ organizationId: () => props.organizationId,
89
+ wabaId: () => props.wabaId,
90
+ emit,
91
+ })
92
+
93
+ // --- Steps: `useStepperNavigation` keeps each step's status in sync ---------
94
+ const STEP_KEYS: MessageSendFlowStep[] = ['message', 'parameters']
95
+ const steps = ref<StepperStep[]>(
96
+ STEP_KEYS.map((id, index) => ({ id, label: '', status: index === 0 ? 'current' : 'todo' })),
97
+ )
98
+ // Labels follow the locale; statuses are the composable's, so they are patched in place.
99
+ watchEffect(() => {
100
+ for (const step of steps.value) {
101
+ step.label = t(`send_flow.steps.${step.id}.title`)
102
+ step.description = t(`send_flow.steps.${step.id}.description`)
103
+ }
104
+ })
105
+ const activeStepId = ref<string>('message')
106
+ const { currentIndex, canGoBack, goBack, goNext, goToStep } = useStepperNavigation(
107
+ steps,
108
+ activeStepId,
109
+ )
110
+ const currentStep = computed(() => activeStepId.value as MessageSendFlowStep)
111
+ const isLastStep = computed(() => currentIndex.value === steps.value.length - 1)
112
+
113
+ const canNext = computed(() => {
114
+ if (currentStep.value === 'message')
115
+ return !!groupId.value && sendable.value && !!selectedLanguage.value && !groupLoading.value
116
+ // Parameters is the last step: Confirm, not Next (empty fields are its MISSING_PARAMETERS).
117
+ return false
118
+ })
119
+
120
+ const approvedCount = computed(() => languages.value.filter((l) => l.approved).length)
121
+
122
+ // The Preview step is the one channel-specific block.
123
+ const whatsappMessage = computed(() =>
124
+ props.renderType === 'whatsapp_v1'
125
+ ? (selectedMessage.value as PostEntity<WhatsappMessage> | undefined)
126
+ : undefined,
127
+ )
128
+
129
+ function cancel() {
130
+ trackEvent('send_flow.cancel', { step: currentStep.value })
131
+ emit('cancel')
132
+ }
133
+ </script>
134
+
135
+ <template>
136
+ <div class="flex flex-col gap-6" :data-testid="messageSendFlowTestIds.root">
137
+ <UAlert
138
+ v-if="flowError"
139
+ color="error"
140
+ variant="subtle"
141
+ icon="i-lucide-triangle-alert"
142
+ :title="$t('common.error')"
143
+ :description="flowError.message"
144
+ :data-testid="messageSendFlowTestIds.alert"
145
+ />
146
+
147
+ <div class="flex min-h-[420px] gap-6">
148
+ <!-- Done steps are clickable (the stepper's own rule); todo steps only through Next. -->
149
+ <div class="w-[200px] shrink-0 border-r border-default pr-4">
150
+ <SStepper
151
+ v-model="activeStepId"
152
+ :steps="steps"
153
+ :data-testid="messageSendFlowTestIds.stepper"
154
+ @step-click="goToStep"
155
+ />
156
+ </div>
157
+
158
+ <div class="min-w-0 flex-1">
159
+ <div v-if="currentStep === 'message'" class="max-w-md space-y-4">
160
+ <div class="space-y-2">
161
+ <p class="label-lg">{{ $t('send_flow.questions.message') }}</p>
162
+ <div :data-testid="messageSendFlowTestIds.picker">
163
+ <MessageGroupSelect
164
+ v-model="groupId"
165
+ :render-type="renderType"
166
+ :organization-id="organizationId"
167
+ :waba-id="wabaId"
168
+ eligibility="sendable"
169
+ class="w-full"
170
+ />
171
+ </div>
172
+ <p class="text-xs text-muted">{{ $t('send_flow.not_sendable_hint') }}</p>
173
+ </div>
174
+
175
+ <div v-if="group && sendable" class="space-y-2">
176
+ <p class="label-lg">{{ $t('send_flow.questions.language') }}</p>
177
+ <p class="text-sm text-muted">
178
+ {{
179
+ $t('send_flow.language.approved_count', { name: group.name, count: approvedCount })
180
+ }}
181
+ </p>
182
+ <LanguageSelect v-model="selectedLanguage" :languages="languages" />
183
+ </div>
184
+ </div>
185
+
186
+ <div v-else class="max-w-md space-y-3">
187
+ <p class="label-lg">{{ $t('send_flow.questions.parameters') }}</p>
188
+ <ParametersForm
189
+ v-model="parameterValues"
190
+ :parameter-keys="parameterKeys"
191
+ :placeholders="placeholders"
192
+ :loading="parametersLoading"
193
+ />
194
+ </div>
195
+ </div>
196
+
197
+ <!-- The preview follows every step: the picked Message, then the typed values. -->
198
+ <aside
199
+ class="flex w-[400px] shrink-0 flex-col items-center gap-2 border-l border-default pl-6"
200
+ :data-testid="messageSendFlowTestIds.previewPanel"
201
+ >
202
+ <p class="label-lg self-start">{{ $t('send_flow.questions.preview') }}</p>
203
+ <WhatsappPreview
204
+ v-if="whatsappMessage && groupId"
205
+ :message="whatsappMessage"
206
+ :message-group-id="groupId"
207
+ :parameters="parameterValues"
208
+ :data-testid="messageSendFlowTestIds.preview"
209
+ />
210
+ <EmailPreview
211
+ v-else-if="selectedMessage && groupId && selectedLanguage"
212
+ :message-group-id="groupId"
213
+ :language="selectedLanguage"
214
+ :parameters="parameterValues"
215
+ :brand-id="brandId"
216
+ />
217
+ <p v-else class="self-start text-sm text-muted">{{ $t('email_preview.no_preview') }}</p>
218
+ </aside>
219
+ </div>
220
+
221
+ <!-- `defer`: a host footer renders after the body, so the target is resolved after this render. -->
222
+ <Teleport :to="actionsTo" :disabled="!actionsTo" defer>
223
+ <div
224
+ class="flex w-full items-center justify-between"
225
+ :class="{ 'border-t border-default pt-4': !actionsTo }"
226
+ :data-testid="messageSendFlowTestIds.actions"
227
+ >
228
+ <div class="flex gap-2">
229
+ <UButton
230
+ variant="ghost"
231
+ color="neutral"
232
+ :label="$t('send_flow.actions.cancel')"
233
+ :data-testid="messageSendFlowTestIds.cancel"
234
+ @click="cancel"
235
+ />
236
+ <UButton
237
+ v-if="canGoBack"
238
+ variant="outline"
239
+ color="neutral"
240
+ :label="$t('send_flow.actions.back')"
241
+ :data-testid="messageSendFlowTestIds.back"
242
+ @click="goBack()"
243
+ />
244
+ </div>
245
+ <UButton
246
+ v-if="!isLastStep"
247
+ :label="$t('send_flow.actions.next')"
248
+ trailing-icon="i-lucide-arrow-right"
249
+ :disabled="!canNext"
250
+ :data-testid="messageSendFlowTestIds.next"
251
+ @click="goNext()"
252
+ />
253
+ <UButton
254
+ v-else
255
+ :label="$t('send_flow.actions.confirm')"
256
+ icon="i-lucide-send"
257
+ :loading="compiling"
258
+ :disabled="!canConfirm"
259
+ :data-testid="messageSendFlowTestIds.confirm"
260
+ @click="confirm()"
261
+ />
262
+ </div>
263
+ </Teleport>
264
+ </div>
265
+ </template>
@@ -0,0 +1,51 @@
1
+ <script setup lang="ts">
2
+ import { messageSendFlowTestIds } from '~/utils/testIds.const'
3
+
4
+ defineOptions({ name: 'MessageSendFlowParametersForm' })
5
+
6
+ /**
7
+ * One required input per operator parameter of the chosen Message. Labels are
8
+ * humanized from the key (`guest_name` → "Guest name"), placeholders are the
9
+ * organization-level values.
10
+ */
11
+ defineProps<{
12
+ parameterKeys: string[]
13
+ placeholders: Record<string, string>
14
+ loading?: boolean
15
+ }>()
16
+
17
+ const values = defineModel<Record<string, string>>({ required: true })
18
+
19
+ function humanize(key: string): string {
20
+ const words = key.replace(/[_-]+/g, ' ').trim()
21
+ return words.charAt(0).toUpperCase() + words.slice(1)
22
+ }
23
+
24
+ function setValue(key: string, value: string) {
25
+ values.value = { ...values.value, [key]: value }
26
+ }
27
+ </script>
28
+
29
+ <template>
30
+ <div class="space-y-3" :data-testid="messageSendFlowTestIds.parametersForm">
31
+ <div v-if="loading" class="space-y-2">
32
+ <USkeleton class="h-9" />
33
+ <USkeleton class="h-9" />
34
+ </div>
35
+ <template v-else-if="parameterKeys.length">
36
+ <UFormField v-for="key in parameterKeys" :key="key" :label="humanize(key)" required>
37
+ <UInput
38
+ :model-value="values[key] ?? ''"
39
+ :placeholder="placeholders[key]"
40
+ class="w-full"
41
+ :data-testid="messageSendFlowTestIds.parameterInput"
42
+ :data-parameter="key"
43
+ @update:model-value="setValue(key, String($event))"
44
+ />
45
+ </UFormField>
46
+ </template>
47
+ <p v-else class="text-sm text-muted" :data-testid="messageSendFlowTestIds.noParameters">
48
+ {{ $t('send_flow.no_parameters') }}
49
+ </p>
50
+ </div>
51
+ </template>
@@ -0,0 +1,50 @@
1
+ <script setup lang="ts">
2
+ import MetaImportDialog from '~/components/MetaImport/Dialog.vue'
3
+ import { useMetaImportCheckQuery } from '~/queries'
4
+
5
+ /**
6
+ * The Import from Meta button of the Message Group list (ADR 0020). It is
7
+ * there only when a WABA of the Organization holds Meta Templates the
8
+ * composer does not, and says how many. The check behind it runs on its own:
9
+ * the list never waits for it.
10
+ */
11
+ const props = defineProps<{
12
+ /** False until the list has loaded: the check is asked only after it. */
13
+ enabled: boolean
14
+ }>()
15
+
16
+ const emit = defineEmits<{
17
+ /** An Import was confirmed: the list holds new WhatsApp Message Groups. */
18
+ imported: []
19
+ }>()
20
+
21
+ const appContext = useAppContextStore()
22
+ const organization = useEffectiveOrganizationStore()
23
+
24
+ const { data: checks } = useMetaImportCheckQuery({ enabled: () => props.enabled })
25
+
26
+ const count = computed(() => (checks.value ?? []).reduce((sum, check) => sum + check.count, 0))
27
+
28
+ const dialog = useOverlay().create(MetaImportDialog)
29
+
30
+ async function openDialog() {
31
+ const organizationId = organization.organizationId
32
+ const product = appContext.product
33
+ if (!checks.value?.length || !organizationId || !product) return
34
+
35
+ const imported = await dialog.open({ checks: checks.value, organizationId, product }).result
36
+ if (imported) emit('imported')
37
+ }
38
+ </script>
39
+
40
+ <template>
41
+ <UButton
42
+ v-if="count > 0"
43
+ :label="$t('pages.message_library.import_from_meta', { count })"
44
+ icon="ph:download-simple"
45
+ color="neutral"
46
+ variant="outline"
47
+ data-testid="meta-import-button"
48
+ @click="openDialog"
49
+ />
50
+ </template>
@@ -0,0 +1,261 @@
1
+ <script setup lang="ts">
2
+ import type {
3
+ MessageGroupProduct,
4
+ MetaImportProposal,
5
+ MetaImportProposalGroup,
6
+ MetaImportResult,
7
+ MetaImportScope,
8
+ } from '@dev.smartpricing/message-composer-utils/types'
9
+ import { useConfirmMetaImportMutation, useMetaImportProposalQuery } from '~/queries'
10
+ import type { WabaImportCheck } from '~/queries/meta'
11
+
12
+ /**
13
+ * Import from Meta (ADR 0020): the WABA to import from, when the
14
+ * Organization has several; then the proposal, read from Meta; then the
15
+ * outcome. Nothing is written before the user confirms the proposal.
16
+ * Opened through `useOverlay`: closes with whether an Import was confirmed.
17
+ */
18
+ const props = defineProps<{
19
+ /** The Organization's WABAs, each with what the check counted. */
20
+ checks: WabaImportCheck[]
21
+ organizationId: string
22
+ /** The Product the Host supplied: the imported Message Groups belong to it. */
23
+ product: MessageGroupProduct
24
+ }>()
25
+
26
+ const emit = defineEmits<{ close: [imported: boolean] }>()
27
+
28
+ const { metaWabaId } = storeToRefs(useAppContextStore())
29
+
30
+ const severalWabas = props.checks.length > 1
31
+ const step = ref<'waba' | 'proposal' | 'result'>(severalWabas ? 'waba' : 'proposal')
32
+
33
+ // The WABA in the radio group: the Host's when it is one of them, else the
34
+ // first that has something to import.
35
+ const selectedWabaId = ref<string | undefined>(
36
+ (
37
+ props.checks.find(({ waba }) => waba.id === metaWabaId.value) ??
38
+ props.checks.find(({ count }) => count > 0)
39
+ )?.waba.id,
40
+ )
41
+ /** The WABA the proposal is read from: set once the choice is made. */
42
+ const wabaId = ref<string | undefined>(severalWabas ? undefined : props.checks[0]?.waba.id)
43
+
44
+ const wabaItems = computed(() =>
45
+ props.checks.map(({ waba, count }) => ({
46
+ value: waba.id,
47
+ label: waba.name || waba.id,
48
+ numbers: waba.phone_numbers.join(', '),
49
+ count,
50
+ // Not `id`: the radio group gives each item one of its own.
51
+ wabaId: waba.id,
52
+ })),
53
+ )
54
+
55
+ function chooseWaba() {
56
+ wabaId.value = selectedWabaId.value
57
+ step.value = 'proposal'
58
+ }
59
+
60
+ const scope = computed<MetaImportScope | undefined>(() =>
61
+ wabaId.value
62
+ ? { organization_id: props.organizationId, product: props.product, waba_id: wabaId.value }
63
+ : undefined,
64
+ )
65
+
66
+ const { data: proposed, isLoading, error, refetch } = useMetaImportProposalQuery(scope)
67
+
68
+ /** What tells a proposed group from the others: a Meta Template is in one only. */
69
+ const groupKey = (group: MetaImportProposalGroup) => group.templates[0]?.id
70
+
71
+ // The groups of differently named Meta Templates the user split back into
72
+ // the groups their names make. There is no putting them together again.
73
+ const split = ref<Array<string | undefined>>([])
74
+
75
+ function splitGroup(group: MetaImportProposalGroup) {
76
+ split.value = [...split.value, groupKey(group)]
77
+ }
78
+
79
+ /** The proposal as the user left it: what is shown, confirmed and reported on. */
80
+ const proposal = computed<MetaImportProposal | undefined>(() => {
81
+ if (!proposed.value) return undefined
82
+ return {
83
+ ...proposed.value,
84
+ groups: proposed.value.groups.flatMap((group) =>
85
+ group.name_groups && split.value.includes(groupKey(group))
86
+ ? group.name_groups.map((part) => ({ ...part, name_groups: null }))
87
+ : [group],
88
+ ),
89
+ }
90
+ })
91
+
92
+ // Everything that can be imported starts ticked: the user unticks.
93
+ const ticked = ref<string[]>([])
94
+ watch(
95
+ proposed,
96
+ (value) => {
97
+ split.value = []
98
+ ticked.value = (value?.groups ?? []).flatMap((group) =>
99
+ group.templates.filter((template) => template.importable).map((template) => template.id),
100
+ )
101
+ },
102
+ { immediate: true },
103
+ )
104
+
105
+ /** The ticked Meta Templates, grouped as proposed; a group with none ticked is left out. */
106
+ const groupsToImport = computed(() => {
107
+ const tickedIds = new Set(ticked.value)
108
+ return (proposal.value?.groups ?? [])
109
+ .map((group) => ({
110
+ template_ids: group.templates.map(({ id }) => id).filter((id) => tickedIds.has(id)),
111
+ }))
112
+ .filter((group) => group.template_ids.length > 0)
113
+ })
114
+
115
+ const { mutateAsync: confirmImport, isLoading: isImporting } = useConfirmMetaImportMutation()
116
+ const result = shallowRef<MetaImportResult>()
117
+
118
+ async function confirm() {
119
+ if (!scope.value || groupsToImport.value.length === 0) return
120
+ try {
121
+ const answer = await confirmImport({ ...scope.value, groups: groupsToImport.value })
122
+ // A demo session is answered without an outcome: nothing was written.
123
+ result.value = { groups: answer.groups ?? [], refreshed: answer.refreshed ?? [] }
124
+ step.value = 'result'
125
+ } catch {
126
+ // The API client has told the user; the proposal stays to try again.
127
+ }
128
+ }
129
+
130
+ function close() {
131
+ if (isImporting.value) return
132
+ emit('close', !!result.value)
133
+ }
134
+ </script>
135
+
136
+ <template>
137
+ <UModal
138
+ :title="
139
+ step === 'result' ? $t('dialogs.meta_import.result_title') : $t('dialogs.meta_import.title')
140
+ "
141
+ :description="$t('dialogs.meta_import.description')"
142
+ close-icon="ph:x"
143
+ :close="{ onClick: close }"
144
+ :dismissible="false"
145
+ :ui="{ content: 'sm:max-w-3xl' }"
146
+ data-testid="meta-import-dialog"
147
+ >
148
+ <template #body>
149
+ <div v-if="step === 'waba'" class="flex flex-col gap-3">
150
+ <p class="text-sm text-muted">{{ $t('dialogs.meta_import.choose_waba') }}</p>
151
+ <URadioGroup
152
+ v-model="selectedWabaId"
153
+ :items="wabaItems"
154
+ variant="table"
155
+ class="w-full"
156
+ :ui="{ item: 'w-full' }"
157
+ data-testid="meta-import-waba-options"
158
+ >
159
+ <template #description="{ item }">
160
+ <span class="flex flex-col">
161
+ <span>{{ item.numbers || $t('dialogs.select_waba.no_numbers') }}</span>
162
+ <span class="text-xs text-dimmed font-mono">{{ item.wabaId }}</span>
163
+ <span class="text-xs">
164
+ {{ $t('dialogs.meta_import.waba_count', { count: item.count }) }}
165
+ </span>
166
+ </span>
167
+ </template>
168
+ </URadioGroup>
169
+ </div>
170
+
171
+ <MetaImportOutcome
172
+ v-else-if="step === 'result' && result && proposal"
173
+ :result="result"
174
+ :proposal="proposal"
175
+ />
176
+
177
+ <div
178
+ v-else-if="isLoading"
179
+ class="flex items-center justify-center gap-2 py-10 text-sm text-muted"
180
+ data-testid="meta-import-loading"
181
+ >
182
+ <UIcon name="ph:circle-notch" class="size-5 animate-spin" />
183
+ {{ $t('dialogs.meta_import.loading') }}
184
+ </div>
185
+
186
+ <UAlert
187
+ v-else-if="error || !proposal"
188
+ color="error"
189
+ variant="subtle"
190
+ icon="ph:warning-circle"
191
+ :title="$t('dialogs.meta_import.load_failed_title')"
192
+ :description="$t('dialogs.meta_import.load_failed_description')"
193
+ :actions="[
194
+ {
195
+ label: $t('dialogs.meta_import.retry'),
196
+ color: 'neutral',
197
+ variant: 'outline',
198
+ onClick: () => void refetch(),
199
+ },
200
+ ]"
201
+ data-testid="meta-import-load-failed"
202
+ />
203
+
204
+ <MetaImportProposalList
205
+ v-else
206
+ v-model:ticked="ticked"
207
+ :proposal="proposal"
208
+ @split="splitGroup"
209
+ />
210
+ </template>
211
+
212
+ <template #footer>
213
+ <div class="flex items-center gap-2 justify-end w-full">
214
+ <span
215
+ v-if="step === 'proposal' && proposal && !isLoading && !error"
216
+ class="text-sm text-muted mr-auto"
217
+ data-testid="meta-import-selection"
218
+ >
219
+ {{
220
+ $t('dialogs.meta_import.selection', {
221
+ groups: groupsToImport.length,
222
+ templates: ticked.length,
223
+ })
224
+ }}
225
+ </span>
226
+
227
+ <UButton
228
+ v-if="step === 'result'"
229
+ :label="$t('dialogs.meta_import.close')"
230
+ data-testid="meta-import-close"
231
+ @click="close"
232
+ />
233
+ <template v-else>
234
+ <UButton
235
+ variant="outline"
236
+ color="neutral"
237
+ :label="$t('common.actions.cancel')"
238
+ :disabled="isImporting"
239
+ data-testid="meta-import-cancel"
240
+ @click="close"
241
+ />
242
+ <UButton
243
+ v-if="step === 'waba'"
244
+ :label="$t('dialogs.meta_import.continue')"
245
+ :disabled="!selectedWabaId"
246
+ data-testid="meta-import-continue"
247
+ @click="chooseWaba"
248
+ />
249
+ <UButton
250
+ v-else
251
+ :label="$t('dialogs.meta_import.confirm')"
252
+ :loading="isImporting"
253
+ :disabled="isLoading || !!error || groupsToImport.length === 0"
254
+ data-testid="meta-import-confirm"
255
+ @click="confirm"
256
+ />
257
+ </template>
258
+ </div>
259
+ </template>
260
+ </UModal>
261
+ </template>