AppointmentRegisterInputs.svelte 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <script lang="ts">
  2. import { api_host } from "$lib";
  3. import type { AppointmentInputs, DynamicJson } from "$lib/dbdata";
  4. import validator from "validator";
  5. export let dynamicInputs: DynamicJson[] = [];
  6. export let appointmentId: string;
  7. export let date: Date;
  8. export let modalActive: boolean;
  9. export let errorMessage: string = "";
  10. export let successMessage: string = "";
  11. let inputValues: Record<string, string> = {};
  12. function validateInput(value: string, type: string): boolean {
  13. switch (type) {
  14. case "email":
  15. return validator.isEmail(value);
  16. case "text":
  17. return !validator.isEmpty(value);
  18. case "tel":
  19. return validator.isMobilePhone(value);
  20. default:
  21. return false;
  22. }
  23. }
  24. async function confirmBooking(customInputs: DynamicJson[]) {
  25. try {
  26. const response = await fetch(`${api_host}/api/schedule/create`, {
  27. method: "POST",
  28. headers: {
  29. "Content-Type": "application/json"
  30. },
  31. body: JSON.stringify({
  32. appointmentId: appointmentId,
  33. time: date,
  34. inputs: customInputs
  35. })
  36. })
  37. if (response.status === 200) {
  38. successMessage = "successfully booked";
  39. } else {
  40. errorMessage = "invalid credentials";
  41. }
  42. } catch (error) {
  43. console.log(error);
  44. }
  45. }
  46. async function submit() {
  47. let customInputs: DynamicJson[] = [];
  48. errorMessage = "";
  49. if (Object.keys(inputValues).length != dynamicInputs.length) {
  50. errorMessage = "Not all inputs filled";
  51. return;
  52. }
  53. for (const dInput of dynamicInputs) {
  54. if (inputValues[dInput.name]) {
  55. if (!validateInput(inputValues[dInput.name], dInput.type)) {
  56. errorMessage = "Invalid inputs";
  57. return;
  58. }
  59. customInputs = [...customInputs, {name: dInput.name, value: inputValues[dInput.name]}];
  60. }
  61. }
  62. await confirmBooking(customInputs);
  63. }
  64. function closeModal() {
  65. modalActive = false;
  66. }
  67. </script>
  68. {#each dynamicInputs as dInput}
  69. <div class="field border">
  70. <input id={dInput.name} type={dInput.type} placeholder={dInput.name} bind:value={inputValues[dInput.name]}>
  71. <label for={dInput.name}>{dInput.name}</label>
  72. </div>
  73. {/each}
  74. <nav class="right-align">
  75. <button on:click={submit}>Submit</button>
  76. <button class="border" on:click={closeModal}>Close</button>
  77. </nav>