form.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. (function () {
  2. const boot = window.APP_BOOT || { steps: [], csrf: '' };
  3. const state = {
  4. email: '',
  5. currentStep: 1,
  6. totalSteps: boot.steps.length,
  7. autosaveId: null,
  8. };
  9. const startForm = document.getElementById('startForm');
  10. const wizardSection = document.getElementById('wizardSection');
  11. const blockedSection = document.getElementById('blockedSection');
  12. const statusSection = document.getElementById('statusSection');
  13. const statusMessage = document.getElementById('statusMessage');
  14. const applicationForm = document.getElementById('applicationForm');
  15. const applicationEmail = document.getElementById('applicationEmail');
  16. const progress = document.getElementById('progress');
  17. const prevBtn = document.getElementById('prevBtn');
  18. const nextBtn = document.getElementById('nextBtn');
  19. const submitBtn = document.getElementById('submitBtn');
  20. const uploadNowBtn = document.getElementById('uploadNowBtn');
  21. const stepElements = Array.from(document.querySelectorAll('.step'));
  22. function showMessage(text) {
  23. statusSection.classList.remove('hidden');
  24. statusMessage.textContent = text;
  25. }
  26. function clearErrors() {
  27. document.querySelectorAll('[data-error-for]').forEach((el) => {
  28. el.textContent = '';
  29. });
  30. }
  31. function showErrors(errors) {
  32. clearErrors();
  33. Object.keys(errors || {}).forEach((key) => {
  34. const el = document.querySelector('[data-error-for="' + key + '"]');
  35. if (el) {
  36. el.textContent = errors[key];
  37. }
  38. });
  39. }
  40. function updateProgress() {
  41. progress.textContent = 'Schritt ' + state.currentStep + ' von ' + state.totalSteps;
  42. stepElements.forEach((el) => {
  43. const step = Number(el.getAttribute('data-step'));
  44. el.classList.toggle('hidden', step !== state.currentStep);
  45. });
  46. prevBtn.disabled = state.currentStep === 1;
  47. nextBtn.classList.toggle('hidden', state.currentStep === state.totalSteps);
  48. submitBtn.classList.toggle('hidden', state.currentStep !== state.totalSteps);
  49. }
  50. function fillFormData(data) {
  51. Object.keys(data || {}).forEach((key) => {
  52. const field = applicationForm.querySelector('[name="form_data[' + key + ']"]');
  53. if (!field) return;
  54. if (field.type === 'checkbox') {
  55. field.checked = ['1', 'on', 'true', true].includes(data[key]);
  56. } else {
  57. field.value = data[key] || '';
  58. }
  59. });
  60. }
  61. function renderUploadInfo(uploads) {
  62. document.querySelectorAll('[data-upload-list]').forEach((el) => {
  63. el.innerHTML = '';
  64. });
  65. Object.keys(uploads || {}).forEach((field) => {
  66. const target = document.querySelector('[data-upload-list="' + field + '"]');
  67. if (!target || !Array.isArray(uploads[field])) return;
  68. uploads[field].forEach((item) => {
  69. const div = document.createElement('div');
  70. div.className = 'upload-item';
  71. div.textContent = item.original_filename + ' (' + item.uploaded_at + ')';
  72. target.appendChild(div);
  73. });
  74. });
  75. }
  76. async function postForm(url, formData) {
  77. const response = await fetch(url, {
  78. method: 'POST',
  79. body: formData,
  80. credentials: 'same-origin',
  81. headers: { 'X-Requested-With': 'XMLHttpRequest' },
  82. });
  83. const payload = await response.json();
  84. if (!response.ok || payload.ok === false) {
  85. const err = new Error(payload.message || 'Anfrage fehlgeschlagen');
  86. err.payload = payload;
  87. throw err;
  88. }
  89. return payload;
  90. }
  91. function collectPayload(includeFiles) {
  92. const fd = new FormData();
  93. fd.append('csrf', boot.csrf);
  94. fd.append('email', state.email);
  95. fd.append('step', String(state.currentStep));
  96. fd.append('website', '');
  97. Array.from(applicationForm.elements).forEach((el) => {
  98. if (!el.name) return;
  99. if (!el.name.startsWith('form_data[')) return;
  100. if (el.type === 'checkbox') {
  101. fd.append(el.name, el.checked ? '1' : '0');
  102. } else {
  103. fd.append(el.name, el.value || '');
  104. }
  105. });
  106. if (includeFiles) {
  107. Array.from(applicationForm.querySelectorAll('input[type="file"]')).forEach((input) => {
  108. if (input.files && input.files[0]) {
  109. fd.append(input.name, input.files[0]);
  110. }
  111. });
  112. }
  113. return fd;
  114. }
  115. async function loadDraft(email) {
  116. const fd = new FormData();
  117. fd.append('csrf', boot.csrf);
  118. fd.append('email', email);
  119. fd.append('website', '');
  120. return postForm('/api/load-draft.php', fd);
  121. }
  122. async function saveDraft(includeFiles, showSavedText) {
  123. const payload = collectPayload(includeFiles);
  124. const response = await postForm('/api/save-draft.php', payload);
  125. if (response.upload_errors && Object.keys(response.upload_errors).length > 0) {
  126. showErrors(response.upload_errors);
  127. showMessage('Einige Dateien konnten nicht gespeichert werden.');
  128. } else if (showSavedText) {
  129. showMessage('Entwurf gespeichert: ' + (response.updated_at || ''));
  130. }
  131. if (response.uploads) {
  132. renderUploadInfo(response.uploads);
  133. }
  134. if (includeFiles) {
  135. Array.from(applicationForm.querySelectorAll('input[type="file"]')).forEach((input) => {
  136. input.value = '';
  137. });
  138. }
  139. return response;
  140. }
  141. async function submitApplication() {
  142. const payload = collectPayload(true);
  143. const response = await postForm('/api/submit.php', payload);
  144. clearErrors();
  145. showMessage('Antrag erfolgreich abgeschlossen. Vielen Dank.');
  146. submitBtn.disabled = true;
  147. nextBtn.disabled = true;
  148. prevBtn.disabled = true;
  149. return response;
  150. }
  151. startForm.addEventListener('submit', async (event) => {
  152. event.preventDefault();
  153. const emailInput = document.getElementById('startEmail');
  154. const email = (emailInput.value || '').trim().toLowerCase();
  155. if (!email) {
  156. showMessage('Bitte E-Mail eingeben.');
  157. return;
  158. }
  159. try {
  160. const result = await loadDraft(email);
  161. state.email = email;
  162. applicationEmail.value = email;
  163. if (result.already_submitted) {
  164. wizardSection.classList.add('hidden');
  165. blockedSection.classList.remove('hidden');
  166. showMessage(result.message || 'Antrag bereits abgeschlossen.');
  167. return;
  168. }
  169. blockedSection.classList.add('hidden');
  170. wizardSection.classList.remove('hidden');
  171. fillFormData(result.data || {});
  172. renderUploadInfo(result.uploads || {});
  173. state.currentStep = Math.min(Math.max(Number(result.step || 1), 1), state.totalSteps);
  174. updateProgress();
  175. showMessage('Formular geladen. Entwurf wird automatisch gespeichert.');
  176. if (state.autosaveId) {
  177. clearInterval(state.autosaveId);
  178. }
  179. state.autosaveId = setInterval(async () => {
  180. if (!state.email || wizardSection.classList.contains('hidden')) {
  181. return;
  182. }
  183. try {
  184. await saveDraft(false, false);
  185. } catch (_err) {
  186. // Autsave errors are visible on next manual action.
  187. }
  188. }, 15000);
  189. } catch (err) {
  190. const msg = (err.payload && err.payload.message) || err.message || 'Laden fehlgeschlagen.';
  191. showMessage(msg);
  192. }
  193. });
  194. prevBtn.addEventListener('click', async () => {
  195. if (state.currentStep <= 1) return;
  196. try {
  197. await saveDraft(false, true);
  198. state.currentStep -= 1;
  199. updateProgress();
  200. } catch (err) {
  201. const msg = (err.payload && err.payload.message) || err.message;
  202. showMessage(msg);
  203. }
  204. });
  205. nextBtn.addEventListener('click', async () => {
  206. if (state.currentStep >= state.totalSteps) return;
  207. try {
  208. await saveDraft(false, true);
  209. state.currentStep += 1;
  210. updateProgress();
  211. } catch (err) {
  212. const msg = (err.payload && err.payload.message) || err.message;
  213. showMessage(msg);
  214. }
  215. });
  216. if (uploadNowBtn) {
  217. uploadNowBtn.addEventListener('click', async () => {
  218. try {
  219. await saveDraft(true, true);
  220. } catch (err) {
  221. const msg = (err.payload && err.payload.message) || err.message;
  222. showMessage(msg);
  223. }
  224. });
  225. }
  226. submitBtn.addEventListener('click', async () => {
  227. try {
  228. await submitApplication();
  229. } catch (err) {
  230. const payload = err.payload || {};
  231. if (payload.errors) {
  232. showErrors(payload.errors);
  233. }
  234. const msg = payload.message || err.message || 'Absenden fehlgeschlagen.';
  235. showMessage(msg);
  236. if (payload.already_submitted) {
  237. blockedSection.classList.remove('hidden');
  238. wizardSection.classList.add('hidden');
  239. }
  240. }
  241. });
  242. updateProgress();
  243. })();