Used global approach to update org IDs
Code refactor
MODIFY
src/migration/tasks/AlignEntitiesWithOrganizationIDsTask.ts
src/migration/tasks/AlignEntitiesWithOrganizationIDsTask.ts
import Constants from '../../utils/Constants';
import Logging from '../../utils/Logging';
import { ServerAction } from '../../types/Server';
+import SiteAreaStorage from '../../storage/mongodb/SiteAreaStorage';
import Tenant from '../../types/Tenant';
import TenantMigrationTask from '../TenantMigrationTask';
import Utils from '../../utils/Utils';
@@ -25,45 +26,9 @@ export default class AlignEntitiesWithOrganizationIDsTask extends TenantMigratio
}
const foundSite = sites.find((site) => site._id.toString() === siteArea.siteID.toString());
if (foundSite) {
- // Update Charging Stations
- let result = await global.database.getCollection<any>(tenant.id, 'chargingstations').updateMany(
- {
- siteAreaID: siteArea._id
- },
- {
- $set: {
- siteID: siteArea.siteID,
- companyID: foundSite.companyID
- }
- }
- );
- updated += result.modifiedCount;
- // Update Transactions
- result = await global.database.getCollection<any>(tenant.id, 'transactions').updateMany(
- {
- siteAreaID: siteArea._id
- },
- {
- $set: {
- siteID: siteArea.siteID,
- companyID: foundSite.companyID
- }
- }
- );
- updated += result.modifiedCount;
- // Update Assets
- result = await global.database.getCollection<any>(tenant.id, 'assets').updateMany(
- {
- siteAreaID: siteArea._id
- },
- {
- $set: {
- siteID: siteArea.siteID,
- companyID: foundSite.companyID
- }
- }
- );
- updated += result.modifiedCount;
+ // Update all
+ updated += await SiteAreaStorage.updateEntitiesWithOrganizationIDs(
+ tenant, foundSite.companyID.toString(), siteArea.siteID.toString(), siteArea._id.toString());
} else {
await Logging.logError({
tenantID: Constants.DEFAULT_TENANT,
@@ -90,7 +55,7 @@ export default class AlignEntitiesWithOrganizationIDsTask extends TenantMigratio
}
public getName(): string {
- return 'FixChargingStationCompanyAndSiteIDsTask';
+ return 'AlignEntitiesWithOrganizationIDsTask';
}
public isAsynchronous(): boolean {

MODIFY
src/server/rest/v1/service/SiteAreaService.ts
src/server/rest/v1/service/SiteAreaService.ts
@@ -7,7 +7,6 @@ import AppAuthError from '../../../../exception/AppAuthError';
import AppError from '../../../../exception/AppError';
import AuthorizationService from './AuthorizationService';
import { ChargingProfilePurposeType } from '../../../../types/ChargingProfile';
-import ChargingStationStorage from '../../../../storage/mongodb/ChargingStationStorage';
import Constants from '../../../../utils/Constants';
import ConsumptionStorage from '../../../../storage/mongodb/ConsumptionStorage';
import LockingHelper from '../../../../locking/LockingHelper';
@@ -370,8 +369,8 @@ export default class SiteAreaService {
siteArea.lastChangedOn = new Date();
// Save
await SiteAreaStorage.saveSiteArea(req.tenant, siteArea, Utils.objectHasProperty(filteredRequest, 'image'));
- // Update charging station
- await ChargingStationStorage.updateChargingStationsSite(req.tenant, filteredRequest.id, filteredRequest.siteID, site.companyID);
+ // Update all refs
+ await SiteAreaStorage.updateEntitiesWithOrganizationIDs(req.tenant, site.companyID, filteredRequest.siteID, filteredRequest.id);
// Retrigger Smart Charging
if (filteredRequest.smartCharging) {
// FIXME: the lock acquisition can wait for 30s before timeout and the whole code execution timeout at 3s

MODIFY
src/server/rest/v1/service/SiteService.ts
src/server/rest/v1/service/SiteService.ts
-import { Action, DynamicAuthorizationDataSourceName, Entity, SitesAdminDynamicAuthorizationDataSourceData } from '../../../../types/Authorization';
+import { Action, DynamicAuthorizationDataSourceName, Entity } from '../../../../types/Authorization';
import { HTTPAuthError, HTTPError } from '../../../../types/HTTPError';
import { NextFunction, Request, Response } from 'express';
@@ -440,8 +440,8 @@ export default class SiteService {
site.lastChangedOn = new Date();
// Save
await SiteStorage.saveSite(req.tenant, site, Utils.objectHasProperty(filteredRequest, 'image') ? true : false);
- // Update charging station
- await ChargingStationStorage.updateChargingStationsCompany(req.tenant, filteredRequest.id, filteredRequest.companyID);
+ // Update all refs
+ await SiteStorage.updateEntitiesWithOrganizationIDs(req.tenant, site.companyID, filteredRequest.id);
await Logging.logInfo({
tenantID: req.user.tenantID,
user: req.user, module: MODULE_NAME, method: 'handleUpdateSite',

MODIFY
src/storage/mongodb/AssetStorage.ts
src/storage/mongodb/AssetStorage.ts
+import { ObjectId, UpdateResult } from 'mongodb';
import global, { DatabaseCount, FilterParams, Image } from '../../types/GlobalType';
import Asset from '../../types/Asset';
@@ -7,7 +8,6 @@ import { DataResult } from '../../types/DataResult';
import DatabaseUtils from './DatabaseUtils';
import DbParams from '../../types/database/DbParams';
import Logging from '../../utils/Logging';
-import { ObjectId } from 'mongodb';
import Tenant from '../../types/Tenant';
import Utils from '../../utils/Utils';
@@ -221,6 +221,36 @@ export default class AssetStorage {
};
}
+ public static async updateAssetsWithOrganizationIDs(tenant: Tenant, companyID: string, siteID: string, siteAreaID?: string): Promise<number> {
+ const startTime = Logging.traceDatabaseRequestStart();
+ DatabaseUtils.checkTenantObject(tenant);
+ let result: UpdateResult;
+ if (siteAreaID) {
+ result = await global.database.getCollection<any>(tenant.id, 'assets').updateMany(
+ {
+ siteAreaID: DatabaseUtils.convertToObjectID(siteAreaID),
+ },
+ {
+ $set: {
+ siteID: DatabaseUtils.convertToObjectID(siteID),
+ companyID: DatabaseUtils.convertToObjectID(companyID)
+ }
+ }) as UpdateResult;
+ } else {
+ result = await global.database.getCollection<any>(tenant.id, 'assets').updateMany(
+ {
+ siteID: DatabaseUtils.convertToObjectID(siteID),
+ },
+ {
+ $set: {
+ companyID: DatabaseUtils.convertToObjectID(companyID)
+ }
+ }) as UpdateResult;
+ }
+ await Logging.traceDatabaseRequestEnd(tenant, MODULE_NAME, 'updateAssetsWithOrganizationIDs', startTime, { siteID, companyID });
+ return result.modifiedCount;
+ }
+
public static async getAssetsInError(tenant: Tenant,
params: { search?: string; siteAreaIDs?: string[]; siteIDs?: string[]; errorType?: string[]; issuer?: boolean } = {},
dbParams?: DbParams, projectFields?: string[]): Promise<DataResult<Asset>> {

MODIFY
src/storage/mongodb/ChargingStationStorage.ts
src/storage/mongodb/ChargingStationStorage.ts
@@ -2,7 +2,7 @@ import { ChargePointStatus, OCPPFirmwareStatus } from '../../types/ocpp/OCPPServ
import { ChargingProfile, ChargingProfilePurposeType, ChargingRateUnitType } from '../../types/ChargingProfile';
import ChargingStation, { ChargePoint, ChargingStationOcpiData, ChargingStationOcppParameters, ChargingStationOicpData, ChargingStationTemplate, Connector, ConnectorType, CurrentType, OcppParameter, PhaseAssignmentToGrid, RemoteAuthorization, Voltage } from '../../types/ChargingStation';
import { ChargingStationInError, ChargingStationInErrorType } from '../../types/InError';
-import { GridFSBucket, GridFSBucketReadStream, GridFSBucketWriteStream, ObjectId } from 'mongodb';
+import { GridFSBucket, GridFSBucketReadStream, GridFSBucketWriteStream, ObjectId, UpdateResult } from 'mongodb';
import Tenant, { TenantComponents } from '../../types/Tenant';
import global, { DatabaseCount, FilterParams } from '../../types/GlobalType';
@@ -969,10 +969,12 @@ export default class ChargingStationStorage {
return firmware;
}
- public static async updateChargingStationsSite(tenant: Tenant, siteAreaID: string, siteID: string, companyID: string): Promise<void> {
+ public static async updateChargingStationsWithOrganizationIDs(tenant: Tenant, companyID: string, siteID: string, siteAreaID?: string): Promise<number> {
const startTime = Logging.traceDatabaseRequestStart();
DatabaseUtils.checkTenantObject(tenant);
- await global.database.getCollection<any>(tenant.id, 'chargingstations').updateMany(
+ let result: UpdateResult;
+ if (siteAreaID) {
+ result = await global.database.getCollection<any>(tenant.id, 'chargingstations').updateMany(
{
siteAreaID: DatabaseUtils.convertToObjectID(siteAreaID),
},
@@ -981,21 +983,20 @@ export default class ChargingStationStorage {
siteID: DatabaseUtils.convertToObjectID(siteID),
companyID: DatabaseUtils.convertToObjectID(companyID)
}
- });
- await Logging.traceDatabaseRequestEnd(tenant, MODULE_NAME, 'updateChargingStationsSite', startTime, { siteID });
- }
-
- public static async updateChargingStationsCompany(tenant: Tenant, siteID: string, companyID: string): Promise<void> {
- const startTime = Logging.traceDatabaseRequestStart();
- DatabaseUtils.checkTenantObject(tenant);
- await global.database.getCollection<any>(tenant.id, 'chargingstations').updateMany(
+ }) as UpdateResult;
+ } else {
+ result = await global.database.getCollection<any>(tenant.id, 'chargingstations').updateMany(
{
siteID: DatabaseUtils.convertToObjectID(siteID),
},
{
- $set: { companyID: DatabaseUtils.convertToObjectID(companyID) }
- });
- await Logging.traceDatabaseRequestEnd(tenant, MODULE_NAME, 'updateChargingStationsCompanies', startTime, { companyID });
+ $set: {
+ companyID: DatabaseUtils.convertToObjectID(companyID)
+ }
+ }) as UpdateResult;
+ }
+ await Logging.traceDatabaseRequestEnd(tenant, MODULE_NAME, 'updateChargingStationsWithOrganizationIDs', startTime, { siteID, companyID, siteAreaID });
+ return result.modifiedCount;
}
private static getChargerInErrorFacet(errorType: string) {

MODIFY
src/storage/mongodb/DatabaseUtils.ts
src/storage/mongodb/DatabaseUtils.ts
@@ -40,9 +40,9 @@ export default class DatabaseUtils {
public static pushCreatedLastChangedInAggregation(tenantID: string, aggregation: any[]): void {
// Add Created By
- DatabaseUtils._pushUserInAggregation(tenantID, aggregation, 'createdBy');
+ DatabaseUtils.pushUserInAggregation(tenantID, aggregation, 'createdBy');
// Add Last Changed By
- DatabaseUtils._pushUserInAggregation(tenantID, aggregation, 'lastChangedBy');
+ DatabaseUtils.pushUserInAggregation(tenantID, aggregation, 'lastChangedBy');
}
public static getCollectionName(tenantID: string, collectionNameSuffix: string): string {
@@ -345,11 +345,11 @@ export default class DatabaseUtils {
dest.createdBy = null;
dest.lastChangedBy = null;
if (entity.createdBy || entity.createdOn) {
- dest.createdBy = DatabaseUtils._mongoConvertUserID(entity, 'createdBy');
+ dest.createdBy = DatabaseUtils.mongoConvertUserID(entity, 'createdBy');
dest.createdOn = Utils.convertToDate(entity.createdOn);
}
if (entity.lastChangedBy || entity.lastChangedOn) {
- dest.lastChangedBy = DatabaseUtils._mongoConvertUserID(entity, 'lastChangedBy');
+ dest.lastChangedBy = DatabaseUtils.mongoConvertUserID(entity, 'lastChangedBy');
dest.lastChangedOn = Utils.convertToDate(entity.lastChangedOn);
}
}
@@ -441,7 +441,7 @@ export default class DatabaseUtils {
}
// Temporary hack to fix user Id saving. fix all this when user is typed...
- private static _mongoConvertUserID(obj: any, prop: string): ObjectId | null {
+ private static mongoConvertUserID(obj: any, prop: string): ObjectId | null {
if (!obj || !obj[prop]) {
return null;
}
@@ -454,7 +454,7 @@ export default class DatabaseUtils {
return null;
}
- private static _pushUserInAggregation(tenantID: string, aggregation: any[], fieldName: string) {
+ private static pushUserInAggregation(tenantID: string, aggregation: any[], fieldName: string) {
// Created By Lookup
aggregation.push({
$lookup: {

MODIFY
src/storage/mongodb/SiteAreaStorage.ts
src/storage/mongodb/SiteAreaStorage.ts
import global, { DatabaseCount, FilterParams, Image } from '../../types/GlobalType';
+import AssetStorage from './AssetStorage';
+import ChargingStationStorage from './ChargingStationStorage';
import Constants from '../../utils/Constants';
import { DataResult } from '../../types/DataResult';
import DatabaseUtils from './DatabaseUtils';
@@ -8,11 +10,22 @@ import Logging from '../../utils/Logging';
import { ObjectId } from 'mongodb';
import SiteArea from '../../types/SiteArea';
import Tenant from '../../types/Tenant';
+import TransactionStorage from './TransactionStorage';
import Utils from '../../utils/Utils';
const MODULE_NAME = 'SiteAreaStorage';
export default class SiteAreaStorage {
+ public static async updateEntitiesWithOrganizationIDs(tenant: Tenant, companyID: string, siteID: string, siteAreaID: string): Promise<number> {
+ // Update Charging Stations
+ let updated = await ChargingStationStorage.updateChargingStationsWithOrganizationIDs(tenant, companyID, siteID, siteAreaID);
+ // Update Transactions
+ updated += await TransactionStorage.updateTransactionsWithOrganizationIDs(tenant, companyID, siteID, siteAreaID);
+ // Update Assets
+ updated += await AssetStorage.updateAssetsWithOrganizationIDs(tenant, companyID, siteID, siteAreaID);
+ return updated;
+ }
+
public static async addAssetsToSiteArea(tenant: Tenant, siteArea: SiteArea, assetIDs: string[]): Promise<void> {
const startTime = Logging.traceDatabaseRequestStart();
DatabaseUtils.checkTenantObject(tenant);

MODIFY
src/storage/mongodb/SiteStorage.ts
src/storage/mongodb/SiteStorage.ts
import global, { DatabaseCount, FilterParams, Image } from '../../types/GlobalType';
+import AssetStorage from './AssetStorage';
import ChargingStationStorage from './ChargingStationStorage';
import Constants from '../../utils/Constants';
import { DataResult } from '../../types/DataResult';
@@ -10,12 +11,23 @@ import { ObjectId } from 'mongodb';
import Site from '../../types/Site';
import SiteAreaStorage from './SiteAreaStorage';
import Tenant from '../../types/Tenant';
+import TransactionStorage from './TransactionStorage';
import { UserSite } from '../../types/User';
import Utils from '../../utils/Utils';
const MODULE_NAME = 'SiteStorage';
export default class SiteStorage {
+ public static async updateEntitiesWithOrganizationIDs(tenant: Tenant, companyID: string, siteID: string): Promise<number> {
+ // Update Charging Stations
+ let updated = await ChargingStationStorage.updateChargingStationsWithOrganizationIDs(tenant, companyID, siteID);
+ // Update Transactions
+ updated += await TransactionStorage.updateTransactionsWithOrganizationIDs(tenant, companyID, siteID);
+ // Update Assets
+ updated += await AssetStorage.updateAssetsWithOrganizationIDs(tenant, companyID, siteID);
+ return updated;
+ }
+
public static async getSite(tenant: Tenant, id: string = Constants.UNKNOWN_OBJECT_ID,
params: { withCompany?: boolean, withImage?: boolean; issuer?: boolean; } = {}, projectFields?: string[]): Promise<Site> {
const sitesMDB = await SiteStorage.getSites(tenant, {

MODIFY
src/storage/mongodb/TransactionStorage.ts
src/storage/mongodb/TransactionStorage.ts
@@ -13,6 +13,7 @@ import Logging from '../../utils/Logging';
import { NotifySessionNotStarted } from '../../types/UserNotifications';
import { ServerAction } from '../../types/Server';
import Tenant from '../../types/Tenant';
+import { UpdateResult } from 'mongodb';
import Utils from '../../utils/Utils';
import moment from 'moment';
@@ -227,6 +228,36 @@ export default class TransactionStorage {
await Logging.traceDatabaseRequestEnd(tenant, MODULE_NAME, 'saveTransactionOcpiData', startTime, ocpiData);
}
+ public static async updateTransactionsWithOrganizationIDs(tenant: Tenant, companyID: string, siteID: string, siteAreaID?: string): Promise<number> {
+ const startTime = Logging.traceDatabaseRequestStart();
+ DatabaseUtils.checkTenantObject(tenant);
+ let result: UpdateResult;
+ if (siteAreaID) {
+ result = await global.database.getCollection<any>(tenant.id, 'transactions').updateMany(
+ {
+ siteAreaID: DatabaseUtils.convertToObjectID(siteAreaID),
+ },
+ {
+ $set: {
+ siteID: DatabaseUtils.convertToObjectID(siteID),
+ companyID: DatabaseUtils.convertToObjectID(companyID)
+ }
+ }) as UpdateResult;
+ } else {
+ result = await global.database.getCollection<any>(tenant.id, 'transactions').updateMany(
+ {
+ siteID: DatabaseUtils.convertToObjectID(siteID),
+ },
+ {
+ $set: {
+ companyID: DatabaseUtils.convertToObjectID(companyID)
+ }
+ }) as UpdateResult;
+ }
+ await Logging.traceDatabaseRequestEnd(tenant, MODULE_NAME, 'updateTransactionsWithOrganizationIDs', startTime, { siteID, companyID, siteAreaID });
+ return result.modifiedCount;
+ }
+
public static async saveTransactionOicpData(tenant: Tenant, id: number,
oicpData: TransactionOicpData): Promise<void> {
const startTime = Logging.traceDatabaseRequestStart();

Used global approach to update org IDs
Code refactor