-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo_workflow.py
More file actions
365 lines (289 loc) · 11.7 KB
/
demo_workflow.py
File metadata and controls
365 lines (289 loc) · 11.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
#!/usr/bin/env python
"""
Demonstration script showing the complete formkit-ninja workflow.
This script demonstrates:
1. Creating a FormKit schema programmatically
2. Bootstrapping a Django app from the schema
3. Submitting data and watching it flow through the system
4. Adding a new field and regenerating code
"""
import json
import os
import sys
from pathlib import Path
# Add the project to the path
sys.path.insert(0, str(Path(__file__).parent))
# Setup Django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings")
import django
django.setup()
from django.contrib.auth import get_user_model # noqa: E402
from formkit_ninja import models as fk_models # noqa: E402
from formkit_ninja.form_submission.models import Submission # noqa: E402
def print_section(title):
"""Print a section header."""
print("\n" + "=" * 70)
print(f" {title}")
print("=" * 70 + "\n")
def create_demo_schema():
"""Create a demo FormKit schema."""
print_section("Step 1: Creating FormKit Schema")
# Delete existing schema if it exists
fk_models.FormKitSchema.objects.filter(label="Demo Data Collection").delete()
# Create schema
schema = fk_models.FormKitSchema.objects.create(label="Demo Data Collection")
print(f"✓ Created schema: {schema.label}")
# Create root group
root_group = fk_models.FormKitSchemaNode.objects.create(
node={"$formkit": "group", "name": "data_collection"},
label="Data Collection Form",
)
fk_models.FormComponents.objects.create(
schema=schema,
node=root_group,
label="Data Collection Form",
order=0,
)
print(f"✓ Created root group: {root_group.node.get('name', 'data_collection')}")
# Add fields to root group
fields = [
{"formkit": "text", "name": "collector_name", "label": "Collector Name"},
{"formkit": "email", "name": "collector_email", "label": "Collector Email"},
{"formkit": "date", "name": "collection_date", "label": "Collection Date"},
]
for order, field_data in enumerate(fields):
field_node = fk_models.FormKitSchemaNode.objects.create(
node={"$formkit": field_data["formkit"], "name": field_data["name"]},
label=field_data["label"],
)
fk_models.NodeChildren.objects.create(
parent=root_group,
child=field_node,
order=order,
)
print(f"✓ Added field: {field_data['name']} ({field_data['formkit']})")
# Add a nested group
location_group = fk_models.FormKitSchemaNode.objects.create(
node={"$formkit": "group", "name": "location"},
label="Location Information",
)
fk_models.NodeChildren.objects.create(
parent=root_group,
child=location_group,
order=len(fields),
)
print(f"✓ Added nested group: {location_group.node.get('name', 'location')}")
# Add fields to location group
location_fields = [
{"formkit": "text", "name": "district", "label": "District"},
{"formkit": "text", "name": "village", "label": "Village"},
]
for order, field_data in enumerate(location_fields):
field_node = fk_models.FormKitSchemaNode.objects.create(
node={"$formkit": field_data["formkit"], "name": field_data["name"]},
label=field_data["label"],
)
fk_models.NodeChildren.objects.create(
parent=location_group,
child=field_node,
order=order,
)
print(f" ✓ Added to location: {field_data['name']}")
# Add a repeater
observations_repeater = fk_models.FormKitSchemaNode.objects.create(
node={"$formkit": "repeater", "name": "observations"},
label="Observations",
)
fk_models.NodeChildren.objects.create(
parent=root_group,
child=observations_repeater,
order=len(fields) + 1,
)
print(f"✓ Added repeater: {observations_repeater.node.get('name', 'observations')}")
# Add fields to repeater
repeater_fields = [
{"formkit": "text", "name": "observation_type", "label": "Type"},
{"formkit": "textarea", "name": "notes", "label": "Notes"},
{"formkit": "number", "name": "count", "label": "Count"},
]
for order, field_data in enumerate(repeater_fields):
field_node = fk_models.FormKitSchemaNode.objects.create(
node={"$formkit": field_data["formkit"], "name": field_data["name"]},
label=field_data["label"],
)
fk_models.NodeChildren.objects.create(
parent=observations_repeater,
child=field_node,
order=order,
)
print(f" ✓ Added to observations: {field_data['name']}")
print(f"\n✓ Schema created with {fk_models.FormKitSchemaNode.objects.count()} nodes")
return schema
def show_schema_structure(schema):
"""Display the schema structure."""
print_section("Schema Structure")
def print_node(node, indent=0):
prefix = " " * indent
# Access name and formkit from the node JSON field
node_data = node.node or {}
name = node_data.get("name", "unnamed")
formkit = node_data.get("$formkit", "unknown")
print(f"{prefix}- {name} ({formkit})")
# Get children
children = fk_models.NodeChildren.objects.filter(parent=node).order_by("order")
for child_rel in children:
print_node(child_rel.child, indent + 1)
# Get root node
root_component = fk_models.FormComponents.objects.filter(schema=schema).first()
if root_component and root_component.node:
print_node(root_component.node)
def demonstrate_code_generation(schema):
"""Demonstrate code generation."""
print_section("Step 2: Code Generation Preview")
from formkit_ninja import formkit_schema
from formkit_ninja.parser.formatter import CodeFormatter
from formkit_ninja.parser.generator import CodeGenerator
from formkit_ninja.parser.generator_config import GeneratorConfig
from formkit_ninja.parser.template_loader import DefaultTemplateLoader
# Setup generator
output_dir = Path("/tmp/demo_app")
output_dir.mkdir(exist_ok=True)
config = GeneratorConfig(
app_name="demo_app",
output_dir=output_dir,
schema_name=schema.label,
)
template_loader = DefaultTemplateLoader()
formatter = CodeFormatter()
generator = CodeGenerator(
config=config,
template_loader=template_loader,
formatter=formatter,
)
# Convert schema to Pydantic format
values = list(schema.get_schema_values(recursive=True))
pydantic_schema = formkit_schema.FormKitSchema.parse_obj(values)
# Generate code
print("Generating code...")
generator.generate(pydantic_schema)
print(f"\n✓ Code generated in: {output_dir}")
print("\nGenerated files:")
for file_path in sorted(output_dir.rglob("*.py")):
rel_path = file_path.relative_to(output_dir)
print(f" - {rel_path}")
def demonstrate_data_flow(schema):
"""Demonstrate how data flows through the system."""
print_section("Step 3: Data Flow Demonstration")
# Create a submission
User = get_user_model()
user, _ = User.objects.get_or_create(username="demo_user", email="demo@example.com")
submission_data = {
"collector_name": "John Doe",
"collector_email": "john@example.com",
"collection_date": "2026-02-01",
"location": {
"district": "Dili",
"village": "Comoro",
},
"observations": [
{
"uuid": "550e8400-e29b-41d4-a716-446655440001",
"observation_type": "Wildlife",
"notes": "Saw several birds",
"count": 5,
},
{
"uuid": "550e8400-e29b-41d4-a716-446655440002",
"observation_type": "Plants",
"notes": "Rare orchid species",
"count": 2,
},
],
}
print("Creating submission with data:")
print(json.dumps(submission_data, indent=2))
submission = Submission.objects.create(
user=user,
form_type="DataCollection",
fields=submission_data,
)
print(f"\n✓ Created Submission: {submission.key}")
# Show SeparatedSubmissions
from formkit_ninja.form_submission.models import SeparatedSubmission
separated = SeparatedSubmission.objects.filter(submission=submission)
print(f"\n✓ Created {separated.count()} SeparatedSubmission instances:")
for sep in separated:
print(f"\n - {sep.form_type} (ID: {sep.id})")
print(f" Fields: {list(sep.fields.keys())}")
if sep.repeater_parent:
print(f" Parent: {sep.repeater_parent.form_type}")
if sep.repeater_key:
print(f" Repeater: {sep.repeater_key} (order: {sep.repeater_order})")
def demonstrate_adding_field(schema):
"""Demonstrate adding a new field to the schema."""
print_section("Step 4: Adding a New Field")
# Find the root group
root_component = fk_models.FormComponents.objects.filter(schema=schema).first()
root_node = root_component.node
print(f"Adding new field to: {root_node.node.get('name', 'root')}")
# Create new field
new_field = fk_models.FormKitSchemaNode.objects.create(
node={"$formkit": "text", "name": "project_code"},
label="Project Code",
)
# Get current max order
max_order = fk_models.NodeChildren.objects.filter(parent=root_node).count()
# Add as child
fk_models.NodeChildren.objects.create(
parent=root_node,
child=new_field,
order=max_order,
)
print(f"✓ Added field: {new_field.node.get('name', 'project_code')} ({new_field.node.get('$formkit', 'text')})")
print("\nUpdated schema structure:")
# Show updated structure
def print_node(node, indent=0):
prefix = " " * indent
node_data = node.node or {}
name = node_data.get("name", "unnamed")
formkit = node_data.get("$formkit", "unknown")
marker = " [NEW]" if name == "project_code" else ""
print(f"{prefix}- {name} ({formkit}){marker}")
children = fk_models.NodeChildren.objects.filter(parent=node).order_by("order")
for child_rel in children:
print_node(child_rel.child, indent + 1)
print_node(root_node)
print("\n✓ Code would be regenerated with the new field included")
def main():
"""Run the demonstration."""
print("\n" + "🚀 " * 35)
print(" FormKit-Ninja: Complete Workflow Demonstration")
print("🚀 " * 35)
# Create schema
schema = create_demo_schema()
# Show structure
show_schema_structure(schema)
# Generate code
demonstrate_code_generation(schema)
# Show data flow
demonstrate_data_flow(schema)
# Add field
demonstrate_adding_field(schema)
# Summary
print_section("Summary")
print("This demonstration showed:")
print(" ✓ Creating a FormKit schema with groups and repeaters")
print(" ✓ Generating Django models, schemas, admin, and API code")
print(" ✓ Submitting data and seeing it flow through the system")
print(" ✓ Adding new fields and regenerating code")
print("\nWith formkit-ninja, you can build complete data collection")
print("applications with minimal coding required!")
print("\nNext steps:")
print(" 1. Try the management commands:")
print(" ./manage.py create_schema --label 'My Form'")
print(" ./manage.py bootstrap_app --schema-label 'My Form' --app-name myapp")
print(" 2. Read the Quick Start Guide: docs/quick_start.md")
print(" 3. Explore the generated code in /tmp/demo_app/")
print("\n" + "🎉 " * 35 + "\n")
if __name__ == "__main__":
main()