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
2 changes: 1 addition & 1 deletion api/src/routes/migration.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ router.post(
* @returns {Promise<void>} - A promise that resolves when the test stack is deleted.
*/
router.post(
"/create-test-stack/:projectId",
"/create-test-stack/:orgId/:projectId",
asyncRouter(migrationController.createTestStack)
);

Expand Down
61 changes: 34 additions & 27 deletions api/src/services/migration.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@ import https from "../utils/https.utils.js";
import { LoginServiceType } from "../models/types.js";
import getAuthtoken from "../utils/auth.utils.js";
import logger from "../utils/logger.js";
import { HTTP_TEXTS, HTTP_CODES, CS_REGIONS } from "../constants/index.js";
import { HTTP_TEXTS, HTTP_CODES, CS_REGIONS, LOCALE_MAPPER } from "../constants/index.js";
import { ExceptionFunction } from "../utils/custom-errors.utils.js";
import { fieldAttacher } from "../utils/field-attacher.utils.js";
import ProjectModelLowdb from "../models/project-lowdb.js";
import shell from 'shelljs'
import path from "path";
import AuthenticationModel from "../models/authentication.js";
import { siteCoreService } from "./sitecore.service.js";
import { fileURLToPath } from 'url';
import { copyDirectory } from '../utils/index.js'
import { v4 } from "uuid";
import { setLogFilePath } from "../server.js";
import { mkdirp } from 'mkdirp';
import { testFolderCreator } from "../utils/test-folder-creator.utils.js";



Expand All @@ -35,7 +35,11 @@ const createTestStack = async (req: Request): Promise<LoginServiceType> => {
const srcFun = "createTestStack";
const orgId = req?.params?.orgId;
const projectId = req?.params?.projectId;
const { token_payload, name, description, master_locale } = req.body;
const { token_payload } = req.body;
const description = 'This is a system-generated test stack.'
const name = 'Test';
const master_locale = Object?.keys?.(LOCALE_MAPPER?.masterLocale)?.[0];


try {
const authtoken = await getAuthtoken(
Expand All @@ -44,8 +48,9 @@ const createTestStack = async (req: Request): Promise<LoginServiceType> => {
);

await ProjectModelLowdb.read();
const projectData = ProjectModelLowdb.chain.get("projects").value();
const testStackCount = projectData[0]?.test_stacks?.length + 1;
const projectData: any = ProjectModelLowdb.chain.get("projects").find({ id: projectId }).value();
console.info("🚀 ~ createTestStack ~ projectData:", projectData)
const testStackCount = projectData?.test_stacks?.length + 1;
const newName = name + "-" + testStackCount;

const [err, res] = await safePromise(
Expand Down Expand Up @@ -88,11 +93,10 @@ const createTestStack = async (req: Request): Promise<LoginServiceType> => {
.get("projects")
.findIndex({ id: projectId })
.value();
console.info(index);
if (index > -1) {
ProjectModelLowdb.update((data: any) => {
data.projects[index].current_test_stack_id = res.data.stack.uid;
data.projects[index].test_stacks.push(res.data.stack.uid);
data.projects[index].current_test_stack_id = res?.data?.stack?.api_key;
data.projects[index].test_stacks.push({ stackUid: res?.data?.stack?.api_key, isMigrated: false });
});
}
return {
Expand Down Expand Up @@ -224,22 +228,19 @@ function createDirectoryAndFile(filePath: string) {
}


const runCli = async (rg: string, user_id: string, project: any) => {
const runCli = async (rg: string, user_id: string, stack_uid: any) => {
try {
const regionPresent = CS_REGIONS?.find((item: string) => item === rg) ?? 'NA';
await AuthenticationModel.read();
const userData = AuthenticationModel.chain
.get("users")
.find({ region: regionPresent, user_id })
.value();
if (userData?.authtoken && project?.destination_stack_id) {
// Manually define __filename and __dirname
const __filename = fileURLToPath(import.meta.url);
const dirPath = path.join(path.dirname(__filename), '..', '..');
const sourcePath = path.join(dirPath, 'sitecoreMigrationData', project?.destination_stack_id);
const backupPath = path.join(process.cwd(), 'migration-data', `${project?.destination_stack_id}_${v4().slice(0, 4)}`);
if (userData?.authtoken && stack_uid) {
const sourcePath = path.join(process.cwd(), 'sitecoreMigrationData', stack_uid);
const backupPath = path.join(process.cwd(), 'migration-data', `${stack_uid}_${v4().slice(0, 4)}`);
await copyDirectory(sourcePath, backupPath);
const loggerPath = path.join(backupPath, 'logs', 'import', 'combine.log');
const loggerPath = path.join(backupPath, 'logs', 'import', 'success.log');
createDirectoryAndFile(loggerPath);
await setLogFilePath(loggerPath);
shell.cd(path.join(process.cwd(), '..', 'cli', 'packages', 'contentstack'));
Expand All @@ -249,7 +250,7 @@ const runCli = async (rg: string, user_id: string, project: any) => {
cliLogger(region);
const login = shell.exec(`node bin/run login -a ${userData?.authtoken} -e ${userData?.email}`);
cliLogger(login);
const exportData = shell.exec(`node bin/run cm:stacks:import -k ${project?.destination_stack_id} -d ${sourcePath} --backup-dir=${backupPath} --yes`, { async: true });
const exportData = shell.exec(`node bin/run cm:stacks:import -k ${stack_uid} -d ${sourcePath} --backup-dir=${backupPath} --yes`, { async: true });
cliLogger(exportData);
} else {
console.info('user not found.')
Expand All @@ -262,17 +263,23 @@ const runCli = async (rg: string, user_id: string, project: any) => {
const fieldMapping = async (req: Request): Promise<any> => {
const { orgId, projectId } = req?.params ?? {};
const { region, user_id } = req?.body?.token_payload ?? {};
const project = ProjectModelLowdb.chain
.get("projects")
.find({ id: projectId })
.value();
if (project?.extract_path && project?.destination_stack_id) {
const project = ProjectModelLowdb.chain.get("projects").find({ id: projectId }).value();
if (project?.extract_path && project?.current_test_stack_id) {
const packagePath = project?.extract_path;
const contentTypes = await fieldAttacher({ orgId, projectId, destinationStackId: project?.destination_stack_id });
await siteCoreService?.createEntry({ packagePath, contentTypes, destinationStackId: project?.destination_stack_id });
await siteCoreService?.createLocale(req, project?.destination_stack_id);
await siteCoreService?.createVersionFile(project?.destination_stack_id);
await runCli(region, user_id, project);
const contentTypes = await fieldAttacher({ orgId, projectId, destinationStackId: project?.current_test_stack_id });
await siteCoreService?.createEntry({ packagePath, contentTypes, destinationStackId: project?.current_test_stack_id });
await siteCoreService?.createLocale(req, project?.current_test_stack_id);
await siteCoreService?.createVersionFile(project?.current_test_stack_id);
await testFolderCreator?.({ destinationStackId: project?.current_test_stack_id });
await runCli(region, user_id, project?.current_test_stack_id);
// const projectIndex = ProjectModelLowdb.chain.get("projects").findIndex({ id: projectId }).value();
// if (projectIndex > -1) {
// ProjectModelLowdb.update((data: any) => {
// const index = data.projects[projectIndex].test_stacks.findIndex((item: any) => item?.stackUid === project?.current_test_stack_id);
// console.info("🚀 ~ ProjectModelLowdb.update ~ index:", index)
// data.projects[projectIndex].current_test_stack_id = '';
// });
// }
}
}

Expand Down
14 changes: 8 additions & 6 deletions api/src/services/projects.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ const createProject = async (req: Request) => {
uid: '',
label: '',
master_locale: '',
created_at: '',
created_at: '',
isNewStack: false
},
mapperKeys: {}
Expand Down Expand Up @@ -542,11 +542,13 @@ const fileformatConfirmation = async (req: Request) => {
true
)) as number;

ProjectModelLowdb.update((data: any) => {
data.projects[projectIndex].legacy_cms.file_format_confirmation =
fileformat_confirmation;
data.projects[projectIndex].updated_at = new Date().toISOString();
});
if (!fileformat_confirmation) {
ProjectModelLowdb.update((data: any) => {
data.projects[projectIndex].legacy_cms.file_format_confirmation =
fileformat_confirmation;
data.projects[projectIndex].updated_at = new Date().toISOString();
});
}

return {
status: HTTP_CODES.OK,
Expand Down
44 changes: 23 additions & 21 deletions api/src/services/sitecore.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,23 +122,23 @@ const cretaeAssets = async ({ packagePath, baseDir }: any) => {
} catch (err) {
console.error("🚀 ~ file: assets.js:52 ~ xml_folder?.forEach ~ err:", err)
}
allAssetJSON[mestaData?.uid] = {
urlPath: `/assets/${mestaData?.uid}`,
uid: mestaData?.uid,
content_type: mestaData?.content_type,
file_size: mestaData.size,
tags: [],
filename: `${jsonAsset?.item?.$?.name}.${mestaData?.extension}`,
is_dir: false,
parent_uid: null,
title: jsonAsset?.item?.$?.name,
publish_details: [],
assetPath
}
allAssetJSON[mestaData?.uid].parent_uid = '2146b0cee522cc3a38d'
} else {
console.info("asstes id not found.")
}
allAssetJSON[mestaData?.uid] = {
urlPath: `/assets/${mestaData?.uid}`,
uid: mestaData?.uid,
content_type: mestaData?.content_type,
file_size: mestaData.size,
tags: [],
filename: `${jsonAsset?.item?.$?.name}.${mestaData?.extension}`,
is_dir: false,
parent_uid: null,
title: jsonAsset?.item?.$?.name,
publish_details: [],
assetPath
console.info('blob is not there for this asstes', mestaData?.uid, '.')
}
allAssetJSON[mestaData?.uid].parent_uid = '2146b0cee522cc3a38d'
}
}
}
Expand Down Expand Up @@ -191,7 +191,6 @@ const createEntry = async ({ packagePath, contentTypes, master_locale = 'en-us',
}
}
}

for await (const ctType of contentTypes) {
const entryPresent: any = entriesData?.find((item: any) => uidCorrector({ uid: item?.template }) === ctType?.contentstackUid)
if (entryPresent) {
Expand All @@ -201,7 +200,7 @@ const createEntry = async ({ packagePath, contentTypes, master_locale = 'en-us',
const entryLocale: any = {};
if (typeof LOCALE_MAPPER?.masterLocale === 'object' && LOCALE_MAPPER?.masterLocale !== null && LOCALE_MAPPER?.masterLocale?.[master_locale] === locale) {
newLocale = Object?.keys(LOCALE_MAPPER?.masterLocale)?.[0];
Object.entries(entryPresent?.locale?.[locale] || {}).forEach(async ([uid, entry]: any) => {
Object.entries(entryPresent?.locale?.[locale] || {}).map(async ([uid, entry]: any) => {
const entryObj: any = {};
entryObj.uid = uid;
for await (const field of entry?.fields?.field ?? []) {
Expand All @@ -214,28 +213,31 @@ const createEntry = async ({ packagePath, contentTypes, master_locale = 'en-us',
entryObj[fsc?.contentstackFieldUid] = `/${entry?.meta?.key}`;
}
if (getLastKey(fsc?.uid) === field?.$?.key) {
const content: any = await entriesFieldCreator({ field: fsc, content: field?.content, idCorrector, allAssetJSON })
const content: any = await entriesFieldCreator({ field: fsc, content: field?.content, idCorrector, allAssetJSON, contentTypes, entriesData, locale })
entryObj[fsc?.contentstackFieldUid] = content;
}
}
}
}
entryLocale[uid] = unflatten(entryObj) ?? {};
if (Object.keys?.(entryObj)?.length > 1) {
entryLocale[uid] = unflatten(entryObj) ?? {};
}
});
}
const fileMeta = { "1": `${locale}.json` };
const fileMeta = { "1": `${newLocale}.json` };
const entryPath = path.join(
process.cwd(),
entrySave,
ctType?.contentstackUid,
newLocale
);
await writeFiles(entryPath, fileMeta, entryLocale, locale)
await writeFiles(entryPath, fileMeta, entryLocale, newLocale)
}
} else {
console.info('Entries missing for', ctType?.contentstackUid)
}
}
return true;
} catch (err) {
console.error("🚀 ~ createEntry ~ err:", err)
}
Expand Down
25 changes: 18 additions & 7 deletions api/src/utils/content-type-creator.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,17 +86,28 @@ const convertToSchemaFormate = ({ field, advanced = true }: any) => {
case 'json': {
return {
"data_type": "json",
"display_name": field?.name,
"display_name": field?.title ?? field?.uid,
"uid": field?.uid,
"field_metadata": {
"allow_json_rte": true,
"embed_entry": false,
"description": "",
"default_value": "",
"multiline": false,
"rich_text_type": "advanced",
"options": []
},
"reference_to": [],
"non_localizable": false,
"format": "",
"error_messages": {
"format": ""
},
"reference_to": [
"sys_assets"
],
"multiple": false,
"mandatory": false,
"unique": false
"non_localizable": false,
"unique": false,
"mandatory": false
}
// return {
// "display_name": name,
Expand Down Expand Up @@ -316,7 +327,7 @@ const convertToSchemaFormate = ({ field, advanced = true }: any) => {
"display_name": field?.title,
"uid": field?.uid,
"data_type": "text",
"mandatory": true,
"mandatory": false,
"unique": true,
"field_metadata": {
"_default": true
Expand Down Expand Up @@ -409,7 +420,7 @@ export const contenTypeMaker = async ({ contentType, destinationStackId }: any)
"field_metadata": {},
"schema": [],
"uid": item?.contentstackFieldUid,
"multiple": true,
"multiple": false,
"mandatory": false,
"unique": false
}
Expand Down
Loading