@dev.smartpricing/message-composer-layer 4.4.1-next.0 → 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 (112) hide show
  1. package/README.md +182 -7
  2. package/app/api/automations.ts +74 -0
  3. package/app/api/brands.ts +20 -13
  4. package/app/api/client.ts +3 -6
  5. package/app/api/dynamicValues.ts +2 -1
  6. package/app/api/index.ts +1 -0
  7. package/app/api/media.ts +6 -3
  8. package/app/api/messageGroups.ts +11 -3
  9. package/app/api/meta.ts +62 -4
  10. package/app/api/organization.ts +10 -1
  11. package/app/api/tracking.ts +2 -2
  12. package/app/app.config.ts +10 -0
  13. package/app/components/Automations/ActionCard.vue +174 -0
  14. package/app/components/Automations/ActionEditor.vue +398 -0
  15. package/app/components/Automations/Actions.vue +158 -0
  16. package/app/components/Automations/CloneModal.vue +78 -0
  17. package/app/components/Automations/Conditions.vue +155 -0
  18. package/app/components/Automations/Create.vue +114 -0
  19. package/app/components/Automations/Data.vue +46 -0
  20. package/app/components/Automations/DeleteModal.vue +80 -0
  21. package/app/components/Automations/Edit.vue +145 -0
  22. package/app/components/Automations/Form.vue +282 -0
  23. package/app/components/Automations/List.vue +370 -0
  24. package/app/components/Automations/PageGate.vue +50 -0
  25. package/app/components/Automations/SaveProblems.vue +54 -0
  26. package/app/components/Automations/Unavailable.vue +71 -0
  27. package/app/components/Automations/UnavailableBadge.vue +35 -0
  28. package/app/components/Common/AppContextErrors.vue +2 -2
  29. package/app/components/Common/MessageGroupSelect.vue +43 -3
  30. package/app/components/Common/OrganizationGate.vue +51 -0
  31. package/app/components/Common/OrganizationSelect.vue +27 -0
  32. package/app/components/Common/WhatsappNotConfigured.vue +20 -0
  33. package/app/components/Composer/EmailComposer.vue +9 -1
  34. package/app/components/Composer/MessageLibrary.vue +8 -0
  35. package/app/components/Composer/WabaSelectModal.vue +73 -0
  36. package/app/components/Composer/WhatsappComposer.vue +83 -4
  37. package/app/components/Editor/RichTextEditor.vue +14 -2
  38. package/app/components/Filters/DateInput.vue +57 -0
  39. package/app/components/Filters/Editor.vue +163 -0
  40. package/app/components/Filters/Row.vue +119 -0
  41. package/app/components/Filters/Summary.vue +215 -0
  42. package/app/components/Filters/UnavailableRow.vue +74 -0
  43. package/app/components/Filters/ValueInput.vue +215 -0
  44. package/app/components/Layout/BasePage.vue +2 -0
  45. package/app/components/MessageSendFlow/EmailPreview.vue +3 -0
  46. package/app/components/MessageSendFlow/MessageSendFlow.vue +15 -2
  47. package/app/components/MetaImport/Button.vue +50 -0
  48. package/app/components/MetaImport/Dialog.vue +261 -0
  49. package/app/components/MetaImport/Outcome.vue +136 -0
  50. package/app/components/MetaImport/ProposalList.vue +192 -0
  51. package/app/components/TemplateList/BaseTable.vue +22 -1
  52. package/app/components/Whatsapp/Preview.vue +5 -12
  53. package/app/components/Whatsapp/Translator/Header.vue +4 -19
  54. package/app/composables/apiErrorMessages.ts +1 -0
  55. package/app/composables/automationsContext.ts +42 -0
  56. package/app/composables/composerContext.ts +5 -5
  57. package/app/composables/useAutomationClone.ts +33 -0
  58. package/app/composables/useAutomationEditorTrip.ts +77 -0
  59. package/app/composables/useAutomationSaveProblems.ts +82 -0
  60. package/app/composables/useAutomationUnavailable.ts +98 -0
  61. package/app/composables/useAutomationsGate.ts +68 -0
  62. package/app/composables/useBuiltInOptionLists.ts +44 -0
  63. package/app/composables/useEditorTripBack.ts +15 -0
  64. package/app/composables/useEffectiveOrganization.ts +34 -0
  65. package/app/composables/useMessageGroupWaba.ts +76 -0
  66. package/app/composables/useMessageSendFlow.ts +46 -8
  67. package/app/composables/usePagedMessageGroups.ts +14 -2
  68. package/app/composables/useTemplateOperations.ts +18 -4
  69. package/app/composables/useTracking.ts +14 -5
  70. package/app/composables/useWhatsappConfiguration.ts +32 -0
  71. package/app/layouts/default.vue +4 -1
  72. package/app/middleware/automations-enabled.ts +12 -0
  73. package/app/pages/automations/[id].vue +87 -0
  74. package/app/pages/automations/index.vue +28 -0
  75. package/app/pages/automations/new.vue +53 -0
  76. package/app/pages/brands.vue +1 -0
  77. package/app/pages/images.vue +4 -0
  78. package/app/pages/index.vue +6 -1
  79. package/app/pages/preview/[id].vue +2 -0
  80. package/app/pages/template/email/[id].vue +5 -0
  81. package/app/pages/template/email/create.vue +5 -0
  82. package/app/pages/template/whatsapp/[id].vue +6 -0
  83. package/app/pages/template/whatsapp/create.vue +5 -0
  84. package/app/queries/automations.ts +206 -0
  85. package/app/queries/brands.ts +27 -7
  86. package/app/queries/compilation.ts +15 -2
  87. package/app/queries/dynamicValues.ts +13 -2
  88. package/app/queries/index.ts +1 -0
  89. package/app/queries/media.ts +8 -3
  90. package/app/queries/messageGroups.ts +60 -25
  91. package/app/queries/meta.ts +100 -5
  92. package/app/stores/appContext.ts +9 -45
  93. package/app/stores/editorTrip.ts +67 -0
  94. package/app/stores/effectiveOrganization.ts +128 -0
  95. package/app/stores/emailEditor.ts +5 -1
  96. package/app/stores/metaSubmission.ts +7 -17
  97. package/app/types/app-config.d.ts +3 -0
  98. package/app/types/tracking.ts +33 -0
  99. package/app/utils/automations/form.ts +389 -0
  100. package/app/utils/automations/metadata.ts +71 -0
  101. package/app/utils/automations/unavailable.ts +90 -0
  102. package/app/utils/filters/data/countries.json +998 -0
  103. package/app/utils/filters/data/languages.json +754 -0
  104. package/app/utils/filters/rows.ts +367 -0
  105. package/app/utils/testIds.const.ts +108 -0
  106. package/i18n/locales/de.ts +363 -0
  107. package/i18n/locales/en.ts +345 -0
  108. package/i18n/locales/es.ts +349 -0
  109. package/i18n/locales/fr.ts +357 -0
  110. package/i18n/locales/it.ts +354 -0
  111. package/package.json +4 -4
  112. package/app.config.ts +0 -5
@@ -7,6 +7,9 @@ definePageMeta({
7
7
 
8
8
  const composerRef = useTemplateRef('composerRef')
9
9
  const store = useWhatsappComposerStore()
10
+ const tripBack = useEditorTripBack(
11
+ () => composerRef.value?.saving || composerRef.value?.isTranslating,
12
+ )
10
13
  </script>
11
14
 
12
15
  <template>
@@ -18,6 +21,8 @@ const store = useWhatsappComposerStore()
18
21
  ]"
19
22
  :active-tab="store.activeTab"
20
23
  :test-id="templateWhatsappCreateTestIds.navbar"
24
+ :back="tripBack"
25
+ @back="composerRef?.handleCancel()"
21
26
  @tab-change="store.activeTab = $event as 'content' | 'translations'"
22
27
  >
23
28
  <template #actions>
@@ -0,0 +1,206 @@
1
+ import { useMutation, useQuery, useQueryCache } from '@pinia/colada'
2
+ import {
3
+ AUTOMATION_CATALOG_LANGUAGES,
4
+ type Automation,
5
+ type AutomationCatalogLanguage,
6
+ type CreateAutomationBody,
7
+ } from '@dev.smartpricing/message-composer-utils/types'
8
+ import type { MaybeRefOrGetter } from 'vue'
9
+ import { toValue } from 'vue'
10
+ import { automationsApi, messageGroupsApi } from '~/api'
11
+ import type { AutomationChanges } from '~/utils/automations/form'
12
+
13
+ function isCatalogLanguage(language: string): language is AutomationCatalogLanguage {
14
+ return (AUTOMATION_CATALOG_LANGUAGES as readonly string[]).includes(language)
15
+ }
16
+
17
+ /** The Automations of the Effective Organization for the Host's Product. */
18
+ export function useAutomationsQuery() {
19
+ const { product } = storeToRefs(useAppContextStore())
20
+ const organization = useEffectiveOrganizationStore()
21
+
22
+ return useQuery({
23
+ key: () => ['automations', product.value ?? '', organization.organizationId],
24
+ query: () =>
25
+ automationsApi.getAll({
26
+ organization_id: organization.requireOrganizationId(),
27
+ product: product.value!,
28
+ }),
29
+ enabled: () => Boolean(product.value && organization.organizationId),
30
+ staleTime: 2 * 60 * 1000,
31
+ })
32
+ }
33
+
34
+ /**
35
+ * One Automation of the Host's Product, read once for the page that edits it:
36
+ * nothing is kept for the next visit, and no refetch replaces what the user
37
+ * is editing. Its key is not under the list's, so a save does not refetch it.
38
+ */
39
+ export function useAutomationQuery(id: MaybeRefOrGetter<string>) {
40
+ const { product } = storeToRefs(useAppContextStore())
41
+ const organization = useEffectiveOrganizationStore()
42
+
43
+ return useQuery({
44
+ key: () => ['automation', product.value ?? '', organization.organizationId, toValue(id)],
45
+ query: () => automationsApi.getById(toValue(id), { product: product.value! }),
46
+ enabled: () => Boolean(product.value && organization.organizationId),
47
+ staleTime: 0,
48
+ gcTime: 0,
49
+ refetchOnWindowFocus: false,
50
+ refetchOnReconnect: false,
51
+ })
52
+ }
53
+
54
+ /**
55
+ * The Automation Catalog of the Host's Product, with its labels in the
56
+ * language of the interface (ADR 0017).
57
+ */
58
+ export function useAutomationCatalogQuery() {
59
+ const { product } = storeToRefs(useAppContextStore())
60
+ const organization = useEffectiveOrganizationStore()
61
+ const { locale } = useI18n()
62
+ const language = computed(() => (isCatalogLanguage(locale.value) ? locale.value : 'en'))
63
+
64
+ return useQuery({
65
+ key: () => [
66
+ 'automation-catalog',
67
+ product.value ?? '',
68
+ language.value,
69
+ organization.organizationId,
70
+ ],
71
+ query: () =>
72
+ automationsApi.getCatalog({
73
+ organization_id: organization.requireOrganizationId(),
74
+ product: product.value!,
75
+ language: language.value,
76
+ }),
77
+ enabled: () => Boolean(product.value && organization.organizationId),
78
+ staleTime: 30 * 60 * 1000,
79
+ })
80
+ }
81
+
82
+ /** A new Automation names its Organization and its Product (ADR 0014, ADR 0019). */
83
+ export function useCreateAutomationMutation() {
84
+ const queryCache = useQueryCache()
85
+ const { product } = storeToRefs(useAppContextStore())
86
+ const organization = useEffectiveOrganizationStore()
87
+
88
+ return useMutation({
89
+ mutation: (automation: Omit<CreateAutomationBody, 'organization_id' | 'product'>) =>
90
+ automationsApi.create({
91
+ ...automation,
92
+ organization_id: organization.requireOrganizationId(),
93
+ product: product.value!,
94
+ }),
95
+ onSuccess: () => {
96
+ queryCache.invalidateQueries({ key: ['automations'] })
97
+ },
98
+ })
99
+ }
100
+
101
+ /** An update names its Product; the Organization is the stored one (ADR 0016). */
102
+ export function useUpdateAutomationMutation() {
103
+ const queryCache = useQueryCache()
104
+ const { product } = storeToRefs(useAppContextStore())
105
+
106
+ return useMutation({
107
+ mutation: ({ id, ...changes }: AutomationChanges & { id: string }) =>
108
+ automationsApi.update(id, { ...changes, product: product.value! }),
109
+ // After a failure too: an update can be saved in part.
110
+ onSettled: () => {
111
+ queryCache.invalidateQueries({ key: ['automations'] })
112
+ },
113
+ })
114
+ }
115
+
116
+ /** A clone names its Product; the copy stays in the source's Organization (ADR 0016). */
117
+ export function useCloneAutomationMutation() {
118
+ const queryCache = useQueryCache()
119
+ const { product } = storeToRefs(useAppContextStore())
120
+
121
+ return useMutation({
122
+ mutation: ({ id, name }: { id: string; name: string }) =>
123
+ automationsApi.clone(id, { name, product: product.value! }),
124
+ // The copy comes with Message Groups of its own. After a failure too: it
125
+ // can be made when the answer is lost.
126
+ onSettled: () => {
127
+ queryCache.invalidateQueries({ key: ['automations'] })
128
+ queryCache.invalidateQueries({ key: ['message-groups'] })
129
+ },
130
+ })
131
+ }
132
+
133
+ /**
134
+ * The Message Groups the Actions of an Automation use, each once, by their
135
+ * current name. One that cannot be read (deleted, or of an Organization the
136
+ * user cannot reach) is left out: it could not be deleted either.
137
+ */
138
+ export function useAutomationMessageGroupsQuery(automation: MaybeRefOrGetter<Automation>) {
139
+ const ids = computed(() => [
140
+ ...new Set(toValue(automation).actions.map((action) => action.config.template.toLowerCase())),
141
+ ])
142
+
143
+ return useQuery({
144
+ key: () => ['automation-message-groups', toValue(automation).id, ...ids.value],
145
+ query: async () => {
146
+ const results = await Promise.allSettled(
147
+ ids.value.map((id) => messageGroupsApi.getById(id, { skipErrorToast: true })),
148
+ )
149
+ return results.flatMap((result) =>
150
+ result.status === 'fulfilled' ? [{ id: result.value.id, name: result.value.name }] : [],
151
+ )
152
+ },
153
+ staleTime: 0,
154
+ gcTime: 0,
155
+ })
156
+ }
157
+
158
+ /**
159
+ * Whether each of these Message Groups is approved in every language, by its
160
+ * id in lower case. One that cannot be read is left out: it is not known to
161
+ * be unapproved. Under `message-groups`, so a change to any of them asks again.
162
+ */
163
+ export function useMessageGroupApprovalsQuery(messageGroupIds: MaybeRefOrGetter<string[]>) {
164
+ const ids = computed(() =>
165
+ [...new Set(toValue(messageGroupIds).map((id) => id.toLowerCase()))].filter(Boolean).sort(),
166
+ )
167
+
168
+ return useQuery({
169
+ key: () => ['message-groups', 'approvals', ...ids.value],
170
+ query: async () => {
171
+ const requested = ids.value
172
+ const results = await Promise.allSettled(
173
+ requested.map((id) => messageGroupsApi.getById(id, { skipErrorToast: true })),
174
+ )
175
+ return new Map(
176
+ results.flatMap((result, index) => {
177
+ if (result.status !== 'fulfilled') return []
178
+ const { messages } = result.value
179
+ const approved =
180
+ messages.length > 0 && messages.every((message) => message.status === 'approved')
181
+ return [[requested[index]!, approved] as const]
182
+ }),
183
+ )
184
+ },
185
+ enabled: () => ids.value.length > 0,
186
+ // The set changes with every Action added or re-pointed: what was known stays while it loads.
187
+ placeholderData: (previous) => previous,
188
+ staleTime: 2 * 60 * 1000,
189
+ })
190
+ }
191
+
192
+ /** A delete names its Product, and the Message Groups that go with the Automation (ADR 0016). */
193
+ export function useDeleteAutomationMutation() {
194
+ const queryCache = useQueryCache()
195
+ const { product } = storeToRefs(useAppContextStore())
196
+
197
+ return useMutation({
198
+ mutation: ({ id, messageGroupIds }: { id: string; messageGroupIds: string[] }) =>
199
+ automationsApi.delete(id, { product: product.value!, message_group_ids: messageGroupIds }),
200
+ // After a failure too: the Automation can be gone when the answer is lost.
201
+ onSettled: (_result, _error, { messageGroupIds }) => {
202
+ queryCache.invalidateQueries({ key: ['automations'] })
203
+ if (messageGroupIds.length > 0) queryCache.invalidateQueries({ key: ['message-groups'] })
204
+ },
205
+ })
206
+ }
@@ -3,20 +3,32 @@ import type {
3
3
  BrandCreateBody,
4
4
  BrandUpdateBody,
5
5
  } from '@dev.smartpricing/message-composer-utils/types'
6
- import { brandsApi, propertiesApi } from '~/api'
6
+ import { brandsApi, propertiesApi, type BrandPreviewRequest } from '~/api'
7
7
 
8
8
  // QUERIES
9
9
  export function useBrandsQuery(options?: {
10
10
  sort_by?: 'created_at' | 'name'
11
11
  direction?: 'asc' | 'desc'
12
12
  }) {
13
+ const organization = useEffectiveOrganizationStore()
14
+
13
15
  return useQuery({
14
- key: () => ['brands', options?.sort_by ?? '', options?.direction ?? ''],
15
- query: () => brandsApi.getAll(options),
16
+ key: () => [
17
+ 'brands',
18
+ options?.sort_by ?? '',
19
+ options?.direction ?? '',
20
+ organization.organizationId,
21
+ ],
22
+ query: () =>
23
+ brandsApi.getAll({ ...options, organization_id: organization.requireOrganizationId() }),
16
24
  staleTime: 2 * 60 * 1000,
17
25
  })
18
26
  }
19
27
 
28
+ /**
29
+ * A Brand by id. No Organization in the key: the request names none, it acts
30
+ * on the Organization of the Brand itself (ADR 0014).
31
+ */
20
32
  export function useBrandQuery(id: MaybeRefOrGetter<string>) {
21
33
  return useQuery({
22
34
  key: () => ['brands', toValue(id)],
@@ -27,19 +39,24 @@ export function useBrandQuery(id: MaybeRefOrGetter<string>) {
27
39
  }
28
40
 
29
41
  export function usePropertiesQuery() {
42
+ const organization = useEffectiveOrganizationStore()
43
+
30
44
  return useQuery({
31
- key: () => ['properties'],
32
- query: () => propertiesApi.getAll(),
45
+ key: () => ['properties', organization.organizationId],
46
+ query: () => propertiesApi.getAll(organization.requireOrganizationId()),
33
47
  staleTime: 10 * 60 * 1000,
34
48
  })
35
49
  }
36
50
 
37
51
  // MUTATIONS
52
+ /** A new Brand names its Organization (ADR 0014): the Effective one. */
38
53
  export function useCreateBrandMutation() {
39
54
  const queryCache = useQueryCache()
55
+ const organization = useEffectiveOrganizationStore()
40
56
 
41
57
  return useMutation({
42
- mutation: (data: BrandCreateBody) => brandsApi.create(data),
58
+ mutation: (data: BrandCreateBody) =>
59
+ brandsApi.create({ ...data, organization_id: organization.requireOrganizationId() }),
43
60
  onSuccess: () => {
44
61
  queryCache.invalidateQueries({ key: ['brands'] })
45
62
  },
@@ -70,7 +87,10 @@ export function useDeleteBrandMutation() {
70
87
  }
71
88
 
72
89
  export function useBrandPreviewMutation() {
90
+ const organization = useEffectiveOrganizationStore()
91
+
73
92
  return useMutation({
74
- mutation: brandsApi.preview,
93
+ mutation: (data: BrandPreviewRequest) =>
94
+ brandsApi.preview({ ...data, organization_id: organization.requireOrganizationId() }),
75
95
  })
76
96
  }
@@ -5,11 +5,18 @@ import { compilationApi } from '~/api'
5
5
  import type {
6
6
  CompileMessageRequest,
7
7
  PreviewMessageRequest,
8
+ TestEmailRequest,
8
9
  } from '@dev.smartpricing/message-composer-utils/types'
9
10
 
10
11
  export function useSendTestEmailMutation() {
12
+ const organization = useEffectiveOrganizationStore()
13
+
11
14
  return useMutation({
12
- mutation: compilationApi.sendTestEmail,
15
+ mutation: (data: TestEmailRequest) =>
16
+ compilationApi.sendTestEmail({
17
+ ...data,
18
+ organization_id: organization.requireOrganizationId(),
19
+ }),
13
20
  })
14
21
  }
15
22
 
@@ -42,7 +49,13 @@ export function useCompileEmailMutation() {
42
49
  }
43
50
 
44
51
  export function usePreviewEmailMutation() {
52
+ const organization = useEffectiveOrganizationStore()
53
+
45
54
  return useMutation({
46
- mutation: (data: PreviewMessageRequest) => compilationApi.previewEmail(data),
55
+ mutation: (data: PreviewMessageRequest) =>
56
+ compilationApi.previewEmail({
57
+ ...data,
58
+ organization_id: organization.requireOrganizationId(),
59
+ }),
47
60
  })
48
61
  }
@@ -6,13 +6,24 @@ import { useAppContextStore } from '~/stores/appContext'
6
6
  export function useDynamicValuesQuery() {
7
7
  const { product, mainLanguage } = storeToRefs(useAppContextStore())
8
8
 
9
+ const organization = useEffectiveOrganizationStore()
10
+
9
11
  return useQuery({
10
- key: () => ['dynamic-values', product.value ?? '', mainLanguage.value],
12
+ key: () => [
13
+ 'dynamic-values',
14
+ product.value ?? '',
15
+ mainLanguage.value,
16
+ organization.organizationId,
17
+ ],
11
18
  // No Product, no request: the picker stays empty and the store lists the
12
19
  // missing Product in `validationErrors`.
13
20
  query: () => {
14
21
  if (!product.value) return Promise.resolve<DynamicValuesResponse>({})
15
- return dynamicValuesApi.get(product.value, mainLanguage.value || 'en')
22
+ return dynamicValuesApi.get(
23
+ product.value,
24
+ mainLanguage.value || 'en',
25
+ organization.requireOrganizationId(),
26
+ )
16
27
  },
17
28
  staleTime: 30 * 60 * 1000,
18
29
  })
@@ -7,3 +7,4 @@ export * from './meta'
7
7
  export * from './compilation'
8
8
  export * from './dynamicValues'
9
9
  export * from './brands'
10
+ export * from './automations'
@@ -2,15 +2,20 @@ import { useMutation, useQuery } from '@pinia/colada'
2
2
  import { mediaApi } from '~/api'
3
3
 
4
4
  export function useMediaQuery() {
5
+ const organization = useEffectiveOrganizationStore()
6
+
5
7
  return useQuery({
6
- key: ['media'],
7
- query: mediaApi.list,
8
+ key: () => ['media', organization.organizationId],
9
+ query: () => mediaApi.list(organization.requireOrganizationId()),
8
10
  })
9
11
  }
10
12
 
13
+ /** An uploaded image names its Organization (ADR 0014): the Effective one. */
11
14
  export function useUploadMediaMutation() {
15
+ const organization = useEffectiveOrganizationStore()
16
+
12
17
  return useMutation({
13
- mutation: mediaApi.upload,
18
+ mutation: (file: File) => mediaApi.upload(file, organization.requireOrganizationId()),
14
19
  })
15
20
  }
16
21
 
@@ -3,7 +3,6 @@ import type { MaybeRefOrGetter } from 'vue'
3
3
  import type {
4
4
  DuplicateMessageGroupBody,
5
5
  MessageGroup,
6
- MessageGroupWithMessageSummary,
7
6
  PostEntity,
8
7
  } from '@dev.smartpricing/message-composer-utils/types'
9
8
  import { messageGroupsApi } from '~/api'
@@ -23,21 +22,49 @@ function enabledOption(enabled?: MaybeRefOrGetter<boolean>) {
23
22
  /**
24
23
  * One page of the server-side filtered list, in the Laravel envelope (ADR 0012).
25
24
  * The previous page stays as placeholder data while the next one loads, so
26
- * paging and filtering never flash an empty table.
25
+ * paging and filtering never flash an empty table. The Organization closes
26
+ * every key, so each Organization has its own cache (ADR 0014). A list is
27
+ * filtered by the resolved Organization, never by the one an editor page
28
+ * claimed for its resource, which may still be held while the list mounts.
29
+ * `organizationId` lists another Organization instead (the Message Send Flow's).
27
30
  */
28
31
  export function useMessageGroupListQuery(
29
32
  options: MaybeRefOrGetter<ListMessageGroupsOptions>,
30
- queryOptions: { enabled?: MaybeRefOrGetter<boolean> } = {},
33
+ queryOptions: {
34
+ enabled?: MaybeRefOrGetter<boolean>
35
+ organizationId?: MaybeRefOrGetter<string | undefined>
36
+ } = {},
31
37
  ) {
38
+ const organization = useEffectiveOrganizationStore()
39
+ const listOrganizationId = () =>
40
+ toValue(queryOptions.organizationId) || organization.resolvedOrganizationId
41
+
32
42
  return useQuery({
33
- key: () => ['message-groups', JSON.stringify(toValue(options))],
34
- query: () => messageGroupsApi.list(toValue(options)),
43
+ key: () => ['message-groups', JSON.stringify(toValue(options)), listOrganizationId()],
44
+ query: () => {
45
+ // No "all Organizations" list in the layer: never ask without the filter.
46
+ const organization_id = listOrganizationId()
47
+ if (!organization_id) {
48
+ throw new Error(
49
+ '[message-composer] No Organization resolved yet: the list was not requested',
50
+ )
51
+ }
52
+ return messageGroupsApi.list({ ...toValue(options), organization_id })
53
+ },
35
54
  staleTime: 0,
36
- placeholderData: (previousData) => previousData,
37
- ...enabledOption(queryOptions.enabled),
55
+ // Never across Organizations: a switch must not show the previous one's rows.
56
+ placeholderData: (previousData, previousEntry) =>
57
+ previousEntry?.key.at(-1) === listOrganizationId() ? previousData : undefined,
58
+ // Until an Organization is resolved the list waits (pending, so callers
59
+ // show it as loading) instead of failing into an empty table.
60
+ enabled: () => toValue(queryOptions.enabled ?? true) && !!listOrganizationId(),
38
61
  })
39
62
  }
40
63
 
64
+ /**
65
+ * A Message Group by id. No Organization in the key: the request names none,
66
+ * it acts on the Organization of the Message Group itself (ADR 0014).
67
+ */
41
68
  export function useMessageGroupQuery(
42
69
  id: MaybeRefOrGetter<string>,
43
70
  queryOptions: { enabled?: MaybeRefOrGetter<boolean> } = {},
@@ -50,6 +77,32 @@ export function useMessageGroupQuery(
50
77
  })
51
78
  }
52
79
 
80
+ /**
81
+ * The names of the Message Groups of these ids, by id. One that cannot be
82
+ * read is missing from the answer: the caller shows what it has instead.
83
+ */
84
+ export function useMessageGroupNamesQuery(ids: MaybeRefOrGetter<string[]>) {
85
+ return useQuery({
86
+ key: () => ['message-groups', 'names', ...toValue(ids)],
87
+ query: async () => {
88
+ const names: Record<string, string> = {}
89
+ await Promise.all(
90
+ toValue(ids).map((id) =>
91
+ messageGroupsApi
92
+ .getById(id)
93
+ .then((group) => {
94
+ names[id] = group.name
95
+ })
96
+ .catch(() => {}),
97
+ ),
98
+ )
99
+ return names
100
+ },
101
+ staleTime: 0,
102
+ enabled: () => toValue(ids).length > 0,
103
+ })
104
+ }
105
+
53
106
  // MUTATIONS
54
107
  export function useCreateMessageGroupMutation() {
55
108
  const queryCache = useQueryCache()
@@ -113,24 +166,6 @@ export function useDeleteMessageGroupMutation() {
113
166
 
114
167
  return useMutation({
115
168
  mutation: messageGroupsApi.delete,
116
- onMutate: async (id) => {
117
- // Optimistic update
118
- queryCache.cancelQueries({ key: ['message-groups'] })
119
- const previous = queryCache.getQueryData(['message-groups'])
120
-
121
- queryCache.setQueryData(
122
- ['message-groups'],
123
- (old: MessageGroupWithMessageSummary[] | undefined) => old?.filter((g) => g.id !== id),
124
- )
125
-
126
- return { previous }
127
- },
128
- onError: (_, __, context) => {
129
- // Rollback on error
130
- if (context?.previous) {
131
- queryCache.setQueryData(['message-groups'], context.previous)
132
- }
133
- },
134
169
  onSuccess: () => {
135
170
  queryCache.invalidateQueries({ key: ['message-groups'] })
136
171
  },
@@ -1,13 +1,108 @@
1
- import { useMutation, useQueryCache } from '@pinia/colada'
1
+ import { useMutation, useQuery, useQueryCache } from '@pinia/colada'
2
+ import type { MaybeRefOrGetter } from 'vue'
3
+ import type {
4
+ MetaImportScope,
5
+ OrganizationWaba,
6
+ } from '@dev.smartpricing/message-composer-utils/types'
2
7
  import { metaApi } from '~/api'
3
8
 
4
- export function useSubmitToMetaMutation() {
9
+ /**
10
+ * The WABAs of the Effective Organization (ADR 0015). Asked only when the
11
+ * Host's channels include WhatsApp and an Organization is resolved.
12
+ */
13
+ export function useOrganizationWabasQuery() {
14
+ const organization = useEffectiveOrganizationStore()
15
+ const { hasWhatsapp } = useChannels()
16
+
17
+ return useQuery({
18
+ key: () => ['organization-wabas', organization.organizationId],
19
+ query: () => metaApi.getWabas(organization.requireOrganizationId()),
20
+ enabled: () => hasWhatsapp.value && !!organization.organizationId,
21
+ staleTime: 5 * 60 * 1000,
22
+ })
23
+ }
24
+
25
+ /** A WABA with how many of its Meta Templates an Import would offer. */
26
+ export interface WabaImportCheck {
27
+ waba: OrganizationWaba
28
+ count: number
29
+ }
30
+
31
+ /**
32
+ * The check of an Import (ADR 0020), for the Message Group list: each WABA of
33
+ * the list's Organization with how many Meta Templates an Import would offer,
34
+ * under the Host's Product. Not asked for an Organization without a WABA. A
35
+ * WABA whose check fails counts zero, like one Meta cannot read.
36
+ */
37
+ export function useMetaImportCheckQuery(options: { enabled?: MaybeRefOrGetter<boolean> } = {}) {
38
+ const organization = useEffectiveOrganizationStore()
39
+ const appContext = useAppContextStore()
40
+ const { data: wabas } = useOrganizationWabasQuery()
41
+
42
+ return useQuery({
43
+ key: () => [
44
+ 'meta-import-check',
45
+ organization.organizationId,
46
+ appContext.product ?? null,
47
+ (wabas.value ?? []).map((waba) => waba.id).join(','),
48
+ ],
49
+ query: (): Promise<WabaImportCheck[]> => {
50
+ const organization_id = organization.requireOrganizationId()
51
+ const product = appContext.product
52
+ if (!product) throw new Error('[message-composer] No Product: the import check was not sent')
53
+
54
+ return Promise.all(
55
+ (wabas.value ?? []).map(async (waba) => {
56
+ const { count } = await metaApi
57
+ .checkImport({ organization_id, product, waba_id: waba.id })
58
+ .catch(() => ({ count: 0 }))
59
+ return { waba, count }
60
+ }),
61
+ )
62
+ },
63
+ enabled: () =>
64
+ toValue(options.enabled ?? true) &&
65
+ !!appContext.product &&
66
+ !!wabas.value?.length &&
67
+ // The list's Organization, not one an editor page still claims while
68
+ // the list mounts.
69
+ organization.organizationId === organization.resolvedOrganizationId,
70
+ // The backend keeps each WABA's count for ten minutes; this only spares
71
+ // the round trip when the list is left and reopened.
72
+ staleTime: 60 * 1000,
73
+ })
74
+ }
75
+
76
+ /**
77
+ * The proposal of an Import, read from Meta when the dialog asks and never
78
+ * reused: the user ticks against exactly what this answered, so nothing
79
+ * refetches it behind their back.
80
+ */
81
+ export function useMetaImportProposalQuery(scope: MaybeRefOrGetter<MetaImportScope | undefined>) {
82
+ return useQuery({
83
+ key: () => ['meta-import-proposal', JSON.stringify(toValue(scope) ?? null)],
84
+ query: () => {
85
+ const value = toValue(scope)
86
+ if (!value) throw new Error('[message-composer] No WABA chosen: the proposal was not asked')
87
+ return metaApi.getImportProposal(value)
88
+ },
89
+ enabled: () => !!toValue(scope),
90
+ staleTime: 0,
91
+ gcTime: 0,
92
+ refetchOnWindowFocus: false,
93
+ refetchOnReconnect: false,
94
+ })
95
+ }
96
+
97
+ /** Confirms an Import. The list and the check are read again whatever the outcome. */
98
+ export function useConfirmMetaImportMutation() {
5
99
  const queryCache = useQueryCache()
6
100
 
7
101
  return useMutation({
8
- mutation: metaApi.submitGroup,
9
- onSuccess: (_, messageGroupId) => {
10
- queryCache.invalidateQueries({ key: ['message-groups', messageGroupId] })
102
+ mutation: metaApi.confirmImport,
103
+ onSettled: () => {
104
+ queryCache.invalidateQueries({ key: ['message-groups'] })
105
+ queryCache.invalidateQueries({ key: ['meta-import-check'] })
11
106
  },
12
107
  })
13
108
  }