All files / public/js UpdateMember.mjs

96% Statements 120/125
100% Branches 18/18
94.44% Functions 17/18
95.9% Lines 117/122

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372                            15x           15x           15x           15x       15x 15x 15x 15x                   12x           12x           12x       12x   12x   12x                 12x                 12x                 12x         13x         10x         13x         10x         13x         10x       12x 12x 12x 12x 12x 12x 12x   12x                 17x   17x         17x                 17x     17x   17x   2x 2x 2x 2x 2x     17x   1x 1x           16x   16x   1x 1x     15x 15x 15x   15x           15x       15x   15x 15x 15x   15x 15x           15x   15x 15x 15x 15x   15x 15x 15x 15x   15x 15x 15x   15x 15x 15x 15x   15x 15x 15x 15x       15x   2x 2x 2x 2x   2x 2x 2x 2x         13x     15x               15x       12x         12x   10x   10x   10x   10x   13x   10x       12x       13x 13x             12x   13x             13x   5x 5x                     8x   8x             8x                 8x   8x               3x   3x     5x   5x  
import { constructGET, constructPUT } from "./helpers/RequestHelpers.mjs";
import { Endpoints } from "./Endpoints.mjs";
import { ElementCollection } from "./ElementCollection.mjs";
import { Modal, ModalInput } from "./Modal.mjs";
import { MemberDTO, MemberDTOSchema } from "../../common/dtos/MemberDTO.mjs";
import { z } from "zod";
import { errorsToText } from "../../common/helpers/ErrorHelpers.mjs";
 
class MemberCardElementChildren
{
    /**
     * @type { string }
     * @public
     */
    id;
 
    /**
     * @type { HTMLHeadingElement }
     * @public
     */
    titleElement;
 
    /**
     * @type { HTMLParagraphElement }
     * @public
     */
    adminNumberValueElement;
 
    /**
     * @type { HTMLUListElement | undefined }
     * @public
     */
    gymProgramsValueElement;
 
    constructor({ id, titleElement, adminNumberValueElement, gymProgramsValueElement })
    {
        this.id = id;
        this.titleElement = titleElement;
        this.adminNumberValueElement = adminNumberValueElement;
        this.gymProgramsValueElement = gymProgramsValueElement;
    }
}
 
class UpdateModal extends Modal
{
    /**
     * @type { HTMLInputElement }
     * @private
     */
    nameInputElement;
 
    /**
     * @type { HTMLInputElement }
     * @private
     */
    adminNumberInputElement;
 
    /**
     * @type { HTMLInputElement }
     * @private
     */
    gymProgramsInputElement;
 
    constructor()
    {
        super();
 
        this.title = "Update Member";
 
        this.nameInputElement = this.addInput(
            new ModalInput(
                {
                    label: "Name",
                    placeholder: "Enter new name",
                    required: false
                })
        ).valueElement;
 
        this.adminNumberInputElement = this.addInput(
            new ModalInput(
                {
                    label: "Admin Number",
                    placeholder: "Enter new admin number",
                    required: false
                })
        ).valueElement;
 
        this.gymProgramsInputElement = this.addInput(
            new ModalInput(
                {
                    label: "Gym Program(s)",
                    placeholder: "Enter new gym program(s) ( Comma-separated )",
                    required: false
                })
        ).valueElement;
 
        this.actionButtonText = "Update Member!";
    }
 
    get name()
    {
        return this.nameInputElement.value;
    }
 
    set name(value)
    {
        this.nameInputElement.value = value;
    }
 
    get adminNumber()
    {
        return this.adminNumberInputElement.value;
    }
 
    set adminNumber(value)
    {
        this.adminNumberInputElement.value = value;
    }
 
    get gymPrograms()
    {
        return this.gymProgramsInputElement.value;
    }
 
    set gymPrograms(value)
    {
        this.gymProgramsInputElement.value = value;
    }
}
 
const updateMemberModal = new UpdateModal();
updateMemberModal.modalElement.id = ElementCollection.MEMBER_UDPATE_MODAL_ID;
updateMemberModal.nameInputElement.id = ElementCollection.MEMBER_UDPATE_MODAL_NAME_FIELD_ID;
updateMemberModal.adminNumberInputElement.id = ElementCollection.MEMBER_UDPATE_MODAL_ADMIN_NUMBER_FIELD_ID;
updateMemberModal.gymProgramsInputElement.id = ElementCollection.MEMBER_UDPATE_MODAL_GYM_PROGRAMS_FIELD_ID;
updateMemberModal.actionButtonElement.id = ElementCollection.MEMBER_UDPATE_MODAL_SUBMIT_BUTTON_ID;
updateMemberModal.modalMessageElement.id = ElementCollection.MEMBER_UDPATE_MODAL_MESSAGE_ID;
 
const onLoadAsync = async () =>
{
    /**
     * @type { Response }
     */
    let response;
 
    let isOk;
 
    try
    {
        response = await fetch(
            Endpoints.MEMBER_GET_ENDPOINT,
            constructGET()
        );
 
        isOk = response.ok;
    }
 
    catch (error)
    {
        console.error(error);
        isOk = false;
    }
 
    let memberListElement = ElementCollection.getMemberListContainer();
 
    // Clear the member list, we use this function for reloading as well.
    memberListElement.innerText = "";
 
    const createCenteredHeadingForError = (text) =>
    {
        const headingElement = document.createElement("h2");
        headingElement.id = ElementCollection.MEMBER_LIST_ERROR_HEADING_ID;
        headingElement.classList.add("text-center", "p-5");
        headingElement.innerText = text;
        return headingElement;
    }
 
    if (!isOk)
    {
        memberListElement.appendChild(createCenteredHeadingForError("Failed to fetch members!"));
        return;
    }
 
    /**
     * @type { MemberDTO[] }
     */
    const members = (await response.json()).members;
 
    if (members.length === 0)
    {
        memberListElement.appendChild(createCenteredHeadingForError("No members found!"));
        return;
    }
 
    const memberListPaddedElement = document.createElement("div");
    memberListPaddedElement.classList.add("container");
    memberListElement.appendChild(memberListPaddedElement);
 
    members.sort((left, right) =>
        Number(
            BigInt(right.id) - BigInt(left.id)
        )
    );
 
    for (const member of members)
    {
        // https://getbootstrap.com/docs/4.1/components/card/
 
        const cardElement = document.createElement("div");
        // mb-3 is for bottom margin
        cardElement.classList.add("card", "mb-3");
        cardElement.id = member.id;
        memberListPaddedElement.appendChild(cardElement);
 
        const cardHeaderElement = document.createElement("div");
        cardHeaderElement.classList.add(
            "card-header",
            "d-flex",
            "justify-content-between",
            "align-items-center"
        );
        cardElement.appendChild(cardHeaderElement);
 
        const memberNameElement = document.createElement("h5");
        memberNameElement.classList.add("card-title", "m-0", ElementCollection.MEMBER_LISTING_NAME_ELEMENT);
        memberNameElement.innerText = member.name;
        cardHeaderElement.appendChild(memberNameElement);
 
        const editButtonElement = document.createElement("button");
        editButtonElement.classList.add("btn", "btn-primary");
        editButtonElement.innerText = "Edit";
        cardHeaderElement.appendChild(editButtonElement);
 
        const cardBodyElement = document.createElement("div");
        cardBodyElement.classList.add("card-body");
        cardElement.appendChild(cardBodyElement);
 
        const adminNumberTitleElement = document.createElement("h5");
        adminNumberTitleElement.classList.add("card-title");
        adminNumberTitleElement.innerText = "Admin Number";
        cardBodyElement.appendChild(adminNumberTitleElement);
 
        const adminNumberValueElement = document.createElement("p");
        adminNumberValueElement.classList.add("card-text", ElementCollection.MEMBER_LISTING_ADMIN_NUMBER_ELEMENT);
        adminNumberValueElement.innerText = member.adminNumber;
        cardBodyElement.appendChild(adminNumberValueElement);
 
        let gymProgramsValueElement;
 
        if (member.gymPrograms.length !== 0)
        {
            const gymProgramsTitleElement = document.createElement("h5");
            gymProgramsTitleElement.classList.add("card-title", ElementCollection.GYM_PROGRAMS_FIELD_TITLE_MEMBER_LIST_CLASS_NAME);
            gymProgramsTitleElement.innerText = "Gym Programs";
            cardBodyElement.appendChild(gymProgramsTitleElement);
 
            gymProgramsValueElement = document.createElement("ul");
            gymProgramsValueElement.classList.add("list-group", ElementCollection.MEMBER_LISTING_GYM_PROGRAMS_ELEMENT);
            cardBodyElement.appendChild(gymProgramsValueElement);
            gymProgramsValueElement.innerText = member.gymPrograms.join(", ");
        }
 
        else
        {
            gymProgramsValueElement = undefined;
        }
 
        const memberCardElementChildren = new MemberCardElementChildren(
        {
            id: member.id,
            titleElement: memberNameElement,
            adminNumberValueElement: adminNumberValueElement,
            gymProgramsValueElement: gymProgramsValueElement
        });
 
        editButtonElement.onclick = () => showUpdateMemberModal(memberCardElementChildren);
    }
}
 
document.addEventListener("DOMContentLoaded", onLoadAsync);
 
/**
 * @param { MemberCardElementChildren } memberCardElementChildren
 */
const showUpdateMemberModal = (memberCardElementChildren) =>
{
    const memberID = memberCardElementChildren.id;
 
    updateMemberModal.name = memberCardElementChildren.titleElement.innerText;
 
    updateMemberModal.adminNumber = memberCardElementChildren.adminNumberValueElement.innerText;
 
    updateMemberModal.gymPrograms = memberCardElementChildren.gymProgramsValueElement?.innerText ?? "";
 
    updateMemberModal.actionButtonCallback = (modal) => updateMemberAsync(modal, memberID);
 
    updateMemberModal.show(true);
}
 
 
const updateMemberModalSchema = MemberDTOSchema.extend(
{
    gymPrograms: z
        .string()
        .transform(programs => programs.split(',').map(program => program.trim()))
        .transform(programs => programs.length === 1 && programs[0] === '' ? [] : programs)
});
 
/**
 * @param { UpdateModal } modal
 * @param { string } memberID
 */
const updateMemberAsync = async (modal, memberID) =>
{
    const parseResult = await updateMemberModalSchema.safeParseAsync(
    {
        name: modal.name,
        adminNumber: modal.adminNumber,
        gymPrograms: modal.gymPrograms
    });
 
    if (!parseResult.success)
    {
        modal.errorMessage = errorsToText(parseResult.error.errors);
        return;
    }
 
    /**
     * @type { Response }
     */
 
    let response;
 
    let isOk;
 
    try
    {
        response = await fetch(
            `${Endpoints.MEMBER_UPDATE_ENDPOINT}/${memberID}`,
            constructPUT(
                MemberDTO.fromSchema(parseResult.data)
            )
        );
 
        isOk = response.ok;
    }
 
    catch (error)
    {
        console.error(error);
        isOk = false;
    }
 
    const responseJSON = await response.json();
 
    if (!isOk)
    {
        /**
         * @type { ErrorDTO }
         */
        responseJSON;
 
        // TODO: Improve this to be specific to the input field.
        modal.errorMessage = errorsToText(responseJSON.errors);
 
        return;
    }
 
    modal.show(false);
 
    await onLoadAsync();
}