Skip to content

Commit 4dc27bb

Browse files
fix attributes not being shown when admin view trainee data (#144)
1 parent e7198ae commit 4dc27bb

File tree

1 file changed

+70
-40
lines changed

1 file changed

+70
-40
lines changed

src/resolvers/traineeApplicantResolver.ts

+70-40
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
11
import TraineeApplicant from "../models/traineeApplicant";
22
import { traineEAttributes } from "../models/traineeAttribute";
3-
import {applicationCycle} from "../models/applicationCycle";
3+
import { applicationCycle } from "../models/applicationCycle";
44
import mongoose, { ObjectId } from "mongoose";
55
import { sendEmailTemplate } from "../helpers/bulkyMails";
66
import { Types } from 'mongoose';
77
import { AuthenticationError } from 'apollo-server';
88
import { LoggedUserModel } from "../models/AuthUser";
99
import { RoleModel } from "../models/roleModel";
1010

11-
const FrontendUrl = process.env.FRONTEND_URL || ""
11+
const FrontendUrl = process.env.FRONTEND_URL || "";
1212

1313
import { CustomGraphQLError } from "../utils/customErrorHandler";
1414
import { cohortModels } from "../models/cohortModel";
1515
import { publishNotification } from "./adminNotificationsResolver";
1616
import { any } from "joi";
1717

18+
1819
interface Context {
1920
currentUser: { _id: string };
2021
}
@@ -41,24 +42,24 @@ export const traineeApplicantResolver: any = {
4142
items = 3;
4243
}
4344
}
44-
45+
4546
const itemsToSkip = (pages - 1) * items;
4647
const allTrainee = await TraineeApplicant.find({ delete_at: false })
4748
.populate("cycle_id")
48-
49+
4950
.skip(itemsToSkip)
5051
.limit(items);
5152

52-
const formattedTrainees = allTrainee.map((trainee) => ({
53-
...trainee.toObject(),
54-
createdAt: trainee.createdAt.toLocaleString(), // Format createdAt as ISO string
55-
}));
56-
return {
57-
data: formattedTrainees,
58-
totalItems,
59-
page: pages,
60-
itemsPerPage: items,
61-
};
53+
const formattedTrainees = allTrainee.map((trainee) => ({
54+
...trainee.toObject(),
55+
createdAt: trainee.createdAt.toLocaleString(), // Format createdAt as ISO string
56+
}));
57+
return {
58+
data: formattedTrainees,
59+
totalItems,
60+
page: pages,
61+
itemsPerPage: items,
62+
};
6263
},
6364

6465
async getOneTrainee(_: any, { ID }: any) {
@@ -68,15 +69,15 @@ export const traineeApplicantResolver: any = {
6869
return trainee;
6970
},
7071

71-
async getTraineeByUserId(_: any, { userId }: any){
72-
const trainee = await TraineeApplicant.findOne({ user: userId })
73-
74-
if (!trainee) {
75-
throw new Error('Trainee not found');
76-
}
72+
async getTraineeByUserId(_: any, { userId }: any) {
73+
const trainee = await TraineeApplicant.findOne({ user: userId });
74+
75+
if (!trainee) {
76+
throw new Error("Trainee not found");
77+
}
7778

78-
return trainee._id;
79-
}
79+
return trainee._id;
80+
},
8081
},
8182

8283
Mutation: {
@@ -126,9 +127,12 @@ export const traineeApplicantResolver: any = {
126127
return false;
127128
}
128129
},
129-
async createNewTraineeApplicant(_:any, { input }:any) {
130+
async createNewTraineeApplicant(_: any, { input }: any, context: any) {
130131
const { lastName, firstName, email, cycle_id, attributes } = input;
131-
132+
const userWithRole = await LoggedUserModel.findById(
133+
context.currentUser?._id
134+
).populate("role");
135+
132136
// Validate email
133137
const validateEmail = (email: string) => {
134138
return String(email)
@@ -137,27 +141,35 @@ export const traineeApplicantResolver: any = {
137141
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
138142
);
139143
};
140-
144+
141145
if (!validateEmail(email)) {
142-
throw new Error("This email is not valid. Please provide a valid email.");
146+
throw new Error(
147+
"This email is not valid. Please provide a valid email."
148+
);
143149
}
144-
150+
145151
const session = await mongoose.startSession();
146152
session.startTransaction();
147153

148154
try {
149-
const cycle = await applicationCycle.findById(cycle_id).session(session);
155+
const cycle = await applicationCycle
156+
.findById(cycle_id)
157+
.session(session);
150158
if (!cycle) {
151159
throw new Error("Application cycle not found");
152160
}
153161

154-
const existingTrainee = await TraineeApplicant.findOne({ email }).session(session);
162+
const existingTrainee = await TraineeApplicant.findOne({
163+
email,
164+
}).session(session);
155165
if (existingTrainee) {
156166
const existingApplication = existingTrainee.cycleApplied.find(
157-
( app: any) => app.cycle.toString() === cycle_id
167+
(app: any) => app.cycle.toString() === cycle_id
158168
);
159169
if (existingApplication) {
160-
throw new Error("You have already applied to this application cycle");
170+
throw new Error(
171+
"You have already applied to this application cycle"
172+
);
161173
}
162174

163175
existingTrainee.cycle_id = cycle_id;
@@ -166,18 +178,35 @@ export const traineeApplicantResolver: any = {
166178
});
167179
await existingTrainee.save({ session });
168180
await session.commitTransaction();
169-
return existingTrainee;
181+
//populating traineeApplicant with cycle_id
182+
return await TraineeApplicant.findById(existingTrainee._id).populate(
183+
"cycle_id"
184+
);
170185
}
171186

172187
const newTrainee = new TraineeApplicant({
173188
lastName,
174189
firstName,
175190
email,
176191
cycle_id,
177-
cycleApplied: [{
178-
cycle: cycle_id,
179-
}]
192+
cycleApplied: [
193+
{
194+
cycle: cycle_id,
195+
},
196+
],
180197
});
198+
// Create the corresponding traineEAttributes
199+
if (
200+
userWithRole &&
201+
((userWithRole.role as any)?.roleName === "admin" ||
202+
(userWithRole.role as any)?.roleName === "superAdmin")
203+
) {
204+
const newTraineeAttributes = new traineEAttributes({
205+
trainee_id: newTrainee._id,
206+
...attributes,
207+
});
208+
await newTraineeAttributes.save({ session });
209+
}
181210

182211
await newTrainee.save({ session });
183212
await session.commitTransaction();
@@ -187,9 +216,11 @@ export const traineeApplicantResolver: any = {
187216
);
188217
const result = {
189218
...newTrainee.toObject(),
190-
createdAt: newTrainee.createdAt.toLocaleString()
219+
createdAt: newTrainee.createdAt.toLocaleString(),
191220
};
192-
return result;
221+
222+
//return populated traineeApplicant
223+
return await TraineeApplicant.findById(result._id).populate("cycle_id");
193224
} catch (error) {
194225
await session.abortTransaction();
195226
throw error;
@@ -241,10 +272,9 @@ export const traineeApplicantResolver: any = {
241272
await cohort.save();
242273

243274
return { success: true, message: "Trainee accepted successfully" };
244-
245275
} catch (error) {
246276
throw new CustomGraphQLError(`Failed to accept trainee: ${error}`);
247277
}
248-
}
278+
},
249279
},
250-
};
280+
};

0 commit comments

Comments
 (0)