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
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { Box, Flex, Typography, Field, Button, Alert, Link, Loader, Dialog } fro
import { Check, WarningCircle, Information, Link as LinkIcon } from '@strapi/icons';
import ProjectService from '../../@common/services/project-service';

const WEBHOOK_PATH = '/api/localazy/public/transfer/download';
// the plugin's public route (server/src/routes/localazy-public-transfer-routes.ts); not under `/api`
const WEBHOOK_PATH = '/localazy/public/transfer/download';
const LOCALAZY_DOCS_URL = 'https://localazy.com/docs/general/webhooks';

type WebhookState = 'loading' | 'configured' | 'not_configured';
Expand Down
33 changes: 10 additions & 23 deletions server/src/services/localazy-transfer-upload-service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import type { Core } from '@strapi/strapi';
import { flattenObject } from '../utils/flatten-object';
import { projectBlocksFields } from '../utils/blocks-to-translatable';
import { getUploadKeysForEntries } from '../utils/get-upload-keys-for-entries';
import {
getCollectionsNames,
findSetupModelByCollectionName,
isCollectionTransferEnabled,
getPickPathsWithComponents,
} from '../utils/transfer-setup-utils';
import { pickEntries } from '../utils/pick-entries';
import { getCharacterLimitsMetadata } from '../utils/get-character-limits-metadata';
import config from '../config';
import { isoStrapiToLocalazy } from '../utils/iso-locales-utils';
Expand Down Expand Up @@ -100,12 +98,6 @@ const LocalazyTransferUploadService = ({ strapi }: { strapi: Core.Strapi }) => (
continue;
}

/**
* Contains the paths to the fields with the model uid.
* These paths will be used (selected) from the content and then uploaded to Localazy.
*/
const pickPathsWithUid = pickPaths.map((pickPath) => `${modelUid}.${pickPath}`);

// https://docs.strapi.io/dev-docs/api/document-service#examples-1;
let entries = await strapi.documents(modelUid).findMany({
locUploadPLevel: 6,
Expand Down Expand Up @@ -165,20 +157,15 @@ const LocalazyTransferUploadService = ({ strapi }: { strapi: Core.Strapi }) => (
*/
entries = omitDeep(entries, ['locale', 'createdAt', 'updatedAt', 'publishedAt']);

entries.forEach((entry) => {
const projectedEntry = projectBlocksFields(entry, strapi.getModel(modelUid), (uid) =>
strapi.getModel(uid as any)
);
const flatten = flattenObject({
[modelUid]: projectedEntry,
});
// get only enabled fields; "__component" will be filtered out inside of the function
const pickedFlatten = pickEntries(flatten, pickPathsWithUid);
pickedFlattenStrapiContent = {
...pickedFlattenStrapiContent,
...pickedFlatten,
};
});
pickedFlattenStrapiContent = {
...pickedFlattenStrapiContent,
...getUploadKeysForEntries({
entries,
modelUid,
transferSetupModelProps: currentTransferSetupModel,
getModel: (uid) => strapi.getModel(uid as any),
}),
};

// Add character limit metadata for fields that have maxLength defined in the content type schema
const characterLimitsMetadata = getCharacterLimitsMetadata(pickedFlattenStrapiContent, modelUid);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import getPickedFlattenKeysForHookEntry from '../get-picked-flatten-keys-for-hook-entry';
import { getUploadKeysForEntries } from '../get-upload-keys-for-entries';

/**
* The automated upload (on create/update) and deprecation (on delete) must send exactly the keys
* the manual upload sends: blocks projected to their text leaves, dynamic zone fields included,
* and entries excluded from translation left out.
*/

const uid = 'api::about.about';
const documentId = 'about-doc';

const models: Record<string, any> = {
[uid]: {
uid,
collectionName: 'about',
attributes: {
title: { type: 'string' },
story: { type: 'blocks' },
meta: { type: 'json' },
seo: { type: 'component', repeatable: false, component: 'shared.seo' },
beats: { type: 'dynamiczone', components: ['about.hero', 'about.timeline'] },
},
},
'shared.seo': { uid: 'shared.seo', attributes: { summary: { type: 'blocks' }, metaTitle: { type: 'string' } } },
'about.hero': { uid: 'about.hero', attributes: { chapter: { type: 'string' }, line: { type: 'blocks' } } },
'about.timeline': {
uid: 'about.timeline',
attributes: { stops: { type: 'component', repeatable: true, component: 'about.stop' } },
},
'about.stop': { uid: 'about.stop', attributes: { label: { type: 'string' }, notes: { type: 'blocks' } } },
};

const setupModel = {
__model__: true,
title: true,
story: true,
meta: true,
seo: { summary: true, metaTitle: true },
beats: [
{ __component__: 'about.hero', chapter: true, line: true },
{ __component__: 'about.timeline', stops: { label: true, notes: true } },
],
};

const paragraph = (...children: any[]) => ({ type: 'paragraph', children });
const entry = {
documentId,
locale: 'cs',
title: 'O mně',
story: [
paragraph(
{ type: 'text', text: 'Ahoj ' },
{ type: 'text', text: 'světe', bold: true },
{ type: 'link', url: 'https://localazy.com', children: [{ type: 'text', text: 'odkaz' }] }
),
],
meta: { og: { title: 'Titulek' } },
seo: { id: 4, metaTitle: 'O mně | Web', summary: [paragraph({ type: 'text', text: 'Shrnutí' })] },
beats: [
{ __component: 'about.hero', id: 1, chapter: 'Úvod', line: [paragraph({ type: 'text', text: 'Řádek' })] },
{
__component: 'about.timeline',
id: 3,
stops: [{ id: 10, label: 'Děčín', notes: [paragraph({ type: 'text', text: 'Odtud pocházím.' })] }],
},
],
};

let excluded: string[] = [];

jest.mock('../../core', () => ({
getPluginSettingsService: () => ({
getContentTransferSetup: async () => ({ has_setup: true, setup: [{ about: setupModel }] }),
}),
getLocalazyUserService: () => ({ getUser: async () => ({ accessToken: 'token', project: { id: 'project' } }) }),
getLocalazyPubAPIService: () => ({
getProject: async () => ({ sourceLanguage: 1, languages: [{ id: 1, code: 'cs' }] }),
}),
// as Strapi's i18n returns them: locale rows carry no `isDefault`, the default comes separately
getStrapiI18nService: () => ({
getLocales: async () => [{ code: 'en' }, { code: 'cs' }],
getDefaultLocaleCode: async () => 'cs',
}),
getEntryExclusionService: () => ({ getContentTypeExclusions: async () => excluded }),
}));

jest.mock('../../services/helpers/plugin-settings-service-helper', () => ({
__esModule: true,
default: jest.fn().mockImplementation(() => ({
setup: async () => undefined,
shouldAllowAutomatedCreatedTrigger: () => true,
shouldAllowAutomatedUpdatedTrigger: () => true,
shouldAllowDeprecateOnDeletion: () => true,
})),
}));

describe('getPickedFlattenKeysForHookEntry', () => {
const originalStrapi = { ...(global as any).strapi };

beforeEach(() => {
excluded = [];
Object.assign((global as any).strapi, {
documents: jest.fn(() => ({ findOne: jest.fn(async () => JSON.parse(JSON.stringify(entry))) })),
getModel: (modelUid: string) => models[modelUid],
contentTypes: { [uid]: models[uid] },
components: Object.fromEntries(Object.entries(models).filter(([key]) => key !== uid)),
});
});

afterEach(() => {
Object.assign((global as any).strapi, originalStrapi);
});

const params = (action: string) => ({
context: { action, contentType: { uid, collectionName: 'about' } } as any,
documentId,
locale: 'cs',
});

it.each(['create', 'update', 'delete'])('on %s, sends the same keys as the manual upload', async (action) => {
const result = await getPickedFlattenKeysForHookEntry(params(action));

const manualUploadKeys = getUploadKeysForEntries({
entries: [entry],
modelUid: uid,
transferSetupModelProps: setupModel,
getModel: (modelUid) => models[modelUid],
});
expect(result.pickedFlatten).toEqual(expect.objectContaining(manualUploadKeys));
expect(Object.keys(result.pickedFlatten).filter((key) => !key.endsWith('[limit]'))).toEqual(
Object.keys(manualUploadKeys)
);

expect(result.pickedFlatten).toMatchObject({
[`${uid}[${documentId}].story[0].children[1].text`]: 'světe',
[`${uid}[${documentId}].story[0].children[2].children[0].text`]: 'odkaz',
[`${uid}[${documentId}].seo[4].summary[0].children[0].text`]: 'Shrnutí',
[`${uid}[${documentId}].beats[1;about.hero].line[0].children[0].text`]: 'Řádek',
[`${uid}[${documentId}].beats[3;about.timeline].stops[10].notes[0].children[0].text`]: 'Odtud pocházím.',
});
// blocks structure is never uploaded as text
expect(Object.keys(result.pickedFlatten).some((key) => /\.(type|bold|url)$/.test(key))).toBe(false);
});

it('skips entries excluded from translation', async () => {
excluded = [documentId];
expect(await getPickedFlattenKeysForHookEntry(params('update'))).toBeUndefined();
});
});
15 changes: 7 additions & 8 deletions server/src/utils/__tests__/transfer-round-trip.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { cloneDeep, isPlainObject } from 'lodash-es';
import { projectBlocksFields } from '../blocks-to-translatable';
import { flattenObject } from '../flatten-object';
import { pickEntries } from '../pick-entries';
import { getPickPathsWithComponents } from '../transfer-setup-utils';
import { getUploadKeysForEntries } from '../get-upload-keys-for-entries';
import { collectDownloadedContent, DownloadedLocalazyKey } from '../collect-downloaded-content';
import { buildLocalizedCreateEntry } from '../build-localized-create-entry';
import { parsedLocalazyEntryToUpdateEntry } from '../parsed-localazy-entry-to-update-entry';
Expand Down Expand Up @@ -259,10 +256,12 @@ const normalize = (value: any): any => {
// ---------------------------------------------------------------------------------------------

const upload = (sourceEntry: any): Record<string, string> => {
const projected = projectBlocksFields(sourceEntry, getModel(uid), getModel);
const flat = flattenObject({ [uid]: projected });
const pickPaths = getPickPathsWithComponents(setupModel).map((path) => `${uid}.${path}`);
const picked = pickEntries(flat, pickPaths);
const picked = getUploadKeysForEntries({
entries: [sourceEntry],
modelUid: uid,
transferSetupModelProps: setupModel,
getModel,
});
// Localazy stores no empty source strings
return Object.fromEntries(Object.entries(picked).filter(([, v]) => typeof v === 'string' && v !== '')) as any;
};
Expand Down
40 changes: 19 additions & 21 deletions server/src/utils/get-picked-flatten-keys-for-hook-entry.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { isoStrapiToLocalazy } from './iso-locales-utils';
import config from '../config';
import { omitDeep } from './omit-deep';
import { flattenObject } from './flatten-object';
import { pickEntries } from './pick-entries';
import { getCharacterLimitsMetadata } from './get-character-limits-metadata';
import { findSetupModelByCollectionName, getPickPaths } from './transfer-setup-utils';
import { getUploadKeysForEntries } from './get-upload-keys-for-entries';
import PluginSettingsServiceHelper from '../services/helpers/plugin-settings-service-helper';
import { ContentTransferSetup } from '../models/plugin/content-transfer-setup';
import { UID } from '@strapi/strapi';
Expand All @@ -13,6 +12,7 @@ import {
getStrapiI18nService,
getLocalazyUserService,
getLocalazyPubAPIService,
getEntryExclusionService,
} from '../core';
import type { Context } from '@strapi/types/dist/modules/documents/middleware';
import type { HookParams } from '../models/plugin/hook-params';
Expand Down Expand Up @@ -144,11 +144,11 @@ export default async (params: HookParams) => {
const projectSourceLanguageCode = sourceLanguage.code;

// Strapi default locale not compatible with project source language
const strapiLocales = await StrapiI18nService.getLocales();
const defaultLocale = strapiLocales.find((locale) => locale.isDefault);
// `locales.find()` returns plain rows without `isDefault`; ask i18n for the default locale itself
const strapiDefaultLocaleCode = await StrapiI18nService.getDefaultLocaleCode();

const strapiDefaultLocale = defaultLocale
? isoStrapiToLocalazy(defaultLocale.code)
const strapiDefaultLocale = strapiDefaultLocaleCode
? isoStrapiToLocalazy(strapiDefaultLocaleCode)
: config.default.LOCALAZY_DEFAULT_LOCALE;
if (strapiDefaultLocale !== projectSourceLanguageCode) {
strapi.log.warn("Localazy Plugin: Source locales do not match; the operation won't proceed");
Expand All @@ -167,7 +167,11 @@ export default async (params: HookParams) => {
* Prepare the data structure and upload it to Localazy
*/
const modelUid = context.contentType.uid;
const entries = await getEventEntries(params);
// entries excluded from translation are not uploaded (nor deprecated), as in the manual upload
const excludedEntries = await getEntryExclusionService().getContentTypeExclusions(modelUid);
const entries = (await getEventEntries(params)).filter(
(entry) => !!entry && !excludedEntries.includes(entry.documentId)
);

if (entries.length === 0) {
return;
Expand All @@ -186,20 +190,14 @@ export default async (params: HookParams) => {
strapi.log.warn(`No fields for collection ${contextModel} transfer are enabled.`);
return;
}
const pickPathsWithUid = pickPaths.map((pickPath) => `${modelUid}.${pickPath}`);

// flatten Strapi content
let flatten = {};
for (const reducedEntry of reducedEntries) {
flatten = {
...flatten,
...flattenObject({
[modelUid]: reducedEntry,
}),
};
}
// get only enabled fields; "__component" will be filtered out inside of the function
const pickedFlatten = pickEntries(flatten, pickPathsWithUid);

// the same keys as the manual upload (blocks projected to text leaves, dynamic zones included)
const pickedFlatten = getUploadKeysForEntries({
entries: reducedEntries,
modelUid,
transferSetupModelProps: currentTransferSetupModel,
getModel: (uid) => strapi.getModel(uid as any),
});

// Add character limit metadata for fields that have maxLength defined in the content type schema
const characterLimitsMetadata = getCharacterLimitsMetadata(pickedFlatten, modelUid);
Expand Down
39 changes: 39 additions & 0 deletions server/src/utils/get-upload-keys-for-entries.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { flattenObject } from './flatten-object';
import { pickEntries } from './pick-entries';
import { projectBlocksFields } from './blocks-to-translatable';
import { getPickPathsWithComponents } from './transfer-setup-utils';

type GetModel = (uid: string) => { attributes?: Record<string, any> } | undefined;

/**
* The Localazy keys (and source values) of the enabled fields of `entries`, as uploaded by both
* the manual upload and the automated upload/deprecation on create, update and delete: blocks
* fields are projected to their text leaves (see `projectBlocksFields`) and dynamic zone fields
* are picked per component (see `getPickPathsWithComponents`).
*
* @param transferSetupModelProps the model's entry of the Content Transfer Setup
*/
export const getUploadKeysForEntries = ({
entries,
modelUid,
transferSetupModelProps,
getModel,
}: {
entries: any[];
modelUid: string;
transferSetupModelProps: any;
getModel: GetModel;
}): Record<string, any> => {
const pickPathsWithUid = getPickPathsWithComponents(transferSetupModelProps).map(
(pickPath) => `${modelUid}.${pickPath}`
);

let uploadKeys: Record<string, any> = {};
for (const entry of entries) {
const projectedEntry = projectBlocksFields(entry, getModel(modelUid), getModel);
const flatten = flattenObject({ [modelUid]: projectedEntry });
// get only enabled fields; "__component" will be filtered out inside of the function
uploadKeys = { ...uploadKeys, ...pickEntries(flatten, pickPathsWithUid) };
}
return uploadKeys;
};
Loading