74 lines
2.6 KiB
JavaScript
74 lines
2.6 KiB
JavaScript
const
|
|
Schema = require('mongoose').Schema,
|
|
Job = require('./job'),
|
|
User = require('./user'),
|
|
UserTypes = require('../helpers/constants').UserTypes,
|
|
Location = require('./location'),
|
|
Location_Cache = require('./location_cache'),
|
|
mongoUtil = require('../helpers/mongo');
|
|
|
|
const schema = new Schema({
|
|
vehicleType: { type: Number, required: false, default: 0 }, //0: fixed swing, 1: helicopter
|
|
unitId: {
|
|
type: String, trim: true, required: false, maxlength: 15,
|
|
index: {
|
|
unique: true,
|
|
partialFilterExpression: { unitId: { $type: 'string' } }
|
|
},
|
|
set: v => (v === '' ? null : v)
|
|
},
|
|
model: { type: String, required: false },
|
|
desc: { type: String, required: false },
|
|
color: { type: String, default: 'yellow' },
|
|
// Whether the vehicle is tracking enabled.
|
|
tracking: { type: Boolean, default: false },
|
|
trackonDate: { type: Date, default: null }
|
|
}, { strictQuery: false });
|
|
|
|
async function updateRelatedJobs(session) {
|
|
session && (session.startTransaction(mongoUtil.getTranOps()));
|
|
try {
|
|
await Job.updateMany({ vehicle: this._id }, { $set: { vehicle: null } }).session(session);
|
|
} catch (error) {
|
|
session && (session.abortTransaction());
|
|
throw error;
|
|
}
|
|
await mongoUtil.commitWithRetry(session);
|
|
}
|
|
|
|
async function deleteTrackingData() {
|
|
if (this.unitId) {
|
|
await Location.deleteMany({ unitId: this.unitId });
|
|
await Location_Cache.deleteMany({ unitId: this.unitId });
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Remove the Vehicle with all related data.
|
|
* @param {ClientSession} ses the transactional db session. If ses is null, create a session and end when done.
|
|
* @param {boolean} markDeletedOnly Determine whether to just mark the item as deleted only. Default is true.
|
|
*/
|
|
schema.methods.removeFull = async function (ses = null, markDeletedOnly = true) {
|
|
const endSesDone = !ses;
|
|
const session = ses || await this.db.startSession({ readPreference: { mode: "primary" } });
|
|
try {
|
|
// 1. Mark this application and all its files as deleted - use transaction
|
|
await mongoUtil.runTransactionWithRetry(this.markAsDeleted.bind(this), session);
|
|
if (!markDeletedOnly) {
|
|
// 2. Set null for related jobs
|
|
await mongoUtil.runTransactionWithRetry(updateRelatedJobs.bind(this), session);
|
|
|
|
// 3. Clear tracking data
|
|
await deleteTrackingData.call(this);
|
|
|
|
// 4. Delete the application
|
|
await mongoUtil.runTransactionWithRetry(this.deleteMarked.bind(this), session);
|
|
}
|
|
} catch (error) {
|
|
throw error;
|
|
} finally {
|
|
if (session && endSesDone) await session.endSession();
|
|
}
|
|
}
|
|
|
|
module.exports = User.discriminator(UserTypes.DEVICE, schema, { clone: false }); |