sgnm-neo4j-excel
Version:
neo4j excel module for nestJs
1,404 lines (1,263 loc) • 96.6 kB
text/typescript
import {
Injectable,
Inject,
OnApplicationShutdown,
HttpException,
} from "@nestjs/common";
import neo4j, { Driver, Result, int, Transaction } from "neo4j-driver";
import { Neo4jConfig } from "./interfaces/neo4j-config.interface";
import { NEO4J_OPTIONS, NEO4J_DRIVER } from "./neo4j.constants";
import TransactionImpl from "neo4j-driver-core/lib/transaction";
import {
changeObjectKeyName,
dynamicFilterPropertiesAdder,
dynamicFilterPropertiesAdderAndAddParameterKey,
dynamicLabelAdder,
filterArrayForEmptyString,
} from "./func/common.func";
import {
ExportExcelDto,
ExportExcelDtoForSystem,
ExportExcelDtoForType,
} from "./dtos/export-import.dtos";
import {
MainHeaderInterface,
UserInformationInterface,
} from "./interfaces/header.interface";
import { CustomClassificationError } from "./constant/import-export.error.enum";
import {
block_already_exist_object,
building_already_exist_object,
contact_already_exist_object,
floor_already_exist_object,
space_already_exist_object,
space_has_already_relation_object,
there_are_no_contacts_object,
there_are_no_jointSpaces_object,
there_are_no_spaces_object,
there_are_no_system_or_component_or_type_object,
there_are_no_type_or_component_or_type_id_is_wrong_object,
there_are_no_zones_object,
there_is_no_type_object,
} from "./constant/import-export.error.object";
import { FilterPropertiesType } from "./constant/filter.properties.type.enum";
const exceljs = require("exceljs");
const { v4: uuidv4 } = require("uuid");
const moment = require("moment");
@Injectable()
export class Neo4jExcelService implements OnApplicationShutdown {
private readonly driver: Driver;
private readonly config: Neo4jConfig;
constructor(
@Inject(NEO4J_OPTIONS) config: Neo4jConfig,
@Inject(NEO4J_DRIVER) driver: Driver
) {
this.driver = driver;
this.config = config;
}
getDriver(): Driver {
return this.driver;
}
getConfig(): Neo4jConfig {
return this.config;
}
int(value: number) {
return int(value);
}
beginTransaction(database?: string): Transaction {
const session = this.getWriteSession(database);
return session.beginTransaction();
}
getReadSession(database?: string) {
return this.driver.session({
database: database || this.config.database,
defaultAccessMode: neo4j.session.READ,
});
}
getWriteSession(database?: string) {
return this.driver.session({
database: database || this.config.database,
defaultAccessMode: neo4j.session.WRITE,
});
}
read(
cypher: string,
params?: Record<string, any>,
databaseOrTransaction?: string | Transaction
): Result {
if (databaseOrTransaction instanceof TransactionImpl) {
return (<Transaction>databaseOrTransaction).run(cypher, params);
}
const session = this.getReadSession(<string>databaseOrTransaction);
return session.run(cypher, params);
}
write(
cypher: string,
params?: Record<string, any>,
databaseOrTransaction?: string | Transaction
): Result {
if (databaseOrTransaction instanceof TransactionImpl) {
return (<Transaction>databaseOrTransaction).run(cypher, params);
}
const session = this.getWriteSession(<string>databaseOrTransaction);
return session.run(cypher, params);
}
onApplicationShutdown() {
return this.driver.close();
}
async findChildrensByLabelsAndFilters(
root_labels: string[] = [],
root_filters: object = {},
children_labels: string[] = [],
children_filters: object = {},
relation_name: string,
relation_filters: object = {},
relation_depth: number | "" = "",
databaseOrTransaction?: string | Transaction
) {
try {
const rootLabelsWithoutEmptyString =
filterArrayForEmptyString(root_labels);
const childrenLabelsWithoutEmptyString =
filterArrayForEmptyString(children_labels);
const cypher =
`MATCH p=(n` +
dynamicLabelAdder(rootLabelsWithoutEmptyString) +
dynamicFilterPropertiesAdder(root_filters) +
`-[r:${relation_name}*1..${relation_depth}` +
dynamicFilterPropertiesAdderAndAddParameterKey(relation_filters,FilterPropertiesType.RELATION,'2') +
` ]->(m` +
dynamicLabelAdder(childrenLabelsWithoutEmptyString) +
dynamicFilterPropertiesAdderAndAddParameterKey(children_filters) +
` RETURN n as parent,m as children,r as relation`;
children_filters = changeObjectKeyName(children_filters);
relation_filters = changeObjectKeyName(relation_filters,'2');
const parameters = { ...root_filters, ...children_filters,...relation_filters};
const result = await this.read(cypher, parameters, databaseOrTransaction);
return result["records"];
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error, 500);
}
}
}
//** ASSET //
async getTypesExcel(
res,
body: ExportExcelDtoForType,
header: UserInformationInterface
) {
try {
let data = [];
const { typeKeys } = body;
const { username, language, realm } = header;
for (let key of typeKeys) {
let newData = await this.getTypesByRealmAndByLanguage(
realm,
key,
language,
username
);
if (newData instanceof Error) {
throw new HttpException(there_is_no_type_object, 404);
} else {
data = [...data, ...newData];
}
}
let workbook = new exceljs.Workbook();
let worksheet = workbook.addWorksheet("Types");
worksheet.columns = [
{ header: "Type Name", key: "typeName", width: 50 },
{ header: "Model Name", key: "modelNumber", width: 50 },
{ header: "Super Set", key: "superSet", width: 50 },
{ header: "Description", key: "description", width: 50 },
{
header: "Warranty Duration Parts",
key: "warrantyDurationParts",
width: 50,
},
{
header: "Warranty Duration Labor",
key: "warrantyDurationLabor",
width: 50,
},
{ header: "Omni Category", key: "omniCategory", width: 50 },
{ header: "Asset Type", key: "assetType", width: 50 },
{ header: "Type Category", key: "typeCategory", width: 50 },
{ header: "Brand", key: "brand", width: 50 },
{ header: "Duration Unit", key: "durationUnit", width: 50 },
{ header: "Warranty Duration Unit", key: "warrantyDurationUnit", width: 50 },
{ header: "Measurement Unit", key: "measurementUnit", width: 50 },
{ header: "Created At", key: "createdAt", width: 50 },
];
worksheet.addRows(data);
return workbook.xlsx.write(res).then(function () {
res.status(200).end();
});
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
async getTypesByRealmAndByLanguage(
realm: string,
typeKey: string,
language: string,
userName: string
) {
try {
let data: any;
let jsonData = [];
let cypher = `WITH 'MATCH (c:Asset {realm:"${realm}"})-[:PARENT_OF {isDeleted:false}]->(b:Types) MATCH path = (b)-[:PARENT_OF {isDeleted:false}]->(m:Type {key:"${typeKey}"})-[:CLASSIFIED_BY| ASSET_TYPE_BY| WARRANTY_DURATION_UNIT_BY | TYPE_CLASSIFIED_BY| BRAND_BY | DURATION_UNIT_BY | MEASUREMENT_UNIT_BY {isDeleted:false}]->(z) where z.language="${language}" and m.isDeleted=false and not (m:Component)
WITH collect(path) AS paths
CALL apoc.convert.toTree(paths)
YIELD value
RETURN value' AS query
CALL apoc.export.json.query(query,'/${userName}.json',{jsonFormat:'ARRAY_JSON'})
YIELD file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data
RETURN file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data`;
await this.write(cypher);
//call the file using below code
let cypher2 = `CALL apoc.load.json("${userName}.json")`;
let returnData = await this.read(cypher2);
data = await returnData.records[0]["_fields"][0];
if (data.length == 0) {
throw new HttpException(there_is_no_type_object, 404);
} else {
for (let index = 0; index < data.value.parent_of?.length; index++) {
let typeProperties = data.value.parent_of[index];
jsonData.push({
typeName: typeProperties.name,
modelNumber: typeProperties.modelNumber,
superSet:typeProperties.superSet,
description: typeProperties.description,
warrantyDurationParts: typeProperties.warrantyDurationParts,
warrantyDurationLabor: typeProperties.warrantyDurationLabor,
omniCategory: typeProperties.classified_by[0].name,
assetType: typeProperties.asset_type_by[0].name,
typeCategory: typeProperties.type_classified_by[0].name,
brand: typeProperties.brand_by[0].name,
durationUnit: typeProperties.duration_unit_by[0].name,
warrantyDurationUnit: typeProperties.warranty_duration_unit_by[0].name,
measurementUnit: typeProperties.measurement_unit_by[0].name,
createdAt: typeProperties.createdAt,
});
}
return jsonData;
}
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
async getComponentsExcel(
res,
body: ExportExcelDtoForType,
header: UserInformationInterface
) {
let data = [];
const { typeKeys } = body;
const { username, realm } = header;
try {
for (let key of typeKeys) {
let newData = await this.getComponentsOfTypeWithTypekey(
realm,
key,
username
);
if (newData instanceof Error) {
throw new HttpException(
there_are_no_type_or_component_or_type_id_is_wrong_object,
404
);
} else {
data = [...data, ...newData];
}
}
let workbook = new exceljs.Workbook();
let worksheet = workbook.addWorksheet("Components");
worksheet.columns = [
{ header: "Type Name", key: "typeName", width: 50 },
{ header: "Component Name", key: "componentName", width: 50 },
{ header: "Space Name", key: "spaceName", width: 50 },
{ header: "Description", key: "description", width: 50 },
{ header: "AssetIdentifier", key: "assetIdentifier", width: 50 },
{ header: "Serial No", key: "serialNo", width: 50 },
{
header: "Warranty Duration Labor",
key: "warrantyDurationLabor",
width: 50,
},
{
header: "Warranty Duration Parts",
key: "warrantyDurationParts",
width: 50,
},
];
worksheet.addRows(data);
return workbook.xlsx.write(res).then(function () {
res.status(200).end();
});
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
async getComponentsOfTypeWithTypekey(
realm: string,
typeKey: string,
username: string
) {
try {
let data: any;
let jsonData = [];
let cypher = `WITH 'MATCH (a:Asset {realm:"${realm}"})-[:PARENT_OF {isDeleted:false}]->(b:Types) MATCH path = (b)-[:PARENT_OF {isDeleted:false}]->(t:Type {key:"${typeKey}"})-[:PARENT_OF {isDeleted:false}]->(c:Component)-[:WARRANTY_GUARANTOR_LABOR_BY | WARRANTY_GUARANTOR_PARTS_BY | LOCATED_IN {isDeleted:false}]->(x) where t.isDeleted=false and c.isDeleted=false
WITH collect(path) AS paths
CALL apoc.convert.toTree(paths)
YIELD value
RETURN value' AS query
CALL apoc.export.json.query(query,'/${username}.json',{jsonFormat:'ARRAY_JSON'})
YIELD file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data
RETURN file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data`;
await this.write(cypher);
//call the file using below code
let cypher2 = `CALL apoc.load.json("${username}.json")`;
let returnData = await this.read(cypher2);
data = await returnData.records[0]["_fields"][0];
if (data.length == 0) {
throw new HttpException(
there_are_no_type_or_component_or_type_id_is_wrong_object,
404
);
} else {
for (let j = 0; j < data.value.parent_of?.length; j++) {
// type
for (let i = 0; i < data.value.parent_of[j].parent_of?.length; i++) {
// components
let componentProperties = data.value.parent_of[j].parent_of[i];
jsonData.push({
typeName: data.value.parent_of[j].name,
componentName: componentProperties.name,
spaceName: componentProperties.located_in[0].name,
description: componentProperties.description,
assetIdentifier: componentProperties.assetIdentifier,
serialNo: componentProperties.serialNo,
warrantyDurationLabor:
componentProperties.warrantyDurationLabor,
warrantyDurationParts:
componentProperties.warrantyDurationParts,
});
}
}
return jsonData;
}
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
async getSparesWithExcel(
res,
body: ExportExcelDtoForType,
header: UserInformationInterface
) {
let data = [];
const { typeKeys } = body;
const { username, realm,language } = header;
try {
for (let key of typeKeys) {
let newData = await this.getSparesOfTypeWithTypekey(
realm,
key,
username,
language
);
if (newData instanceof Error) {
throw new HttpException(
there_are_no_type_or_component_or_type_id_is_wrong_object,
404
);
} else {
data = [...data, ...newData];
}
}
let workbook = new exceljs.Workbook();
let worksheet = workbook.addWorksheet("Spares");
worksheet.columns = [
{ header: "Type Name", key: "typeName", width: 50 },
{ header: "Spare Name", key: "spareName", width: 50 },
{ header: "Space Name", key: "spaceName", width: 50 },
{ header: "Count", key: "count", width: 50 },
{ header: "Description", key: "description", width: 50 },
{ header: "PartNumber", key: "partNumber", width: 50 },
{ header: "SetNumber", key: "setNumber", width: 50 },
];
worksheet.addRows(data);
return workbook.xlsx.write(res).then(function () {
res.status(200).end();
});
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
async getSparesOfTypeWithTypekey(
realm: string,
typeKey: string,
username: string,
language:string
) {
try {
let data: any;
let jsonData = [];
let cypher = `WITH 'MATCH (a:Asset {realm:"${realm}"})-[:PARENT_OF {isDeleted:false}]->(b:Types) MATCH path = (b)-[:PARENT_OF {isDeleted:false}]->(t:Type {key:"${typeKey}"})-[:PARENT_OF {isDeleted:false}]->(c:Spare)-[:CLASSIFIED_BY | STORED_IN {isDeleted:false}]->(x) where (x.language="${language}" or not exists(x.language)) and t.isDeleted=false and c.isDeleted=false
WITH collect(path) AS paths
CALL apoc.convert.toTree(paths)
YIELD value
RETURN value' AS query
CALL apoc.export.json.query(query,'/${username}.json',{jsonFormat:'ARRAY_JSON'})
YIELD file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data
RETURN file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data`;
await this.write(cypher);
//call the file using below code
let cypher2 = `CALL apoc.load.json("${username}.json")`;
let returnData = await this.read(cypher2);
data = await returnData.records[0]["_fields"][0];
if (data.length == 0) {
throw new HttpException(
there_are_no_type_or_component_or_type_id_is_wrong_object,
404
);
} else {
for (let j = 0; j < data.value.parent_of?.length; j++) {
// type
for (let i = 0; i < data.value.parent_of[j].parent_of?.length; i++) {
// spares
let spareProperties = data.value.parent_of[j].parent_of[i];
jsonData.push({
typeName: data.value.parent_of[j].name,
spareName: spareProperties.name,
spaceName: spareProperties.stored_in[0].name,
count: spareProperties.count,
description: spareProperties.description,
partNumber: spareProperties.partNumber,
setNumber: spareProperties.setNumber,
});
}
}
return jsonData;
}
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
async getResourcesWithExcel(
res,
body: ExportExcelDtoForType,
header
) {
let data = [];
const { typeKeys } = body;
const { username, realm,language } = header;
try {
for (let key of typeKeys) {
let newData = await this.getResourcesOfTypeWithTypeKey(
realm,
key,
username,
language
);
if (newData instanceof Error) {
throw new HttpException(
//there_are_no_type_or_component_or_type_id_is_wrong_object,
"",
404
);
} else {
data = [...data, ...newData];
}
}
let workbook = new exceljs.Workbook();
let worksheet = workbook.addWorksheet("Resources");
worksheet.columns = [
{ header: "Type Name", key: "typeName", width: 50 },
{ header: "Resource Name", key: "resourceName", width: 50 },
{ header: "Space Name", key: "spaceName", width: 50 },
{ header: "Count", key: "count", width: 50 },
// { header: "Classification", key: "classification", width: 50 },
{ header: "Measurement Unit", key: "measurementUnit", width: 50 },
{ header: "Description", key: "description", width: 50 },
{ header: "SetNumber", key: "setNumber", width: 50 },
];
worksheet.addRows(data);
return workbook.xlsx.write(res).then(function () {
res.status(200).end();
});
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
async getResourcesOfTypeWithTypeKey(
realm: string,
typeKey: string,
username: string,
language:string
) {
try {
let data: any;
let jsonData = [];
let cypher = `WITH 'MATCH (a:Asset {realm:"${realm}"})-[:PARENT_OF {isDeleted:false}]->(b:Types) MATCH path = (b)-[:PARENT_OF {isDeleted:false}]->(t:Type {key:"${typeKey}"})-[:PARENT_OF {isDeleted:false}]->(c:Resource)-[:CLASSIFIED_BY | STORED_IN | MEASUREMENT_UNIT_BY {isDeleted:false}]->(x) where (x.language="${language}" or not exists(x.language)) and t.isDeleted=false and c.isDeleted=false
WITH collect(path) AS paths
CALL apoc.convert.toTree(paths)
YIELD value
RETURN value' AS query
CALL apoc.export.json.query(query,'/${username}.json',{jsonFormat:'ARRAY_JSON'})
YIELD file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data
RETURN file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data`;
await this.write(cypher);
//call the file using below code
let cypher2 = `CALL apoc.load.json("${username}.json")`;
let returnData = await this.read(cypher2);
data = await returnData.records[0]["_fields"][0];
if (data.length == 0) {
throw new HttpException(
// there_are_no_type_or_component_or_type_id_is_wrong_object,
"",
404
);
} else {
for (let j = 0; j < data.value.parent_of?.length; j++) {
// type
for (let i = 0; i < data.value.parent_of[j].parent_of?.length; i++) {
// resources
let resourceProperties = data.value.parent_of[j].parent_of[i];
jsonData.push({
typeName: data.value.parent_of[j].name,
resourceName: resourceProperties.name,
spaceName: resourceProperties.stored_in[0].name,
count: resourceProperties.count,
// classification: resourceProperties.classified_by[0].name,
measurementUnit: resourceProperties.measurement_unit_by[0].name,
description: resourceProperties.description,
setNumber: resourceProperties.setNumber,
});
}
}
return jsonData;
}
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
async getSystemsExcel(
res,
body: ExportExcelDtoForSystem,
header: UserInformationInterface
) {
let data = [];
const { systemKeys } = body;
const { username, realm } = header;
try {
for (let key of systemKeys) {
let newData = await this.getSystemsByKey(realm, key, username);
if (newData instanceof Error) {
throw new HttpException(
there_are_no_system_or_component_or_type_object,
404
);
} else {
data = [...data, ...newData];
}
}
let workbook = new exceljs.Workbook();
let worksheet = workbook.addWorksheet("Systems");
worksheet.columns = [
{ header: "System Name", key: "systemName", width: 50 },
{ header: "System Description", key: "systemDescription", width: 50 },
{ header: "Creator", key: "creator", width: 50 },
{ header: "Type Name", key: "typeName", width: 50 },
{ header: "Component Name", key: "componentName", width: 50 },
{ header: "Space Name", key: "spaceName", width: 50 },
{ header: "Description", key: "description", width: 50 },
{ header: "Serial No", key: "serialNo", width: 50 },
{
header: "Warranty Duration Labor",
key: "warrantyDurationLabor",
width: 50,
},
{
header: "Warranty Duration Parts",
key: "warrantyDurationParts",
width: 50,
},
];
worksheet.addRows(data);
return workbook.xlsx.write(res).then(function () {
res.status(200).end();
});
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
async getSystemsByKey(realm: string, systemKey: string, username: string) {
try {
let data: any;
let jsonData = [];
let cypher = `WITH 'MATCH (a:Asset {realm:"${realm}"})-[:PARENT_OF {isDeleted:false}]->(b:Systems)-[:PARENT_OF* {isDeleted:false}]->(s:System {key:"${systemKey}",isDeleted:false}) MATCH path = (s)-[:SYSTEM_OF | TYPE_OF_SYSTEM | CREATED_BY {isDeleted:false}]->(ct) where ct.isDeleted=false
WITH collect(path) AS paths
CALL apoc.convert.toTree(paths)
YIELD value
RETURN value' AS query
CALL apoc.export.json.query(query,'/${username}.json',{jsonFormat:'ARRAY_JSON'})
YIELD file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data
RETURN file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data`;
await this.write(cypher);
//call the file using below code
let cypher2 = `CALL apoc.load.json("${username}.json")`;
let returnData = await this.read(cypher2);
data = await returnData.records[0]["_fields"][0];
console.log(data);
if (data.length == 0) {
throw new HttpException(
there_are_no_system_or_component_or_type_object,
404
);
} else {
// system
if(data.value.system_of?.length>0){
for (let c = 0; c < data.value.system_of?.length; c++) {
// components
let componentProperties = data.value.system_of[c];
jsonData.push({
systemName: data.value.name,
systemDescription: data.value.description,
creator: data.value.created_by[0].name,
typeName: "",
componentName: componentProperties.name,
spaceName: componentProperties.spaceName,
description: componentProperties.description,
serialNo: componentProperties.serialNumber,
warrantyDurationLabor:
componentProperties.warrantyDurationLabor.low,
warrantyDurationParts:
componentProperties.warrantyDurationParts.low,
});
}
}
if(data.value.type_of_system?.length>0){
for (let c = 0; c < data.value.type_of_system?.length; c++) {
// types
let typeProperties = data.value.type_of_system[c];
jsonData.push({
systemName: data.value.name,
systemDescription: data.value.description,
creator: data.value.created_by[0].name,
typeName: typeProperties.name ? typeProperties.name:"",
componentName: "",
spaceName: "",
description: "",
serialNo: "",
warrantyDurationLabor:
"",
warrantyDurationParts:
"",
});
}
}
return jsonData;
}
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
//! FACILITY //
async getSpacesByBuilding(
realm: string,
username: string,
buildingKey: string,
language: string
) {
try {
let data: any;
let jsonData = [];
let buildingType = [];
let cypher = `WITH 'MATCH (c:FacilityStructure {realm:"${realm}"})-[:PARENT_OF {isDeleted:false}]->(b {key:"${buildingKey}",isDeleted:false}) MATCH path = (b)-[:PARENT_OF* {isDeleted:false}]->(m)-[:CLASSIFIED_BY| CREATED_BY {isDeleted:false}]->(z) where (z.language="${language}" or not exists(z.language)) and m.isDeleted=false and not (m:JointSpaces OR m:JointSpace OR m:Zones or m:Zone)
WITH collect(path) AS paths
CALL apoc.convert.toTree(paths)
YIELD value
RETURN value' AS query
CALL apoc.export.json.query(query,'/${username}.json',{jsonFormat:'ARRAY_JSON'})
YIELD file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data
RETURN file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data`;
await this.write(cypher);
//call the file using below code
let cypher2 = `CALL apoc.load.json("${username}.json")`;
let returnData = await this.read(cypher2);
data = await returnData.records[0]["_fields"][0];
if (
data.value.parent_of == undefined ||
(data.value.parent_of[0]?.nodeType == "Floor" &&
typeof data.value.parent_of[0].parent_of == "undefined") ||
(data.value.parent_of[0]?.nodeType == "Block" &&
(typeof data.value.parent_of[0].parent_of == "undefined" ||
typeof data.value.parent_of[0].parent_of[0].parent_of ==
"undefined"))
) {
throw new HttpException(there_are_no_spaces_object, 404);
} else {
if (data.value.parent_of[0]?.parent_of[0]?.parent_of == undefined) {
for (let index = 0; index < data.value.parent_of?.length; index++) {
for (
let i = 0;
i < data.value.parent_of[index].parent_of?.length;
i++
) {
buildingType.push({
1: data.value.nodeType,
2: data.value.parent_of[index].nodeType,
3: data.value.parent_of[index].parent_of[i].nodeType,
});
}
}
} else {
for (let index = 0; index < data.value.parent_of?.length; index++) {
for (
let i = 0;
i < data.value.parent_of[index].parent_of?.length;
i++
) {
for (
let a = 0;
a < data.value.parent_of[index].parent_of[i].parent_of?.length;
a++
) {
buildingType.push({
1: data.value.nodeType,
2: data.value.parent_of[index].nodeType,
3: data.value.parent_of[index].parent_of[i].nodeType,
4: data.value.parent_of[index].parent_of[i].parent_of[a]
.nodeType,
});
}
}
}
}
let typeList = await Object.values(buildingType[0]);
if (!typeList.includes("Block")) {
for (let index = 0; index < data.value.parent_of?.length; index++) {
for (
let i = 0;
i < data.value.parent_of[index].parent_of?.length;
i++
) {
let spaceProperties = data.value.parent_of[index].parent_of[i];
jsonData.push({
buildingName: data.value.name,
blockName: "-",
floorName: data.value.parent_of[index].name,
spaceName: spaceProperties.name,
code: spaceProperties.code ? spaceProperties.code : " ",
architecturalName: spaceProperties.architecturalName,
architecturalCode: spaceProperties.architecturalCode
? spaceProperties.architecturalCode
: " ",
category: spaceProperties.classified_by[0].name,
grossArea: spaceProperties.grossArea.low,
netArea: spaceProperties.netArea.low,
usage: spaceProperties.usage ? spaceProperties.usage : " ",
tag: spaceProperties.tag.toString(),
roomTag: spaceProperties.roomTag.toString(),
status: spaceProperties.status ? spaceProperties.status : " ",
operatorName: spaceProperties.operatorName
? spaceProperties.operatorName
: " ",
operatorCode: spaceProperties.operatorCode
? spaceProperties.operatorCode
: " ",
description: spaceProperties.description,
usableHeight: spaceProperties.usableHeight.low,
externalSystem: spaceProperties.externalSystem,
externalObject: spaceProperties.externalObject,
externalIdentifier: spaceProperties.externalIdentifier,
createdAt: spaceProperties.createdAt,
createdBy: spaceProperties.created_by[0].email,
});
}
}
} else {
for (let index = 0; index < data.value.parent_of?.length; index++) {
for (
let i = 0;
i < data.value.parent_of[index]?.parent_of?.length;
i++
) {
for (
let a = 0;
a <
data.value.parent_of[index]?.parent_of[i]?.parent_of?.length;
a++
) {
let spaceProperties =
data.value.parent_of[index]?.parent_of[i]?.parent_of[a];
jsonData.push({
buildingName: data.value.name,
blockName: data.value.parent_of[index].name,
floorName: data.value.parent_of[index].parent_of[i].name,
spaceName:
data.value.parent_of[index].parent_of[i].parent_of[a].name,
code: spaceProperties.code ? spaceProperties.code : " ",
architecturalName: spaceProperties.architecturalName,
architecturalCode: spaceProperties.architecturalCode
? spaceProperties.architecturalCode
: " ",
category: spaceProperties.classified_by[0].name,
grossArea: spaceProperties.grossArea,
netArea: spaceProperties.netArea,
usage: spaceProperties.usage ? spaceProperties.usage : " ",
tag: spaceProperties.tag.toString(),
roomTag: spaceProperties.roomTag.toString(),
status: spaceProperties.status ? spaceProperties.status : " ",
operatorName: spaceProperties.operatorName
? spaceProperties.operatorName
: " ",
operatorCode: spaceProperties.operatorCode
? spaceProperties.operatorCode
: " ",
description: spaceProperties.description,
usableHeight: spaceProperties.usableHeight,
externalSystem: spaceProperties.externalSystem,
externalObject: spaceProperties.externalObject,
externalIdentifier: spaceProperties.externalIdentifier,
createdAt: spaceProperties.createdAt,
createdBy: spaceProperties.created_by[0].email,
});
}
}
}
}
return jsonData;
}
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
async getJointSpacesByBuilding(
realm: string,
username: string,
buildingKey: string,
language: string
) {
try {
let data: any;
let jsonData = [];
let cypher = `WITH 'MATCH (c:FacilityStructure {realm:"${realm}"})-[:PARENT_OF {isDeleted:false}]->(b {key:"${buildingKey}",isDeleted:false}) MATCH path = (b)-[:PARENT_OF* {isDeleted:false}]->(m)-[:CLASSIFIED_BY| CREATED_BY {isDeleted:false}]->(z) where (z.language="${language}" or not exists(z.language)) and m.isDeleted=false and not (m:Space OR m:Zone OR m:Zones OR m:Floor OR m:Block)
WITH collect(path) AS paths
CALL apoc.convert.toTree(paths)
YIELD value
RETURN value' AS query
CALL apoc.export.json.query(query,'/${username}.json',{jsonFormat:'ARRAY_JSON'})
YIELD file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data
RETURN file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data`;
await this.write(cypher);
//call the file using below code
let cypher2 = `CALL apoc.load.json("${username}.json")`;
let returnData = await this.read(cypher2);
data = await returnData.records[0]["_fields"][0];
if (Object.keys(data?.value).length == 0) {
throw new HttpException(there_are_no_jointSpaces_object(), 404);
}
for (let index = 0; index < data.value.parent_of?.length; index++) {
for (
let i = 0;
i < data.value.parent_of[index].parent_of?.length;
i++
) {
let jointSpaceProperties = data.value.parent_of[index].parent_of[i];
jsonData.push({
buildingName: data.value.name,
jointSpaceName: jointSpaceProperties.name,
category: jointSpaceProperties.classified_by[0].name,
spaceNames: jointSpaceProperties.jointSpaceTitle,
description: jointSpaceProperties.description,
tags: jointSpaceProperties.tag.toString(),
roomTags: jointSpaceProperties.roomTag.toString(),
status: jointSpaceProperties.status
? jointSpaceProperties.status
: " ",
usage: jointSpaceProperties.usage
? jointSpaceProperties.usage
: " ",
usableHeight: jointSpaceProperties.usableHeight
? jointSpaceProperties.usableHeight
: " ",
grossArea: jointSpaceProperties.grossArea
? jointSpaceProperties.grossArea
: " ",
netArea: jointSpaceProperties.netArea
? jointSpaceProperties.netArea
: " ",
});
}
}
return jsonData;
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(
{
code: CustomClassificationError.DEFAULT_ERROR,
message: error.message,
},
error.status
);
}
}
}
async getZonesByBuilding(
realm: string,
username: string,
buildingKey: string,
language: string
) {
try {
let data: any;
let jsonData = [];
let cypher = `WITH 'MATCH (c:FacilityStructure {realm:"${realm}"})-[:PARENT_OF {isDeleted:false}]->(b:Building {key:"${buildingKey}",isDeleted:false}) MATCH path = (b)-[:PARENT_OF* {isDeleted:false}]->(m)-[:CREATED_BY| CLASSIFIED_BY {isDeleted:false}]->(z) where (z.language="${language}" or not exists(z.language)) and m.isDeleted=false and not (m:Space OR m:JointSpaces OR m:JointSpace OR m:Floor OR m:Block)
WITH collect(path) AS paths
CALL apoc.convert.toTree(paths)
YIELD value
RETURN value' AS query
CALL apoc.export.json.query(query,'/${username}.json',{jsonFormat:'ARRAY_JSON'})
YIELD file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data
RETURN file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data`;
await this.write(cypher);
//call the file using below code
let cypher2 = `CALL apoc.load.json("${username}.json")`;
let returnData = await this.read(cypher2);
data = await returnData.records[0]["_fields"][0];
if (Object.keys(data?.value).length == 0) {
throw new HttpException(there_are_no_zones_object, 404);
} else {
for (let index = 0; index < data.value.parent_of?.length; index++) {
for (
let i = 0;
i < data.value.parent_of[index].parent_of?.length;
i++
) {
jsonData.push({
buildingName: data.value.name,
zoneName: data.value.parent_of[index].parent_of[i].name,
category:
data.value.parent_of[index].parent_of[i].classified_by[0].name,
createdBy:
data.value.parent_of[index].parent_of[i].created_by[0].email,
spaceNames:
data.value.parent_of[index].parent_of[i].spaceNames.toString(),
description: data.value.parent_of[index].parent_of[i].description,
tags: data.value.parent_of[index].parent_of[i].tag.toString(),
});
}
}
return jsonData;
}
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
async getSpacesAnExcelFile(
res,
body: ExportExcelDto,
header: UserInformationInterface
) {
let { buildingKeys } = body;
let { realm, username, language } = header;
try {
let data = [];
for (let item of buildingKeys) {
let newData = await this.getSpacesByBuilding(
realm,
username,
item,
language
);
if (newData instanceof Error) {
throw new HttpException(there_are_no_spaces_object, 404);
} else {
data = [...data, ...newData];
}
}
let workbook = new exceljs.Workbook();
let worksheet = workbook.addWorksheet("Spaces");
worksheet.columns = [
{ header: "Building Name", key: "buildingName", width: 50 },
{ header: "Block Name", key: "blockName", width: 50 },
{ header: "Floor Name", key: "floorName", width: 50 },
{ header: "Space Name", key: "spaceName", width: 50 },
{ header: "Code", key: "code", width: 50 },
{ header: "architecturalName", key: "architecturalName", width: 50 },
{ header: "architecturalCode", key: "architecturalCode", width: 50 },
{ header: "grossArea", key: "grossArea", width: 50 },
{ header: "netArea", key: "netArea", width: 50 },
{ header: "usage", key: "usage", width: 50 },
{ header: "tag", key: "tag", width: 50 },
{ header: "roomTag", key: "roomTag", width: 50 },
{ header: "status", key: "status", width: 50 },
{ header: "operatorName", key: "operatorName", width: 50 },
{ header: "operatorCode", key: "operatorCode", width: 50 },
{ header: "description", key: "description", width: 50 },
{ header: "usableHeight", key: "usableHeight", width: 50 },
{ header: "externalSystem", key: "externalSystem", width: 50 },
{ header: "externalObject", key: "externalObject", width: 50 },
{ header: "externalIdentifier", key: "externalIdentifier", width: 50 },
{ header: "createdAt", key: "createdAt", width: 50 },
{ header: "createdBy", key: "createdBy", width: 50 },
];
worksheet.addRows(data);
return workbook.xlsx.write(res).then(function () {
res.status(200).end();
});
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
async getZonesAnExcelFile(
res,
body: ExportExcelDto,
header: UserInformationInterface
) {
let { buildingKeys } = body;
let { realm, username, language } = header;
try {
let data = [];
for (let item of buildingKeys) {
let newData = await this.getZonesByBuilding(
realm,
username,
item,
language
);
if (newData instanceof Error) {
throw new HttpException(there_are_no_zones_object, 404);
} else {
data = [...data, ...newData];
}
}
let workbook = new exceljs.Workbook();
let worksheet = workbook.addWorksheet("Zones");
worksheet.columns = [
{ header: "buildingName", key: "buildingName", width: 50 },
{ header: "zoneName", key: "zoneName", width: 50 },
{ header: "category", key: "category", width: 50 },
{ header: "createdBy", key: "createdBy", width: 50 },
{ header: "spaceNames", key: "spaceNames", width: 50 },
{ header: "description", key: "description", width: 90 },
{ header: "tags", key: "tags", width: 50 },
];
worksheet.addRows(data);
return workbook.xlsx.write(res).then(function () {
res.status(200).end();
});
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
// if(error.response?.code===10012){
// there_are_no_zones()
// }else {
// default_error()
// }
}
}
async getJointSpacesAnExcelFile(
res,
body: ExportExcelDto,
header: UserInformationInterface
) {
let { buildingKeys } = body;
let { realm, username, language } = header;
try {
let data = [];
for (let item of buildingKeys) {
let newData = await this.getJointSpacesByBuilding(
realm,
username,
item,
language
);
if (newData instanceof Error) {
throw new HttpException(there_are_no_jointSpaces_object, 404);
} else {
data = [...data, ...newData];
}
}
let workbook = new exceljs.Workbook();
let worksheet = workbook.addWorksheet("JointSpaces");
worksheet.columns = [
{ header: "buildingName", key: "buildingName", width: 50 },
{ header: "jointSpaceName", key: "jointSpaceName", width: 50 },
{ header: "category", key: "category", width: 50 },
{ header: "createdBy", key: "createdBy", width: 50 },
{ header: "description", key: "description", width: 90 },
{ header: "tags", key: "tags", width: 50 },
{ header: "roomTags", key: "roomTags", width: 50 },
{ header: "status", key: "status", width: 50 },
{ header: "usage", key: "usage", width: 50 },
{ header: "usableHeight", key: "usableHeight", width: 50 },
{ header: "grossArea", key: "grossArea", width: 50 },
{ header: "netArea", key: "netArea", width: 50 },
];
worksheet.addRows(data);
return workbook.xlsx.write(res).then(function () {
res.status(200).end();
});
} catch (error) {
if (error.response?.code) {
throw new HttpException(
{ message: error.response?.message, code: error.response?.code },
error.status
);
} else {
throw new HttpException(error,500);
}
}
}
async getContactByRealmAndByLanguage(res, header: UserInformationInterface) {
const { language, username, realm } = header;
try {
let data: any;
let jsonData = [];
let cypher = `CALL apoc.export.json.query("match (b:Contacts {realm:'${realm}'})-[:PARENT_OF {isDeleted:false}]->(m:Contact)-[:CLASSIFIED_BY {isDeleted:false}]->(c) where m.isDeleted=false and c.language='${language}' return m,c.name as classificationName limit 100000",'/${username}.json',{jsonFormat:'ARRAY_JSON'})
YIELD file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data
RETURN file, source, format, nodes, relationships, properties, time, rows, batchSize, batches, done, data`;
await this.write(cypher);
//call the file using below code
let cypher2 = `CALL apoc.load.json("${username}.json")`;
let returnData = await this.read(cypher2);
data = returnData.records;
if (data.length == 0) {
throw new HttpException(there_are_no_contacts_object, 404);
} else {
for (let index = 0; index < data.length; index++) {
jsonData.push({
...data[index]["_fields"][0].m.properties,
...{
classificationName:
data[index]["_fields"][0]["classificationName"],
},
});
}
let workbook = new exceljs.Workbook();
let worksheet = workbook.addWorksheet("Contacts");
worksheet.columns = [
{ header: "Email", key: "email", width: 50 },
{ header: "Name", key: "givenName", width: 50 },
{ header: "Last Name", key: "familyName", width: 50 },
{ header: "Phone", key: "phone", width: 50 },
{ header: "Company", key: "company", width: 50 },
{ header: "Department", key: "department", width: 50 },
{ header: "Organization Code", key: "organizationCode", width: 50 },
{ header: "State Region", key: "stateRegion", width: 50 },
{ header: "Town", key: "town", width: 50 },
{ header: "Postal Box", key: "postalBox", width: 50 },
{ header: "Postal Code", key: "postalCode", width: 50 },
{ heade