65 lines
2.2 KiB
JavaScript
65 lines
2.2 KiB
JavaScript
const mongoose = require('mongoose'),
|
|
Schema = mongoose.Schema,
|
|
mongoUtil = require('../helpers/mongo'),
|
|
User = require('../model/user'),
|
|
{ Fields, UserTypes } = require('../helpers/constants'),
|
|
Job = require('../model/job'),
|
|
Area = require('../model/area');
|
|
|
|
const schema = new Schema({
|
|
contact: { type: String, required: false },
|
|
fax: { type: String, required: false },
|
|
}, { strictQuery: false });
|
|
|
|
async function deleteClientJobs(session, markDeletedOnly) {
|
|
const jobs = await Job.find({ client: this._id });
|
|
for (let i = 0; i < jobs.length; i++) {
|
|
await jobs[i].removeFull(session, markDeletedOnly);
|
|
}
|
|
}
|
|
|
|
async function deleteClientAreaLibs() {
|
|
/* Clear areas library of this client
|
|
* There would be housands of records or more so may need 'cleanup' later
|
|
*/
|
|
await Area.deleteMany({ client: this._id });
|
|
}
|
|
|
|
/**
|
|
* Remove the Client with all related data in atomic db session's transactions
|
|
* @param {ClientSession} ses the 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.
|
|
* @param {boolean} endSesDone whether to end the session
|
|
*/
|
|
schema.methods.removeFull = async function (ses = null, markDeletedOnly = true, endSesDone = false) {
|
|
let session = ses;
|
|
if (!ses) {
|
|
session = await this.db.startSession({ readPreference: { mode: "primary" } });
|
|
endSesDone = true;
|
|
}
|
|
try {
|
|
// 1. Mark the client as deleted
|
|
if (!this[Fields.MARKED_DELETE])
|
|
await mongoUtil.runTransactionWithRetry(this.markAsDeleted.bind(this), session);
|
|
|
|
if (markDeletedOnly) {
|
|
// 1.1 Mark the client's jobs as deleted
|
|
await deleteClientJobs.call(this, session, markDeletedOnly);
|
|
} else {
|
|
// 2. Delete related Jobs
|
|
await deleteClientJobs.call(this, session, markDeletedOnly);
|
|
|
|
// 3. Delete related area libraries
|
|
await deleteClientAreaLibs.call(this);
|
|
|
|
// 4. Delete the client
|
|
await mongoUtil.runTransactionWithRetry(this.deleteMarked.bind(this), session);
|
|
}
|
|
} catch (error) {
|
|
throw error;
|
|
} finally {
|
|
if (endSesDone && session) await session.endSession();
|
|
}
|
|
}
|
|
|
|
module.exports = User.discriminator(UserTypes.CLIENT, schema, { clone: false }); |