Change tenant ID to object for Car Storage.
MODIFY
src/migration/tasks/CleanUpCarUsersWithDeletedUsersTask.ts
src/migration/tasks/CleanUpCarUsersWithDeletedUsersTask.ts
@@ -32,21 +32,21 @@ export default class CleanUpCarUsersWithDeletedUsersTask extends MigrationTask {
// Owner?
if (carUserMDB.owner) {
// Get the Private Cars of the Deleted User
- const privateCar = await CarStorage.getCar(tenant.id, carUserMDB.carID.toString(), { type: CarType.PRIVATE });
+ const privateCar = await CarStorage.getCar(tenant, carUserMDB.carID.toString(), { type: CarType.PRIVATE });
if (privateCar) {
// Delete All Private Cars assignment
- carUsersCounter += await CarStorage.deleteCarUsersByCarID(tenant.id, privateCar.id);
+ carUsersCounter += await CarStorage.deleteCarUsersByCarID(tenant, privateCar.id);
// Delete Private Car
- await CarStorage.deleteCar(tenant.id, privateCar.id);
+ await CarStorage.deleteCar(tenant, privateCar.id);
carsCounter++;
} else {
// Delete Car assignment
- await CarStorage.deleteCarUser(tenant.id, carUserMDB._id);
+ await CarStorage.deleteCarUser(tenant, carUserMDB._id);
carUsersCounter++;
}
} else {
// Delete Car assignment
- await CarStorage.deleteCarUser(tenant.id, carUserMDB._id);
+ await CarStorage.deleteCarUser(tenant, carUserMDB._id);
carUsersCounter++;
}
}

MODIFY
src/migration/tasks/CleanUpLogicallyDeletedUsersTask.ts
src/migration/tasks/CleanUpLogicallyDeletedUsersTask.ts
@@ -28,25 +28,25 @@ export default class CleanUpLogicallyDeletedUsersTask extends MigrationTask {
let counter = 0;
for (const deletedUserMDB of deletedUsersMDB) {
const userID = deletedUserMDB._id.toString();
- const carUsers = await CarStorage.getCarUsers(tenant.id, { userIDs : [userID] }, Constants.DB_PARAMS_MAX_LIMIT);
+ const carUsers = await CarStorage.getCarUsers(tenant, { userIDs : [userID] }, Constants.DB_PARAMS_MAX_LIMIT);
if (!Utils.isEmptyArray(carUsers.result)) {
for (const carUser of carUsers.result) {
// Owner?
if (carUser.owner) {
// Get the Private Cars of the Deleted User
- const privateCar = await CarStorage.getCar(tenant.id, carUser.carID, { type: CarType.PRIVATE });
+ const privateCar = await CarStorage.getCar(tenant, carUser.carID, { type: CarType.PRIVATE });
if (privateCar) {
// Delete All Private Cars assignment
- await CarStorage.deleteCarUsersByCarID(tenant.id, privateCar.id);
+ await CarStorage.deleteCarUsersByCarID(tenant, privateCar.id);
// Delete Private Car
- await CarStorage.deleteCar(tenant.id, privateCar.id);
+ await CarStorage.deleteCar(tenant, privateCar.id);
} else {
// Delete Car assignment
- await CarStorage.deleteCarUser(tenant.id, carUser.id);
+ await CarStorage.deleteCarUser(tenant, carUser.id);
}
} else {
// Delete Car assignment
- await CarStorage.deleteCarUser(tenant.id, carUser.id);
+ await CarStorage.deleteCarUser(tenant, carUser.id);
}
}
}

MODIFY
src/server/ocpp/services/OCPPService.ts
src/server/ocpp/services/OCPPService.ts
@@ -1538,14 +1538,14 @@ export default class OCPPService {
transaction.carID = user.lastSelectedCarID;
} else {
// Get default car if any
- const defaultCar = await CarStorage.getDefaultUserCar(tenant.id, user.id, {}, ['id']);
+ const defaultCar = await CarStorage.getDefaultUserCar(tenant, user.id, {}, ['id']);
if (defaultCar) {
transaction.carID = defaultCar.id;
}
}
// Set Car Catalog ID
if (transaction.carID) {
- const car = await CarStorage.getCar(tenant.id, transaction.carID, {}, ['id', 'carCatalogID']);
+ const car = await CarStorage.getCar(tenant, transaction.carID, {}, ['id', 'carCatalogID']);
transaction.carCatalogID = car?.carCatalogID;
}
// Clear

MODIFY
src/server/rest/v1/service/CarService.ts
src/server/rest/v1/service/CarService.ts
@@ -234,7 +234,7 @@ export default class CarService {
// Keep the current user to add for Basic role
const carUserToAdd = filteredRequest.usersAdded.find((carUser) => carUser.user.id === req.user.id);
// Check Car
- const car = await CarStorage.getCarByVinLicensePlate(req.user.tenantID,
+ const car = await CarStorage.getCarByVinLicensePlate(req.tenant,
filteredRequest.licensePlate, filteredRequest.vin, {
withUsers: Authorizations.isBasic(req.user) ? true : false,
});
@@ -293,7 +293,7 @@ export default class CarService {
converter: filteredRequest.converter,
createdOn: new Date()
} as Car;
- newCar.id = await CarStorage.saveCar(req.user.tenantID, newCar);
+ newCar.id = await CarStorage.saveCar(req.tenant, newCar);
// If Basic, this is the car owner
if (Authorizations.isBasic(req.user)) {
carUserToAdd.owner = true;
@@ -345,7 +345,7 @@ export default class CarService {
}
// Car already exists with same VIN and License Plate
if (car.licensePlate !== filteredRequest.licensePlate || car.vin !== filteredRequest.vin) {
- const checkCar = await CarStorage.getCarByVinLicensePlate(req.user.tenantID, filteredRequest.licensePlate, filteredRequest.vin);
+ const checkCar = await CarStorage.getCarByVinLicensePlate(req.tenant, filteredRequest.licensePlate, filteredRequest.vin);
if (checkCar) {
throw new AppError({
source: Constants.CENTRAL_SERVER,
@@ -366,7 +366,7 @@ export default class CarService {
car.converter = filteredRequest.converter;
car.lastChangedBy = { 'id': req.user.id };
car.lastChangedOn = new Date();
- await CarStorage.saveCar(req.user.tenantID, car);
+ await CarStorage.saveCar(req.tenant, car);
// Log
await Logging.logSecurityInfo({
tenantID: req.user.tenantID,
@@ -384,7 +384,7 @@ export default class CarService {
}
} else {
// Remove all users for Pool car
- await CarStorage.deleteCarUsersByCarID(req.user.tenantID, car.id);
+ await CarStorage.deleteCarUsersByCarID(req.tenant, car.id);
}
// Handle Users to Update/Remove/Add
res.json(Constants.REST_RESPONSE_SUCCESS);
@@ -404,7 +404,7 @@ export default class CarService {
return;
}
// Get cars
- const cars = await CarStorage.getCars(req.user.tenantID,
+ const cars = await CarStorage.getCars(req.tenant,
{
search: filteredRequest.Search,
carMakers: filteredRequest.CarMaker ? filteredRequest.CarMaker.split('|') : null,
@@ -464,7 +464,7 @@ export default class CarService {
return;
}
// Get cars
- const usersCars = await CarStorage.getCarUsers(req.user.tenantID,
+ const usersCars = await CarStorage.getCarUsers(req.tenant,
{
search: filteredRequest.Search,
carIDs: [filteredRequest.CarID],
@@ -512,7 +512,7 @@ export default class CarService {
// Basic User
if (Authorizations.isBasic(req.user) && !carUser.owner) {
// Delete the association
- await CarStorage.deleteCarUser(req.user.tenantID, carUser.id);
+ await CarStorage.deleteCarUser(req.tenant, carUser.id);
await Logging.logSecurityInfo({
tenantID: req.user.tenantID,
user: req.user, module: MODULE_NAME, method: 'handleDeleteCar',
@@ -525,9 +525,9 @@ export default class CarService {
if (Authorizations.isAdmin(req.user) || (Authorizations.isBasic(req.user) && carUser.owner)) {
// Check if Transaction exist (to Be implemented later)
// Delete all the associations
- await CarStorage.deleteCarUsersByCarID(req.user.tenantID, carId);
+ await CarStorage.deleteCarUsersByCarID(req.tenant, carId);
// Delete the car
- await CarStorage.deleteCar(req.user.tenantID, carId);
+ await CarStorage.deleteCar(req.tenant, carId);
await Logging.logSecurityInfo({
tenantID: req.user.tenantID,
user: req.user, module: MODULE_NAME, method: 'handleDeleteCar',
@@ -585,7 +585,7 @@ export default class CarService {
// Users to Upsert
if (!Utils.isEmptyArray(usersCarsToUpsert)) {
// Read all car users
- const carUsersDB = await CarStorage.getCarUsers(tenant.id,
+ const carUsersDB = await CarStorage.getCarUsers(tenant,
{ carUsersIDs: usersCarsToUpsert.map((userToUpsert) => userToUpsert.id) },
Constants.DB_PARAMS_MAX_LIMIT);
const userCarsToInsert: UserCar[] = [];
@@ -595,11 +595,11 @@ export default class CarService {
const foundCarUserDB = carUsersDB.result.find((carUserDB) => carUserDB.id === userToUpsert.id);
// Check Default
if (userToUpsert.default && (!foundCarUserDB || (userToUpsert.default !== foundCarUserDB.default))) {
- await CarStorage.clearCarUserDefault(tenant.id, userToUpsert.user.id);
+ await CarStorage.clearCarUserDefault(tenant, userToUpsert.user.id);
}
// Check Owner
if (Authorizations.isAdmin(loggedUser) && userToUpsert.owner && (!foundCarUserDB || (userToUpsert.owner !== foundCarUserDB.owner))) {
- await CarStorage.clearCarUserOwner(tenant.id, userToUpsert.carID);
+ await CarStorage.clearCarUserOwner(tenant, userToUpsert.carID);
}
// Update
if (foundCarUserDB) {
@@ -608,7 +608,7 @@ export default class CarService {
userToUpsert.lastChangedBy = { 'id': loggedUser.id };
userToUpsert.lastChangedOn = new Date();
// Save (multi updates one shot does not exist in MongoDB)
- await CarStorage.saveCarUser(tenant.id, foundCarUserDB);
+ await CarStorage.saveCarUser(tenant, foundCarUserDB);
// Create
} else {
userToUpsert.carID = car.id;
@@ -620,7 +620,7 @@ export default class CarService {
}
// Insert one shot
if (!Utils.isEmptyArray(userCarsToInsert)) {
- await CarStorage.insertCarUsers(tenant.id, userCarsToInsert);
+ await CarStorage.insertCarUsers(tenant, userCarsToInsert);
}
// Log
await Logging.logDebug({
@@ -635,7 +635,7 @@ export default class CarService {
// Users to Delete
if (usersCarsToDelete.length > 0) {
// Delete
- await CarStorage.deleteCarUsers(tenant.id, usersCarsToDelete.map((userToDelete) => userToDelete.id));
+ await CarStorage.deleteCarUsers(tenant, usersCarsToDelete.map((userToDelete) => userToDelete.id));
// Log
await Logging.logDebug({
tenantID: tenant.id,

MODIFY
src/server/rest/v1/service/UserService.ts
src/server/rest/v1/service/UserService.ts
@@ -71,12 +71,12 @@ export default class UserService {
let car: Car;
if (Utils.isComponentActiveFromToken(req.user, TenantComponents.CAR)) {
// Get the default Car
- car = await CarStorage.getDefaultUserCar(req.user.tenantID, userID, {},
+ car = await CarStorage.getDefaultUserCar(req.tenant, userID, {},
['id', 'type', 'licensePlate', 'carCatalog.vehicleMake', 'carCatalog.vehicleModel', 'carCatalog.vehicleModelVersion']
);
if (!car) {
// Get the first available car
- car = await CarStorage.getFirstAvailableUserCar(req.user.tenantID, userID,
+ car = await CarStorage.getFirstAvailableUserCar(req.tenant, userID,
['id', 'type', 'licensePlate', 'carCatalog.vehicleMake', 'carCatalog.vehicleModel', 'carCatalog.vehicleModelVersion']
);
}
@@ -936,25 +936,25 @@ export default class UserService {
private static async checkAndDeleteUserCar(tenant: Tenant, loggedUser: UserToken, user: User) {
// Delete cars
if (Utils.isComponentActiveFromToken(loggedUser, TenantComponents.CAR)) {
- const carUsers = await CarStorage.getCarUsers(tenant.id, { userIDs : [user.id] }, Constants.DB_PARAMS_MAX_LIMIT);
+ const carUsers = await CarStorage.getCarUsers(tenant, { userIDs : [user.id] }, Constants.DB_PARAMS_MAX_LIMIT);
if (carUsers.count > 0) {
for (const carUser of carUsers.result) {
// Owner ?
if (carUser.owner) {
// Private ?
- const car = await CarStorage.getCar(tenant.id, carUser.carID, { type: CarType.PRIVATE });
+ const car = await CarStorage.getCar(tenant, carUser.carID, { type: CarType.PRIVATE });
if (car) {
// Delete All Users Car
- await CarStorage.deleteCarUsersByCarID(tenant.id, car.id);
+ await CarStorage.deleteCarUsersByCarID(tenant, car.id);
// Delete Car
- await CarStorage.deleteCar(tenant.id, car.id);
+ await CarStorage.deleteCar(tenant, car.id);
} else {
// Delete User Car
- await CarStorage.deleteCarUser(tenant.id, carUser.id);
+ await CarStorage.deleteCarUser(tenant, carUser.id);
}
} else {
// Delete User Car
- await CarStorage.deleteCarUser(tenant.id, carUser.id);
+ await CarStorage.deleteCarUser(tenant, carUser.id);
}
}
}

MODIFY
src/server/rest/v1/service/UtilsService.ts
src/server/rest/v1/service/UtilsService.ts
@@ -33,6 +33,7 @@ import Tag from '../../../../types/Tag';
import TagStorage from '../../../../storage/mongodb/TagStorage';
import Tenant from '../../../../types/Tenant';
import TenantComponents from '../../../../types/TenantComponents';
+import TenantStorage from '../../../../storage/mongodb/TenantStorage';
import { TransactionInErrorType } from '../../../../types/InError';
import UserStorage from '../../../../storage/mongodb/UserStorage';
import UserToken from '../../../../types/UserToken';
@@ -601,8 +602,9 @@ export default class UtilsService {
];
authorizationFilter.projectFields = authorizationFilter.projectFields.concat(userProject);
}
+ const userTokenTenant = await TenantStorage.getTenant(userToken.tenantID);
// Get Car
- const car = await CarStorage.getCar(userToken.tenantID, carID,
+ const car = await CarStorage.getCar(userTokenTenant, carID,
{
...additionalFilters,
...authorizationFilter.filters

MODIFY
src/storage/mongodb/CarStorage.ts
src/storage/mongodb/CarStorage.ts
@@ -8,6 +8,7 @@ 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 { UserCar } from '../../types/User';
import Utils from '../../utils/Utils';
@@ -478,11 +479,11 @@ export default class CarStorage {
};
}
- public static async saveCar(tenantID: string, carToSave: Car): Promise<string> {
+ public static async saveCar(tenant: Tenant, carToSave: Car): Promise<string> {
// Debug
- const uniqueTimerID = Logging.traceStart(tenantID, MODULE_NAME, 'saveCar');
+ const uniqueTimerID = Logging.traceStart(tenant.id, MODULE_NAME, 'saveCar');
// Check Tenant
- await DatabaseUtils.checkTenant(tenantID);
+ DatabaseUtils.checkTenantObject(tenant);
// Set
const carMDB: any = {
_id: carToSave.id ? Utils.convertToObjectID(carToSave.id) : new ObjectID(),
@@ -500,21 +501,21 @@ export default class CarStorage {
// Add Last Changed/Created props
DatabaseUtils.addLastChangedCreatedProps(carMDB, carToSave);
// Modify
- await global.database.getCollection<Car>(tenantID, 'cars').findOneAndUpdate(
+ await global.database.getCollection<Car>(tenant.id, 'cars').findOneAndUpdate(
{ _id: carMDB._id },
{ $set: carMDB },
{ upsert: true, returnDocument: 'after' }
);
// Debug
- await Logging.traceEnd(tenantID, MODULE_NAME, 'saveCar', uniqueTimerID, carMDB);
+ await Logging.traceEnd(tenant.id, MODULE_NAME, 'saveCar', uniqueTimerID, carMDB);
return carMDB._id.toHexString();
}
- public static async saveCarUser(tenantID: string, carUserToSave: UserCar): Promise<string> {
+ public static async saveCarUser(tenant: Tenant, carUserToSave: UserCar): Promise<string> {
// Debug
- const uniqueTimerID = Logging.traceStart(tenantID, MODULE_NAME, 'saveCarUser');
+ const uniqueTimerID = Logging.traceStart(tenant.id, MODULE_NAME, 'saveCarUser');
// Check Tenant
- await DatabaseUtils.checkTenant(tenantID);
+ DatabaseUtils.checkTenantObject(tenant);
// Set
const carUserMDB: any = {
_id: Cypher.hash(`${carUserToSave.carID}~${carUserToSave.user.id}`),
@@ -526,7 +527,7 @@ export default class CarStorage {
// Add Last Changed/Created props
DatabaseUtils.addLastChangedCreatedProps(carUserMDB, carUserToSave);
// Modify
- await global.database.getCollection(tenantID, 'carusers').findOneAndUpdate(
+ await global.database.getCollection(tenant.id, 'carusers').findOneAndUpdate(
{
_id: carUserMDB._id
},
@@ -535,15 +536,15 @@ export default class CarStorage {
{ upsert: true, returnDocument: 'after' }
);
// Debug
- await Logging.traceEnd(tenantID, MODULE_NAME, 'saveCarUser', uniqueTimerID, carUserMDB);
+ await Logging.traceEnd(tenant.id, MODULE_NAME, 'saveCarUser', uniqueTimerID, carUserMDB);
return carUserMDB._id;
}
- public static async insertCarUsers(tenantID: string, carUsersToSave: UserCar[]): Promise<void> {
+ public static async insertCarUsers(tenant: Tenant, carUsersToSave: UserCar[]): Promise<void> {
// Debug
- const uniqueTimerID = Logging.traceStart(tenantID, MODULE_NAME, 'insertCarUsers');
+ const uniqueTimerID = Logging.traceStart(tenant.id, MODULE_NAME, 'insertCarUsers');
// Check Tenant
- await DatabaseUtils.checkTenant(tenantID);
+ DatabaseUtils.checkTenantObject(tenant);
// At least one user
const carUsersMDB = [];
if (carUsersToSave && carUsersToSave.length > 0) {
@@ -561,18 +562,18 @@ export default class CarStorage {
carUsersMDB.push(carUserMDB);
}
// Execute
- await global.database.getCollection<any>(tenantID, 'carusers').insertMany(
+ await global.database.getCollection<any>(tenant.id, 'carusers').insertMany(
carUsersMDB,
{ ordered: false }
);
}
// Debug
- await Logging.traceEnd(tenantID, MODULE_NAME, 'insertCarUsers', uniqueTimerID, carUsersMDB);
+ await Logging.traceEnd(tenant.id, MODULE_NAME, 'insertCarUsers', uniqueTimerID, carUsersMDB);
}
- public static async getCar(tenantID: string, id: string = Constants.UNKNOWN_STRING_ID,
+ public static async getCar(tenant: Tenant, id: string = Constants.UNKNOWN_STRING_ID,
params: { withUsers?: boolean, userIDs?: string[]; type?: CarType } = {}, projectFields?: string[]): Promise<Car> {
- const carsMDB = await CarStorage.getCars(tenantID, {
+ const carsMDB = await CarStorage.getCars(tenant, {
carIDs: [id],
withUsers: params.withUsers,
userIDs: params.userIDs,
@@ -581,27 +582,27 @@ export default class CarStorage {
return carsMDB.count === 1 ? carsMDB.result[0] : null;
}
- public static async getDefaultUserCar(tenantID: string, userID: string,
+ public static async getDefaultUserCar(tenant: Tenant, userID: string,
params = {}, projectFields?: string[]): Promise<Car> {
- const carMDB = await CarStorage.getCars(tenantID, {
+ const carMDB = await CarStorage.getCars(tenant, {
userIDs: [userID],
defaultCar: true,
}, Constants.DB_PARAMS_SINGLE_RECORD, projectFields);
return carMDB.count === 1 ? carMDB.result[0] : null;
}
- public static async getFirstAvailableUserCar(tenantID: string, userID: string,
+ public static async getFirstAvailableUserCar(tenant: Tenant, userID: string,
params = {}, projectFields?: string[]): Promise<Car> {
- const carMDB = await CarStorage.getCars(tenantID, {
+ const carMDB = await CarStorage.getCars(tenant, {
userIDs: [userID],
}, Constants.DB_PARAMS_SINGLE_RECORD, projectFields);
return carMDB.count === 1 ? carMDB.result[0] : null;
}
- public static async getCarByVinLicensePlate(tenantID: string,
+ public static async getCarByVinLicensePlate(tenant: Tenant,
licensePlate: string = Constants.UNKNOWN_STRING_ID, vin: string = Constants.UNKNOWN_STRING_ID,
params: { withUsers?: boolean, userIDs?: string[]; } = {}, projectFields?: string[]): Promise<Car> {
- const carsMDB = await CarStorage.getCars(tenantID, {
+ const carsMDB = await CarStorage.getCars(tenant, {
licensePlate: licensePlate,
vin: vin,
withUsers: params.withUsers,
@@ -610,14 +611,14 @@ export default class CarStorage {
return carsMDB.count === 1 ? carsMDB.result[0] : null;
}
- public static async getCars(tenantID: string,
+ public static async getCars(tenant: Tenant,
params: {
search?: string; userIDs?: string[]; carIDs?: string[]; licensePlate?: string; vin?: string;
withUsers?: boolean; defaultCar?: boolean; carMakers?: string[], type?: CarType;
} = {},
dbParams?: DbParams, projectFields?: string[]): Promise<DataResult<Car>> {
// Debug
- const uniqueTimerID = Logging.traceStart(tenantID, MODULE_NAME, 'getCars');
+ const uniqueTimerID = Logging.traceStart(tenant.id, MODULE_NAME, 'getCars');
// Clone before updating the values
dbParams = Utils.cloneObject(dbParams);
// Check Limit
@@ -653,7 +654,7 @@ export default class CarStorage {
// Filter on Users
if (!Utils.isEmptyArray(params.userIDs) || params.withUsers) {
DatabaseUtils.pushUserCarLookupInAggregation({
- tenantID: tenantID, aggregation, localField: '_id', foreignField: 'carID',
+ tenantID: tenant.id, aggregation, localField: '_id', foreignField: 'carID',
asField: 'carUsers', oneToOneCardinality: false
});
if (!Utils.isEmptyArray(params.userIDs)) {
@@ -682,13 +683,13 @@ export default class CarStorage {
aggregation.push({ $limit: Constants.DB_RECORD_COUNT_CEIL });
}
// Count Records
- const carsCountMDB = await global.database.getCollection<DataResult<Car>>(tenantID, 'cars')
+ const carsCountMDB = await global.database.getCollection<DataResult<Car>>(tenant.id, 'cars')
.aggregate([...aggregation, { $count: 'count' }], { allowDiskUse: true })
.toArray();
// Check if only the total count is requested
if (dbParams.onlyRecordCount) {
// Return only the count
- await Logging.traceEnd(tenantID, MODULE_NAME, 'getCars', uniqueTimerID, carsCountMDB);
+ await Logging.traceEnd(tenant.id, MODULE_NAME, 'getCars', uniqueTimerID, carsCountMDB);
return {
count: (carsCountMDB.length > 0 ? carsCountMDB[0].count : 0),
result: []
@@ -735,7 +736,7 @@ export default class CarStorage {
}
});
// Add Created By / Last Changed By
- DatabaseUtils.pushCreatedLastChangedInAggregation(tenantID, aggregation);
+ DatabaseUtils.pushCreatedLastChangedInAggregation(tenant.id, aggregation);
// Handle the ID
DatabaseUtils.pushRenameDatabaseID(aggregation);
// Add Users
@@ -749,20 +750,20 @@ export default class CarStorage {
}
// User on Car Users
DatabaseUtils.pushArrayLookupInAggregation('carUsers', DatabaseUtils.pushUserLookupInAggregation.bind(this), {
- tenantID, aggregation: aggregation, localField: 'carUsers.userID', foreignField: '_id',
+ tenantID: tenant.id, aggregation: aggregation, localField: 'carUsers.userID', foreignField: '_id',
asField: 'carUsers.user', oneToOneCardinality: true, objectIDFields: ['createdBy', 'lastChangedBy']
}, { pipeline: carUsersPipeline, sort: dbParams.sort });
}
// Project
DatabaseUtils.projectFields(aggregation, projectFields);
// Read DB
- const cars = await global.database.getCollection<Car>(tenantID, 'cars')
+ const cars = await global.database.getCollection<Car>(tenant.id, 'cars')
.aggregate(aggregation, {
allowDiskUse: true
})
.toArray();
// Debug
- await Logging.traceEnd(tenantID, MODULE_NAME, 'getCars', uniqueTimerID, cars);
+ await Logging.traceEnd(tenant.id, MODULE_NAME, 'getCars', uniqueTimerID, cars);
return {
count: (carsCountMDB.length > 0 ?
(carsCountMDB[0].count === Constants.DB_RECORD_COUNT_CEIL ? -1 : carsCountMDB[0].count) : 0),
@@ -770,10 +771,10 @@ export default class CarStorage {
};
}
- public static async clearCarUserDefault(tenantID: string, userID: string): Promise<void> {
- const uniqueTimerID = Logging.traceStart(tenantID, MODULE_NAME, 'clearCarUserDefault');
- await DatabaseUtils.checkTenant(tenantID);
- await global.database.getCollection<any>(tenantID, 'carusers').updateMany(
+ public static async clearCarUserDefault(tenant: Tenant, userID: string): Promise<void> {
+ const uniqueTimerID = Logging.traceStart(tenant.id, MODULE_NAME, 'clearCarUserDefault');
+ DatabaseUtils.checkTenantObject(tenant);
+ await global.database.getCollection<any>(tenant.id, 'carusers').updateMany(
{
userID: Utils.convertToObjectID(userID),
default: true
@@ -781,13 +782,13 @@ export default class CarStorage {
{
$set: { default: false }
});
- await Logging.traceEnd(tenantID, MODULE_NAME, 'clearCarUserDefault', uniqueTimerID, { userID });
+ await Logging.traceEnd(tenant.id, MODULE_NAME, 'clearCarUserDefault', uniqueTimerID, { userID });
}
- public static async clearCarUserOwner(tenantID: string, carID: string): Promise<void> {
- const uniqueTimerID = Logging.traceStart(tenantID, MODULE_NAME, 'clearCarUserOwner');
- await DatabaseUtils.checkTenant(tenantID);
- await global.database.getCollection<any>(tenantID, 'carusers').updateMany(
+ public static async clearCarUserOwner(tenant: Tenant, carID: string): Promise<void> {
+ const uniqueTimerID = Logging.traceStart(tenant.id, MODULE_NAME, 'clearCarUserOwner');
+ DatabaseUtils.checkTenantObject(tenant);
+ await global.database.getCollection<any>(tenant.id, 'carusers').updateMany(
{
carID: Utils.convertToObjectID(carID),
owner: true
@@ -795,73 +796,73 @@ export default class CarStorage {
{
$set: { owner: false }
});
- await Logging.traceEnd(tenantID, MODULE_NAME, 'clearCarUserOwner', uniqueTimerID, { carID });
+ await Logging.traceEnd(tenant.id, MODULE_NAME, 'clearCarUserOwner', uniqueTimerID, { carID });
}
- public static async getCarUserByCarUser(tenantID: string,
+ public static async getCarUserByCarUser(tenant: Tenant,
carID: string = Constants.UNKNOWN_STRING_ID, userID: string = Constants.UNKNOWN_STRING_ID,
projectFields?: string[]): Promise<UserCar> {
- const carUsersMDB = await CarStorage.getCarUsers(tenantID, {
+ const carUsersMDB = await CarStorage.getCarUsers(tenant, {
carIDs: [carID],
userIDs: [userID]
}, Constants.DB_PARAMS_SINGLE_RECORD, projectFields);
return carUsersMDB.count === 1 ? carUsersMDB.result[0] : null;
}
- public static async getCarUser(tenantID: string, carUserID: string = Constants.UNKNOWN_STRING_ID,
+ public static async getCarUser(tenant: Tenant, carUserID: string = Constants.UNKNOWN_STRING_ID,
projectFields?: string[]): Promise<UserCar> {
- const carUsersMDB = await CarStorage.getCarUsers(tenantID, {
+ const carUsersMDB = await CarStorage.getCarUsers(tenant, {
carUsersIDs: [carUserID]
}, Constants.DB_PARAMS_SINGLE_RECORD, projectFields);
return carUsersMDB.count === 1 ? carUsersMDB.result[0] : null;
}
- public static async deleteCarUser(tenantID: string, id: string): Promise<void> {
+ public static async deleteCarUser(tenant: Tenant, id: string): Promise<void> {
// Debug
- const uniqueTimerID = Logging.traceStart(tenantID, MODULE_NAME, 'deleteCarUser');
+ const uniqueTimerID = Logging.traceStart(tenant.id, MODULE_NAME, 'deleteCarUser');
// Delete singular site area
- await global.database.getCollection(tenantID, 'carusers')
+ await global.database.getCollection(tenant.id, 'carusers')
.findOneAndDelete({ '_id': id });
// Debug
- await Logging.traceEnd(tenantID, MODULE_NAME, 'deleteCarUser', uniqueTimerID, { id });
+ await Logging.traceEnd(tenant.id, MODULE_NAME, 'deleteCarUser', uniqueTimerID, { id });
}
- public static async deleteCarUsersByCarID(tenantID: string, carID: string): Promise<number> {
+ public static async deleteCarUsersByCarID(tenant: Tenant, carID: string): Promise<number> {
// Debug
- const uniqueTimerID = Logging.traceStart(tenantID, MODULE_NAME, 'deleteCarUserByCarID');
+ const uniqueTimerID = Logging.traceStart(tenant.id, MODULE_NAME, 'deleteCarUserByCarID');
// Delete singular site area
- const result = await global.database.getCollection(tenantID, 'carusers')
+ const result = await global.database.getCollection(tenant.id, 'carusers')
.deleteMany({ 'carID': Utils.convertToObjectID(carID) });
// Debug
- await Logging.traceEnd(tenantID, MODULE_NAME, 'deleteCarUserByCarID', uniqueTimerID, { carID });
+ await Logging.traceEnd(tenant.id, MODULE_NAME, 'deleteCarUserByCarID', uniqueTimerID, { carID });
return result.deletedCount;
}
- public static async deleteCar(tenantID: string, carID: string): Promise<void> {
+ public static async deleteCar(tenant: Tenant, carID: string): Promise<void> {
// Debug
- const uniqueTimerID = Logging.traceStart(tenantID, MODULE_NAME, 'deleteCar');
+ const uniqueTimerID = Logging.traceStart(tenant.id, MODULE_NAME, 'deleteCar');
// Delete singular site area
- await global.database.getCollection(tenantID, 'cars')
+ await global.database.getCollection(tenant.id, 'cars')
.deleteOne({ '_id': Utils.convertToObjectID(carID) });
// Debug
- await Logging.traceEnd(tenantID, MODULE_NAME, 'deleteCar', uniqueTimerID, { carID });
+ await Logging.traceEnd(tenant.id, MODULE_NAME, 'deleteCar', uniqueTimerID, { carID });
}
- public static async deleteCarUsers(tenantID: string, ids: string[]): Promise<void> {
+ public static async deleteCarUsers(tenant: Tenant, ids: string[]): Promise<void> {
// Debug
- const uniqueTimerID = Logging.traceStart(tenantID, MODULE_NAME, 'deleteCarUserByCarID');
+ const uniqueTimerID = Logging.traceStart(tenant.id, MODULE_NAME, 'deleteCarUserByCarID');
// Delete singular site area
- await global.database.getCollection(tenantID, 'carusers')
+ await global.database.getCollection(tenant.id, 'carusers')
.deleteMany({ '_id': { $in: ids } });
// Debug
- await Logging.traceEnd(tenantID, MODULE_NAME, 'deleteCarUserByCarID', uniqueTimerID, { ids });
+ await Logging.traceEnd(tenant.id, MODULE_NAME, 'deleteCarUserByCarID', uniqueTimerID, { ids });
}
- public static async getCarUsers(tenantID: string,
+ public static async getCarUsers(tenant: Tenant,
params: { search?: string; carUsersIDs?: string[]; userIDs?: string[]; carIDs?: string[]; } = {},
dbParams?: DbParams, projectFields?: string[]): Promise<DataResult<UserCar>> {
// Debug
- const uniqueTimerID = Logging.traceStart(tenantID, MODULE_NAME, 'getCarUsers');
+ const uniqueTimerID = Logging.traceStart(tenant.id, MODULE_NAME, 'getCarUsers');
// Clone before updating the values
dbParams = Utils.cloneObject(dbParams);
// Check Limit
@@ -896,13 +897,13 @@ export default class CarStorage {
aggregation.push({ $limit: Constants.DB_RECORD_COUNT_CEIL });
}
// Count Records
- const carUsersCountMDB = await global.database.getCollection<DataResult<UserCar>>(tenantID, 'carusers')
+ const carUsersCountMDB = await global.database.getCollection<DataResult<UserCar>>(tenant.id, 'carusers')
.aggregate([...aggregation, { $count: 'count' }], { allowDiskUse: true })
.toArray();
// Check if only the total count is requested
if (dbParams.onlyRecordCount) {
// Return only the count
- await Logging.traceEnd(tenantID, MODULE_NAME, 'getCarUsers', uniqueTimerID, carUsersCountMDB);
+ await Logging.traceEnd(tenant.id, MODULE_NAME, 'getCarUsers', uniqueTimerID, carUsersCountMDB);
return {
count: (carUsersCountMDB.length > 0 ? carUsersCountMDB[0].count : 0),
result: []
@@ -927,25 +928,25 @@ export default class CarStorage {
});
// Add User
DatabaseUtils.pushUserLookupInAggregation({
- tenantID: tenantID, aggregation, localField: 'userID', foreignField: '_id',
+ tenantID: tenant.id, aggregation, localField: 'userID', foreignField: '_id',
asField: 'user', oneToOneCardinality: true
});
// Convert Object ID to string
DatabaseUtils.pushConvertObjectIDToString(aggregation, 'userID');
// Add Created By / Last Changed By
- DatabaseUtils.pushCreatedLastChangedInAggregation(tenantID, aggregation);
+ DatabaseUtils.pushCreatedLastChangedInAggregation(tenant.id, aggregation);
// Handle the ID
DatabaseUtils.pushRenameDatabaseID(aggregation);
// Project
DatabaseUtils.projectFields(aggregation, projectFields);
// Read DB
- const carUsers = await global.database.getCollection<UserCar>(tenantID, 'carusers')
+ const carUsers = await global.database.getCollection<UserCar>(tenant.id, 'carusers')
.aggregate(aggregation, {
allowDiskUse: true
})
.toArray();
// Debug
- await Logging.traceEnd(tenantID, MODULE_NAME, 'getCarUsers', uniqueTimerID, carUsers);
+ await Logging.traceEnd(tenant.id, MODULE_NAME, 'getCarUsers', uniqueTimerID, carUsers);
return {
count: (carUsersCountMDB.length > 0 ?
(carUsersCountMDB[0].count === Constants.DB_RECORD_COUNT_CEIL ? -1 : carUsersCountMDB[0].count) : 0),

Change tenant ID to object for Car Storage.