form.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. (function () {
  2. const EMAIL_STORAGE_KEY = 'ff_member_form_email_v1';
  3. const boot = window.APP_BOOT || { steps: [], csrf: '', contactEmail: '' };
  4. const state = {
  5. email: '',
  6. currentStep: 1,
  7. totalSteps: boot.steps.length,
  8. autosaveId: null,
  9. };
  10. const startForm = document.getElementById('startForm');
  11. const startEmailInput = document.getElementById('startEmail');
  12. const resetDataBtn = document.getElementById('resetDataBtn');
  13. const wizardSection = document.getElementById('wizardSection');
  14. const statusMessage = document.getElementById('statusMessage');
  15. const applicationForm = document.getElementById('applicationForm');
  16. const applicationEmail = document.getElementById('applicationEmail');
  17. const progress = document.getElementById('progress');
  18. const prevBtn = document.getElementById('prevBtn');
  19. const nextBtn = document.getElementById('nextBtn');
  20. const submitBtn = document.getElementById('submitBtn');
  21. const uploadNowBtn = document.getElementById('uploadNowBtn');
  22. const stepElements = Array.from(document.querySelectorAll('.step'));
  23. function showMessage(text) {
  24. statusMessage.textContent = text || '';
  25. }
  26. function normalizeEmail(email) {
  27. return (email || '').trim().toLowerCase();
  28. }
  29. function isValidEmail(email) {
  30. return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  31. }
  32. function rememberEmail(email) {
  33. try {
  34. localStorage.setItem(EMAIL_STORAGE_KEY, email);
  35. } catch (_err) {
  36. // ignore localStorage errors
  37. }
  38. }
  39. function getRememberedEmail() {
  40. try {
  41. return localStorage.getItem(EMAIL_STORAGE_KEY) || '';
  42. } catch (_err) {
  43. return '';
  44. }
  45. }
  46. function forgetRememberedEmail() {
  47. try {
  48. localStorage.removeItem(EMAIL_STORAGE_KEY);
  49. } catch (_err) {
  50. // ignore localStorage errors
  51. }
  52. }
  53. function lockEmail(email) {
  54. state.email = email;
  55. applicationEmail.value = email;
  56. startEmailInput.value = email;
  57. startEmailInput.readOnly = true;
  58. startEmailInput.setAttribute('aria-readonly', 'true');
  59. resetDataBtn.classList.remove('hidden');
  60. rememberEmail(email);
  61. }
  62. function unlockEmail(clearInput) {
  63. state.email = '';
  64. applicationEmail.value = '';
  65. startEmailInput.readOnly = false;
  66. startEmailInput.removeAttribute('aria-readonly');
  67. resetDataBtn.classList.add('hidden');
  68. if (clearInput) {
  69. startEmailInput.value = '';
  70. }
  71. forgetRememberedEmail();
  72. }
  73. function stopAutosave() {
  74. if (state.autosaveId) {
  75. clearInterval(state.autosaveId);
  76. state.autosaveId = null;
  77. }
  78. }
  79. function startAutosave() {
  80. stopAutosave();
  81. state.autosaveId = setInterval(async () => {
  82. if (!state.email || wizardSection.classList.contains('hidden')) {
  83. return;
  84. }
  85. try {
  86. await saveDraft(false, false);
  87. } catch (_err) {
  88. // visible on next manual action
  89. }
  90. }, 15000);
  91. }
  92. function clearErrors() {
  93. document.querySelectorAll('[data-error-for]').forEach((el) => {
  94. el.textContent = '';
  95. });
  96. }
  97. function showErrors(errors) {
  98. clearErrors();
  99. Object.keys(errors || {}).forEach((key) => {
  100. const el = document.querySelector('[data-error-for="' + key + '"]');
  101. if (el) {
  102. el.textContent = errors[key];
  103. }
  104. });
  105. }
  106. function clearWizardData() {
  107. applicationForm.reset();
  108. clearErrors();
  109. renderUploadInfo({});
  110. state.currentStep = 1;
  111. submitBtn.disabled = false;
  112. nextBtn.disabled = false;
  113. prevBtn.disabled = false;
  114. updateProgress();
  115. }
  116. function updateProgress() {
  117. progress.textContent = 'Schritt ' + state.currentStep + ' von ' + state.totalSteps;
  118. stepElements.forEach((el) => {
  119. const step = Number(el.getAttribute('data-step'));
  120. el.classList.toggle('hidden', step !== state.currentStep);
  121. });
  122. prevBtn.disabled = state.currentStep === 1;
  123. nextBtn.classList.toggle('hidden', state.currentStep === state.totalSteps);
  124. submitBtn.classList.toggle('hidden', state.currentStep !== state.totalSteps);
  125. }
  126. function fillFormData(data) {
  127. Object.keys(data || {}).forEach((key) => {
  128. const field = applicationForm.querySelector('[name="form_data[' + key + ']"]');
  129. if (!field) return;
  130. if (field.type === 'checkbox') {
  131. field.checked = ['1', 'on', 'true', true].includes(data[key]);
  132. } else {
  133. field.value = data[key] || '';
  134. }
  135. });
  136. }
  137. function renderUploadInfo(uploads) {
  138. document.querySelectorAll('[data-upload-list]').forEach((el) => {
  139. el.innerHTML = '';
  140. });
  141. Object.keys(uploads || {}).forEach((field) => {
  142. const target = document.querySelector('[data-upload-list="' + field + '"]');
  143. if (!target || !Array.isArray(uploads[field])) return;
  144. uploads[field].forEach((item) => {
  145. const div = document.createElement('div');
  146. div.className = 'upload-item';
  147. div.textContent = item.original_filename + ' (' + item.uploaded_at + ')';
  148. target.appendChild(div);
  149. });
  150. });
  151. }
  152. function updateUploadSelectionText(fieldKey) {
  153. const target = document.querySelector('[data-upload-selected="' + fieldKey + '"]');
  154. if (!target) {
  155. return;
  156. }
  157. const fileInput = applicationForm.querySelector('[name="' + fieldKey + '"]');
  158. const cameraInput = applicationForm.querySelector('[name="' + fieldKey + '__camera"]');
  159. let label = 'Keine Datei gewählt';
  160. if (fileInput && fileInput.files && fileInput.files[0]) {
  161. label = 'Ausgewählt: ' + fileInput.files[0].name;
  162. }
  163. if (cameraInput && cameraInput.files && cameraInput.files[0]) {
  164. label = 'Ausgewählt: ' + cameraInput.files[0].name + ' (Foto)';
  165. }
  166. target.textContent = label;
  167. }
  168. function initUploadControls() {
  169. const controls = Array.from(document.querySelectorAll('[data-upload-key]'));
  170. controls.forEach((control) => {
  171. const fieldKey = control.getAttribute('data-upload-key') || '';
  172. if (!fieldKey) {
  173. return;
  174. }
  175. const fileInput = applicationForm.querySelector('[name="' + fieldKey + '"]');
  176. const cameraInput = applicationForm.querySelector('[name="' + fieldKey + '__camera"]');
  177. if (fileInput) {
  178. fileInput.addEventListener('change', () => {
  179. if (fileInput.files && fileInput.files[0] && cameraInput) {
  180. cameraInput.value = '';
  181. }
  182. updateUploadSelectionText(fieldKey);
  183. });
  184. }
  185. if (cameraInput) {
  186. cameraInput.addEventListener('change', () => {
  187. if (cameraInput.files && cameraInput.files[0] && fileInput) {
  188. fileInput.value = '';
  189. }
  190. updateUploadSelectionText(fieldKey);
  191. });
  192. }
  193. updateUploadSelectionText(fieldKey);
  194. });
  195. }
  196. async function postForm(url, formData) {
  197. const response = await fetch(url, {
  198. method: 'POST',
  199. body: formData,
  200. credentials: 'same-origin',
  201. headers: { 'X-Requested-With': 'XMLHttpRequest' },
  202. });
  203. const payload = await response.json();
  204. if (!response.ok || payload.ok === false) {
  205. const err = new Error(payload.message || 'Anfrage fehlgeschlagen');
  206. err.payload = payload;
  207. throw err;
  208. }
  209. return payload;
  210. }
  211. function collectPayload(includeFiles) {
  212. const fd = new FormData();
  213. fd.append('csrf', boot.csrf);
  214. fd.append('email', state.email);
  215. fd.append('step', String(state.currentStep));
  216. fd.append('website', '');
  217. Array.from(applicationForm.elements).forEach((el) => {
  218. if (!el.name) return;
  219. if (!el.name.startsWith('form_data[')) return;
  220. if (el.type === 'checkbox') {
  221. fd.append(el.name, el.checked ? '1' : '0');
  222. } else {
  223. fd.append(el.name, el.value || '');
  224. }
  225. });
  226. if (includeFiles) {
  227. Array.from(applicationForm.querySelectorAll('input[type="file"]')).forEach((input) => {
  228. if (input.files && input.files[0]) {
  229. fd.append(input.name, input.files[0]);
  230. }
  231. });
  232. }
  233. return fd;
  234. }
  235. async function loadDraft(email) {
  236. const fd = new FormData();
  237. fd.append('csrf', boot.csrf);
  238. fd.append('email', email);
  239. fd.append('website', '');
  240. return postForm('/api/load-draft.php', fd);
  241. }
  242. async function resetSavedData(email) {
  243. const fd = new FormData();
  244. fd.append('csrf', boot.csrf);
  245. fd.append('email', email);
  246. fd.append('website', '');
  247. return postForm('/api/reset.php', fd);
  248. }
  249. async function saveDraft(includeFiles, showSavedText) {
  250. const payload = collectPayload(includeFiles);
  251. const response = await postForm('/api/save-draft.php', payload);
  252. if (response.upload_errors && Object.keys(response.upload_errors).length > 0) {
  253. showErrors(response.upload_errors);
  254. showMessage('Einige Dateien konnten nicht gespeichert werden.');
  255. } else if (showSavedText) {
  256. showMessage('Entwurf gespeichert: ' + (response.updated_at || ''));
  257. }
  258. if (response.uploads) {
  259. renderUploadInfo(response.uploads);
  260. }
  261. if (includeFiles) {
  262. Array.from(applicationForm.querySelectorAll('input[type="file"]')).forEach((input) => {
  263. input.value = '';
  264. });
  265. Array.from(document.querySelectorAll('[data-upload-key]')).forEach((control) => {
  266. const fieldKey = control.getAttribute('data-upload-key');
  267. if (fieldKey) {
  268. updateUploadSelectionText(fieldKey);
  269. }
  270. });
  271. }
  272. return response;
  273. }
  274. async function submitApplication() {
  275. const payload = collectPayload(true);
  276. const response = await postForm('/api/submit.php', payload);
  277. clearErrors();
  278. showMessage('Antrag erfolgreich abgeschlossen. Vielen Dank.');
  279. submitBtn.disabled = true;
  280. nextBtn.disabled = true;
  281. prevBtn.disabled = true;
  282. return response;
  283. }
  284. async function startProcess(rawEmail) {
  285. const email = normalizeEmail(rawEmail);
  286. if (!isValidEmail(email)) {
  287. showMessage('Bitte eine gültige E-Mail-Adresse eingeben.');
  288. startEmailInput.focus();
  289. return;
  290. }
  291. try {
  292. const result = await loadDraft(email);
  293. lockEmail(email);
  294. if (result.already_submitted) {
  295. wizardSection.classList.add('hidden');
  296. showMessage(
  297. (result.message || 'Antrag bereits abgeschlossen.') +
  298. (boot.contactEmail ? ' Kontakt: ' + boot.contactEmail : '')
  299. );
  300. stopAutosave();
  301. return;
  302. }
  303. wizardSection.classList.remove('hidden');
  304. fillFormData(result.data || {});
  305. renderUploadInfo(result.uploads || {});
  306. state.currentStep = Math.min(Math.max(Number(result.step || 1), 1), state.totalSteps);
  307. updateProgress();
  308. startAutosave();
  309. showMessage('Formular geladen. Entwurf wird automatisch gespeichert.');
  310. } catch (err) {
  311. const msg = (err.payload && err.payload.message) || err.message || 'Laden fehlgeschlagen.';
  312. showMessage(msg);
  313. }
  314. }
  315. startForm.addEventListener('submit', async (event) => {
  316. event.preventDefault();
  317. await startProcess(startEmailInput.value || '');
  318. });
  319. resetDataBtn.addEventListener('click', async () => {
  320. if (!state.email) {
  321. showMessage('Keine aktive E-Mail vorhanden.');
  322. return;
  323. }
  324. const confirmed = window.confirm('Alle gespeicherten Daten zu dieser E-Mail endgültig löschen und neu starten?');
  325. if (!confirmed) {
  326. return;
  327. }
  328. try {
  329. await resetSavedData(state.email);
  330. stopAutosave();
  331. wizardSection.classList.add('hidden');
  332. clearWizardData();
  333. unlockEmail(true);
  334. showMessage('Alle gespeicherten Daten wurden gelöscht. Sie können neu starten.');
  335. startEmailInput.focus();
  336. } catch (err) {
  337. const msg = (err.payload && err.payload.message) || err.message || 'Löschen fehlgeschlagen.';
  338. showMessage(msg);
  339. }
  340. });
  341. prevBtn.addEventListener('click', async () => {
  342. if (state.currentStep <= 1) return;
  343. try {
  344. await saveDraft(false, true);
  345. state.currentStep -= 1;
  346. updateProgress();
  347. } catch (err) {
  348. const msg = (err.payload && err.payload.message) || err.message;
  349. showMessage(msg);
  350. }
  351. });
  352. nextBtn.addEventListener('click', async () => {
  353. if (state.currentStep >= state.totalSteps) return;
  354. try {
  355. await saveDraft(false, true);
  356. state.currentStep += 1;
  357. updateProgress();
  358. } catch (err) {
  359. const msg = (err.payload && err.payload.message) || err.message;
  360. showMessage(msg);
  361. }
  362. });
  363. if (uploadNowBtn) {
  364. uploadNowBtn.addEventListener('click', async () => {
  365. try {
  366. await saveDraft(true, true);
  367. } catch (err) {
  368. const msg = (err.payload && err.payload.message) || err.message;
  369. showMessage(msg);
  370. }
  371. });
  372. }
  373. submitBtn.addEventListener('click', async () => {
  374. try {
  375. await submitApplication();
  376. } catch (err) {
  377. const payload = err.payload || {};
  378. if (payload.errors) {
  379. showErrors(payload.errors);
  380. }
  381. const msg = payload.message || err.message || 'Absenden fehlgeschlagen.';
  382. showMessage(msg);
  383. if (payload.already_submitted) {
  384. wizardSection.classList.add('hidden');
  385. }
  386. }
  387. });
  388. const rememberedEmail = normalizeEmail(getRememberedEmail());
  389. if (rememberedEmail !== '') {
  390. if (isValidEmail(rememberedEmail)) {
  391. startEmailInput.value = rememberedEmail;
  392. showMessage('Gespeicherte E-Mail erkannt. Formular wird geladen ...');
  393. startProcess(rememberedEmail);
  394. } else {
  395. forgetRememberedEmail();
  396. }
  397. }
  398. initUploadControls();
  399. updateProgress();
  400. })();