@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
@@ -1,39 +1,105 @@
1
1
  import { useQuery, useMutation, useQueryCache } from '@pinia/colada'
2
+ import type { MaybeRefOrGetter } from 'vue'
2
3
  import type {
3
4
  DuplicateMessageGroupBody,
4
5
  MessageGroup,
5
- MessageGroupWithMessageSummary,
6
6
  PostEntity,
7
- RenderType,
8
7
  } from '@dev.smartpricing/message-composer-utils/types'
9
8
  import { messageGroupsApi } from '~/api'
9
+ import type { ListMessageGroupsOptions } from '~/api/messageGroups'
10
10
 
11
11
  // QUERIES
12
- export function useMessageGroupsQuery(
13
- options?: MaybeRefOrGetter<{
14
- renderType?: RenderType
15
- tags?: string[]
16
- tagsMode?: 'and' | 'or'
17
- }>,
18
- _queryOptions?: { polling?: boolean },
12
+
13
+ /**
14
+ * Colada merges `{ ...defaults, ...options }`, so forwarding `enabled: undefined`
15
+ * overrides its default `true` and silently disables the query: it then only
16
+ * runs on an explicit `refetch` (the library's 15 s poll, mutation invalidations).
17
+ * Forward `enabled` only when the caller set it.
18
+ */
19
+ function enabledOption(enabled?: MaybeRefOrGetter<boolean>) {
20
+ return enabled === undefined ? {} : { enabled }
21
+ }
22
+ /**
23
+ * One page of the server-side filtered list, in the Laravel envelope (ADR 0012).
24
+ * The previous page stays as placeholder data while the next one loads, so
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).
30
+ */
31
+ export function useMessageGroupListQuery(
32
+ options: MaybeRefOrGetter<ListMessageGroupsOptions>,
33
+ queryOptions: {
34
+ enabled?: MaybeRefOrGetter<boolean>
35
+ organizationId?: MaybeRefOrGetter<string | undefined>
36
+ } = {},
19
37
  ) {
20
- const query = useQuery({
21
- key: () => ['message-groups', JSON.stringify(toValue(options))],
22
- query: () => messageGroupsApi.getAll(toValue(options)),
38
+ const organization = useEffectiveOrganizationStore()
39
+ const listOrganizationId = () =>
40
+ toValue(queryOptions.organizationId) || organization.resolvedOrganizationId
41
+
42
+ return useQuery({
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
+ },
23
54
  staleTime: 0,
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(),
24
61
  })
25
-
26
- // TODO: Implement polling when Pinia Colada supports it
27
- // For now, polling can be done manually in the component using setInterval + refetch
28
-
29
- return query
30
62
  }
31
63
 
32
- export function useMessageGroupQuery(id: MaybeRefOrGetter<string>) {
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
+ */
68
+ export function useMessageGroupQuery(
69
+ id: MaybeRefOrGetter<string>,
70
+ queryOptions: { enabled?: MaybeRefOrGetter<boolean> } = {},
71
+ ) {
33
72
  return useQuery({
34
73
  key: () => ['message-groups', toValue(id)],
35
74
  query: () => messageGroupsApi.getById(toValue(id)),
36
75
  staleTime: 2 * 60 * 1000,
76
+ ...enabledOption(queryOptions.enabled),
77
+ })
78
+ }
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,
37
103
  })
38
104
  }
39
105
 
@@ -100,24 +166,6 @@ export function useDeleteMessageGroupMutation() {
100
166
 
101
167
  return useMutation({
102
168
  mutation: messageGroupsApi.delete,
103
- onMutate: async (id) => {
104
- // Optimistic update
105
- queryCache.cancelQueries({ key: ['message-groups'] })
106
- const previous = queryCache.getQueryData(['message-groups'])
107
-
108
- queryCache.setQueryData(
109
- ['message-groups'],
110
- (old: MessageGroupWithMessageSummary[] | undefined) => old?.filter((g) => g.id !== id),
111
- )
112
-
113
- return { previous }
114
- },
115
- onError: (_, __, context) => {
116
- // Rollback on error
117
- if (context?.previous) {
118
- queryCache.setQueryData(['message-groups'], context.previous)
119
- }
120
- },
121
169
  onSuccess: () => {
122
170
  queryCache.invalidateQueries({ key: ['message-groups'] })
123
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
  }
@@ -1,34 +1,30 @@
1
- import { ref, computed, watch } from 'vue'
2
- import type {
3
- AppContextConfig,
4
- AppContextState,
1
+ import { computed, watch } from 'vue'
2
+ import {
3
+ MESSAGE_GROUP_PRODUCTS,
4
+ type AppContextConfig,
5
5
  } from '@dev.smartpricing/message-composer-utils/types'
6
6
 
7
7
  export const useAppContextStore = defineStore('appContext', () => {
8
8
  const ctx = useComposerContext()
9
9
 
10
- const isInitialized = ref<boolean>(false)
11
-
12
- // Proxy from injection with defaults (same interface as before)
10
+ // Proxy from injection with defaults
13
11
  const organization_id = computed(() => ctx.organization_id?.value ?? '')
14
- const product = computed<NonNullable<AppContextConfig['product']>>(
15
- () => ctx.product?.value ?? 'browser',
16
- )
17
- const strategy = computed<NonNullable<AppContextConfig['strategy']>>(
18
- () => ctx.strategy?.value ?? 'native',
19
- )
12
+ // A Host that passes the key owns the choice of Organization, even while
13
+ // the value is still empty (ADR 0014). Fixed for the session, like the key.
14
+ const hostOwnsOrganization = ctx.organization_id !== undefined
15
+ // The Product is required by the context type (ADR 0011), but a host can
16
+ // still omit it at runtime: read defensively and list it in
17
+ // `validationErrors` rather than crashing or falling back to a fake Product.
18
+ const product = computed<AppContextConfig['product'] | undefined>(() => ctx.product?.value)
20
19
  const channels = computed<NonNullable<AppContextConfig['channels']>>(
21
20
  () => ctx.channels?.value ?? ['email', 'whatsapp'],
22
21
  )
23
22
  const languages = computed<string[]>(() => ctx.languages?.value ?? ['en', 'de', 'fr', 'it', 'es'])
24
23
  const mainLanguage = computed(() => ctx.mainLanguage?.value ?? 'en')
25
- const dinamicValues = computed<Array<{ value: string; label: string }>>(
26
- () => ctx.dinamicValues?.value ?? [],
27
- )
28
24
  const default_tags = computed<string[]>(() => ctx.default_tags?.value ?? [])
29
25
  const isAdmin = computed(() => ctx.isAdmin?.value ?? false)
30
- const metaWabaId = computed(() => ctx.metaWabaId?.value ?? '')
31
- const metaAccessToken = computed(() => ctx.metaAccessToken?.value ?? '')
26
+ // The WABA the Host works on: the target of a new Message Group (ADR 0015).
27
+ const metaWabaId = computed(() => ctx.metaWabaId?.value || undefined)
32
28
 
33
29
  // Sync i18n locale when mainLanguage changes
34
30
  watch(
@@ -41,54 +37,28 @@ export const useAppContextStore = defineStore('appContext', () => {
41
37
  { immediate: true },
42
38
  )
43
39
 
44
- // Computed context object for convenience
45
- const context = computed<AppContextState>(() => ({
46
- product: product.value,
47
- strategy: strategy.value,
48
- channels: channels.value,
49
- languages: languages.value,
50
- mainLanguage: mainLanguage.value,
51
- metaWabaId: metaWabaId.value,
52
- metaAccessToken: metaAccessToken.value,
53
- organization_id: organization_id.value,
54
- default_tags: default_tags.value,
55
- initializationSource: 'injection',
56
- }))
57
-
58
40
  // Validation
59
41
  const validationErrors = computed<Record<string, string>>(() => {
60
42
  const errors: Record<string, string> = {}
61
43
 
62
- if (channels.value?.includes('whatsapp') && !metaWabaId.value) {
63
- errors.metaConfig = 'Meta WABA ID is required for WhatsApp'
44
+ if (!product.value) {
45
+ errors.product = `Product is required: pass \`product\` (${MESSAGE_GROUP_PRODUCTS.join(' | ')}) in the composer context`
64
46
  }
65
47
 
66
48
  return errors
67
49
  })
68
50
 
69
- // Initialize — parent is responsible for providing valid context
70
- async function initialize() {
71
- isInitialized.value = true
72
- }
73
-
74
51
  return {
75
52
  product,
76
- strategy,
77
53
  channels,
78
54
  languages,
79
55
  mainLanguage,
80
- dinamicValues,
81
- metaWabaId,
82
- metaAccessToken,
83
56
  organization_id,
57
+ hostOwnsOrganization,
84
58
  default_tags,
85
59
  isAdmin,
60
+ metaWabaId,
86
61
 
87
- isInitialized: computed(() => isInitialized.value),
88
-
89
- context,
90
62
  validationErrors,
91
-
92
- initialize,
93
63
  }
94
64
  })
@@ -0,0 +1,67 @@
1
+ /** The Message Group an editor saved. */
2
+ export interface EditorTripResult {
3
+ id: string
4
+ name: string
5
+ }
6
+
7
+ export interface EditorTrip<Kept = unknown> {
8
+ /** Where the trip started: the route it returns to, and the back button's label, already translated. */
9
+ origin: { routeName: string; backLabel: string }
10
+ /** What the opener wants back on its return. The editor never reads it. */
11
+ kept: Kept
12
+ /** The last Message Group saved during the trip; none until a save. */
13
+ result?: EditorTripResult
14
+ }
15
+
16
+ /** The pages a trip goes through, by Channel. */
17
+ export const EDITOR_ROUTES = {
18
+ email: { create: 'email-message-create', edit: 'email-message-edit' },
19
+ whatsapp: { create: 'whatsapp-message-create', edit: 'whatsapp-message-edit' },
20
+ } as const
21
+
22
+ const EDITOR_ROUTE_NAMES: ReadonlySet<string> = new Set(
23
+ Object.values(EDITOR_ROUTES).flatMap((routes) => Object.values(routes)),
24
+ )
25
+
26
+ /**
27
+ * A round trip from a page to the Message editor and back. Layer-internal and
28
+ * in memory only: not Host contract, and a reload loses it.
29
+ *
30
+ * The opener starts it and takes it back on its return. The editor knows a
31
+ * trip, not who opened it: it shows the trip's back button and records what
32
+ * it saves.
33
+ */
34
+ export const useEditorTripStore = defineStore('editorTrip', () => {
35
+ const trip = shallowRef<EditorTrip>()
36
+
37
+ // A trip ends where the user leaves its path: an editor opened later, from
38
+ // the library, is not part of it.
39
+ useRouter().afterEach((to, _from, failure) => {
40
+ if (failure || !trip.value) return
41
+ const name = String(to.name)
42
+ if (name === trip.value.origin.routeName || EDITOR_ROUTE_NAMES.has(name)) return
43
+ trip.value = undefined
44
+ })
45
+
46
+ function start<Kept>(origin: EditorTrip['origin'], kept: Kept) {
47
+ trip.value = { origin, kept }
48
+ }
49
+
50
+ /** The last Message Group saved wins, also if the user then cancels. */
51
+ function recordSaved(saved: EditorTripResult) {
52
+ if (trip.value) trip.value = { ...trip.value, result: saved }
53
+ }
54
+
55
+ /** The trip that started on this route, handed over once. */
56
+ function consume<Kept>(routeName: string): EditorTrip<Kept> | undefined {
57
+ const current = trip.value
58
+ if (current?.origin.routeName !== routeName) return undefined
59
+ trip.value = undefined
60
+ return current as EditorTrip<Kept>
61
+ }
62
+
63
+ /** The label of the editor's back button; none without a trip. */
64
+ const backLabel = computed(() => trip.value?.origin.backLabel)
65
+
66
+ return { start, recordSaved, consume, backLabel }
67
+ })
@@ -0,0 +1,128 @@
1
+ import type { ReachableOrganization } from '@dev.smartpricing/message-composer-utils/types'
2
+
3
+ /** Local storage key of the Organization last picked in the selector. */
4
+ const REMEMBERED_ORGANIZATION_KEY = 'message-composer:organization'
5
+
6
+ /**
7
+ * - `resolving`: the Reachable Organizations lookup is running, or the Host
8
+ * that owns the choice has not supplied its Organization yet
9
+ * - `resolved`: there is an Organization to work on
10
+ * - `failed`: the lookup failed, `retry()` runs it again
11
+ * - `none`: the user reaches no Organization
12
+ */
13
+ export type OrganizationResolutionStatus = 'resolving' | 'resolved' | 'failed' | 'none'
14
+
15
+ /**
16
+ * The Effective Organization (ADR 0014): the Organization of the resource
17
+ * being viewed or edited while a page claims one, otherwise the resolved one.
18
+ * A Host that passes `organization_id` owns the choice: the resolved one is
19
+ * its value, and nothing is resolved until that value arrives. Otherwise it
20
+ * is the user's only Reachable Organization; else the remembered selection if
21
+ * still reachable; else the first Reachable Organization.
22
+ */
23
+ export const useEffectiveOrganizationStore = defineStore('effectiveOrganization', () => {
24
+ const appContext = useAppContextStore()
25
+ const { organization_id: hostOrganizationId } = storeToRefs(appContext)
26
+ const { hostOwnsOrganization } = appContext
27
+ const remembered = useLocalStorage(REMEMBERED_ORGANIZATION_KEY, '')
28
+
29
+ /** Undefined until the lookup has answered. */
30
+ const reachable = shallowRef<ReachableOrganization[]>()
31
+ const lookupState = ref<'idle' | 'loading' | 'failed'>('idle')
32
+
33
+ async function lookUp() {
34
+ if (lookupState.value === 'loading') return
35
+ lookupState.value = 'loading'
36
+ try {
37
+ // Imported on demand: the API client reads the runtime config when its
38
+ // module loads, and this store is reachable from plugins that load
39
+ // before the Nuxt app exists (same reason as in `useTracking`).
40
+ const { organizationApi } = await import('~/api/organization')
41
+ reachable.value = await organizationApi.getReachable()
42
+ lookupState.value = 'idle'
43
+ } catch {
44
+ lookupState.value = 'failed'
45
+ }
46
+ }
47
+
48
+ // A Host that supplies the Organization needs no lookup, however late its
49
+ // value arrives: falling back to a Reachable Organization meanwhile would
50
+ // send requests to one the Host did not mean (PAY-2882). Plain state rather
51
+ // than a query: the store outlives whichever component first asks for it.
52
+ if (!hostOwnsOrganization) void lookUp()
53
+
54
+ const reachableOrganizations = computed(() => reachable.value ?? [])
55
+
56
+ const resolvedOrganizationId = computed<string | null>(() => {
57
+ if (hostOwnsOrganization) return hostOrganizationId.value || null
58
+
59
+ const organizations = reachableOrganizations.value
60
+ // Reading `remembered` here is what validates it on load: a selection that
61
+ // is no longer reachable is ignored.
62
+ const selected =
63
+ organizations.length > 1 ? organizations.find((o) => o.id === remembered.value) : undefined
64
+ return (selected ?? organizations[0])?.id ?? null
65
+ })
66
+
67
+ /** The Organization of the resource on screen, and the component that claimed it. */
68
+ const resourceClaim = shallowRef<{ claimant: symbol; organizationId: string }>()
69
+
70
+ const organizationId = computed<string | null>(
71
+ () => resourceClaim.value?.organizationId ?? resolvedOrganizationId.value,
72
+ )
73
+
74
+ /**
75
+ * The Effective Organization for a request that has to name it (ADR 0014).
76
+ * Throws while none is resolved, so a resource request never leaves without
77
+ * its Organization (PAY-2882): callers wait for it to be resolved.
78
+ */
79
+ function requireOrganizationId(): string {
80
+ if (!organizationId.value) {
81
+ throw new Error('[message-composer] No Organization resolved yet: the request was not sent')
82
+ }
83
+ return organizationId.value
84
+ }
85
+
86
+ /** See `useResourceOrganization`: pages do not call this directly. */
87
+ function claimResource(claimant: symbol, id: string | null | undefined) {
88
+ if (id) resourceClaim.value = { claimant, organizationId: id }
89
+ else releaseResource(claimant)
90
+ }
91
+
92
+ // Only the claimant releases: a page that mounts before the previous one is
93
+ // gone must not lose its claim to the other's cleanup.
94
+ function releaseResource(claimant: symbol) {
95
+ if (resourceClaim.value?.claimant === claimant) resourceClaim.value = undefined
96
+ }
97
+
98
+ const status = computed<OrganizationResolutionStatus>(() => {
99
+ if (organizationId.value) return 'resolved'
100
+ if (lookupState.value === 'failed') return 'failed'
101
+ if (lookupState.value === 'idle' && reachable.value) return 'none'
102
+ return 'resolving'
103
+ })
104
+
105
+ /** The selector is offered only when the choice is the user's to make. */
106
+ const isSelectable = computed(
107
+ () => !hostOwnsOrganization && reachableOrganizations.value.length > 1,
108
+ )
109
+
110
+ function select(id: string) {
111
+ if (reachableOrganizations.value.some((o) => o.id === id)) {
112
+ remembered.value = id
113
+ }
114
+ }
115
+
116
+ return {
117
+ organizationId,
118
+ requireOrganizationId,
119
+ resolvedOrganizationId,
120
+ reachableOrganizations,
121
+ status,
122
+ isSelectable,
123
+ select,
124
+ retry: lookUp,
125
+ claimResource,
126
+ releaseResource,
127
+ }
128
+ })
@@ -199,7 +199,11 @@ export const useEmailEditorStore = defineStore('emailEditor', () => {
199
199
  sort_by?: 'created_at' | 'name'
200
200
  direction?: 'asc' | 'desc'
201
201
  }) {
202
- brands.value = await brandsApi.getAll(options)
202
+ // The Brands of the Effective Organization: the edited Message Group's.
203
+ brands.value = await brandsApi.getAll({
204
+ ...options,
205
+ organization_id: useEffectiveOrganizationStore().requireOrganizationId(),
206
+ })
203
207
  return brands.value
204
208
  }
205
209
 
@@ -1,7 +1,6 @@
1
1
  import type { SubmissionJob } from '@dev.smartpricing/message-composer-utils/types'
2
2
  import { metaApi } from '~/api/meta'
3
3
  import { useQueryCache } from '@pinia/colada'
4
- import { useAppContextStore } from './appContext'
5
4
 
6
5
  interface ActiveJob {
7
6
  jobId: string
@@ -12,21 +11,17 @@ interface ActiveJob {
12
11
  export const useMetaSubmissionStore = () => {
13
12
  const toast = useToast()
14
13
  const queryCache = useQueryCache()
15
- const appContext = useAppContextStore()
16
14
  const { t } = useI18n()
17
15
 
18
16
  const activeJobs = useState<Map<string, ActiveJob>>('meta-submission-jobs', () => new Map())
19
17
  const pollingInterval = useState<NodeJS.Timeout | null>('meta-polling-interval', () => null)
20
18
 
21
- const isConfigured = computed(() => !!appContext.metaWabaId)
22
-
23
- const submitToMeta = async (messageGroupId: string) => {
24
- if (!isConfigured.value) {
25
- throw new Error('Meta configuration not available')
26
- }
27
-
19
+ // `wabaId` is the WABA the user picked for a first submission, if any.
20
+ const submitToMeta = async (messageGroupId: string, wabaId?: string) => {
28
21
  try {
29
- const response = await metaApi.submitGroup(messageGroupId)
22
+ const response = await metaApi.submitGroup(messageGroupId, wabaId)
23
+ // The Message Group is on its WABA from now on: read it again.
24
+ queryCache.invalidateQueries({ key: ['message-groups', messageGroupId] })
30
25
  startBackgroundPolling(response.jobId, messageGroupId)
31
26
  return response
32
27
  } catch (error) {
@@ -38,13 +33,9 @@ export const useMetaSubmissionStore = () => {
38
33
  // Submit a single message (one language) for Meta review. Synchronous:
39
34
  // the endpoint submits inline and flips the message to `pending`, so there
40
35
  // is no job to poll — unlike the group flow.
41
- const submitMessageToMeta = async (messageId: string) => {
42
- if (!isConfigured.value) {
43
- throw new Error('Meta configuration not available')
44
- }
45
-
36
+ const submitMessageToMeta = async (messageId: string, wabaId?: string) => {
46
37
  try {
47
- const response = await metaApi.submitMessage(messageId)
38
+ const response = await metaApi.submitMessage(messageId, wabaId)
48
39
  toast.add({
49
40
  color: 'success',
50
41
  title: t('meta_submission.message_success'),
@@ -133,7 +124,6 @@ export const useMetaSubmissionStore = () => {
133
124
  return {
134
125
  activeJobs,
135
126
  hasActiveJobs,
136
- isConfigured,
137
127
  submitToMeta,
138
128
  submitMessageToMeta,
139
129
  startBackgroundPolling,
@@ -2,11 +2,14 @@ declare module 'nuxt/schema' {
2
2
  interface AppConfigInput {
3
3
  composer?: {
4
4
  tracking?: boolean
5
+ /** Turns the Automation pages on (ADR 0019). Off, their routes answer 404. */
6
+ automations?: boolean
5
7
  }
6
8
  }
7
9
  interface AppConfig {
8
10
  composer: {
9
11
  tracking: boolean
12
+ automations: boolean
10
13
  }
11
14
  }
12
15
  }