Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions api/src/groups/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import type { SessionStateAuthenticated } from '@data-fair/lib-express'
import Debug from 'debug'
import eventsQueue from '@data-fair/lib-node/events-queue.js'
import mongo from '#mongo'
import { type EventAction, type EventText, eventText } from '../utils/event-texts.ts'

const debug = Debug('groups')

Expand Down Expand Up @@ -57,26 +56,29 @@ export const patchGroup = async (group: Group, patch: Partial<Group>, session: S
return updatedGroup
}

const groupTitles = {
create: (title: string) => ({ en: `The page group ${title} was created`, fr: `Le groupe de pages ${title} a été créé` }),
patch: (title: string) => ({ en: `The page group ${title} was updated`, fr: `Le groupe de pages ${title} a été modifié` }),
delete: (title: string) => ({ en: `The page group ${title} was deleted`, fr: `Le groupe de pages ${title} a été supprimé` })
}

/**
* Helper function to send events related to groups
* @param topicAction The action part of the topic key, it also selects the event title (e.g. "create", "draft-validate")
* @param body Optional additional information to include in the event
* Send an event about a group of pages.
* @param topicAction The action part of the topic key, it also selects the event title
*/
export const sendGroupEvent = (
group: Group,
topicAction: EventAction<'group'>,
sessionState?: SessionStateAuthenticated,
body?: EventText
topicAction: keyof typeof groupTitles,
sessionState?: SessionStateAuthenticated
) => {
eventsQueue.pushEvent({
title: eventText(`group-${topicAction}`, { title: group.title }),
title: groupTitles[topicAction](group.title),
topic: { key: `groups:group-${topicAction}:${group._id}` },
sender: group.owner,
resource: {
type: 'group',
id: group._id,
title: group.title,
},
body
}
}, sessionState)
}
74 changes: 51 additions & 23 deletions api/src/pages/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ import type { Page, PageElement, PageConfig } from '#types/page/index.ts'
import debugModule from 'debug'
import slug from 'slugify'
import { assertAccountRole, httpError, type SessionStateAuthenticated } from '@data-fair/lib-express'
import eventsQueue from '@data-fair/lib-node/events-queue.js'
import eventsQueue, { type PushEvent } from '@data-fair/lib-node/events-queue.js'
import { renderMarkdown } from '@data-fair/portals-shared-markdown'
import { randomUUID } from 'node:crypto'
import mongo from '#mongo'
import { duplicateImage } from '../images/service.ts'
import { assertNbPagesLimit } from '../limits/service.ts'
import { traversePageElements, resolvePageAnchors } from './operations.ts'
import { type EventAction, type EventText, eventText, joinEventTexts } from '../utils/event-texts.ts'

const debug = debugModule('pages')

Expand Down Expand Up @@ -135,22 +134,28 @@ export const createPage = async (page: Page, sourcePageId?: string) => {
page.config._toc = await resolvePageAnchors(page.config)
await mongo.pages.insertOne(page)

const details: EventText[] = []
details.push(eventText('pageType', { type: page.type }))
const details = [{ en: `Type: ${page.type}`, fr: `Type : ${page.type}` }]
if (page.type === 'generic' && page.config.genericMetadata?.group) {
details.push(eventText('pageGroup', { group: page.config.genericMetadata.group.title }))
const group = page.config.genericMetadata.group.title
details.push({ en: `Group: ${group}`, fr: `Groupe : ${group}` })
}
// Duplication info
if (sourcePageId) {
const sourcePage = await mongo.pages.findOne({ _id: sourcePageId })
if (sourcePage?.isReference) {
details.push(eventText('duplicatedFromReferencePage', { title: sourcePage.title, id: sourcePageId }))
details.push({
en: `Duplicated from the reference page "${sourcePage.title}" (${sourcePageId})`,
fr: `Dupliquée depuis la page de référence "${sourcePage.title}" (${sourcePageId})`
})
} else if (sourcePage) {
details.push(eventText('duplicatedFromPage', { title: sourcePage.title, id: sourcePageId }))
details.push({
en: `Duplicated from the page "${sourcePage.title}" (${sourcePageId})`,
fr: `Dupliquée depuis la page "${sourcePage.title}" (${sourcePageId})`
})
}
}

return joinEventTexts(details, '; ')
return { en: details.map(d => d.en).join('; '), fr: details.map(d => d.fr).join('; ') }
}

export const patchPage = async (page: Page, patch: Partial<Page>, session: SessionStateAuthenticated, skipEvents = false) => {
Expand All @@ -171,12 +176,12 @@ export const patchPage = async (page: Page, patch: Partial<Page>, session: Sessi
// Track portal additions/removals
const addedPortals = patch.portals ? patch.portals.filter(portalId => !page.portals.includes(portalId)) : []
const removedPortals = patch.portals ? page.portals.filter(portalId => !patch.portals!.includes(portalId)) : []
let standardReplacements: Record<string, EventText> = {}
let replacedPages: Record<string, string[]> = {}

// Handle standard page type publication: auto-switch pages of same type on the same portal
if (patch.portals && ['home', 'contact', 'accessibility', 'terms-of-service', 'legal-notice', 'privacy-policy', 'cookie-policy', 'datasets', 'applications', 'reuses', 'event-catalog', 'news-catalog'].includes(page.type)) {
if (addedPortals.length > 0) {
standardReplacements = await switchStandardPages(page, addedPortals)
replacedPages = await switchStandardPages(page, addedPortals)
}
}

Expand Down Expand Up @@ -239,13 +244,25 @@ export const patchPage = async (page: Page, patch: Partial<Page>, session: Sessi

// Publish events for added portals
for (const portalId of addedPortals) {
const publishBody = standardReplacements[portalId] ?? eventText('pagePublished', { portal: portalId })
const replaced = replacedPages[portalId]
const publishBody = replaced
? {
en: replaced.map(title => `The page "${title}" was replaced by the page "${page.title}" on the portal: ${portalId}`).join(' | '),
fr: replaced.map(title => `La page "${title}" a été remplacée par la page "${page.title}" sur le portail : ${portalId}`).join(' | ')
}
: {
en: `The page was published on the portal: ${portalId}`,
fr: `La page a été publiée sur le portail : ${portalId}`
}
sendPageEvent(updatedPage, 'publish', session, publishBody)
}

// Unpublish events for removed portals
for (const portalId of removedPortals) {
sendPageEvent(updatedPage, 'unpublish', session, eventText('pageUnpublished', { portal: portalId }))
sendPageEvent(updatedPage, 'unpublish', session, {
en: `The page was unpublished from the portal: ${portalId}`,
fr: `La page a été dépubliée du portail : ${portalId}`
})
}

// Generic patch event only if other fields changed beyond portals/draft
Expand Down Expand Up @@ -284,19 +301,29 @@ export const cancelPageDraft = async (page: Page, session: SessionStateAuthentic
return updatedPage
}

const pageTitles = {
create: (title: string) => ({ en: `The page ${title} was created`, fr: `La page ${title} a été créée` }),
patch: (title: string) => ({ en: `The page ${title} was updated`, fr: `La page ${title} a été modifiée` }),
delete: (title: string) => ({ en: `The page ${title} was deleted`, fr: `La page ${title} a été supprimée` }),
publish: (title: string) => ({ en: `The page ${title} was published on a portal`, fr: `La page ${title} a été publiée sur un portail` }),
unpublish: (title: string) => ({ en: `The page ${title} was unpublished from a portal`, fr: `La page ${title} a été dépubliée d'un portail` }),
'draft-validate': (title: string) => ({ en: `The draft of the page ${title} was validated`, fr: `Le brouillon de la page ${title} a été validé` }),
'draft-discard': (title: string) => ({ en: `The draft of the page ${title} was discarded`, fr: `Le brouillon de la page ${title} a été annulé` })
}

/**
* Helper function to send events related to pages
* @param topicAction The action part of the topic key, it also selects the event title (e.g. "create", "draft-validate")
* @param body Optional additional information to include in the event
* Send an event about a page.
* @param topicAction The action part of the topic key, it also selects the event title
* @param body Details of the event
*/
export const sendPageEvent = (
page: Page,
topicAction: EventAction<'page'>,
topicAction: keyof typeof pageTitles,
sessionState?: SessionStateAuthenticated,
body?: EventText
body?: PushEvent['body']
) => {
eventsQueue.pushEvent({
title: eventText(`page-${topicAction}`, { title: page.title }),
title: pageTitles[topicAction](page.title),
topic: { key: `pages:page-${topicAction}:${page._id}` },
sender: page.owner,
resource: {
Expand Down Expand Up @@ -370,8 +397,9 @@ const validateMetadata = (page: Page, patch?: Partial<Page>) => {
}
}

const switchStandardPages = async (page: Page, addedPortals: string[]): Promise<Record<string, EventText>> => {
const replacements: Record<string, EventText[]> = {}
/** Unpublish the pages of the same type from the added portals, returns their titles by portal. */
const switchStandardPages = async (page: Page, addedPortals: string[]) => {
const replacedPages: Record<string, string[]> = {}

// Find other pages of the same type already published on these portals
const conflictingPages = await mongo.pages.find({
Expand All @@ -396,11 +424,11 @@ const switchStandardPages = async (page: Page, addedPortals: string[]): Promise<

for (const portalId of addedPortals) {
if (conflictingPage.portals.includes(portalId)) {
replacements[portalId] ??= []
replacements[portalId].push(eventText('pageReplaced', { replaced: conflictingPage.title, title: page.title, portal: portalId }))
replacedPages[portalId] ??= []
replacedPages[portalId].push(conflictingPage.title)
}
}
}

return Object.fromEntries(Object.entries(replacements).map(([portalId, texts]) => [portalId, joinEventTexts(texts, ' | ')!]))
return replacedPages
}
8 changes: 4 additions & 4 deletions api/src/portals/router.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Portal, PortalConfig } from '#types/portal/index.ts'
import { type PushEvent } from '@data-fair/lib-node/events-queue.js'

import { randomUUID } from 'node:crypto'
import { Router } from 'express'
Expand All @@ -11,8 +12,7 @@ import * as postIngressReqBody from '#types/portal-ingress/index.ts'
import { httpError, reqSessionAuthenticated, assertAccountRole, assertAdminMode, reqOrigin } from '@data-fair/lib-express'
import { defaultTheme, fillTheme } from '@data-fair/lib-common-types/theme/index.js'
import { hasKoumoulMention } from '#types/portal-config-footer/walk.ts'
import { createPortal, validatePortalDraft, cancelPortalDraft, getPortal, getPortalAsAdmin, patchPortal, deletePortal, sendPortalEvent, duplicatePortalConfig } from './service.ts'
import { type EventText, eventText } from '../utils/event-texts.ts'
import { createPortal, validatePortalDraft, cancelPortalDraft, getPortal, getPortalAsAdmin, patchPortal, deletePortal, sendPortalEvent, changesBody, duplicatePortalConfig } from './service.ts'

const router = Router()
export default router
Expand Down Expand Up @@ -99,7 +99,7 @@ router.post('', async (req, res, next) => {
const owner = body.owner ?? session.account

// Handle portal duplication if sourcePortalId is provided
let duplicationEventDetails: EventText | undefined
let duplicationEventDetails: PushEvent['body']
if (body.sourcePortalId) {
const { config: duplicatedConfig, eventDetails } = await duplicatePortalConfig(session, body.sourcePortalId, portalId, owner)
config = { ...config, ...duplicatedConfig }
Expand Down Expand Up @@ -159,7 +159,7 @@ router.patch('/:id', async (req, res, next) => {
// Send patch event only if not just draft changed
const onlyDraftChanged = Object.keys(body).length === 1 && body.draftConfig
if (!onlyDraftChanged) {
sendPortalEvent(updatedPortal, 'patch', session, eventText('changes', { keys: Object.keys(body).join(', ') }))
sendPortalEvent(updatedPortal, 'patch', session, changesBody(Object.keys(body)))
}

res.send(updatedPortal)
Expand Down
36 changes: 24 additions & 12 deletions api/src/portals/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,14 @@ import { type SessionStateAuthenticated, assertAccountRole, assertAdminMode, get
// origin, which only our ingress routes here — the private instance (lib-node refuses non public
// addresses in the default one, which is for URLs a user can influence)
import { privateAxiosInstance as axios } from '@data-fair/lib-node/axios.js'
import eventsQueue from '@data-fair/lib-node/events-queue.js'
import eventsQueue, { type PushEvent } from '@data-fair/lib-node/events-queue.js'
import { defaultTheme, fillTheme } from '@data-fair/lib-common-types/theme/index.js'
import { renderMarkdown } from '@data-fair/portals-shared-markdown'
import { forEachFooterBlock, footerImageRefs, hasKoumoulMention } from '#types/portal-config-footer/walk.ts'
import mongo from '#mongo'
import config from '#config'
import { duplicateImage } from '../images/service.ts'
import { getFontFamilyAssets } from '../fonts/service.ts'
import { type EventAction, type EventText, eventText } from '../utils/event-texts.ts'

const debug = debugModule('portals')
const debugSyncPortal = debugModule('sync-portal')
Expand Down Expand Up @@ -393,19 +392,30 @@ const cleanUnusedImages = async (portal: Portal) => {
await mongo.images.deleteMany(deleteFilter)
}

const portalTitles = {
create: (title: string) => ({ en: `The portal ${title} was created`, fr: `Le portail ${title} a été créé` }),
patch: (title: string) => ({ en: `The portal ${title} was updated`, fr: `Le portail ${title} a été modifié` }),
delete: (title: string) => ({ en: `The portal ${title} was deleted`, fr: `Le portail ${title} a été supprimé` }),
'draft-validate': (title: string) => ({ en: `The draft of the portal ${title} was validated`, fr: `Le brouillon du portail ${title} a été validé` }),
'draft-discard': (title: string) => ({ en: `The draft of the portal ${title} was discarded`, fr: `Le brouillon du portail ${title} a été annulé` })
}

/** Body of a portal event that lists the changed keys of its configuration. */
export const changesBody = (keys: string[]) => ({ en: `Changes: ${keys.join(', ')}`, fr: `Modifications : ${keys.join(', ')}` })

/**
* Helper function to send events related to portals
* @param topicAction The action part of the topic key, it also selects the event title (e.g. "create", "draft-validate")
* @param body Optional additional information to include in the event
* Send an event about a portal.
* @param topicAction The action part of the topic key, it also selects the event title
* @param body Details of the event
*/
export const sendPortalEvent = (
portal: Portal,
topicAction: EventAction<'portal'>,
topicAction: keyof typeof portalTitles,
sessionState?: SessionStateAuthenticated,
body?: EventText
body?: PushEvent['body']
) => {
eventsQueue.pushEvent({
title: eventText(`portal-${topicAction}`, { title: portal.title }),
title: portalTitles[topicAction](portal.title),
topic: { key: `portals:portal-${topicAction}:${portal._id}` },
sender: portal.owner,
resource: {
Expand All @@ -417,15 +427,15 @@ export const sendPortalEvent = (
}, sessionState)
}

const getChangesKeys = (obj1: Record<string, any>, obj2: Record<string, any>): EventText => {
const getChangesKeys = (obj1: Record<string, any>, obj2: Record<string, any>) => {
const allKeys = new Set([...Object.keys(obj1), ...Object.keys(obj2)])
const modifiedKeys: string[] = []

for (const key of allKeys) {
if (!equal(obj1[key], obj2[key])) modifiedKeys.push(key)
}

return eventText('changes', { keys: modifiedKeys.join(', ') })
return changesBody(modifiedKeys)
}

/**
Expand All @@ -438,7 +448,7 @@ export const duplicatePortalConfig = async (
sourcePortalId: string,
newPortalId: string,
newOwner: Portal['owner']
): Promise<{ config: PortalConfig; eventDetails: EventText }> => {
): Promise<{ config: PortalConfig; eventDetails: PushEvent['body'] }> => {
const sourcePortal = await mongo.portals.findOne({ _id: sourcePortalId })
if (!sourcePortal) throw httpError(404, `portal "${sourcePortalId}" not found for duplication`)

Expand Down Expand Up @@ -481,7 +491,9 @@ export const duplicatePortalConfig = async (
for (const topic of duplicatedConfig.topics) rewrite(topic.thumbnail)
}

const eventDetails = eventText(sourcePortal.isReference ? 'duplicatedFromReferencePortal' : 'duplicatedFromPortal', { title: sourcePortal.title, id: sourcePortalId })
const eventDetails = sourcePortal.isReference
? { en: `Duplicated from the reference portal "${sourcePortal.title}" (${sourcePortalId})`, fr: `Dupliqué depuis le portail de référence "${sourcePortal.title}" (${sourcePortalId})` }
: { en: `Duplicated from the portal "${sourcePortal.title}" (${sourcePortalId})`, fr: `Dupliqué depuis le portail "${sourcePortal.title}" (${sourcePortalId})` }

return { config: duplicatedConfig, eventDetails }
}
Expand Down
Loading
Loading