Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions client/src/api/teacher/teacher.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,7 @@ export async function updateMyProfileApi(data: UpdateTeacherProfileInput) {
const res = await apiProtected.put<TeacherType>("/api/teachers/me", data);
return res.data;
}

export async function updateMyPublishApi(payload: { isPublic: boolean }) {
return apiProtected.patch("/api/teachers/me/publish", payload);
}
1 change: 1 addition & 0 deletions client/src/api/teacher/teacher.type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export type TeacherType = {
createdAt: Date;
status: TeacherStatus;
role: Role;
isPublic: boolean;
};

export type TeacherOutputModel = {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { updateMyPublishApi } from "../../../api/teacher/teacher.api";
import { queryKeys } from "../../queryKeys";
import { useNotificationStore } from "../../../store/notification.store";
import { getErrorMessage } from "../../../util/ErrorUtil";

export const useUpdateMyPublishMutation = () => {
const qc = useQueryClient();
const success = useNotificationStore((s) => s.success);
const notifyError = useNotificationStore((s) => s.error);

return useMutation({
mutationFn: (payload: { isPublic: boolean }) => updateMyPublishApi(payload),
onSuccess: async (_data, variables) => {
await qc.invalidateQueries({ queryKey: queryKeys.teachers.myProfile() });
await qc.invalidateQueries({ queryKey: ["teachers", "publicList"] });
if (variables.isPublic) {
success(
"Sent for review. Your profile will be visible after approval.",
);
return;
}
success("Profile is now not public.");
},
onError: (error) => notifyError(getErrorMessage(error)),
});
};
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import {
} from "../../../api/teacher/teacher.api";
import { useMyProfileQuery } from "../../../features/teachers/query/useMyProfileQuery";
import { useUpdateMyProfileMutation } from "../../../features/teachers/mutations/useUpdateMyProfileMutation";
import { useUpdateMyPublishMutation } from "../../../features/teachers/mutations/useUpdateMyPublishMutation";

import { useRegularStudentsQuery } from "../../../features/appointments/query/useRegularStudentsQuery";
import { useModalStore } from "../../../store/modals.store";
import { queryKeys } from "../../../features/queryKeys";
Expand All @@ -35,9 +37,40 @@ export interface TimeSlot {
hour: number;
}

const teacherStatusUi: Record<string, { label: string; className: string }> = {
draft: {
label: "Draft",
className: "bg-yellow-500/20 text-yellow-300 border border-yellow-500/40",
},
pending: {
label: "Pending Review",
className: "bg-purple-500/20 text-purple-300 border border-purple-500/40",
},
active: {
label: "Approved",
className:
"bg-emerald-500/20 text-emerald-300 border border-emerald-500/40",
},
rejected: {
label: "Rejected",
className: "bg-red-500/20 text-red-300 border border-red-500/40",
},
blocked: {
label: "Blocked",
className: "bg-gray-500/20 text-gray-200 border border-gray-500/40",
},
};

export const TeacherProfile = () => {
const { data: profile, isLoading } = useMyProfileQuery();
const updateProfileMutation = useUpdateMyProfileMutation();

const { mutate: updatePublish, isPending: isPublishPending } =
useUpdateMyPublishMutation();

const handlePublishToggle = (nextPublic: boolean) =>
updatePublish({ isPublic: nextPublic });

const { data: regularStudentsData } = useRegularStudentsQuery();
const openModal = useModalStore((s) => s.open);
const queryClient = useQueryClient();
Expand Down Expand Up @@ -415,9 +448,48 @@ export const TeacherProfile = () => {
return (
<div className="px-4 sm:px-6 lg:px-10 flex flex-col">
<div className="pt-6 sm:pt-8 lg:pt-10 flex-1">
<h1 className="text-3xl sm:text-4xl lg:text-5xl font-bold bg-gradient-to-r from-[#7C86F7] to-[#E879F9] bg-clip-text text-transparent mb-8 sm:mb-10 lg:mb-12">
My profile
</h1>
<div className="mb-8 sm:mb-10 lg:mb-12 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<h1 className="text-3xl sm:text-4xl lg:text-5xl font-bold bg-gradient-to-r from-[#7C86F7] to-[#E879F9] bg-clip-text text-transparent">
My profile
</h1>
<label
htmlFor="teacher-visibility-toggle"
className={`flex items-center gap-3 ${
isPublishPending ? "opacity-70" : ""
}`}
>
<span className="text-red-400 text-sm">Private profile</span>
<input
id="teacher-visibility-toggle"
type="checkbox"
className="peer sr-only"
checked={Boolean(profile?.isPublic)}
disabled={isPublishPending}
onChange={(e) => handlePublishToggle(e.target.checked)}
/>
<span
className="relative h-7 w-14 cursor-pointer rounded-full bg-red-500 transition-colors duration-200
peer-checked:bg-green-500 peer-disabled:cursor-not-allowed
after:absolute after:left-1 after:top-1 after:h-5 after:w-5 after:rounded-full after:bg-white after:shadow
after:transition-transform after:duration-200 peer-checked:after:translate-x-7"
aria-hidden="true"
/>
<span className="text-green-400 text-sm">Public profile</span>
</label>
</div>
<div className="mb-6 sm:mb-8">
<span
className={`inline-flex items-center rounded-full px-3 py-1 text-xs sm:text-sm font-medium ${
teacherStatusUi[profile?.status ?? "draft"]?.className ??
"bg-light-500/20 text-light-100 border border-light-500/40"
}`}
>
Account status:{" "}
{teacherStatusUi[profile?.status ?? "draft"]?.label ??
profile?.status ??
"Draft"}
</span>
</div>
<div className="flex flex-col lg:flex-row gap-6 lg:gap-12">
<ProfileAvatar avatarUrl={profile?.profileImageUrl} />
<div className="flex-1 space-y-4 sm:space-y-6">
Expand Down
59 changes: 59 additions & 0 deletions server/src/controllers/teacher.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
TeacherOutputModel,
UpdateTeacherProfileInput,
QueryTeacherForModeratorInput,
UpdateTeacherVisibilityInput,
} from "../types/teacher/teacher.types.js";
import { validateAuthorization } from "../utils/validation/requestValidation.util.js";

Expand Down Expand Up @@ -159,6 +160,16 @@ export class TeacherController {
);

if (!updated) return res.sendStatus(404);

const teacher = await this.teacherQuery.getTeacherById(teacherId);
// If teacher removes all schedule slots, auto-switch to private draft.
if (teacher && !this.isProfileComplete(teacher)) {
await this.teacherService.updateTeacherVisibility({
teacherId,
isPublic: false,
});
}

return res.status(200).json(updated);
} catch (err) {
return next(err);
Expand Down Expand Up @@ -196,9 +207,57 @@ export class TeacherController {
return res.status(404).json({ message: "Teacher not found" });
}

if (!this.isProfileComplete(updatedTeacher)) {
// If profile becomes incomplete, force private + draft.
await this.teacherService.updateTeacherVisibility({
teacherId,
isPublic: false,
});

// Re-fetch to return the final persisted state (status/isPublic included).
const refreshedTeacher =
await this.teacherQuery.getTeacherById(teacherId);
if (!refreshedTeacher) {
return res.status(404).json({ message: "Teacher not found" });
}
return res.status(200).json(refreshedTeacher);
}

// Profile is complete, so the updated profile snapshot is already valid.
return res.status(200).json(updatedTeacher);
} catch (err) {
return next(err);
}
}

async updateMyVisibility(
req: RequestWithBody<UpdateTeacherVisibilityInput>,
res: Response,
next: NextFunction,
) {
try {
const teacherId = validateAuthorization(req.auth?.userId);
const { isPublic } = req.body;
// Teacher controls publish intent; service enforces completeness rules.
await this.teacherService.updateTeacherVisibility({
teacherId,
isPublic,
});
return res.sendStatus(204);
} catch (error) {
return next(error);
}
}

private isProfileComplete(teacher: {
subjects: unknown[];
availability: Record<string, { start: string; end: string }[]>;
}) {
// complete profile means at least one subject and one schedule slot.
const hasSubjects = teacher.subjects.length > 0;
const hasSchedule = Object.values(teacher.availability).some(
(slots) => slots.length > 0,
);
return hasSubjects && hasSchedule;
}
}
1 change: 1 addition & 0 deletions server/src/db/schemes/teacherSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ export const TeacherSchema = new mongoose.Schema<TeacherTypeDB>(
role: { type: String, required: true },
authProvider: { type: String, required: true, default: "local" },
googleSub: { type: String, required: false, default: null },
isPublic: { type: Boolean, default: false },
},
{
versionKey: false,
Expand Down
1 change: 1 addition & 0 deletions server/src/db/schemes/types/teacher.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,5 @@ export type TeacherTypeDB = {
authProvider: "local" | "google";
googleSub: string | null;
status: TeacherStatus;
isPublic: boolean;
};
16 changes: 16 additions & 0 deletions server/src/repositories/commandRepositories/teacher.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
TeacherStatus,
TeacherTypeDB,
} from "../../db/schemes/types/teacher.types.js";
import { NotFoundError } from "../../utils/error.util.js";

@injectable()
export class TeacherCommand {
Expand Down Expand Up @@ -127,4 +128,19 @@ export class TeacherCommand {
throw new HttpError(500, "Password was not updated", { cause: error });
}
}

async updateTeacherVisibility(
id: string,
data: { isPublic: boolean; status: TeacherStatus },
): Promise<void> {
// Keep visibility preference and effective public status in sync atomically.
const updated = await TeacherModel.updateOne(
{ id },
{ $set: { isPublic: data.isPublic, status: data.status } },
);

if (updated.matchedCount === 0) {
throw new NotFoundError("Teacher not found", { id });
}
}
}
16 changes: 9 additions & 7 deletions server/src/repositories/queryRepositories/teacher.query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ export class TeacherQuery {
const filter: Record<string, unknown> = {};
if (status !== "all") {
filter.status = status;
} else {
// Default moderator queue excludes drafts.
filter.status = { $ne: "draft" };
}

const items = await TeacherModel.find(filter)
Expand All @@ -69,7 +72,7 @@ export class TeacherQuery {
.limit(+pageSize)
.lean();

const totalCount = await TeacherModel.countDocuments();
const totalCount = await TeacherModel.countDocuments(filter);

const pagesCount = Math.ceil(totalCount / +pageSize);

Expand Down Expand Up @@ -234,13 +237,12 @@ export class TeacherQuery {
updateFields.profileImageUrl = updates.profileImageUrl;
if (updates.education !== undefined)
updateFields.education = updates.education;
if (updates.subjects !== undefined)
if (updates.subjects !== undefined) {
updateFields.subjects = updates.subjects;

if (updates.subjects) {
updateFields.priceFrom = Math.min(
...updates.subjects.map((s) => s.hourlyRate),
);
updateFields.priceFrom =
updates.subjects.length > 0
? Math.min(...updates.subjects.map((s) => s.hourlyRate))
: 0;
}

const updatedTeacher = await TeacherModel.findOneAndUpdate(
Expand Down
10 changes: 10 additions & 0 deletions server/src/routes/teacherRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
validateWeekAvailabilityPayload,
} from "../validation/availabilitySchedule/teacher/teacherScheduleValidationMiddleware.js";
import { teacherProfileUpdateValidationMiddleware } from "../validation/profile/profileValidationMiddleware.js";
import { teacherVisibilityValidationMiddleware } from "../validation/profile/teacherVisibilityValidationMiddleware.js";

export const teacherRouter = Router();
const teacherController = container.get<TeacherController>(
Expand Down Expand Up @@ -81,3 +82,12 @@ teacherRouter.delete(
requireSelf("id"),
teacherController.deleteTeacher.bind(teacherController),
);

teacherRouter.patch(
"/me/publish",
authMiddleware.handle,
requireRole("teacher"),
teacherVisibilityValidationMiddleware(),
errorMiddleware,
teacherController.updateMyVisibility.bind(teacherController),
);
2 changes: 2 additions & 0 deletions server/src/scripts/seedTeachers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ const createTeacherDoc = async (index: number): Promise<TeacherTypeDB> => {
authProvider: "local",
googleSub: null,
status: "draft",
isPublic: false,
};
};

Expand Down Expand Up @@ -179,6 +180,7 @@ export const seedTeachers = async () => {
availability: teacher.availability,
address: teacher.address,
role: teacher.role,
isPublic: teacher.isPublic,
},
$setOnInsert: {
id: teacher.id,
Expand Down
Loading
Loading