-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrouter_wizard.py
More file actions
2095 lines (1727 loc) · 78.7 KB
/
Copy pathrouter_wizard.py
File metadata and controls
2095 lines (1727 loc) · 78.7 KB
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""HTMX wizard routes for multi-step project forms."""
from __future__ import annotations
import contextlib
import logging
from typing import TYPE_CHECKING, Any
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from opi.core.auth_decorators import get_current_user, requires_sso
from opi.core.project_schema import ProjectIntegrityError, ProjectSchemaError
from opi.core.templates import get_templates
from opi.forms import FormRenderer, ROOSWidgetAdapter, get_default_nl_translator
from opi.forms.editables.processor import EditableFormProcessor
from opi.forms.visualizers.flows import get_flow
from opi.forms.wizard.resolver import (
get_section_metadata,
resolve_active_section_ids,
resolve_active_sections,
)
from opi.forms.wizard.session import (
clear_wizard_state,
get_wizard_state,
init_wizard_state,
save_wizard_state,
)
from opi.forms.wizard.state import CLEARED_FIELD
from opi.utils.csrf import reject_misfired_form_get
from opi.web.menu import get_menu_items
if TYPE_CHECKING:
from opi.forms.visualizers.flows import FormFlow
from opi.forms.visualizers.sections import FormSection
from opi.forms.wizard.state import WizardState
logger = logging.getLogger(__name__)
wizard_router = APIRouter(prefix="/forms/wizard", tags=["wizard"])
def _create_renderer() -> FormRenderer:
"""Create a configured FormRenderer for wizard forms."""
return FormRenderer(
widget_adapter=ROOSWidgetAdapter(),
translator=get_default_nl_translator(),
)
def _get_section_from_flow(flow_id: str, section_id: str) -> FormSection:
"""Look up a section by ID within a flow."""
flow = get_flow(flow_id)
for section in flow.sections:
if section.section_id == section_id:
return section
raise HTTPException(status_code=404, detail=f"Stap '{section_id}' niet gevonden")
def _render_step_html(
section: FormSection,
yaml_data: dict[str, Any],
errors: dict[str, list[str]] | None = None,
edit_mode: bool = False,
warnings: dict[str, list[str]] | None = None,
) -> str:
"""Render the form fields for a single wizard step."""
import copy
from opi.forms.editables.service_path import smart_get_value, smart_set_value
renderer = _create_renderer()
if not section.layout:
return ""
# General solution: restore transient fields from their parent values before rendering.
# When a transient field is deferred to a parent, the transient is stripped from saved state.
# But for rendering, we need the transient field value so the input shows the correct value.
# For each transient field with a depends_on relationship, restore from the dependency.
render_data = copy.deepcopy(yaml_data)
if section.section_id == "domains":
logger.debug("[domains render START] processing %d editables", len(section.editables))
def _restore_transient_fields(editables: list[Any], data: dict[str, Any]) -> None:
"""Recursively restore transient fields from their dependencies, including children."""
for editable in editables:
ed = editable.editable
if section.section_id == "domains":
logger.debug(
"[domains render] checking editable: path=%s, transient=%s, depends_on=%s, has_children=%s",
ed.yaml_path,
ed.transient,
ed.depends_on,
bool(editable.children),
)
# Recursively process children (for GROUP editables)
if editable.children:
_restore_transient_fields(editable.children, data)
# Check if this is a transient field that depends on another field
if ed.transient and ed.depends_on:
# Get the dependency value (the parent field value)
dep_value = smart_get_value(data, ed.depends_on)
if section.section_id == "domains":
logger.debug(
"[domains render] FOUND transient field %s, dep_value=%s",
ed.yaml_path,
dep_value,
)
# If the parent has a non-sentinel value, it's a custom value - restore it to the transient for display
if dep_value and dep_value != "__custom__":
# Restore this transient field from the parent for display
smart_set_value(data, ed.yaml_path, dep_value)
logger.debug(
"[domains render] RESTORED transient field %s from dependency %s (value=%s)",
ed.yaml_path,
ed.depends_on,
dep_value,
)
_restore_transient_fields(section.editables, render_data)
yaml_data = render_data
return renderer.render_fields_from_editables(
editables=section.editables,
yaml_data=yaml_data,
layout=section.layout,
errors=errors,
edit_mode=edit_mode,
warnings=warnings,
)
def _build_step_context(
request: Request,
flow_id: str,
section: FormSection,
step_html: str,
errors: dict[str, list[str]] | None = None,
global_errors: list[str] | None = None,
) -> dict[str, Any]:
"""Build the template context for rendering a wizard step."""
state = get_wizard_state(request)
if not state:
raise HTTPException(status_code=400, detail="Geen wizard sessie gevonden")
flow = get_flow(flow_id)
active_sections = resolve_active_sections(flow, state.step_data)
section_meta = get_section_metadata(active_sections)
steps = state.get_steps(section_meta)
# Build preset cards HTML if presets exist for this section
yaml_data = state.get_merged_data()
preset_html = _render_preset_html(
flow_id, section.section_id, yaml_data=yaml_data, csrf_token=request.state.csrf_token
)
# All steps already completed = user came back from review/submit to fix something
all_steps_completed = set(steps.all).issubset(set(steps.completed))
user = get_current_user(request)
return {
"request": request,
"steps": steps,
"flow_id": flow_id,
"section": section,
"step_html": step_html,
"preset_html": preset_html,
"errors": errors or {},
"global_errors": global_errors or [],
"show_review": flow.show_review,
"all_steps_completed": all_steps_completed,
"menu_items": get_menu_items(user),
"user": user,
}
def _render_preset_html(
flow_id: str,
section_id: str,
yaml_data: dict[str, Any] | None = None,
csrf_token: str = "",
) -> str:
"""Render preset cards for a section, if any presets exist."""
from opi.forms.presets.loader import load_presets
from opi.forms.widgets.roos import render_preset_cards
presets = load_presets(section_id)
if not presets:
return ""
locked_presets: dict[str, str] = {}
if yaml_data is not None:
section = _get_section_from_flow(flow_id, section_id)
# Apply locked_by_service forced values so preset detection sees them.
_apply_locked_by_service(section.editables, yaml_data)
# Detect which presets are locked by active services.
locked_presets = _detect_locked_presets(presets, section.editables, yaml_data)
return render_preset_cards(
presets,
flow_id,
section_id,
yaml_data=yaml_data,
locked_presets=locked_presets,
csrf_token=csrf_token,
)
def _apply_locked_by_service(
editables: list,
yaml_data: dict[str, Any],
) -> None:
"""Inject forced True values for fields locked by an active service.
When a service like ``authorization-wall`` is selected, fields with
``locked_by_service`` pointing to that service are forced to True.
This mirrors the logic in ``FormRenderer.render_fields_from_editables``.
Mutates *yaml_data* in place.
"""
from opi.forms.editables.service_path import smart_set_value
from opi.forms.visualizers.bridge import _is_service_active
for editable in editables:
if editable.locked_by_service and _is_service_active(editable.locked_by_service, yaml_data):
smart_set_value(yaml_data, editable.editable.yaml_path, True)
def _detect_locked_presets(
presets: list,
editables: list,
yaml_data: dict[str, Any],
) -> dict[str, str]:
"""Find presets that are locked because a service forces their values.
A preset is locked when any of its value paths corresponds to an
editable with ``locked_by_service`` whose service is currently active.
Returns:
Map of preset_id -> hint text (e.g. "Vereist door: Authorization Wall").
"""
from opi.forms.visualizers.bridge import _is_service_active, _service_display_name
# Build map: yaml_path -> service display name for active locked fields
locked_paths: dict[str, str] = {}
for editable in editables:
if editable.locked_by_service and _is_service_active(editable.locked_by_service, yaml_data):
locked_paths[editable.editable.yaml_path] = _service_display_name(editable.locked_by_service)
if not locked_paths:
return {}
result: dict[str, str] = {}
for preset in presets:
for path in preset.values:
if path in locked_paths:
result[preset.id] = f"Vereist door: {locked_paths[path]}"
break
return result
# ---------------------------------------------------------------------------
# Restart: clear state and redirect to start
# ---------------------------------------------------------------------------
@wizard_router.get("/restart")
@requires_sso
async def wizard_restart(request: Request) -> RedirectResponse:
"""Clear any existing wizard state and redirect to the start page."""
clear_wizard_state(request)
return RedirectResponse(url="/forms/wizard/start", status_code=302)
# ---------------------------------------------------------------------------
# Landing page: wizard introduction
# ---------------------------------------------------------------------------
@wizard_router.get("/start", response_class=HTMLResponse)
@requires_sso
async def wizard_start(request: Request) -> HTMLResponse:
"""Render the wizard introduction / landing page."""
user = get_current_user(request)
templates = get_templates()
return templates.TemplateResponse(
"wizard/wizard_start.html.j2",
{
"request": request,
"menu_items": get_menu_items(user),
"user": user,
},
)
# ---------------------------------------------------------------------------
# Full page: start wizard
# ---------------------------------------------------------------------------
@wizard_router.get("/{flow_id}", response_class=HTMLResponse)
@requires_sso
async def wizard_page(request: Request, flow_id: str) -> HTMLResponse:
"""Render the full wizard page, resuming existing state if available."""
flow = get_flow(flow_id)
user = get_current_user(request)
templates = get_templates()
# Check for existing wizard state for this flow
existing_state = get_wizard_state(request)
if existing_state and existing_state.flow_id == flow_id:
# Resume from current step
state = existing_state
else:
# Start a new wizard
active_section_ids = resolve_active_section_ids(flow, {})
if not active_section_ids:
raise HTTPException(status_code=500, detail="Geen stappen gevonden in de wizard")
state = init_wizard_state(
request,
flow_id=flow_id,
first_step=active_section_ids[0],
active_sections=active_section_ids,
)
state.populate_virt_mappings(flow.sections)
# Seed template data (repositories, base config) as the lowest-priority layer
from opi.forms.editables.template import load_project_template
state.template_data = load_project_template()
# Seed the team step with the current user as administrator
user_email = (user or {}).get("email", "")
if user_email:
state.store_step_data("team", {"users": [{"email": user_email, "role": "admin"}]})
# Seed the components step with one default component.
# The services checkbox is left unset (None) so the renderer
# auto-populates it with all project-level services on first render.
state.store_step_data(
"components",
{
"components": [
{
"name": "",
"path": "/",
"ports": {"inbound": [8080], "outbound": [80, 443]},
"resources": {
"requests": {"cpu": "50m", "memory": "256Mi"},
"limits": {"cpu": "1", "memory": "512Mi"},
},
},
],
},
)
# Seed the domains step with default domain mode only.
# Do NOT include "name" here - it comes from the deployment step
# and the index-based merge in get_merged_data() would overwrite it.
state.store_step_data(
"domains",
{
"deployments": [
{
"domain-mode": "component-specific",
},
],
},
)
save_wizard_state(request, state)
# Render the current step (first step for new, resumed step for existing)
yaml_data = state.get_merged_data()
section = _get_section_from_flow(flow_id, state.current_step)
step_html = _render_step_html(
section,
yaml_data=yaml_data,
edit_mode=state.project_name is not None,
)
active_sections = resolve_active_sections(flow, state.step_data)
section_meta = get_section_metadata(active_sections)
steps = state.get_steps(section_meta)
return templates.TemplateResponse(
"wizard/wizard_page.html.j2",
{
"request": request,
"flow_title": flow.title,
"flow_id": flow_id,
"project_name": state.project_name,
"steps": steps,
"section": section,
"step_html": step_html,
"errors": {},
"global_errors": [],
"show_review": flow.show_review,
"menu_items": get_menu_items(user),
"user": user,
},
)
# ---------------------------------------------------------------------------
# Full page: edit wizard (pre-filled from existing project)
# ---------------------------------------------------------------------------
@wizard_router.get("/{flow_id}/edit/{project_name}", response_class=HTMLResponse)
@requires_sso
async def wizard_edit_page(request: Request, flow_id: str, project_name: str) -> HTMLResponse:
"""Render the wizard page pre-filled from an existing project."""
from opi.web.project_edit_security import require_project_edit_access
flow = get_flow(flow_id)
user = get_current_user(request)
templates = get_templates()
# Enforce admin/owner role: the wizard edit flow exposes users/role and
# config fields as editable, so a plain member must not be able to enter
# it (project takeover).
project, _user_email = require_project_edit_access(request, project_name)
project_data = project.data
if not project_data:
raise HTTPException(status_code=500, detail="Project data niet beschikbaar")
# Populate transient fields for deferred editables (e.g. custom domain text input)
processor = EditableFormProcessor()
for section in flow.sections:
processor.populate_deferred_fields(project_data, section.editables)
# Pre-fill step data from existing project
step_data = _split_data_across_sections(flow, project_data)
# Resolve active sections with pre-filled data
active_section_ids = resolve_active_section_ids(flow, step_data)
if not active_section_ids:
raise HTTPException(status_code=500, detail="Geen stappen gevonden in de wizard")
first_step = active_section_ids[0]
# Initialize wizard state with project data
state = init_wizard_state(
request,
flow_id=flow_id,
first_step=first_step,
active_sections=active_section_ids,
project_name=project_name,
)
state.populate_virt_mappings(flow.sections)
state.step_data = step_data
# Mark all sections with data as completed
for section_id in active_section_ids:
if step_data.get(section_id):
state.mark_completed(section_id)
save_wizard_state(request, state)
# Render the first step with pre-filled data
section = _get_section_from_flow(flow_id, first_step)
step_html = _render_step_html(section, yaml_data=project_data, edit_mode=True)
active_sections = resolve_active_sections(flow, state.step_data)
section_meta = get_section_metadata(active_sections)
steps = state.get_steps(section_meta)
display_name = project_data.get("display-name", project_name)
return templates.TemplateResponse(
"wizard/wizard_page.html.j2",
{
"request": request,
"flow_title": f"{flow.title} - {display_name}",
"flow_id": flow_id,
"project_name": project_name,
"steps": steps,
"section": section,
"step_html": step_html,
"errors": {},
"global_errors": [],
"show_review": flow.show_review,
"menu_items": get_menu_items(user),
"user": user,
},
)
def _split_data_across_sections(
flow: FormFlow,
project_data: dict[str, Any],
) -> dict[str, dict[str, Any]]:
"""Split existing project data into per-section dicts.
Each section gets the subset of project_data that its editables reference.
This allows the wizard to pre-fill each step with existing values.
Editables with ``virtualize`` store their data under the virtual key
(e.g. ``_services-config``) so config sections don't collide with the
service selection list in ``services``.
"""
from opi.forms.editables.service_path import smart_get_value
step_data: dict[str, dict[str, Any]] = {}
for section in flow.sections:
section_data: dict[str, Any] = {}
for editable in section.editables:
ed = editable.editable
value = smart_get_value(project_data, ed.yaml_path)
if value is not None:
if ed.virtualize:
# Store under virtual key to avoid collisions.
# Extract the service-specific config block.
virt_key = ed.virtualize[1]
parts = ed.yaml_path.split("/")
if len(parts) >= 2:
svc_name = parts[1]
svc_config = smart_get_value(project_data, f"services/{svc_name}")
if svc_config is not None:
section_data.setdefault(virt_key, {})[svc_name] = svc_config
else:
top_key = ed.yaml_path.split("/")[0].split("[")[0]
section_data[top_key] = project_data.get(top_key, value)
if section_data:
step_data[section.section_id] = section_data
return step_data
# ---------------------------------------------------------------------------
# Shared navigation helper
# ---------------------------------------------------------------------------
def _resolve_goto_target(
goto: str,
current_section_id: str,
active_section_ids: list[str],
) -> str | None:
"""Resolve a navigation direction to a concrete section_id.
Args:
goto: Direction - "next", "prev", "review", or a section_id.
current_section_id: The section the user is currently on.
active_section_ids: Ordered list of active section_ids.
Returns:
A section_id to navigate to, "review" for summary, or None if
at the end with no review.
"""
if goto == "review":
return "review"
try:
current_idx = active_section_ids.index(current_section_id)
except ValueError:
return active_section_ids[0] if active_section_ids else None
if goto == "next":
if current_idx < len(active_section_ids) - 1:
return active_section_ids[current_idx + 1]
return None # past last step
if goto == "prev":
if current_idx > 0:
return active_section_ids[current_idx - 1]
return active_section_ids[0] # already at first step
# Specific section_id (from step indicator jump)
if goto in active_section_ids:
return goto
# Unknown goto - stay on current
logger.warning("[resolve_goto] unknown goto=%r, staying on %s", goto, current_section_id)
return current_section_id
async def _navigate_to_step(
request: Request,
state: WizardState,
flow_id: str,
target_section_id: str,
templates: Any,
) -> HTMLResponse:
"""Save state and render the target step.
Used by both forward navigation (after validation) and jump/back
navigation (skip validation). Runs validation on load when the
target step already has stored data, so errors are shown immediately.
"""
target_section = _get_section_from_flow(flow_id, target_section_id)
state.current_step = target_section_id
save_wizard_state(request, state)
logger.info(
"[navigate] target=%s, active_sections=%s, current_step=%s",
target_section_id,
state.active_sections,
state.current_step,
)
yaml_data = state.get_merged_data()
edit_mode = state.project_name is not None
# Validate on load only for steps the user has explicitly completed (forward-validated).
# Steps that merely have saved data from back-navigation should not show errors.
errors: dict[str, list[str]] | None = None
if target_section_id in state.completed_steps and target_section_id in state.step_data:
processor = EditableFormProcessor()
_, errors = await processor.process_json_submission(
state.step_data[target_section_id],
target_section.editables,
yaml_data,
edit_mode=edit_mode,
)
if not errors:
errors = None
step_html = _render_step_html(
target_section,
yaml_data=yaml_data,
errors=errors,
edit_mode=edit_mode,
)
context = _build_step_context(
request,
flow_id,
target_section,
step_html,
errors=errors,
)
response = templates.TemplateResponse("wizard/wizard_step.html.j2", context)
response.headers["HX-Push-Url"] = f"/forms/wizard/{flow_id}/step/{target_section_id}"
return response
# ---------------------------------------------------------------------------
# HTMX: load a step (GET)
# ---------------------------------------------------------------------------
@wizard_router.get("/{flow_id}/step/{section_id}", response_class=HTMLResponse)
@requires_sso
async def load_step(request: Request, flow_id: str, section_id: str) -> HTMLResponse:
"""Load a wizard step via HTMX or direct browser navigation.
For HTMX requests, delegates to ``_navigate_to_step`` which validates
stored data on load. For direct browser access, renders the full page.
"""
reject_misfired_form_get(request)
state = get_wizard_state(request)
if not state or state.flow_id != flow_id:
# No session - redirect to the wizard start page which will init state
return RedirectResponse(url=f"/forms/wizard/{flow_id}", status_code=302) # type: ignore[return-value]
templates = get_templates()
is_htmx = request.headers.get("HX-Request") == "true"
if is_htmx:
return await _navigate_to_step(request, state, flow_id, section_id, templates)
# Direct browser access: return the full page with the step embedded
section = _get_section_from_flow(flow_id, section_id)
state.current_step = section_id
save_wizard_state(request, state)
yaml_data = state.get_merged_data()
edit_mode = state.project_name is not None
# Validate on load only for completed steps (not just saved from back-navigation)
errors: dict[str, list[str]] | None = None
if section_id in state.completed_steps and section_id in state.step_data:
processor = EditableFormProcessor()
_, errors = await processor.process_json_submission(
state.step_data[section_id],
section.editables,
yaml_data,
edit_mode=edit_mode,
)
if not errors:
errors = None
step_html = _render_step_html(
section,
yaml_data=yaml_data,
errors=errors,
edit_mode=edit_mode,
)
flow = get_flow(flow_id)
user = get_current_user(request)
active_sections = resolve_active_sections(flow, state.step_data)
section_meta = get_section_metadata(active_sections)
steps = state.get_steps(section_meta)
preset_html = _render_preset_html(flow_id, section_id, yaml_data=yaml_data, csrf_token=request.state.csrf_token)
return templates.TemplateResponse(
"wizard/wizard_page.html.j2",
{
"request": request,
"flow_title": flow.title,
"flow_id": flow_id,
"project_name": state.project_name,
"steps": steps,
"section": section,
"step_html": step_html,
"preset_html": preset_html,
"errors": errors or {},
"global_errors": [],
"show_review": flow.show_review,
"menu_items": get_menu_items(user),
"user": user,
},
)
# ---------------------------------------------------------------------------
# HTMX: validate and advance (POST)
# ---------------------------------------------------------------------------
@wizard_router.post("/{flow_id}/step/{section_id}", response_model=None)
@requires_sso
async def submit_step(request: Request, flow_id: str, section_id: str) -> HTMLResponse | RedirectResponse:
"""Process form data and navigate to the requested step.
Also handles sequence add/remove actions when ``_seq_action`` is present
in the form data.
Navigation directions (controlled by ``_goto``):
- ``"next"`` or empty: validate + advance to next step
- ``"prev"``: save without validation + go to previous step
- ``"review"``: validate + show summary page
- any section_id: save without validation + jump to that step
"""
state = get_wizard_state(request)
if not state or state.flow_id != flow_id:
return RedirectResponse(url=f"/forms/wizard/{flow_id}", status_code=303)
# Edit-mode only: fail fast per step instead of stripping data at final
# save. Also covers any future step-driven side-effects (e.g. auto-save).
if state.project_name:
from opi.web.project_edit_security import require_project_edit_access
require_project_edit_access(request, state.project_name)
section = _get_section_from_flow(flow_id, section_id)
flow = get_flow(flow_id)
templates = get_templates()
# Parse JSON body (submitted via HTMX json-enc extension)
body = await request.json()
# Extract control fields (prefixed with _)
seq_action = body.pop("_seq_action", None)
seq_path = body.pop("_seq_path", None)
seq_index = body.pop("_seq_index", None)
is_rerender = body.pop("_rerender", None) == "1"
goto = body.pop("_goto", "next")
# body is now the nested step data
submitted_data = body
# Check for sequence add/remove action - handle before normal validation
if seq_action in ("add", "remove"):
return await _handle_sequence_action(
request,
flow_id,
section_id,
section,
submitted_data,
str(seq_action),
seq_path=str(seq_path or ""),
seq_index=seq_index,
)
processor = EditableFormProcessor()
yaml_data = state.get_merged_data()
edit_mode = state.project_name is not None
# Build enforcer context with out-of-scope metadata
enforcer_context = {"project_name": state.project_name, "edit_mode": edit_mode}
# Re-render only (preview update) — process submission but skip validation
# to prevent spurious "required" errors on newly-visible fields with defaults.
if is_rerender:
submitted_yaml, _errors = await processor.process_json_submission(
submitted_data,
section.editables,
yaml_data,
edit_mode=edit_mode,
enforcer_context=enforcer_context,
)
processor.clear_hidden_depends_on(section.editables, submitted_yaml)
section_data = _extract_section_data(section.editables, submitted_yaml)
state.store_step_data(section_id, section_data)
save_wizard_state(request, state)
step_html = _render_step_html(
section, yaml_data=submitted_yaml, edit_mode=edit_mode, warnings=processor.field_warnings
)
context = _build_step_context(request, flow_id, section, step_html)
return templates.TemplateResponse("wizard/wizard_step.html.j2", context)
# Process the nested JSON: validate, convert, and write to yaml in one pass.
submitted_yaml, errors = await processor.process_json_submission(
submitted_data,
section.editables,
yaml_data,
edit_mode=edit_mode,
enforcer_context=enforcer_context,
)
# CENTRALIZED VALIDATION LOGGING - field-level validation
if errors:
logger.warning(
"[%s validation FAILED] field-level errors: %s",
section_id,
errors,
)
else:
logger.info("[%s validation PASSED] field-level validation ok", section_id)
# --- Resolve navigation direction ---
is_forward = goto in ("next", "review")
logger.info("[submit_step %s] goto=%r, is_forward=%s", section_id, goto, is_forward)
# Auto-add service dependencies when leaving the services step
if section_id == "services" and isinstance(submitted_yaml.get("services"), list):
from opi.services.services import ServiceAdapter
submitted_yaml["services"] = ServiceAdapter.resolve_service_dependencies(submitted_yaml["services"])
# Forward navigation (Next / Review): block on field-level validation errors
if is_forward and errors:
# Extract group-level errors (e.g. from enforcers on GROUP editables)
# and surface them as global_errors so they appear in the alert box.
# Group paths like "deployments[0]" have no leaf field to attach to.
group_errors: list[str] = []
for path, msgs in list(errors.items()):
if path.endswith("]") and "/" not in path.split("]")[-1]:
group_errors.extend(msgs)
step_html = _render_step_html(
section,
yaml_data=submitted_yaml,
errors=errors,
edit_mode=edit_mode,
warnings=processor.field_warnings,
)
context = _build_step_context(
request,
flow_id,
section,
step_html,
errors=errors,
global_errors=group_errors or None,
)
return templates.TemplateResponse("wizard/wizard_step.html.j2", context)
# Forward navigation: run section-level enforcer for cross-field validation
if is_forward and section.enforcer:
global_errors = await processor.enforce_sections(
submitted_yaml, [section], enforcer_context, field_errors=errors, field_warnings=processor.field_warnings
)
# CENTRALIZED VALIDATION LOGGING - section-level (enforcer) validation
if global_errors:
logger.warning(
"[%s validation FAILED] section-level (enforcer) errors: %s",
section_id,
global_errors,
)
step_html = _render_step_html(
section,
yaml_data=submitted_yaml,
errors=errors,
edit_mode=edit_mode,
warnings=processor.field_warnings,
)
context = _build_step_context(
request,
flow_id,
section,
step_html,
errors=errors,
global_errors=global_errors,
)
return templates.TemplateResponse("wizard/wizard_step.html.j2", context)
else:
logger.info("[%s validation PASSED] section-level (enforcer) validation ok", section_id)
# Store converted YAML-format data for this section
section_data = _extract_section_data(section.editables, submitted_yaml)
state.store_step_data(section_id, section_data)
# Run the section's post_merge reconciler against the merged view and
# persist affected component data back into step_data. The services step
# uses this to drop component-level service config when a project service
# is deselected; without persisting it here the components step would
# render stale config blocks until it was itself re-submitted (one
# navigation late).
if section.post_merge is not None:
section.post_merge(submitted_yaml, submitted_yaml)
if "components" in submitted_yaml:
state.store_step_data("components", {"components": submitted_yaml["components"]})
# CENTRALIZED LOGGING - navigation decision point
logger.info(
"[%s] All validations passed. Forward navigation: is_forward=%s, goto=%r",
section_id,
is_forward,
goto,
)
if is_forward:
state.mark_completed(section_id)
# Re-resolve active sections (services step may add/remove conditional steps)
active_section_ids = resolve_active_section_ids(flow, state.step_data)
state.active_sections = active_section_ids
state.stash_inactive_sections(active_section_ids)
# --- Resolve target step ---
target_section_id = _resolve_goto_target(goto, section_id, active_section_ids)
logger.info("[submit_step %s] resolved target=%s", section_id, target_section_id)
# Review page
if target_section_id == "review":
save_wizard_state(request, state)
return await _render_review(request, flow_id, templates)
# Submit (last step, no review)
if target_section_id is None:
save_wizard_state(request, state)
if flow.show_review:
return await _render_review(request, flow_id, templates)
return await _do_submit(request, flow_id, templates)
return await _navigate_to_step(request, state, flow_id, target_section_id, templates)
# ---------------------------------------------------------------------------
# HTMX: apply a preset to the current step
# ---------------------------------------------------------------------------
@wizard_router.post("/{flow_id}/preset/{section_id}/{preset_id}", response_model=None)
@requires_sso
async def toggle_preset(
request: Request,
flow_id: str,
section_id: str,
preset_id: str,
) -> HTMLResponse | RedirectResponse:
"""Toggle a preset: apply if not active, remove if active."""
from opi.forms.presets.loader import get_preset_by_id
from opi.forms.widgets.roos import _is_preset_applied
state = get_wizard_state(request)
if not state or state.flow_id != flow_id:
return RedirectResponse(url=f"/forms/wizard/{flow_id}", status_code=303)
preset = get_preset_by_id(section_id, preset_id)
if not preset:
raise HTTPException(status_code=404, detail=f"Preset '{preset_id}' niet gevonden")
section = _get_section_from_flow(flow_id, section_id)
yaml_data = state.get_merged_data()
if _is_preset_applied(preset, yaml_data):
_remove_preset(preset, yaml_data)
else:
_apply_preset(preset, yaml_data)
# Store updated data back into wizard state
section_data = _extract_section_data(section.editables, yaml_data)
state.store_step_data(section_id, section_data)
save_wizard_state(request, state)
# Re-render the section with the new values
step_html = _render_step_html(
section,
yaml_data=yaml_data,
edit_mode=state.project_name is not None,
)
templates = get_templates()
context = _build_step_context(request, flow_id, section, step_html)
return templates.TemplateResponse("wizard/wizard_step.html.j2", context)