diff --git a/packages/admin-panel-server/src/routes/ExportEntityHierarchiesRoute.ts b/packages/admin-panel-server/src/routes/ExportEntityHierarchiesRoute.ts index b7fa815e99..56cac28c7a 100644 --- a/packages/admin-panel-server/src/routes/ExportEntityHierarchiesRoute.ts +++ b/packages/admin-panel-server/src/routes/ExportEntityHierarchiesRoute.ts @@ -5,6 +5,7 @@ import { Request } from 'express'; import xlsx from 'xlsx'; +import { keyBy } from 'lodash'; import { Route } from '@tupaia/server-boilerplate'; export type ExportEntityHierarchiesRequest = Request< @@ -14,6 +15,15 @@ export type ExportEntityHierarchiesRequest = Request< Record >; +type ExportEntityHierarchiesData = { + parent_name: string; + parent_code: string; + name: string; + code: string; + type: string; + attributes: Record; +}; + export class ExportEntityHierarchiesRoute extends Route { protected readonly type = 'download'; @@ -30,18 +40,59 @@ export class ExportEntityHierarchiesRoute extends Route { + const record = { + 'grandparent name': undefined, + 'grandparent code': undefined, + 'parent name': undefined, + 'parent code': row.parent_code, + name: row.name, + code: row.code, + type: row.type, + attributes: Object.entries(row.attributes) + .map(([key, value]) => `${key}: ${value}`) + .join('\n'), + }; + + if (row.parent_code) { + const parent = descendantsByCode[row.parent_code]; + record['parent name'] = parent?.name; + + if (parent?.parent_code) { + const grandparent = descendantsByCode[parent.parent_code]; + record['grandparent name'] = grandparent?.name; + record['grandparent code'] = grandparent?.code; + } + } + + return record; + }); + const projectEntity = await entityApi.getEntity(hierarchy, hierarchy, { fields: ['name'], }); const sheetName = projectEntity?.name || hierarchy; - const sheet = xlsx.utils.json_to_sheet(descendants); + const sheet = xlsx.utils.json_to_sheet(data, { + header: [ + 'grandparent name', + 'grandparent code', + 'parent name', + 'parent code', + 'name', + 'code', + 'type', + 'attributes', + ], + }); xlsx.utils.book_append_sheet(workbook, sheet, sheetName); }