@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,77 @@
1
+ import type { Automation } from '@dev.smartpricing/message-composer-utils/types'
2
+ import { EDITOR_ROUTES } from '~/stores/editorTrip'
3
+ import {
4
+ cloneFormData,
5
+ type AutomationFormAction,
6
+ type AutomationFormState,
7
+ } from '~/utils/automations/form'
8
+
9
+ /** The Action in the Action editor. */
10
+ export interface OpenAutomationAction {
11
+ action: AutomationFormAction
12
+ /** Whether the form does not hold it yet. */
13
+ isNew: boolean
14
+ }
15
+
16
+ /** A request to leave for the Message editor: a new Message Group, or the Action's own. */
17
+ export interface AutomationMessageRequest extends OpenAutomationAction {
18
+ target: 'create' | 'edit'
19
+ }
20
+
21
+ /** What an Automation page wants back from an editor trip. */
22
+ interface AutomationTripKept {
23
+ /** The unsaved Automation. */
24
+ form: AutomationFormState
25
+ /** The Automation as the Automation Engine holds it; none on the create page. */
26
+ stored?: Automation
27
+ openAction: OpenAutomationAction
28
+ }
29
+
30
+ /**
31
+ * The Automation side of an editor trip: leaving for the Message editor with
32
+ * the unsaved Automation kept, and getting it back on return with the Action
33
+ * reopened and the Message Group just saved selected in it.
34
+ *
35
+ * Called once, in the setup of the component that holds the form: a trip that
36
+ * started on `origin` is consumed there.
37
+ */
38
+ export function useAutomationEditorTrip(
39
+ origin: 'automation-create' | 'automation-edit',
40
+ automationId?: string,
41
+ ) {
42
+ const { t } = useI18n()
43
+ const toast = useToast()
44
+ const editorTrip = useEditorTripStore()
45
+
46
+ const trip = editorTrip.consume<AutomationTripKept>(origin)
47
+ // The edit page of another Automation is not where the trip started.
48
+ const returned = trip && trip.kept.stored?.id === automationId ? trip : undefined
49
+
50
+ let restored: AutomationTripKept | undefined
51
+ if (returned) {
52
+ const { kept, result } = returned
53
+ // Only the Message Group changes: an Action's status is the user's to set.
54
+ const action = result
55
+ ? { ...kept.openAction.action, messageGroupId: result.id, messageGroupName: result.name }
56
+ : kept.openAction.action
57
+ restored = { ...kept, openAction: { ...kept.openAction, action } }
58
+ toast.add({ title: t('automations.trip.kept'), color: 'info' })
59
+ }
60
+
61
+ /** Leaves for the Message editor, keeping the unsaved Automation and the open Action. */
62
+ function leave(
63
+ unsaved: { form: AutomationFormState; stored?: Automation },
64
+ { action, isNew, target }: AutomationMessageRequest,
65
+ ) {
66
+ editorTrip.start<AutomationTripKept>(
67
+ { routeName: origin, backLabel: t('automations.trip.back') },
68
+ { ...cloneFormData(unsaved), openAction: { action: cloneFormData(action), isNew } },
69
+ )
70
+ const name = EDITOR_ROUTES[action.channel][target]
71
+ return navigateTo(
72
+ target === 'edit' ? { name, params: { id: action.messageGroupId } } : { name },
73
+ )
74
+ }
75
+
76
+ return { restored, leave }
77
+ }
@@ -0,0 +1,82 @@
1
+ import type {
2
+ AutomationCatalog,
3
+ AutomationSaveProblem,
4
+ } from '@dev.smartpricing/message-composer-utils/types'
5
+ import type { MaybeRefOrGetter } from 'vue'
6
+ import type { AutomationFormState } from '~/utils/automations/form'
7
+
8
+ /** One line of the alert: what is wrong and, when it has one, the place to jump to. */
9
+ export interface AutomationProblemLine {
10
+ text: string
11
+ /** The id of the element the line is about. */
12
+ target?: string
13
+ actionKey?: string
14
+ }
15
+
16
+ /**
17
+ * What a refused save (422 `AUTOMATION_ACTIONS_INVALID`) says at the top of
18
+ * the Automation form, on the create page and on the edit page alike.
19
+ * `AutomationsSaveProblems` renders the lines.
20
+ */
21
+ export function useAutomationSaveProblems(catalog: MaybeRefOrGetter<AutomationCatalog>) {
22
+ const { t, te } = useI18n()
23
+
24
+ const lines = ref<AutomationProblemLine[]>([])
25
+ const invalidActionKeys = computed(() =>
26
+ lines.value.flatMap(({ actionKey }) => (actionKey ? [actionKey] : [])),
27
+ )
28
+
29
+ /**
30
+ * The line of one problem. A problem points at an Action by its position
31
+ * in what was submitted; `undefined` for a problem this version does not
32
+ * know.
33
+ */
34
+ function toLine(
35
+ problem: AutomationSaveProblem,
36
+ sent: AutomationFormState,
37
+ ): AutomationProblemLine | undefined {
38
+ if (problem.target === 'trigger') {
39
+ return {
40
+ text: t('automations.problems.trigger_not_in_catalog'),
41
+ target: 'automation-trigger',
42
+ }
43
+ }
44
+
45
+ if (problem.target === 'condition') {
46
+ const key = `automations.problems.condition_${problem.reason}`
47
+ const label =
48
+ toValue(catalog)
49
+ .triggers.find(({ type }) => type === sent.triggerType)
50
+ ?.condition_fields.find((field) => field.key === problem.field)?.label ?? problem.field
51
+ return te(key)
52
+ ? { text: t(key, { field: label }), target: 'automation-conditions' }
53
+ : undefined
54
+ }
55
+
56
+ if (problem.target === 'action') {
57
+ const key = `automations.problems.action_${problem.reason}`
58
+ const action = sent.actions[problem.position]
59
+ if (!action || !te(key)) return undefined
60
+ return {
61
+ text: t(key, { name: action.messageGroupName }),
62
+ target: `automation-action-${action.key}`,
63
+ actionKey: action.key,
64
+ }
65
+ }
66
+
67
+ return undefined
68
+ }
69
+
70
+ /** `sent` is the form as it was submitted: the problems point into it. */
71
+ function show(problems: AutomationSaveProblem[], sent: AutomationFormState) {
72
+ const known = problems.flatMap((problem) => toLine(problem, sent) ?? [])
73
+ // Refused for reasons this version cannot name: still say it was refused.
74
+ lines.value = known.length > 0 ? known : [{ text: t('automations.problems.unknown') }]
75
+ }
76
+
77
+ function clear() {
78
+ lines.value = []
79
+ }
80
+
81
+ return { lines, invalidActionKeys, show, clear }
82
+ }
@@ -0,0 +1,98 @@
1
+ import type { FilterField, FiltersReport } from '@dev.smartpricing/message-composer-utils/types'
2
+ import type { AutomationFormAction } from '~/utils/automations/form'
3
+ import {
4
+ actionUnavailableKinds,
5
+ unavailableBlocks,
6
+ type ActionAvailability,
7
+ type AutomationUnavailableItem,
8
+ type AutomationUnavailableKind,
9
+ } from '~/utils/automations/unavailable'
10
+
11
+ export const AUTOMATION_TRIGGER_ELEMENT_ID = 'automation-trigger'
12
+ export const AUTOMATION_CONDITIONS_ELEMENT_ID = 'automation-conditions'
13
+
14
+ export function automationActionElementId(actionKey: string): string {
15
+ return `automation-action-${actionKey}`
16
+ }
17
+
18
+ /**
19
+ * The unavailable things of an Automation as the form says them: one item
20
+ * each, with where it is, its sentence and whether it blocks the save.
21
+ * `AutomationsUnavailable` lists them, `AutomationsUnavailableBadge` marks
22
+ * one in place.
23
+ */
24
+ export function useAutomationUnavailable() {
25
+ const { t } = useI18n()
26
+
27
+ function item(
28
+ kind: AutomationUnavailableKind,
29
+ rest: Omit<AutomationUnavailableItem, 'kind' | 'blocks' | 'text'>,
30
+ params: Record<string, string> = {},
31
+ ): AutomationUnavailableItem {
32
+ return {
33
+ kind,
34
+ blocks: unavailableBlocks(kind),
35
+ text: t(`automations.unavailable.${kind}`, params),
36
+ ...rest,
37
+ }
38
+ }
39
+
40
+ /** A Trigger the Automation Catalog no longer lists. */
41
+ function triggerItem(): AutomationUnavailableItem {
42
+ return item('trigger', {
43
+ key: 'trigger',
44
+ where: t('automations.form.trigger'),
45
+ target: AUTOMATION_TRIGGER_ELEMENT_ID,
46
+ })
47
+ }
48
+
49
+ /** What the filter components report on a list of Conditions (ADR 0018). */
50
+ function conditionItems(
51
+ report: FiltersReport | undefined,
52
+ fields: readonly FilterField[],
53
+ ): AutomationUnavailableItem[] {
54
+ if (!report) return []
55
+
56
+ const where = (field: string) =>
57
+ t('automations.unavailable.where.filter', {
58
+ field: fields.find(({ key }) => key === field)?.label ?? field,
59
+ })
60
+ const place = { target: AUTOMATION_CONDITIONS_ELEMENT_ID, inFilters: true }
61
+
62
+ return [
63
+ ...report.unavailable.map(({ condition, reason }, index) =>
64
+ item(reason === 'unknown_field' ? 'condition_unknown_field' : 'condition_not_editable', {
65
+ key: `condition-${index}`,
66
+ where: where(condition.field),
67
+ ...place,
68
+ }),
69
+ ),
70
+ ...report.unavailableOptions.map(({ field }, index) =>
71
+ item('option', { key: `option-${index}`, where: where(field), ...place }),
72
+ ),
73
+ ]
74
+ }
75
+
76
+ function actionItems(
77
+ action: AutomationFormAction,
78
+ availability: ActionAvailability,
79
+ ): AutomationUnavailableItem[] {
80
+ const channel = t(`automations.channels.${action.channel}`)
81
+
82
+ return actionUnavailableKinds(action, availability).map((kind) =>
83
+ item(
84
+ kind,
85
+ {
86
+ key: `${action.key}-${kind}`,
87
+ where: t('automations.unavailable.where.message', {
88
+ name: action.messageGroupName || channel,
89
+ }),
90
+ target: automationActionElementId(action.key),
91
+ },
92
+ { channel },
93
+ ),
94
+ )
95
+ }
96
+
97
+ return { triggerItem, conditionItems, actionItems }
98
+ }
@@ -0,0 +1,68 @@
1
+ import type { AutomationCatalog } from '@dev.smartpricing/message-composer-utils/types'
2
+ import type { AutomationsContext } from './automationsContext'
3
+
4
+ export type AutomationsGate =
5
+ | { state: 'ready'; catalog: AutomationCatalog; context: AutomationsContext }
6
+ | { state: 'loading' }
7
+ | { state: 'error'; title: string; description: string; retry?: () => void }
8
+
9
+ /**
10
+ * What an Automation page needs before it can show anything: the Host's
11
+ * Automations context, an Organization and an Automation Catalog for the
12
+ * Host's Product. Checked by the page, not by the layout, so a Host that
13
+ * replaces the layout keeps it (ADR 0019). `AutomationsPageGate` renders it.
14
+ */
15
+ export function useAutomationsGate() {
16
+ const { t } = useI18n()
17
+ const context = useAutomationsContext()
18
+ const organization = useEffectiveOrganizationStore()
19
+ const catalogQuery = useAutomationCatalogQuery()
20
+ const { product } = storeToRefs(useAppContextStore())
21
+
22
+ return computed<AutomationsGate>(() => {
23
+ if (!context) {
24
+ return {
25
+ state: 'error',
26
+ title: t('automations.gate.no_context_title'),
27
+ description: t('automations.gate.no_context_description'),
28
+ }
29
+ }
30
+
31
+ if (organization.status === 'resolving') return { state: 'loading' }
32
+ if (organization.status === 'failed') {
33
+ return {
34
+ state: 'error',
35
+ title: t('common.organization.lookup_failed_title'),
36
+ description: t('common.organization.lookup_failed_description'),
37
+ retry: () => void organization.retry(),
38
+ }
39
+ }
40
+ if (organization.status === 'none') {
41
+ return {
42
+ state: 'error',
43
+ title: t('automations.gate.no_organization_title'),
44
+ description: t('automations.gate.no_organization_description'),
45
+ }
46
+ }
47
+
48
+ const response = catalogQuery.data.value
49
+ if (response?.catalog) return { state: 'ready', catalog: response.catalog, context }
50
+ // Answered with no catalog, or nothing to ask for: no Product, no request.
51
+ if (response || !product.value) {
52
+ return {
53
+ state: 'error',
54
+ title: t('automations.gate.no_catalog_title'),
55
+ description: t('automations.gate.no_catalog_description'),
56
+ }
57
+ }
58
+ if (catalogQuery.status.value === 'error') {
59
+ return {
60
+ state: 'error',
61
+ title: t('automations.gate.catalog_failed_title'),
62
+ description: t('automations.gate.catalog_failed_description'),
63
+ retry: () => void catalogQuery.refetch(),
64
+ }
65
+ }
66
+ return { state: 'loading' }
67
+ })
68
+ }
@@ -0,0 +1,44 @@
1
+ import type { FilterOption } from '@dev.smartpricing/message-composer-utils/types'
2
+ import countries from '../utils/filters/data/countries.json'
3
+ import languages from '../utils/filters/data/languages.json'
4
+
5
+ /** The name of a code in a language, or the English one where `Intl` has none. */
6
+ function toOptions(
7
+ entries: { code: string; name: string }[],
8
+ type: 'region' | 'language',
9
+ locale: string,
10
+ ): FilterOption[] {
11
+ let names: Intl.DisplayNames | undefined
12
+ try {
13
+ names = new Intl.DisplayNames([locale], { type, fallback: 'none' })
14
+ } catch {
15
+ // A locale `Intl` does not know: the English names.
16
+ }
17
+
18
+ const options = entries.map(({ code, name }) => {
19
+ let label: string | undefined
20
+ try {
21
+ label = names?.of(type === 'region' ? code.toUpperCase() : code)
22
+ } catch {
23
+ // A code `Intl` rejects keeps its English name.
24
+ }
25
+ return { value: code, label: label ?? name }
26
+ })
27
+
28
+ return options.sort((a, b) => a.label.localeCompare(b.label, locale))
29
+ }
30
+
31
+ /**
32
+ * Public (ADR 0018): the sets built into the layer, as option lists in the
33
+ * current language, sorted by label. The values are lowercase ISO codes
34
+ * (`it`, `de`), the ones Smartconnect stores. For any caller of the filter
35
+ * components, and for a Host to pass on in `defineAutomationsContext`.
36
+ */
37
+ export function useBuiltInOptionLists() {
38
+ const { locale } = useI18n()
39
+
40
+ const countryOptions = computed(() => toOptions(countries, 'region', locale.value))
41
+ const languageOptions = computed(() => toOptions(languages, 'language', locale.value))
42
+
43
+ return { countries: countryOptions, languages: languageOptions }
44
+ }
@@ -0,0 +1,15 @@
1
+ import type { ButtonProps } from '#ui/types'
2
+
3
+ /**
4
+ * The back button of an editor page while an editor trip exists; none
5
+ * otherwise. It does what Cancel does, so it is busy whenever Cancel is.
6
+ */
7
+ export function useEditorTripBack(busy: MaybeRefOrGetter<boolean | undefined>) {
8
+ const editorTrip = useEditorTripStore()
9
+
10
+ return computed<ButtonProps | undefined>(() =>
11
+ editorTrip.backLabel === undefined
12
+ ? undefined
13
+ : { label: editorTrip.backLabel, loading: Boolean(toValue(busy)) },
14
+ )
15
+ }
@@ -0,0 +1,34 @@
1
+ import type { MaybeRefOrGetter } from 'vue'
2
+
3
+ /**
4
+ * Read-only view of the Organization the layer is working with, for the Host:
5
+ * e.g. to supply per-Organization `organizationData`. On an editor or preview
6
+ * page it is the Organization of the loaded Message Group, whatever the
7
+ * selector says. `organizationId` is `null` until `status` is `resolved`.
8
+ */
9
+ export function useEffectiveOrganization() {
10
+ const { organizationId, status } = storeToRefs(useEffectiveOrganizationStore())
11
+ return { organizationId, status }
12
+ }
13
+
14
+ /**
15
+ * Makes the Organization of the resource a page views or edits the Effective
16
+ * Organization for as long as the calling component lives, so every dependent
17
+ * query (Brands, images, dynamic values) and everything the page creates
18
+ * follows the resource, not the selector (ADR 0014). Pass the Organization
19
+ * of the loaded resource; nothing is claimed while it is still loading.
20
+ */
21
+ export function useResourceOrganization(
22
+ organizationId: MaybeRefOrGetter<string | null | undefined>,
23
+ ) {
24
+ const store = useEffectiveOrganizationStore()
25
+ const claimant = Symbol('resource-organization')
26
+
27
+ // Sync: whatever the same load triggers next must already see the claim.
28
+ watch(
29
+ () => toValue(organizationId),
30
+ (id) => store.claimResource(claimant, id),
31
+ { immediate: true, flush: 'sync' },
32
+ )
33
+ onScopeDispose(() => store.releaseResource(claimant))
34
+ }
@@ -0,0 +1,186 @@
1
+ import type { MaybeRefOrGetter } from 'vue'
2
+ import {
3
+ MESSAGE_GROUP_CATEGORIES,
4
+ MESSAGE_GROUP_LIST_SORT,
5
+ MESSAGE_GROUP_LIST_VISIBILITY,
6
+ MESSAGE_GROUP_PRODUCTS,
7
+ MESSAGE_STATUS,
8
+ SORT_ORDER,
9
+ type MessageGroupCategory,
10
+ type MessageGroupListSort,
11
+ type MessageGroupListVisibility,
12
+ type MessageGroupProduct,
13
+ type MessageStatus,
14
+ type RenderType,
15
+ type SortOrder,
16
+ } from '@dev.smartpricing/message-composer-utils/types'
17
+ import { usePagedMessageGroups } from '~/composables/usePagedMessageGroups'
18
+ import { useAppContextStore } from '~/stores/appContext'
19
+
20
+ /** Sentinel for "no filter" in the selects; never sent to the server. */
21
+ export const ALL_FILTER = 'all'
22
+
23
+ export interface MessageGroupListFilters {
24
+ search: string
25
+ category: MessageGroupCategory | typeof ALL_FILTER
26
+ status: MessageStatus | typeof ALL_FILTER
27
+ product: MessageGroupProduct | typeof ALL_FILTER
28
+ /** Only admins may ask for `internal` or `all`; non-admins always request `public`. */
29
+ visibility: MessageGroupListVisibility
30
+ }
31
+
32
+ export interface MessageGroupListSorting {
33
+ sort: MessageGroupListSort
34
+ order: SortOrder
35
+ }
36
+
37
+ export interface MessageGroupListState extends MessageGroupListFilters, MessageGroupListSorting {
38
+ page: number
39
+ perPage: number
40
+ }
41
+
42
+ const STORAGE_KEY = 'message_library_list_state'
43
+ const PER_PAGE = 25
44
+
45
+ function isOneOf<T extends string>(values: readonly T[], value: unknown): value is T {
46
+ return typeof value === 'string' && (values as readonly string[]).includes(value)
47
+ }
48
+
49
+ type StoredState = Partial<Record<keyof MessageGroupListState | 'contextProduct', unknown>>
50
+
51
+ /**
52
+ * Reads the state saved by this composer session. State is scoped to the
53
+ * context Product it was saved under: after a host Product switch the library
54
+ * must open prefiltered on the new Product, not on a stale choice.
55
+ */
56
+ function readStoredState(contextProduct: MessageGroupProduct | undefined): StoredState {
57
+ try {
58
+ const raw = sessionStorage.getItem(STORAGE_KEY)
59
+ const parsed: unknown = raw ? JSON.parse(raw) : null
60
+ if (!parsed || typeof parsed !== 'object') return {}
61
+ const stored = parsed as StoredState
62
+ return stored.contextProduct === contextProduct ? stored : {}
63
+ } catch {
64
+ return {}
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Restores the previous list state of this composer session, field by field:
70
+ * anything missing or no longer valid falls back to the default.
71
+ */
72
+ function restoreState(
73
+ defaults: MessageGroupListState,
74
+ contextProduct: MessageGroupProduct | undefined,
75
+ ): MessageGroupListState {
76
+ const stored = readStoredState(contextProduct)
77
+ const withAll = <T extends string>(values: readonly T[]) => [...values, ALL_FILTER] as const
78
+ return {
79
+ search: typeof stored.search === 'string' ? stored.search : defaults.search,
80
+ category: isOneOf(withAll(MESSAGE_GROUP_CATEGORIES), stored.category)
81
+ ? stored.category
82
+ : defaults.category,
83
+ status: isOneOf(withAll(MESSAGE_STATUS), stored.status) ? stored.status : defaults.status,
84
+ product: isOneOf(withAll(MESSAGE_GROUP_PRODUCTS), stored.product)
85
+ ? stored.product
86
+ : defaults.product,
87
+ visibility: isOneOf(MESSAGE_GROUP_LIST_VISIBILITY, stored.visibility)
88
+ ? stored.visibility
89
+ : defaults.visibility,
90
+ sort: isOneOf(MESSAGE_GROUP_LIST_SORT, stored.sort) ? stored.sort : defaults.sort,
91
+ order: isOneOf(SORT_ORDER, stored.order) ? stored.order : defaults.order,
92
+ page:
93
+ Number.isInteger(stored.page) && (stored.page as number) >= 1 ? (stored.page as number) : 1,
94
+ perPage: defaults.perPage,
95
+ }
96
+ }
97
+
98
+ /** A select value of `all` means "no filter": the param is left out. */
99
+ function unlessAll<T extends string>(value: T | typeof ALL_FILTER): T | undefined {
100
+ return value === ALL_FILTER ? undefined : value
101
+ }
102
+
103
+ function persistState(
104
+ state: MessageGroupListState,
105
+ contextProduct: MessageGroupProduct | undefined,
106
+ ) {
107
+ try {
108
+ sessionStorage.setItem(STORAGE_KEY, JSON.stringify({ ...state, contextProduct }))
109
+ } catch {
110
+ // Storage unavailable (private mode, quota): the list still works, it just won't be restored.
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Owns the library table's state (filters, sorting, page) as component-scoped
116
+ * reactive state and exposes the server-side paginated query (ADR 0012).
117
+ *
118
+ * - The Product filter starts on the context Product and can be widened to all.
119
+ * - Any filter or sort change lands on page one; search is debounced.
120
+ * - The previous page stays visible while the next one loads.
121
+ * - State survives navigating into a group and back within the session, never the host URL.
122
+ */
123
+ export function useMessageGroupList(renderType: MaybeRefOrGetter<RenderType>) {
124
+ const appContext = useAppContextStore()
125
+
126
+ const defaults: MessageGroupListState = {
127
+ search: '',
128
+ category: ALL_FILTER,
129
+ status: ALL_FILTER,
130
+ product: appContext.product ?? ALL_FILTER,
131
+ // Admins keep seeing internal and public groups by default, as before the
132
+ // server-side list; the select lets them narrow. Non-admins never send this.
133
+ visibility: appContext.isAdmin ? 'all' : 'public',
134
+ sort: 'updated_at',
135
+ order: 'desc',
136
+ page: 1,
137
+ perPage: PER_PAGE,
138
+ }
139
+
140
+ const state = reactive<MessageGroupListState>(restoreState(defaults, appContext.product))
141
+
142
+ const { rows, meta, loading, query } = usePagedMessageGroups({
143
+ search: toRef(state, 'search'),
144
+ page: toRef(state, 'page'),
145
+ perPage: PER_PAGE,
146
+ renderType,
147
+ filters: () => ({
148
+ category: unlessAll(state.category),
149
+ status: unlessAll(state.status),
150
+ product: unlessAll(state.product),
151
+ visibility: appContext.isAdmin ? state.visibility : 'public',
152
+ sort: state.sort,
153
+ order: state.order,
154
+ }),
155
+ })
156
+
157
+ watch(state, (value) => persistState(value, appContext.product), { deep: true })
158
+
159
+ function setFilters(patch: Partial<MessageGroupListFilters>) {
160
+ Object.assign(state, patch)
161
+ // Search resets the page only once the debounced value reaches the query.
162
+ const { search: _search, ...immediate } = patch
163
+ if (Object.keys(immediate).length > 0) state.page = 1
164
+ }
165
+
166
+ function setSorting(sorting: MessageGroupListSorting) {
167
+ state.sort = sorting.sort
168
+ state.order = sorting.order
169
+ state.page = 1
170
+ }
171
+
172
+ function setPage(page: number) {
173
+ state.page = page
174
+ }
175
+
176
+ return {
177
+ state: readonly(state),
178
+ setFilters,
179
+ setSorting,
180
+ setPage,
181
+ rows,
182
+ meta,
183
+ loading,
184
+ refetch: query.refetch,
185
+ }
186
+ }
@@ -0,0 +1,76 @@
1
+ import type { OrganizationWaba } from '@dev.smartpricing/message-composer-utils/types'
2
+ import WabaSelectModal from '~/components/Composer/WabaSelectModal.vue'
3
+
4
+ /**
5
+ * The WABA of the Message Group in the WhatsApp editor (ADR 0015): chosen at
6
+ * the first submission and fixed from then on.
7
+ *
8
+ * `storedWabaId` is the WABA the loaded Message Group is on, if any.
9
+ */
10
+ export function useMessageGroupWaba(storedWabaId: MaybeRefOrGetter<string | null | undefined>) {
11
+ const { data: wabas, refresh } = useOrganizationWabasQuery()
12
+ const { metaWabaId } = storeToRefs(useAppContextStore())
13
+ const modal = useOverlay().create(WabaSelectModal)
14
+
15
+ // A submission of one language does not read the Message Group again: its
16
+ // WABA is remembered here until it does.
17
+ const submittedWabaId = ref<string>()
18
+
19
+ const wabaId = computed(() => toValue(storedWabaId) ?? submittedWabaId.value ?? null)
20
+
21
+ /** The WABA the Message Group is on, by id alone when it is not listed. */
22
+ const waba = computed<OrganizationWaba | null>(() => {
23
+ if (!wabaId.value) return null
24
+ return (
25
+ wabas.value?.find((candidate) => candidate.id === wabaId.value) ?? {
26
+ id: wabaId.value,
27
+ name: '',
28
+ phone_numbers: [],
29
+ }
30
+ )
31
+ })
32
+
33
+ /**
34
+ * The Message Group is on a WABA that is no longer one of its
35
+ * Organization's: it cannot be submitted any more. Never true while the
36
+ * lookup is running or failed.
37
+ */
38
+ const isDetached = computed(
39
+ () =>
40
+ !!wabaId.value &&
41
+ !!wabas.value &&
42
+ !wabas.value.some((candidate) => candidate.id === wabaId.value),
43
+ )
44
+
45
+ /**
46
+ * The WABA to name in a submission. At the first submission of a Message
47
+ * Group whose Organization has several WABAs, it is the Host's when the
48
+ * Host passed one of them, otherwise the user is asked. In every other
49
+ * case none is named and the backend resolves it. A lookup that has not
50
+ * answered yet is waited for; one that failed leaves it to the backend.
51
+ * Returns null when the user gives up.
52
+ */
53
+ async function chooseWaba(): Promise<{ wabaId?: string } | null> {
54
+ if (wabaId.value) return {}
55
+ if (!wabas.value) await refresh()
56
+ const candidates = wabas.value
57
+ if (!candidates || candidates.length < 2) return {}
58
+
59
+ const hostWabaId = metaWabaId.value
60
+ if (hostWabaId && candidates.some((candidate) => candidate.id === hostWabaId)) {
61
+ return { wabaId: hostWabaId }
62
+ }
63
+
64
+ const chosen = await modal.open({ wabas: candidates }).result
65
+
66
+ return chosen ? { wabaId: chosen } : null
67
+ }
68
+
69
+ /** After a submission went through, with the WABA it named, if any. */
70
+ function markSubmitted(chosen?: string) {
71
+ if (wabaId.value) return
72
+ submittedWabaId.value = chosen ?? (wabas.value?.length === 1 ? wabas.value[0]!.id : undefined)
73
+ }
74
+
75
+ return { waba, isDetached, chooseWaba, markSubmitted }
76
+ }