fix major field not populating

This commit is contained in:
chark1es 2025-02-03 12:39:30 -08:00
parent 3bc60e4739
commit 6df69275b9
2 changed files with 575 additions and 505 deletions

View file

@ -6,6 +6,12 @@ interface BaseRecord {
[key: string]: any;
}
// Interface for request options
interface RequestOptions {
fields?: string[];
disableAutoCancellation?: boolean;
}
export class Get {
private auth: Authentication;
private static instance: Get;
@ -28,13 +34,13 @@ export class Get {
* Get a single record by ID
* @param collectionName The name of the collection
* @param recordId The ID of the record to retrieve
* @param fields Optional array of fields to select
* @param options Optional request options including fields to select and auto-cancellation control
* @returns The requested record
*/
public async getOne<T extends BaseRecord>(
collectionName: string,
recordId: string,
fields?: string[]
options?: RequestOptions,
): Promise<T> {
if (!this.auth.isAuthenticated()) {
throw new Error("User must be authenticated to retrieve records");
@ -42,8 +48,13 @@ export class Get {
try {
const pb = this.auth.getPocketBase();
const options = fields ? { fields: fields.join(",") } : undefined;
return await pb.collection(collectionName).getOne<T>(recordId, options);
const requestOptions = {
...(options?.fields && { fields: options.fields.join(",") }),
...(options?.disableAutoCancellation && { requestKey: null }),
};
return await pb
.collection(collectionName)
.getOne<T>(recordId, requestOptions);
} catch (err) {
console.error(`Failed to get record from ${collectionName}:`, err);
throw err;
@ -54,13 +65,13 @@ export class Get {
* Get multiple records by their IDs
* @param collectionName The name of the collection
* @param recordIds Array of record IDs to retrieve
* @param fields Optional array of fields to select
* @param options Optional request options including fields to select and auto-cancellation control
* @returns Array of requested records
*/
public async getMany<T extends BaseRecord>(
collectionName: string,
recordIds: string[],
fields?: string[]
options?: RequestOptions,
): Promise<T[]> {
if (!this.auth.isAuthenticated()) {
throw new Error("User must be authenticated to retrieve records");
@ -69,16 +80,19 @@ export class Get {
try {
const pb = this.auth.getPocketBase();
const filter = `id ?~ "${recordIds.join("|")}"`;
const options = {
const requestOptions = {
filter,
...(fields && { fields: fields.join(",") })
...(options?.fields && { fields: options.fields.join(",") }),
...(options?.disableAutoCancellation && { requestKey: null }),
};
const result = await pb.collection(collectionName).getFullList<T>(options);
const result = await pb
.collection(collectionName)
.getFullList<T>(requestOptions);
// Sort results to match the order of requested IDs
const recordMap = new Map(result.map(record => [record.id, record]));
return recordIds.map(id => recordMap.get(id)).filter(Boolean) as T[];
const recordMap = new Map(result.map((record) => [record.id, record]));
return recordIds.map((id) => recordMap.get(id)).filter(Boolean) as T[];
} catch (err) {
console.error(`Failed to get records from ${collectionName}:`, err);
throw err;
@ -92,7 +106,7 @@ export class Get {
* @param perPage Number of items per page
* @param filter Optional filter string
* @param sort Optional sort string
* @param fields Optional array of fields to select
* @param options Optional request options including fields to select and auto-cancellation control
* @returns Paginated list of records
*/
public async getList<T extends BaseRecord>(
@ -101,7 +115,7 @@ export class Get {
perPage: number = 20,
filter?: string,
sort?: string,
fields?: string[]
options?: RequestOptions,
): Promise<{
page: number;
perPage: number;
@ -115,20 +129,23 @@ export class Get {
try {
const pb = this.auth.getPocketBase();
const options = {
const requestOptions = {
...(filter && { filter }),
...(sort && { sort }),
...(fields && { fields: fields.join(",") })
...(options?.fields && { fields: options.fields.join(",") }),
...(options?.disableAutoCancellation && { requestKey: null }),
};
const result = await pb.collection(collectionName).getList<T>(page, perPage, options);
const result = await pb
.collection(collectionName)
.getList<T>(page, perPage, requestOptions);
return {
page: result.page,
perPage: result.perPage,
totalItems: result.totalItems,
totalPages: result.totalPages,
items: result.items
items: result.items,
};
} catch (err) {
console.error(`Failed to get list from ${collectionName}:`, err);
@ -141,14 +158,14 @@ export class Get {
* @param collectionName The name of the collection
* @param filter Optional filter string
* @param sort Optional sort string
* @param fields Optional array of fields to select
* @param options Optional request options including fields to select and auto-cancellation control
* @returns Array of all matching records
*/
public async getAll<T extends BaseRecord>(
collectionName: string,
filter?: string,
sort?: string,
fields?: string[]
options?: RequestOptions,
): Promise<T[]> {
if (!this.auth.isAuthenticated()) {
throw new Error("User must be authenticated to retrieve records");
@ -156,13 +173,14 @@ export class Get {
try {
const pb = this.auth.getPocketBase();
const options = {
const requestOptions = {
...(filter && { filter }),
...(sort && { sort }),
...(fields && { fields: fields.join(",") })
...(options?.fields && { fields: options.fields.join(",") }),
...(options?.disableAutoCancellation && { requestKey: null }),
};
return await pb.collection(collectionName).getFullList<T>(options);
return await pb.collection(collectionName).getFullList<T>(requestOptions);
} catch (err) {
console.error(`Failed to get all records from ${collectionName}:`, err);
throw err;
@ -173,13 +191,13 @@ export class Get {
* Get the first record that matches a filter
* @param collectionName The name of the collection
* @param filter Filter string
* @param fields Optional array of fields to select
* @param options Optional request options including fields to select and auto-cancellation control
* @returns The first matching record or null if none found
*/
public async getFirst<T extends BaseRecord>(
collectionName: string,
filter: string,
fields?: string[]
options?: RequestOptions,
): Promise<T | null> {
if (!this.auth.isAuthenticated()) {
throw new Error("User must be authenticated to retrieve records");
@ -187,14 +205,17 @@ export class Get {
try {
const pb = this.auth.getPocketBase();
const options = {
const requestOptions = {
filter,
...(fields && { fields: fields.join(",") }),
...(options?.fields && { fields: options.fields.join(",") }),
...(options?.disableAutoCancellation && { requestKey: null }),
sort: "created",
perPage: 1
perPage: 1,
};
const result = await pb.collection(collectionName).getList<T>(1, 1, options);
const result = await pb
.collection(collectionName)
.getList<T>(1, 1, requestOptions);
return result.items.length > 0 ? result.items[0] : null;
} catch (err) {
console.error(`Failed to get first record from ${collectionName}:`, err);

View file

@ -63,10 +63,7 @@ const majorsList: string[] = allMajors
>Select your current major</span
>
</label>
<select
id="majorSelect"
class="select select-bordered w-full"
>
<select id="majorSelect" class="select select-bordered w-full">
<option value="">Select your major</option>
{
majorsList.map((major: string) => (
@ -79,17 +76,12 @@ const majorsList: string[] = allMajors
<!-- Graduation Year -->
<div class="form-control">
<label class="label">
<span class="label-text font-medium"
>Expected Graduation</span
>
<span class="label-text font-medium">Expected Graduation</span>
<span class="label-text-alt text-base-content/70"
>When do you plan to graduate?</span
>
</label>
<select
id="gradYearSelect"
class="select select-bordered w-full"
>
<select id="gradYearSelect" class="select select-bordered w-full">
<option value="">Select graduation year</option>
{
Array.from({ length: 6 }, (_, i) => {
@ -123,9 +115,7 @@ const majorsList: string[] = allMajors
<!-- IEEE Member ID -->
<div class="form-control">
<label class="label">
<span class="label-text font-medium"
>IEEE Member ID</span
>
<span class="label-text font-medium">IEEE Member ID</span>
<span class="label-text-alt text-base-content/70"
>Your IEEE membership number</span
>
@ -171,27 +161,20 @@ const majorsList: string[] = allMajors
>
No resume uploaded
</p>
<p
class="text-xs text-base-content/70"
>
<p class="text-xs text-base-content/70">
PDF, DOC, or DOCX
</p>
</div>
</div>
<div class="flex-none flex gap-2">
<button
id="previewResume"
class="btn btn-sm btn-ghost"
>
<button id="previewResume" class="btn btn-sm btn-ghost">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
d="M10 12a2 2 0 100-4 2 2 0 000 4z"
></path>
<path d="M10 12a2 2 0 100-4 2 2 0 000 4z"></path>
<path
fill-rule="evenodd"
d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z"
@ -215,8 +198,7 @@ const majorsList: string[] = allMajors
<!-- Upload Status -->
<div class="text-sm">
<span id="uploadStatus" class="label-text-alt"
></span>
<span id="uploadStatus" class="label-text-alt"></span>
</div>
</div>
</div>
@ -238,24 +220,26 @@ const majorsList: string[] = allMajors
import { Update } from "../pocketbase/Update";
import { SendLog } from "../pocketbase/SendLog";
import { FileManager } from "../pocketbase/FileManager";
import { Get } from "../pocketbase/Get";
const auth = Authentication.getInstance();
const update = Update.getInstance();
const logger = SendLog.getInstance();
const fileManager = FileManager.getInstance();
const get = Get.getInstance();
// Get form elements
const memberIdInput = document.getElementById(
"memberIdInput"
"memberIdInput",
) as HTMLInputElement;
const majorSelect = document.getElementById(
"majorSelect"
"majorSelect",
) as HTMLSelectElement;
const gradYearSelect = document.getElementById(
"gradYearSelect"
"gradYearSelect",
) as HTMLSelectElement;
const resumeUpload = document.getElementById(
"resumeUpload"
"resumeUpload",
) as HTMLInputElement;
const currentResume = document.getElementById("currentResume");
const uploadStatus = document.getElementById("uploadStatus");
@ -277,28 +261,88 @@ const majorsList: string[] = allMajors
};
// Load current user data
const loadUserData = () => {
const loadUserData = async () => {
if (auth.isAuthenticated()) {
const user = auth.getCurrentUser();
if (user) {
if (memberIdInput) memberIdInput.value = user.member_id || "";
if (majorSelect) majorSelect.value = user.major || "";
try {
// Get full user data with auto-cancellation disabled
const userData = await get.getOne("users", user.id, {
disableAutoCancellation: true,
});
console.log("User major from server:", userData.major);
if (memberIdInput) memberIdInput.value = userData.member_id || "";
if (majorSelect) {
const serverMajor = userData.major?.trim();
console.log("Setting major select to:", serverMajor);
// Get all available options with their normalized values
const availableOptions = Array.from(majorSelect.options).map(
(opt) => ({
element: opt,
normalizedValue: opt.value.trim(),
displayValue: opt.textContent?.trim() || opt.value.trim(),
}),
);
console.log(
"Available options:",
availableOptions.map((o) => o.normalizedValue),
);
// First try exact match
let matchingOption = availableOptions.find(
(opt) => opt.normalizedValue === serverMajor,
);
// If no exact match, try case-insensitive match
if (!matchingOption && serverMajor) {
const serverMajorLower = serverMajor.toLowerCase();
matchingOption = availableOptions.find(
(opt) => opt.normalizedValue.toLowerCase() === serverMajorLower,
);
}
// If still no match, try partial match
if (!matchingOption && serverMajor) {
const serverMajorLower = serverMajor.toLowerCase();
matchingOption = availableOptions.find(
(opt) =>
opt.normalizedValue
.toLowerCase()
.includes(serverMajorLower) ||
serverMajorLower.includes(opt.normalizedValue.toLowerCase()),
);
}
if (matchingOption) {
console.log(
"Found matching major:",
matchingOption.normalizedValue,
);
majorSelect.value = matchingOption.normalizedValue;
} else {
console.log("No matching major found for:", serverMajor);
majorSelect.value = "";
}
}
if (gradYearSelect)
gradYearSelect.value = user.graduation_year || "";
gradYearSelect.value = userData.graduation_year || "";
// Update resume display
if (currentResume && resumeDisplay) {
if (user.resume) {
const fileName = user.resume.toString();
currentResume.textContent =
fileName || "Resume uploaded";
if (userData.resume) {
const fileName = userData.resume.toString();
currentResume.textContent = fileName || "Resume uploaded";
resumeDisplay.classList.remove("hidden");
// Get the file URL from PocketBase
const resumeUrl = fileManager.getFileUrl(
"users",
user.id,
fileName
userData.id,
fileName,
);
// Update preview button to use new modal
@ -315,7 +359,7 @@ const majorsList: string[] = allMajors
type: getFileType(fileName),
},
},
}
},
);
window.dispatchEvent(showFileViewerEvent);
};
@ -325,6 +369,14 @@ const majorsList: string[] = allMajors
resumeDisplay.classList.add("hidden");
}
}
} catch (err) {
console.error("Failed to load user data:", err);
await logger.send(
"error",
"profile settings",
`Failed to load user data: ${err instanceof Error ? err.message : "Unknown error"}`,
);
}
}
}
};
@ -339,22 +391,17 @@ const majorsList: string[] = allMajors
const user = auth.getCurrentUser();
if (!user) throw new Error("User not authenticated");
await fileManager.uploadFile(
"users",
user.id,
"resume",
file
);
await fileManager.uploadFile("users", user.id, "resume", file);
uploadStatus.textContent = "Resume uploaded successfully";
// Refresh the user data to show the new resume
loadUserData();
await loadUserData();
// Log successful resume upload
await logger.send(
"update",
"resume upload",
`Successfully uploaded resume: ${file.name}`
`Successfully uploaded resume: ${file.name}`,
);
} catch (err) {
console.error("Resume upload error:", err);
@ -364,7 +411,7 @@ const majorsList: string[] = allMajors
await logger.send(
"error",
"resume upload",
`Failed to upload resume: ${file.name}. Error: ${err instanceof Error ? err.message : "Unknown error"}`
`Failed to upload resume: ${file.name}. Error: ${err instanceof Error ? err.message : "Unknown error"}`,
);
}
}
@ -381,10 +428,13 @@ const majorsList: string[] = allMajors
const user = auth.getCurrentUser();
if (!user) throw new Error("User not authenticated");
// Get current user data for comparison
const currentUserData = await get.getOne("users", user.id);
const oldData = {
major: user.major || null,
graduation_year: user.graduation_year || null,
member_id: user.member_id || null,
major: currentUserData.major || null,
graduation_year: currentUserData.graduation_year || null,
member_id: currentUserData.member_id || null,
};
const newData = {
@ -401,17 +451,17 @@ const majorsList: string[] = allMajors
const changes = [];
if (oldData.major !== newData.major) {
changes.push(
`Major: "${oldData.major || "none"}" → "${newData.major || "none"}"`
`Major: "${oldData.major || "none"}" → "${newData.major || "none"}"`,
);
}
if (oldData.graduation_year !== newData.graduation_year) {
changes.push(
`Graduation Year: "${oldData.graduation_year || "none"}" → "${newData.graduation_year || "none"}"`
`Graduation Year: "${oldData.graduation_year || "none"}" → "${newData.graduation_year || "none"}"`,
);
}
if (oldData.member_id !== newData.member_id) {
changes.push(
`IEEE Member ID: "${oldData.member_id || "none"}" → "${newData.member_id || "none"}"`
`IEEE Member ID: "${oldData.member_id || "none"}" → "${newData.member_id || "none"}"`,
);
}
@ -419,7 +469,7 @@ const majorsList: string[] = allMajors
await logger.send(
"update",
"profile settings",
`Updated profile settings:\n${changes.join("\n")}`
`Updated profile settings:\n${changes.join("\n")}`,
);
}
@ -438,8 +488,8 @@ const majorsList: string[] = allMajors
document.body.appendChild(toast);
setTimeout(() => toast.remove(), 3000);
// Only update form data without affecting visibility
loadUserData();
// Refresh the form data
await loadUserData();
// Ensure settings view stays visible
const defaultView = document.getElementById("defaultView");
@ -456,8 +506,7 @@ const majorsList: string[] = allMajors
attempted_major: majorSelect?.value || "none",
attempted_graduation_year: gradYearSelect?.value || "none",
attempted_member_id: memberIdInput?.value || "none",
error_message:
err instanceof Error ? err.message : "Unknown error",
error_message: err instanceof Error ? err.message : "Unknown error",
};
await logger.send(
@ -467,7 +516,7 @@ const majorsList: string[] = allMajors
`Major: ${errorDetails.attempted_major}\n` +
`Graduation Year: ${errorDetails.attempted_graduation_year}\n` +
`IEEE Member ID: ${errorDetails.attempted_member_id}\n` +
`Error: ${errorDetails.error_message}`
`Error: ${errorDetails.error_message}`,
);
// Show error toast
@ -491,11 +540,11 @@ const majorsList: string[] = allMajors
}
// Load initial data
loadUserData();
await loadUserData();
// Update when auth state changes
auth.onAuthStateChange(() => {
loadUserData();
auth.onAuthStateChange(async () => {
await loadUserData();
});
</script>